diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 3de3608656..7dd740673c 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -91,7 +91,8 @@ jobs: # installer registers with the CLI: `openshell` for the packages, # `tmachine` for the k3s and binaries installers. A row without a # package runs every package in the workspace; each driver suite is a - # workspace of its own. + # workspace of its own. `test_threads` and `test_timeout_secs` + # pass `--test-threads` and `--test-timeout` to the runner. rows='[ {"environment":"ubuntu-docker-rootful","installer":"deb","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","test_threads":4}, {"environment":"ubuntu-docker-rootful","installer":"deb-external-docker-driver","family":"conformance","package":"conformance","gateway":"openshell","runner":"ubuntu-24.04","external_driver":true,"test_threads":4}, @@ -290,6 +291,7 @@ jobs: GATEWAY: ${{ matrix.gateway }} DISRUPTION: ${{ matrix.disruption }} TEST_THREADS: ${{ matrix.test_threads }} + TEST_TIMEOUT_SECS: ${{ matrix.test_timeout_secs }} run: | # The tests this environment can't pass yet; the runner passes the # variable on to the guest. @@ -323,6 +325,9 @@ jobs: if [ -n "${TEST_THREADS}" ]; then selection+=(--test-threads "${TEST_THREADS}") fi + if [ -n "${TEST_TIMEOUT_SECS}" ]; then + selection+=(--test-timeout "${TEST_TIMEOUT_SECS}") + fi # A continuity row seeds state, applies the disruption, and verifies. if [ -n "${DISRUPTION}" ]; then selection+=(--disruption "${DISRUPTION}") diff --git a/TESTING.md b/TESTING.md index 5cf0592fd0..912f520657 100644 --- a/TESTING.md +++ b/TESTING.md @@ -330,6 +330,13 @@ and `nextest.log` to the results directory. Branch E2E builds the runner builds the suite or uses `--bundle` or `--program`. The default is one. CI rows can opt in with `test_threads`. +The runner terminates a test after two minutes, or after 15 minutes for +`--program`. `--test-timeout ` sets the limit (below the run's 45-minute +limit) for a built or `--bundle` run, and CI rows set it with +`test_timeout_secs`. The limit applies to every test in the row, so a +row runs at its slowest test's limit: put slow tests in rows of their own. +Keep it above the test's own step timeouts, so those report first. + `openshell-test-runner build --family --out ` builds a family's test bundle for the guest without booting a VM, and `run --bundle ` runs it instead of building one. `--package` then selects the tests to run from the diff --git a/tests/runner/src/bundle.rs b/tests/runner/src/bundle.rs index 05a485a2aa..2b4b82bb19 100644 --- a/tests/runner/src/bundle.rs +++ b/tests/runner/src/bundle.rs @@ -4,10 +4,11 @@ //! Building a family's test bundle for the guest, on the host. //! //! A bundle is a directory holding a nextest archive built for the guest target, -//! the family workspace's `Cargo.toml` files (for `--workspace-remap`), a -//! `nextest` config with the runner's `JUnit` profile, and `testkit-ready`, -//! which waits for the gateway before the tests run. The guest needs only the -//! `cargo-nextest` binary to run it. +//! the family workspace's `Cargo.toml` files (for `--workspace-remap`), and +//! `testkit-ready`, which waits for the gateway before the tests run. The +//! guest needs only the `cargo-nextest` binary to run it. The runner writes +//! the nextest config for each run ([`Bundle::nextest_config`]), so a bundle +//! is never changed after it is built. //! //! `build` writes a bundle to a directory, so CI can build it once and every //! row can run it (`run --bundle`). A `bundle.json` in it names the family @@ -17,6 +18,7 @@ //! can run it instead: the bundle then holds that program alone, built once //! elsewhere for the guest target, and the runner builds nothing. +use std::num::NonZeroU64; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::process::Command; @@ -39,13 +41,19 @@ const SLOW_TERMINATE_AFTER: u64 = 4; /// How long a terminated test has between SIGTERM and SIGKILL. const GRACE_PERIOD_SECS: u64 = 10; -/// The nextest configuration written into a nextest bundle. -fn nextest_config() -> String { +/// The nextest configuration for a nextest bundle. Each test is terminated +/// after `timeout_secs`, as in a program bundle, or after two minutes without +/// one. +fn archive_config(timeout_secs: Option) -> String { + let (period, terminate_after) = timeout_secs + .map_or((SLOW_PERIOD_SECS, SLOW_TERMINATE_AFTER), |secs| { + (secs.get(), 1) + }); format!( r#"# Written by the OpenShell test runner. [profile.openshell] fail-fast = false -slow-timeout = {{ period = "{SLOW_PERIOD_SECS}s", terminate-after = {SLOW_TERMINATE_AFTER}, grace-period = "{GRACE_PERIOD_SECS}s" }} +slow-timeout = {{ period = "{period}s", terminate-after = {terminate_after}, grace-period = "{GRACE_PERIOD_SECS}s" }} [profile.openshell.junit] path = "junit.xml" @@ -58,8 +66,6 @@ pub const PROGRAM_BINARY: &str = "test-program"; /// The nextest archive in a nextest bundle. const ARCHIVE: &str = "tests.tar.zst"; -/// The nextest config in a nextest bundle. -const CONFIG: &str = "nextest.toml"; /// What a nextest bundle was built from. const MANIFEST: &str = "bundle.json"; @@ -91,6 +97,22 @@ impl Bundle { pub const fn kind(&self) -> Kind { self.1 } + + /// The nextest config to run this bundle with, with the runner's + /// profile. A nextest bundle's tests are terminated after `timeout_secs` + /// instead of two minutes. + pub fn nextest_config(&self, timeout_secs: Option) -> Result { + match self.1 { + Kind::Nextest => Ok(archive_config(timeout_secs)), + Kind::Program => { + ensure!( + timeout_secs.is_none(), + "a per-test timeout applies to nextest bundles, not to a prebuilt program" + ); + Ok(PROGRAM_CONFIG.to_string()) + } + } + } } /// A bundle holding `program`, a testkit program already built for the @@ -105,11 +127,10 @@ pub fn program(program: &Path) -> Result { let dir = tempfile::tempdir().context("create bundle directory")?; std::fs::copy(program, dir.path().join(PROGRAM_BINARY)) .with_context(|| format!("copy {}", program.display()))?; - std::fs::write(dir.path().join(CONFIG), PROGRAM_CONFIG)?; Ok(Bundle(dir, Kind::Program)) } -/// The nextest configuration written into a program bundle, shared with the +/// The nextest configuration for a program bundle, shared with the /// host-lane wrapper (`e2e/support/conformance.sh`). const PROGRAM_CONFIG: &str = include_str!("program-nextest.toml"); @@ -219,7 +240,6 @@ pub fn build(root: &Path, family: &str, packages: &[String], out: &Path) -> Resu run(&mut command).with_context(|| format!("build the {} test archive", workspace.display()))?; copy_manifests(&workspace, out)?; - std::fs::write(out.join(CONFIG), nextest_config())?; std::fs::copy(&ready, out.join(READY_BINARY)) .with_context(|| format!("copy {}", ready.display()))?; let manifest = Manifest { @@ -240,7 +260,7 @@ pub fn prebuilt(dir: &Path, family: &str, packages: &[String]) -> Result .with_context(|| format!("parse {}", dir.join(MANIFEST).display()))?; check_selection(&manifest, family, packages) .with_context(|| format!("--bundle {}", dir.display()))?; - for name in [ARCHIVE, CONFIG, READY_BINARY] { + for name in [ARCHIVE, READY_BINARY] { ensure!( dir.join(name).is_file(), "{} is not a test bundle: it has no {name}", @@ -360,25 +380,44 @@ mod tests { #[test] fn nextest_profile_stops_a_hung_test_after_two_minutes() { - let config = nextest_config(); + let config = archive_config(None); assert!(config.contains( r#"slow-timeout = { period = "30s", terminate-after = 4, grace-period = "10s" }"# )); } #[test] - fn program_bundle_holds_the_program_and_nextest_config() { + fn test_timeout_sets_the_nextest_bundle_slow_timeout() { + let dir = tempfile::tempdir().unwrap(); + write_bundle(dir.path(), "features", &[]); + let bundle = prebuilt(dir.path(), "features", &[]).unwrap(); + let config = bundle.nextest_config(NonZeroU64::new(1200)).unwrap(); + assert!(config.contains( + r#"slow-timeout = { period = "1200s", terminate-after = 1, grace-period = "10s" }"# + )); + assert!(config.contains(&format!("[profile.{PROFILE}.junit]\n"))); + assert_eq!(bundle.nextest_config(None).unwrap(), archive_config(None)); + + let program_dir = tempfile::tempdir().unwrap(); + let path = program_dir.path().join("openshell-conformance"); + std::fs::write(&path, b"binary").unwrap(); + let program = program(&path).unwrap(); + assert_eq!(program.nextest_config(None).unwrap(), PROGRAM_CONFIG); + assert!(program.nextest_config(Some(NonZeroU64::MIN)).is_err()); + } + + #[test] + fn program_bundle_holds_the_program_alone() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("openshell-conformance"); std::fs::write(&path, b"binary").unwrap(); let bundle = program(&path).unwrap(); assert_eq!(bundle.kind(), Kind::Program); - let mut names: Vec<_> = std::fs::read_dir(bundle.path()) + let names: Vec<_> = std::fs::read_dir(bundle.path()) .unwrap() .map(|entry| entry.unwrap().file_name()) .collect(); - names.sort(); - assert_eq!(names, [CONFIG, PROGRAM_BINARY]); + assert_eq!(names, [PROGRAM_BINARY]); assert!(program(&dir.path().join("missing")).is_err()); } @@ -390,7 +429,7 @@ mod tests { fn write_bundle(dir: &Path, family: &str, packages: &[&str]) { std::fs::create_dir_all(dir.join("host-gateway")).unwrap(); - for name in [ARCHIVE, CONFIG, READY_BINARY, "Cargo.toml"] { + for name in [ARCHIVE, READY_BINARY, "Cargo.toml"] { std::fs::write(dir.join(name), name).unwrap(); } std::fs::write(dir.join("host-gateway/Cargo.toml"), "member").unwrap(); diff --git a/tests/runner/src/execute.rs b/tests/runner/src/execute.rs index 9432f6a629..b7415bfb41 100644 --- a/tests/runner/src/execute.rs +++ b/tests/runner/src/execute.rs @@ -12,6 +12,7 @@ //! [`crate::test_env`]). use std::fmt; +use std::io::Write; use std::path::Path; use std::process::{ExitCode, ExitStatus, Output}; use std::time::Duration; @@ -25,6 +26,9 @@ use crate::disruption::Disruption; use crate::test_env; const GUEST_DIR: &str = "/var/tmp/openshell-tests"; +/// The run's nextest config in the guest, outside the bundle so no bundle +/// entry can take its place. +const GUEST_CONFIG: &str = "/var/tmp/openshell-tests.nextest.toml"; /// The test log's name, in the guest directory and in the results. const NEXTEST_LOG: &str = "nextest.log"; /// How long the gateway has to become healthy after the environment is up. @@ -34,7 +38,7 @@ const READY_TIMEOUT_SECS: u64 = 300; /// How long the test run may take in total. Individual tests are bounded by /// the nextest profile's slow-timeout; this catches a run that stops making /// progress some other way. -const RUN_TIMEOUT: Duration = Duration::from_mins(45); +pub const RUN_TIMEOUT: Duration = Duration::from_mins(45); /// Slack beyond the readiness check's own timeout for SSH and process start. const READY_SLACK: Duration = Duration::from_mins(1); /// nextest's exit code when a test failed, as opposed to nextest itself @@ -125,6 +129,9 @@ pub struct Run<'a> { pub filters: &'a [String], /// Concurrency override for nextest. pub test_threads: Option, + /// Seconds after which nextest terminates each test, instead of two + /// minutes. + pub test_timeout: Option, /// Where `junit.xml`, `nextest.log` and, after a failure, the guest's /// `diagnostics/` go. pub results: &'a Path, @@ -257,9 +264,14 @@ async fn run_tests(session: &Session, run: &Run<'_>) -> Result { let guest = GUEST_DIR; checked( "clear guest directory", - session.exec(&["rm", "-rf", guest]).await?, + session.exec(&["rm", "-rf", guest, GUEST_CONFIG]).await?, )?; session.copy_in(run.bundle.path(), guest).await?; + let mut config = tempfile::NamedTempFile::new().context("create the nextest config")?; + config + .write_all(run.bundle.nextest_config(run.test_timeout)?.as_bytes()) + .context("write the nextest config")?; + session.copy_in(config.path(), GUEST_CONFIG).await?; checked( "prepare guest directory", session @@ -389,7 +401,6 @@ async fn run_selected( let program = format!("{guest}/{PROGRAM_BINARY}"); let archive = format!("{guest}/tests.tar.zst"); let extract = format!("{guest}/extract"); - let config = format!("{guest}/nextest.toml"); let test_threads = run .test_threads .map_or(1, std::num::NonZeroUsize::get) @@ -398,7 +409,7 @@ async fn run_selected( let cargo_metadata = format!("{metadata}/cargo-metadata.json"); let binaries_metadata = format!("{metadata}/binaries-metadata.json"); let export = test_env::export_script(test_env::ENV_DIR); - let mut args: Vec<&str> = vec!["--config-file", &config, "--profile", PROFILE]; + let mut args: Vec<&str> = vec!["--config-file", GUEST_CONFIG, "--profile", PROFILE]; let env_args = std::iter::once("env").chain(env.iter().map(String::as_str)); let mut tests: Vec<_> = env_args.clone().collect(); tests.extend([ diff --git a/tests/runner/src/main.rs b/tests/runner/src/main.rs index 5f9f7c032c..e66f9515d9 100644 --- a/tests/runner/src/main.rs +++ b/tests/runner/src/main.rs @@ -8,7 +8,7 @@ //! provides the guest cross-compilation toolchain, QEMU, Ansible, and the //! tmachine configuration. -use std::num::NonZeroUsize; +use std::num::{NonZeroU64, NonZeroUsize}; use std::path::{Path, PathBuf}; use std::process::ExitCode; @@ -88,6 +88,16 @@ struct RunArgs { /// Maximum number of tests nextest runs at once [default: 1]. #[arg(long, value_name = "N")] test_threads: Option, + /// Terminate each test after this many seconds instead of two minutes. It + /// applies to every test in the run, so put slow tests in rows of their + /// own. It must be shorter than the whole run's limit. + #[arg( + long, + value_name = "SECS", + conflicts_with = "program", + value_parser = clap::value_parser!(u64).range(1..execute::RUN_TIMEOUT.as_secs()) + )] + test_timeout: Option, /// The gateway name the installer registers with the CLI. The packaged /// installers register `openshell`. #[arg(long, default_value = "openshell")] @@ -186,6 +196,7 @@ async fn run(args: RunArgs) -> Result { bundle: &bundle, filters: &filters, test_threads: args.test_threads, + test_timeout: args.test_timeout.and_then(NonZeroU64::new), results: &results, keep: args.keep, disruption, @@ -285,6 +296,31 @@ mod tests { } } + #[test] + fn test_timeout_is_seconds_below_the_run_limit_for_nextest_bundles() { + let args = [ + "runner", + "run", + "--environment", + "ubuntu-k3s", + "--installer", + "k3s-ha", + "--family", + "drivers/kubernetes", + "--test-timeout", + ]; + let parse = |extra: &[&str]| Cli::try_parse_from(args.iter().chain(extra)); + let Command::Run(run) = parse(&["1200", "--bundle", "b"]).unwrap().command else { + panic!("not run") + }; + assert_eq!(run.test_timeout, Some(1200)); + assert!(parse(&["2699"]).is_ok()); + for bad in ["0", "2700", "1.5", "20m"] { + assert!(parse(&[bad]).is_err(), "{bad}"); + } + assert!(parse(&["1200", "--program", "p"]).is_err()); + } + #[test] fn family_is_a_path_under_tests_suites() { let root = Path::new("/repo");