diff --git a/TESTING.md b/TESTING.md index 5cf0592fd0..a0725389ad 100644 --- a/TESTING.md +++ b/TESTING.md @@ -459,6 +459,10 @@ nix run .#openshell-test-runner -- run \ --family continuity --disruption gateway-restart ``` +tmachine doesn't run the VM driver yet (#5918), so `mise run e2e:vm` runs the +`seed` tests, restarts its gateway, and runs the `verify` tests itself. It sets +`OPENSHELL_TEST_VM_STATE_DIR` for checks on the VM driver's state. + The `upgrade` disruption installs the candidate over a released package. Use the `deb-upgrade-source` installer, or `rpm-upgrade-source` on `fedora-podman-rootless` or `fedora-podman-rootful`, which installs the latest release as the baseline. @@ -563,7 +567,7 @@ Suites: - Driver suites (`--features e2e-docker`, `e2e-podman`, `e2e-kubernetes`, or `e2e-vm`) - conformance plus the common and driver-specific coverage for the selected deployment. -- Docker suite (`--features e2e-docker`) - includes Docker-only coverage such as Dockerfile image builds, Docker preflight checks, and managed Docker gateway start. +- Docker suite (`--features e2e-docker`) - includes Docker-only coverage such as Dockerfile image builds and Docker preflight checks. - Docker GPU suite (`--features e2e-docker-gpu`) - Docker suite plus GPU sandbox smoke coverage. - VM suite (`--features e2e-vm`) - runs e2e tests on a VM. - Kubernetes credential-driver suite (`--features e2e-kubernetes-credential-drivers`) - targeted Kubernetes Secrets and Vault provider credential storage coverage. @@ -1010,7 +1014,7 @@ cargo test --manifest-path e2e/rust/Cargo.toml --features e2e --test sync Run a single Docker-only test directly with cargo: ```shell -cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test gateway_start +cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test provider_readiness ``` The harness (`e2e/rust/src/harness/`) provides: diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 33464ed903..12c2b52bb9 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -81,26 +81,11 @@ name = "additional_ca" path = "tests/additional_ca.rs" required-features = ["e2e-additional-ca"] -[[test]] -name = "gateway_start" -path = "tests/gateway_start.rs" -required-features = ["e2e-docker"] - -[[test]] -name = "local_driver_token_restart" -path = "tests/local_driver_token_restart.rs" -required-features = ["e2e"] - [[test]] name = "ephemeral_cleanup" path = "tests/ephemeral_cleanup.rs" required-features = ["e2e"] -[[test]] -name = "podman_gateway_start" -path = "tests/podman_gateway_start.rs" -required-features = ["e2e-podman"] - [[test]] name = "provider_refresh_handles" path = "tests/provider_refresh_handles.rs" @@ -116,11 +101,6 @@ name = "provider_readiness" path = "tests/provider_readiness.rs" required-features = ["e2e-docker"] -[[test]] -name = "vm_gateway_start" -path = "tests/vm_gateway_start.rs" -required-features = ["e2e-vm"] - [[test]] name = "vm_corporate_proxy" path = "tests/vm_corporate_proxy.rs" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index d47c0f365b..df4438293f 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -24,7 +24,6 @@ source "${ROOT}/e2e/support/conformance.sh" PODMAN_CI_TESTS=( ephemeral_cleanup edge_tunnel_e2e - podman_gateway_start provider_github_app ) diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index eaef034e0f..34f3f7782a 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -44,6 +44,8 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" source "${ROOT}/e2e/support/gateway-common.sh" # shellcheck source=e2e/support/conformance.sh source "${ROOT}/e2e/support/conformance.sh" +# shellcheck source=e2e/support/continuity.sh +source "${ROOT}/e2e/support/continuity.sh" COMPRESSED_DIR="${ROOT}/target/vm-runtime-compressed" GATEWAY_BIN="${OPENSHELL_GATEWAY_BIN:-${ROOT}/target/debug/openshell-gateway}" @@ -371,10 +373,13 @@ GATEWAY_ARGS=( ) e2e_write_gateway_args_file "${GATEWAY_ARGS_FILE}" "${GATEWAY_ARGS[@]}" -"${GATEWAY_BIN}" "${GATEWAY_ARGS[@]}" \ - >"${GATEWAY_LOG}" 2>&1 & -GATEWAY_PID=$! -printf '%s\n' "${GATEWAY_PID}" >"${GATEWAY_PID_FILE}" +start_gateway() { + "${GATEWAY_BIN}" "${GATEWAY_ARGS[@]}" \ + >>"${GATEWAY_LOG}" 2>&1 & + GATEWAY_PID=$! + printf '%s\n' "${GATEWAY_PID}" >"${GATEWAY_PID_FILE}" +} +start_gateway # Register the gateway before polling so readiness exercises the same mTLS # client path as the smoke tests. @@ -393,25 +398,25 @@ export OPENSHELL_GATEWAY_ENDPOINT="${CLI_GATEWAY_ENDPOINT}" # particular gateway log message. The VM driver is spawned eagerly, while # sandboxes are created on demand. -echo "==> Waiting for gateway readiness (timeout ${GATEWAY_READY_TIMEOUT}s)" -elapsed=0 -last_status_output="" -while [ "${elapsed}" -lt "${GATEWAY_READY_TIMEOUT}" ]; do - if ! kill -0 "${GATEWAY_PID}" 2>/dev/null; then - echo "ERROR: openshell-gateway exited before becoming ready" - exit 1 - fi - if last_status_output="$("${CLI_BIN}" status --output json 2>&1)" && - printf '%s\n' "${last_status_output}" | - grep -Eq '"status"[[:space:]]*:[[:space:]]*"connected"'; then - echo "==> Gateway ready after ${elapsed}s" - break - fi - sleep 2 - elapsed=$((elapsed + 2)) -done +wait_for_gateway() { + echo "==> Waiting for gateway readiness (timeout ${GATEWAY_READY_TIMEOUT}s)" + local elapsed=0 + local last_status_output="" + while [ "${elapsed}" -lt "${GATEWAY_READY_TIMEOUT}" ]; do + if ! kill -0 "${GATEWAY_PID}" 2>/dev/null; then + echo "ERROR: openshell-gateway exited before becoming ready" + exit 1 + fi + if last_status_output="$("${CLI_BIN}" status --output json 2>&1)" && + printf '%s\n' "${last_status_output}" | + grep -Eq '"status"[[:space:]]*:[[:space:]]*"connected"'; then + echo "==> Gateway ready after ${elapsed}s" + return + fi + sleep 2 + elapsed=$((elapsed + 2)) + done -if [ "${elapsed}" -ge "${GATEWAY_READY_TIMEOUT}" ]; then echo "ERROR: openshell-gateway did not become ready after ${GATEWAY_READY_TIMEOUT}s" echo "=== last openshell status output ===" if [ -n "${last_status_output}" ]; then @@ -421,7 +426,8 @@ if [ "${elapsed}" -ge "${GATEWAY_READY_TIMEOUT}" ]; then fi echo "=== end openshell status output ===" exit 1 -fi +} +wait_for_gateway # ── Run the smoke test ─────────────────────────────────────────────── # @@ -496,6 +502,17 @@ else run_e2e_test ephemeral_cleanup run_e2e_test vm_overlay run_e2e_test vm_bind_mount - run_e2e_test vm_gateway_start run_e2e_test vm_corporate_proxy + + # The continuity suite's seed and verify tests, with a gateway restart + # between them, as tmachine's gateway-restart disruption does (#5918). + CONTINUITY_RUN_ID="$(printf '%x' "$(date +%s)")" + export CONTINUITY_RUN_ID + export OPENSHELL_TEST_VM_STATE_DIR="${RUN_STATE_DIR}" + e2e_run_continuity_phase seed + echo "==> Restarting openshell-gateway" + e2e_stop_gateway "${GATEWAY_PID}" "${GATEWAY_PID_FILE}" + start_gateway + wait_for_gateway + e2e_run_continuity_phase verify fi diff --git a/e2e/rust/tests/gateway_start.rs b/e2e/rust/tests/gateway_start.rs deleted file mode 100644 index 2bd9c0c738..0000000000 --- a/e2e/rust/tests/gateway_start.rs +++ /dev/null @@ -1,230 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e")] - -//! E2E coverage for reconciling Docker sandboxes after a standalone gateway restart. -//! -//! This intentionally targets the Docker-driver gateway started by -//! `e2e/with-docker-gateway.sh`. Existing-endpoint E2E runs do not own the -//! gateway process, so they skip this restart-only coverage. - -use std::process::{Command, Stdio}; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use tokio::time::sleep; - -const MANAGED_BY_LABEL_FILTER: &str = "label=openshell.ai/managed-by=openshell"; -const READY_MARKER: &str = "gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/gateway-start-state"; -const SANDBOX_NAMESPACE_LABEL: &str = "openshell.ai/sandbox-namespace"; -const SANDBOX_NAME_LABEL: &str = "openshell.ai/sandbox-name"; -const SANDBOX_ROLE_LABEL_FILTER: &str = "label=openshell.ai/isolation-role=sandbox"; - -fn sandbox_container_id(namespace: &str, sandbox_name: &str) -> Result { - let namespace_filter = format!("label={SANDBOX_NAMESPACE_LABEL}={namespace}"); - let sandbox_name_filter = format!("label={SANDBOX_NAME_LABEL}={sandbox_name}"); - let output = Command::new("docker") - .args([ - "ps", - "-aq", - "--filter", - MANAGED_BY_LABEL_FILTER, - "--filter", - SANDBOX_ROLE_LABEL_FILTER, - "--filter", - ]) - .arg(namespace_filter) - .args(["--filter"]) - .arg(sandbox_name_filter) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run docker ps: {err}"))?; - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - let combined = format!("{stdout}{stderr}"); - if !output.status.success() { - return Err(format!( - "docker ps failed (exit {:?}):\n{combined}", - output.status.code() - )); - } - - let ids = stdout - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .collect::>(); - match ids.as_slice() { - [id] => Ok((*id).to_string()), - [] => Err(format!( - "no Docker container found for sandbox '{sandbox_name}' in namespace '{namespace}'" - )), - _ => Err(format!( - "multiple Docker containers found for sandbox '{sandbox_name}' in namespace '{namespace}': {ids:?}" - )), - } -} - -fn sandbox_container_running(namespace: &str, sandbox_name: &str) -> Result { - let container_id = sandbox_container_id(namespace, sandbox_name)?; - let output = Command::new("docker") - .args(["inspect", "-f", "{{.State.Running}}", &container_id]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run docker inspect: {err}"))?; - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - let combined = format!("{stdout}{stderr}"); - if !output.status.success() { - return Err(format!( - "docker inspect failed (exit {:?}):\n{combined}", - output.status.code() - )); - } - - match stdout.trim() { - "true" => Ok(true), - "false" => Ok(false), - other => Err(format!( - "unexpected Docker running state for container {container_id}: {other}" - )), - } -} - -async fn wait_for_container_running( - namespace: &str, - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state: String; - - loop { - match sandbox_container_running(namespace, sandbox_name) { - Ok(running) if running == expected => return Ok(()), - Ok(running) => last_state = format!("running={running}"), - Err(err) => last_state = err, - } - - if start.elapsed() > timeout { - return Err(format!( - "sandbox container '{sandbox_name}' did not reach running={expected} within {}s. Last state: {last_state}", - timeout.as_secs() - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn docker_gateway_restart_preserves_running_and_stopped_intent() { - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!("Skipping gateway start test: e2e gateway is not managed by this test run"); - return; - }; - let Some(namespace) = std::env::var("OPENSHELL_E2E_DOCKER_NETWORK_NAME") - .ok() - .filter(|value| !value.trim().is_empty()) - else { - eprintln!("Skipping gateway start test: Docker e2e namespace is unavailable"); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!( - "echo before-restart > {START_FILE}; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running sandbox"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "sandbox state was not written before restart:\n{before_restart}" - ); - - wait_for_container_running(&namespace, &sandbox.name, true, Duration::from_mins(1)) - .await - .expect("sandbox container should be running before gateway restart"); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create Docker sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_secs(30)) - .await - .expect("sandbox should be stopped before gateway restart"); - wait_for_container_running( - &namespace, - &stopped_sandbox.name, - false, - Duration::from_secs(30), - ) - .await - .expect("stopped Docker sandbox container should not be running"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_container_running(&namespace, &sandbox.name, false, Duration::from_secs(30)) - .await - .expect("gateway shutdown should stop a running-intent Docker sandbox"); - - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_container_running(&namespace, &sandbox.name, true, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent Docker sandbox container"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped Docker sandbox should remain stopped after restart"); - wait_for_container_running( - &namespace, - &stopped_sandbox.name, - false, - Duration::from_secs(30), - ) - .await - .expect("gateway startup should not start an explicitly stopped Docker sandbox"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("sandbox should become ready again with its state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/local_driver_token_restart.rs b/e2e/rust/tests/local_driver_token_restart.rs deleted file mode 100644 index 976bd217fd..0000000000 --- a/e2e/rust/tests/local_driver_token_restart.rs +++ /dev/null @@ -1,175 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e")] - -//! VM-driver E2E regression for sandbox bootstrap JWT material. Launch-scoped -//! bootstrap tokens must remain valid long enough for driver recovery, so -//! restarting the VM gateway reconnects the running sandbox. The Docker and -//! Podman stop-is-terminal checks live in `tests/suites/drivers`. - -use std::fs; -use std::path::PathBuf; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use base64::Engine as _; -use openshell_e2e::harness::cli::{wait_for_healthy, wait_for_sandbox_exec_contains}; -use openshell_e2e::harness::container::e2e_driver; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use prost::Message; - -const READY_MARKER: &str = "local-driver-token-restart-ready"; -const VM_STATE_DIR_ENV: &str = "OPENSHELL_E2E_VM_STATE_DIR"; - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandbox { - #[prost(string, tag = "2")] - name: String, - #[prost(message, optional, tag = "4")] - spec: Option, -} - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandboxSpec { - #[prost(string, tag = "11")] - sandbox_token: String, -} - -fn read_vm_bootstrap_token(sandbox_name: &str) -> Result { - let state_dir = std::env::var_os(VM_STATE_DIR_ENV) - .map(PathBuf::from) - .ok_or_else(|| format!("{VM_STATE_DIR_ENV} must be set for VM restart coverage"))?; - let sandboxes_dir = state_dir.join("sandboxes"); - let entries = fs::read_dir(&sandboxes_dir) - .map_err(|err| format!("read VM sandboxes dir '{}': {err}", sandboxes_dir.display()))?; - - let mut decoded_names = Vec::new(); - for entry in entries { - let entry = entry.map_err(|err| { - format!( - "read VM sandbox dir entry under '{}': {err}", - sandboxes_dir.display() - ) - })?; - let request_path = entry.path().join("sandbox.pb"); - let bytes = match fs::read(&request_path) { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => { - return Err(format!( - "read VM sandbox request '{}': {err}", - request_path.display() - )); - } - }; - - let sandbox = PersistedDriverSandbox::decode(bytes.as_slice()).map_err(|err| { - format!( - "decode VM sandbox request '{}': {err}", - request_path.display() - ) - })?; - decoded_names.push(sandbox.name.clone()); - if sandbox.name != sandbox_name { - continue; - } - - let spec = sandbox - .spec - .ok_or_else(|| format!("VM sandbox '{sandbox_name}' is missing driver spec"))?; - if spec.sandbox_token.trim().is_empty() { - return Err(format!( - "VM sandbox '{sandbox_name}' persisted driver spec has no sandbox token" - )); - } - return Ok(spec.sandbox_token); - } - - Err(format!( - "no VM sandbox request found for '{sandbox_name}' under '{}'. Decoded sandbox names: {decoded_names:?}", - sandboxes_dir.display() - )) -} - -fn token_exp_claim(token: &str) -> Result { - let payload_b64 = token - .trim() - .split('.') - .nth(1) - .ok_or_else(|| "sandbox JWT has no payload segment".to_string())?; - let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(payload_b64) - .map_err(|err| format!("failed to decode sandbox JWT payload: {err}"))?; - let claims: serde_json::Value = serde_json::from_slice(&payload) - .map_err(|err| format!("failed to parse sandbox JWT claims: {err}"))?; - claims - .get("exp") - .and_then(serde_json::Value::as_i64) - .ok_or_else(|| format!("sandbox JWT missing integer exp claim: {claims}")) -} - -fn require_unexpired_token(token: &str, context: &str) -> Result<(), String> { - let exp = token_exp_claim(token)?; - let now = i64::try_from( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| format!("system clock is before Unix epoch: {err}"))? - .as_secs(), - ) - .map_err(|_| "current Unix timestamp does not fit in i64".to_string())?; - // Sandbox session tokens use exp=0 when no TTL is configured. - if exp != 0 && exp <= now { - return Err(format!( - "{context} should expire in the future, got exp={exp}, now={now}" - )); - } - Ok(()) -} - -async fn restart_vm_sandbox(gateway: &ManagedGateway, sandbox_name: &str) -> Result<(), String> { - let token = read_vm_bootstrap_token(sandbox_name)?; - require_unexpired_token(&token, "VM bootstrap JWT")?; - - gateway.stop()?; - gateway.start()?; - wait_for_healthy(Duration::from_mins(2)).await -} - -#[tokio::test] -async fn vm_gateway_restart_reconnects_sandbox() { - if e2e_driver().as_deref() != Some("vm") { - eprintln!("Skipping VM driver restart test: e2e driver is not VM"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!( - "Skipping VM driver restart test: VM e2e gateway is not managed by this test run" - ); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!("echo {READY_MARKER}; while true; do sleep 1; done"); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running VM sandbox"); - - restart_vm_sandbox(&gateway, &sandbox.name) - .await - .expect("restart e2e VM gateway"); - wait_for_sandbox_exec_contains( - &sandbox.name, - &["echo", "vm-reconnect-ok"], - "vm-reconnect-ok", - Duration::from_mins(4), - ) - .await - .expect("sandbox supervisor should reconnect after VM driver restart"); - - sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/podman_gateway_start.rs b/e2e/rust/tests/podman_gateway_start.rs deleted file mode 100644 index 907f9c71b4..0000000000 --- a/e2e/rust/tests/podman_gateway_start.rs +++ /dev/null @@ -1,205 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-podman")] - -//! Podman-specific E2E coverage for stopping and starting sandboxes across a -//! standalone gateway restart. - -use std::process::{Command, Stdio}; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use tokio::time::sleep; - -const READY_MARKER: &str = "podman-gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "podman-gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/podman-gateway-start-state"; -const MANAGED_BY_LABEL_FILTER: &str = "label=openshell.managed=true"; -const SANDBOX_NAME_LABEL: &str = "openshell.ai/sandbox-name"; - -/// Build a `podman` command that targets the same API socket the gateway uses. -/// -/// The e2e harness (`e2e/with-podman-gateway.sh`) exports -/// `OPENSHELL_PODMAN_SOCKET` (discovered via `podman machine inspect` on macOS, -/// or the rootless socket on Linux) and also clobbers `XDG_CONFIG_HOME` with an -/// empty directory to isolate CLI/SDK gateway metadata. On macOS the podman -/// client resolves its VM connection through `XDG_CONFIG_HOME`, so a bare -/// `podman ps` here falls back to a nonexistent native rootless socket and -/// fails. Pinning `--url` to the exported socket bypasses connection-config -/// resolution entirely and mirrors the shell's `podman_cmd` helper. -/// -/// When `OPENSHELL_PODMAN_SOCKET` is unset (e.g. running this test outside the -/// harness), fall back to plain `podman`, leaving Linux behavior unchanged. -fn podman_command() -> Command { - let mut command = Command::new("podman"); - if let Ok(socket) = std::env::var("OPENSHELL_PODMAN_SOCKET") - && !socket.is_empty() - { - command.arg("--url").arg(format!("unix://{socket}")); - } - command -} - -fn sandbox_container_running(sandbox_name: &str) -> Result { - let sandbox_name_filter = format!("label={SANDBOX_NAME_LABEL}={sandbox_name}"); - let output = podman_command() - .args([ - "ps", - "-aq", - "--filter", - MANAGED_BY_LABEL_FILTER, - "--filter", - "label=openshell.ai/isolation-role=sandbox", - "--filter", - ]) - .arg(sandbox_name_filter) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run podman ps: {err}"))?; - if !output.status.success() { - return Err(format!( - "podman ps failed: {}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )); - } - let ids = String::from_utf8_lossy(&output.stdout) - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .map(str::to_string) - .collect::>(); - let [container_id] = ids.as_slice() else { - return Err(format!( - "expected one Podman container for sandbox '{sandbox_name}', found {ids:?}" - )); - }; - let output = podman_command() - .args(["inspect", "-f", "{{.State.Running}}", container_id]) - .output() - .map_err(|err| format!("failed to run podman inspect: {err}"))?; - if !output.status.success() { - return Err(format!( - "podman inspect failed: {}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )); - } - match String::from_utf8_lossy(&output.stdout).trim() { - "true" => Ok(true), - "false" => Ok(false), - state => Err(format!("unexpected Podman running state: {state}")), - } -} - -async fn wait_for_container_running( - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state; - loop { - match sandbox_container_running(sandbox_name) { - Ok(running) if running == expected => return Ok(()), - Ok(running) => last_state = format!("running={running}"), - Err(err) => last_state = err, - } - if start.elapsed() > timeout { - return Err(format!( - "Podman container for '{sandbox_name}' did not reach running={expected}: {last_state}" - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn podman_gateway_restart_preserves_running_and_stopped_intent() { - if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("podman") { - eprintln!("Skipping Podman gateway start test: e2e driver is not podman"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!( - "Skipping Podman gateway start test: e2e gateway is not managed by this test run" - ); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!( - "echo before-restart > {START_FILE}; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running Podman sandbox"); - wait_for_container_running(&sandbox.name, true, Duration::from_mins(1)) - .await - .expect("Podman sandbox container should initially be running"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read Podman sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "sandbox state was not written before restart:\n{before_restart}" - ); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create Podman sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("Podman sandbox should be stopped before gateway restart"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_container_running(&sandbox.name, false, Duration::from_mins(1)) - .await - .expect("gateway shutdown should stop the running-intent Podman sandbox"); - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_container_running(&sandbox.name, true, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent Podman sandbox"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped Podman sandbox should remain stopped after restart"); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("Podman sandbox should become ready again with its state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/vm_gateway_start.rs b/e2e/rust/tests/vm_gateway_start.rs deleted file mode 100644 index 9c785a46cb..0000000000 --- a/e2e/rust/tests/vm_gateway_start.rs +++ /dev/null @@ -1,165 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-vm")] - -//! VM-specific E2E coverage for starting sandboxes after a standalone gateway -//! restart. -//! -//! This test is gated behind the `e2e-vm` feature because it requires the VM -//! driver runtime prepared by `e2e/rust/e2e-vm.sh`. - -use std::fs; -use std::path::PathBuf; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use prost::Message; -use tokio::time::sleep; - -const READY_MARKER: &str = "vm-gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "vm-gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/vm-gateway-start-state"; -const VM_STATE_DIR_ENV: &str = "OPENSHELL_E2E_VM_STATE_DIR"; - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandbox { - #[prost(string, tag = "2")] - name: String, -} - -fn vm_sandbox_stopped(sandbox_name: &str) -> Result { - let state_dir = std::env::var_os(VM_STATE_DIR_ENV) - .map(PathBuf::from) - .ok_or_else(|| format!("{VM_STATE_DIR_ENV} must be set"))?; - let sandboxes_dir = state_dir.join("sandboxes"); - for entry in fs::read_dir(&sandboxes_dir) - .map_err(|err| format!("read '{}': {err}", sandboxes_dir.display()))? - { - let path = entry - .map_err(|err| format!("read VM sandbox entry: {err}"))? - .path(); - let request_path = path.join("sandbox.pb"); - let bytes = match fs::read(&request_path) { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => return Err(format!("read '{}': {err}", request_path.display())), - }; - let sandbox = PersistedDriverSandbox::decode(bytes.as_slice()) - .map_err(|err| format!("decode '{}': {err}", request_path.display()))?; - if sandbox.name == sandbox_name { - return Ok(path.join("stopped").exists()); - } - } - Err(format!( - "VM state for sandbox '{sandbox_name}' was not found" - )) -} - -async fn wait_for_vm_stopped_marker( - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state; - loop { - match vm_sandbox_stopped(sandbox_name) { - Ok(stopped) if stopped == expected => return Ok(()), - Ok(stopped) => last_state = format!("stopped={stopped}"), - Err(err) => last_state = err, - } - if start.elapsed() > timeout { - return Err(format!( - "VM '{sandbox_name}' did not reach stopped={expected}: {last_state}" - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn vm_gateway_restart_preserves_running_and_stopped_intent() { - if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("vm") { - eprintln!("Skipping VM gateway start test: e2e driver is not vm"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!("Skipping VM gateway start test: e2e gateway is not managed by this test run"); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - // The gateway restart terminates the VM process before re-adopting its - // overlay. Flush the marker before reporting readiness so the assertion - // verifies durable overlay state rather than guest page-cache timing. - let script = format!( - "echo before-restart > {START_FILE}; sync; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running VM sandbox"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read VM sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "VM sandbox state was not written before restart:\n{before_restart}" - ); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create VM sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("VM sandbox should be stopped before gateway restart"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_vm_stopped_marker(&sandbox.name, true, Duration::from_mins(1)) - .await - .expect("gateway shutdown should stop the running-intent VM through its driver"); - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_vm_stopped_marker(&sandbox.name, false, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent VM"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped VM sandbox should remain stopped after restart"); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("VM sandbox should become ready again with its overlay state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/support/continuity.sh b/e2e/support/continuity.sh new file mode 100644 index 0000000000..bae757f9ba --- /dev/null +++ b/e2e/support/continuity.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 + +# Run one phase of the continuity suite (tests/suites/continuity) against an +# already configured e2e gateway, for host lanes that restart their own +# gateway between the phases. The caller sets CONTINUITY_RUN_ID to the same +# value for both phases. + +# Run every scenario's `seed` or `verify` test with nextest. +e2e_run_continuity_phase() ( + local phase=$1 + local root + root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + + e2e_require_openshell_bin || return + if [ -z "${CONTINUITY_RUN_ID:-}" ]; then + echo "ERROR: CONTINUITY_RUN_ID must be set for both continuity phases" >&2 + return 2 + fi + + echo "==> Running continuity ${phase} tests (run ${CONTINUITY_RUN_ID})" + cargo-nextest nextest run --locked \ + --manifest-path "${root}/tests/suites/continuity/Cargo.toml" \ + --config-file "${root}/tests/runner/src/program-nextest.toml" \ + --profile openshell --no-tests fail \ + -E "test(/::${phase}\$/)" +) diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index f031bc1b57..603422f057 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -532,6 +532,7 @@ version = "0.0.0" dependencies = [ "openshell-testkit", "tokio", + "vm-support", ] [[package]] @@ -4395,6 +4396,17 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vm-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-core", + "openshell-testkit", + "prost", + "serde_json", +] + [[package]] name = "vte" version = "0.14.1" diff --git a/tests/suites/continuity/Cargo.toml b/tests/suites/continuity/Cargo.toml index 785102ad6f..60d45f5a2c 100644 --- a/tests/suites/continuity/Cargo.toml +++ b/tests/suites/continuity/Cargo.toml @@ -15,5 +15,6 @@ publish = false [dependencies] openshell-testkit = { path = "../../testkit/testkit" } tokio = { version = "1", features = ["time"] } +vm-support = { path = "../../support/vm" } [workspace] diff --git a/tests/suites/continuity/src/lib.rs b/tests/suites/continuity/src/lib.rs index 678290eaf2..46bd3e0dbc 100644 --- a/tests/suites/continuity/src/lib.rs +++ b/tests/suites/continuity/src/lib.rs @@ -15,6 +15,7 @@ //! through the CLI, which testkit doesn't track, and `verify` adopts them so //! its own cleanup removes them. +mod sandbox_intent; mod sandbox_workspace; mod scenario; diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs new file mode 100644 index 0000000000..40a478c885 --- /dev/null +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A disruption keeps each sandbox's running or stopped intent. +//! +//! Every disruption restarts the gateway, and a gateway that shuts down stops +//! the sandboxes it runs. When it comes back, it starts the running sandbox +//! again, so that sandbox's processes start after `seed`, with the same SSH +//! host key. It leaves the stopped sandbox stopped. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use testkit::sdk::SandboxPhase; +use testkit::{Context, Poll, ResultExt as _}; + +use crate::scenario::{create_and_run, name}; + +/// The time `seed` ran, in seconds since the epoch on the sandbox's clock, +/// and the sandbox's SSH host key fingerprint, one per line. +const MARKER: &str = "/sandbox/.continuity-intent"; +const STOP_TIMEOUT: Duration = Duration::from_secs(120); + +/// Creates a running sandbox that records when `seed` ran and its host key, +/// and a sandbox that is stopped. +#[testkit::test] +async fn seed(cx: &mut Context) -> testkit::Result { + let (running, stopped) = (name("run")?, name("stop")?); + create_and_run(cx, &stopped, "true").await?; + cx.cli(["sandbox", "stop", &stopped]) + .await? + .success() + .context("stop the sandbox")?; + testkit::poll_until( + &format!("sandbox {stopped} to be Stopped"), + STOP_TIMEOUT, + Duration::from_secs(2), + async || { + let phase = cx.client().get_sandbox(&stopped).await?.phase; + Ok(if phase == SandboxPhase::Stopped { + Poll::Ready(()) + } else { + Poll::Pending(format!("phase {phase:?}")) + }) + }, + ) + .await?; + + create_and_run(cx, &running, "true").await?; + let fingerprint = host_key(cx, &running).await?; + let record = + format!("printf '%s\\n%s\\n' \"$(date +%s)\" '{fingerprint}' > '{MARKER}' && sync"); + cx.cli([ + "sandbox", "exec", "--name", &running, "--no-tty", "--", "sh", "-c", &record, + ]) + .await? + .success() + .context("record the seed time and host key")?; + Ok(()) +} + +/// The running sandbox's processes started after `seed`, it kept its host +/// key, and the stopped sandbox is still stopped. +#[testkit::test] +async fn verify(cx: &mut Context) -> testkit::Result { + // Adopting tracks the sandboxes, so cleanup deletes them after this test. + let running = cx + .adopt(&name("run")?) + .await + .context("find the running sandbox")?; + let stopped = cx + .adopt(&name("stop")?) + .await + .context("find the stopped sandbox")?; + running.wait_ready().await?; + + // The marker, the kernel's boot time, the clock tick rate, and the stat + // line of the sandbox's first process. + let script = format!( + "cat '{MARKER}' && grep '^btime ' /proc/stat \ + && (getconf CLK_TCK 2>/dev/null || echo 100) && cat /proc/1/stat" + ); + let probe = running.exec(["sh", "-c", &script]).await?.success()?; + let observed = + Probe::parse(&probe.stdout).context(format!("read the probe output {:?}", probe.stdout))?; + testkit::ensure!( + observed.started > observed.seeded, + "sandbox {} has run since {}, before seed recorded {}: the disruption didn't restart it", + running.name(), + observed.started, + observed.seeded + ); + let fingerprint = host_key(cx, running.name()).await?; + testkit::ensure!( + fingerprint == observed.fingerprint, + "sandbox {}'s host key changed from {} to {fingerprint}", + running.name(), + observed.fingerprint + ); + + // The running sandbox is ready, so the gateway has reconciled both. + let phase = stopped.get().await?.phase; + testkit::ensure!( + phase == SandboxPhase::Stopped, + "sandbox {} was stopped before the disruption and is {phase:?} after it", + stopped.name() + ); + + if cx.compute_driver().await? == "vm" { + let state = vm_support::StateDir::from_env()?; + let expiry = vm_support::token_expiry(&state.sandbox_token(running.name())?)?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|err| testkit::Error::msg(format!("read the clock: {err}")))? + .as_secs(); + // A token without a lifetime has exp 0. + testkit::ensure!( + expiry == 0 || expiry > now, + "the VM driver relaunched sandbox {} with a token that expired at {expiry}; now is {now}", + running.name() + ); + } + Ok(()) +} + +/// The sandbox's SSH host key fingerprint. +async fn host_key(cx: &Context, sandbox: &str) -> testkit::Result { + cx.client() + .get_sandbox(sandbox) + .await + .context(format!("get sandbox {sandbox}"))? + .host_key_fingerprint + .ok_or_else(|| { + testkit::Error::msg(format!("sandbox {sandbox} has no host key fingerprint")) + }) +} + +/// What `verify`'s probe printed, with times in seconds since the epoch. +#[derive(Debug, PartialEq)] +struct Probe { + seeded: u64, + fingerprint: String, + /// When the sandbox's first process started. + started: u64, +} + +impl Probe { + fn parse(output: &str) -> testkit::Result { + let mut lines = output.lines(); + let mut next = |what: &str| { + lines + .next() + .ok_or_else(|| testkit::Error::msg(format!("no {what} line"))) + }; + let seeded = number(next("seed time")?)?; + let fingerprint = next("fingerprint")?.to_string(); + let boot = number( + next("btime")? + .strip_prefix("btime ") + .ok_or_else(|| testkit::Error::msg("the btime line has no btime prefix"))?, + )?; + let ticks_per_second = number(next("clock tick")?)?; + testkit::ensure!(ticks_per_second > 0, "the clock tick rate is 0"); + // The command name in field 2 may hold spaces, so count fields after + // its closing parenthesis. The start time is field 22. + let stat = next("stat")?; + let start_ticks = stat + .rsplit_once(')') + .and_then(|(_, rest)| rest.split_whitespace().nth(19)) + .ok_or_else(|| testkit::Error::msg(format!("no start time in {stat:?}")))?; + let started = boot + number(start_ticks)? / ticks_per_second; + Ok(Self { + seeded, + fingerprint, + started, + }) + } +} + +fn number(text: &str) -> testkit::Result { + text.trim() + .parse() + .map_err(|err| testkit::Error::msg(format!("{text:?} is not a number: {err}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_when_the_first_process_started() { + let output = "1700000000\nSHA256:abc\nbtime 1699990000\n100\n\ + 1 (openshell sandbox) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 1500000 0 0\n"; + assert_eq!( + Probe::parse(output).unwrap(), + Probe { + seeded: 1_700_000_000, + fingerprint: "SHA256:abc".to_string(), + started: 1_700_005_000, + } + ); + } +} diff --git a/tests/suites/continuity/src/sandbox_workspace.rs b/tests/suites/continuity/src/sandbox_workspace.rs index f05827670f..302b4d5583 100644 --- a/tests/suites/continuity/src/sandbox_workspace.rs +++ b/tests/suites/continuity/src/sandbox_workspace.rs @@ -3,46 +3,19 @@ //! A sandbox and its workspace survive a disruption. -use std::time::Duration; - use testkit::{Context, ResultExt as _}; -use crate::scenario::{id, name}; +use crate::scenario::{create_and_run, id, name}; const MARKER: &str = "/sandbox/.continuity-marker"; -const READY_TIMEOUT: Duration = Duration::from_secs(120); /// Creates a sandbox, waits until it runs commands, and writes the run id to a /// file in its workspace. #[testkit::test] async fn seed(cx: &mut Context) -> testkit::Result { let (sandbox, id) = (name("ws")?, id()?); - // Created through the CLI, which testkit doesn't track, so it outlives - // this test. - cx.cli([ - "sandbox", "create", "--name", &sandbox, "--detach", "--", "sleep", "infinity", - ]) - .await? - .success() - .context("create the sandbox")?; - let write = format!("printf '%s\\n' '{id}' > '{MARKER}' && sync"); - let deadline = tokio::time::Instant::now() + READY_TIMEOUT; - loop { - let out = cx - .cli([ - "sandbox", "exec", "--name", &sandbox, "--no-tty", "--", "sh", "-c", &write, - ]) - .await?; - if out.success().is_ok() { - return Ok(()); - } - testkit::ensure!( - tokio::time::Instant::now() < deadline, - "sandbox {sandbox} did not run a command within {READY_TIMEOUT:?}" - ); - tokio::time::sleep(Duration::from_secs(2)).await; - } + create_and_run(cx, &sandbox, &write).await } /// The sandbox is still listed and ready, its file is intact, and a sandbox diff --git a/tests/suites/continuity/src/scenario.rs b/tests/suites/continuity/src/scenario.rs index c9705124cf..71ac016f0c 100644 --- a/tests/suites/continuity/src/scenario.rs +++ b/tests/suites/continuity/src/scenario.rs @@ -3,12 +3,17 @@ //! What a scenario's `seed` and `verify` share. -use testkit::Result; +use std::time::Duration; + +use testkit::{Context, Result, ResultExt as _}; /// The variable the runner sets to the id shared by one run's `seed` and /// `verify` tests. pub const ID_ENV: &str = "CONTINUITY_RUN_ID"; +/// How long a sandbox `seed` creates may take to run a command. +const READY_TIMEOUT: Duration = Duration::from_secs(120); + /// The id of this run. Fails when the tests were not started by the runner's /// `--disruption` mode, because a `seed` without a `verify` proves nothing. pub fn id() -> Result { @@ -26,3 +31,32 @@ pub fn id() -> Result { pub fn name(suffix: &str) -> Result { Ok(format!("cont-{}-{suffix}", id()?)) } + +/// Create a long-running sandbox through the CLI, which testkit doesn't +/// track, so it outlives `seed`, and run `script` in it once it runs +/// commands. +pub async fn create_and_run(cx: &Context, sandbox: &str, script: &str) -> Result { + cx.cli([ + "sandbox", "create", "--name", sandbox, "--detach", "--", "sleep", "infinity", + ]) + .await? + .success() + .context(format!("create sandbox {sandbox}"))?; + + let deadline = tokio::time::Instant::now() + READY_TIMEOUT; + loop { + let out = cx + .cli([ + "sandbox", "exec", "--name", sandbox, "--no-tty", "--", "sh", "-c", script, + ]) + .await?; + if out.success().is_ok() { + return Ok(()); + } + testkit::ensure!( + tokio::time::Instant::now() < deadline, + "sandbox {sandbox} did not run a command within {READY_TIMEOUT:?}" + ); + tokio::time::sleep(Duration::from_secs(2)).await; + } +} diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 83e25ef4da..0665d2a2ba 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -4765,6 +4765,17 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vm-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-core", + "openshell-testkit", + "prost", + "serde_json", +] + [[package]] name = "vte" version = "0.14.1" diff --git a/tests/support/vm/Cargo.toml b/tests/support/vm/Cargo.toml new file mode 100644 index 0000000000..c6599d50fe --- /dev/null +++ b/tests/support/vm/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "vm-support" +description = "Access to the VM driver's sandbox state, for test suites" +version = "0.0.0" +edition = "2024" +rust-version = "1.95" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[dependencies] +base64 = "0.22" +openshell-core = { path = "../../../crates/openshell-core", default-features = false } +openshell-testkit = { path = "../../testkit/testkit" } +prost = "0.14" +serde_json = "1" diff --git a/tests/support/vm/src/lib.rs b/tests/support/vm/src/lib.rs new file mode 100644 index 0000000000..f208d4d988 --- /dev/null +++ b/tests/support/vm/src/lib.rs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The VM driver's sandbox state, for checks the gateway API can't make. +//! +//! The VM driver keeps each sandbox's request under +//! `/sandboxes//sandbox.pb`. The environment names the state +//! directory in `OPENSHELL_TEST_VM_STATE_DIR`, and the test must run as the +//! user that owns it. `e2e/rust/e2e-vm.sh` sets it. A missing variable fails +//! the test; it never skips it. + +use std::path::PathBuf; + +use base64::Engine as _; +use openshell_core::proto::compute::v1::DriverSandbox; +use prost::Message as _; +use testkit::{Error, Result, ResultExt as _}; + +pub const STATE_DIR_ENV: &str = "OPENSHELL_TEST_VM_STATE_DIR"; + +/// The VM driver's state directory. +#[derive(Clone, Debug)] +pub struct StateDir(PathBuf); + +impl StateDir { + /// Read [`STATE_DIR_ENV`]. + pub fn from_env() -> Result { + testkit::required_env(STATE_DIR_ENV, "the VM driver's state directory") + .map(|dir| Self(dir.into())) + } + + /// The request the driver keeps for sandbox `name`. + pub fn sandbox(&self, name: &str) -> Result { + let dir = self.0.join("sandboxes"); + let entries = std::fs::read_dir(&dir).context(format!("read {}", dir.display()))?; + let mut names = Vec::new(); + for entry in entries { + let path = entry + .context(format!("read {}", dir.display()))? + .path() + .join("sandbox.pb"); + let bytes = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, + Err(err) => return Err(Error::msg(format!("read {}: {err}", path.display()))), + }; + let sandbox = DriverSandbox::decode(bytes.as_slice()) + .map_err(|err| Error::msg(format!("decode {}: {err}", path.display())))?; + if sandbox.name == name { + return Ok(sandbox); + } + names.push(sandbox.name); + } + Err(Error::msg(format!( + "no VM sandbox {name} under {}; found {names:?}", + dir.display() + ))) + } + + /// The bootstrap token the driver launches sandbox `name` with. + pub fn sandbox_token(&self, name: &str) -> Result { + let token = self + .sandbox(name)? + .spec + .map(|spec| spec.sandbox_token) + .unwrap_or_default(); + testkit::ensure!( + !token.trim().is_empty(), + "VM sandbox {name} has no sandbox token" + ); + Ok(token) + } +} + +/// The `exp` claim of JWT `token`, unverified. A token without a lifetime has +/// 0. +pub fn token_expiry(token: &str) -> Result { + let payload = token + .trim() + .split('.') + .nth(1) + .ok_or_else(|| Error::msg("the token has no payload"))?; + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .map_err(|err| Error::msg(format!("decode the token payload: {err}")))?; + let claims: serde_json::Value = + serde_json::from_slice(&payload).context("parse the token claims")?; + claims["exp"] + .as_u64() + .ok_or_else(|| Error::msg(format!("the token has no numeric exp claim: {claims}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_expiry_claim() { + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":42}"#); + assert_eq!(token_expiry(&format!("h.{payload}.s")).unwrap(), 42); + assert!(token_expiry("no-payload").is_err()); + } +} diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index 9f09e539ad..385fc32582 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -86,19 +86,15 @@ let # entry says what it needs. Entries marked "wrapper lane" still run in the # wrapper-based Podman lane (`mise run e2e:podman:ci`), so they are covered # there until tmachine provides what they need. - podmanE2eFollowUpBinaries = [ - # Holds only the VM gateway restart test, which skips on Podman. - "local_driver_token_restart" - # Self-skips without wrapper-owned gateway metadata (restart and - # configuration control), so exclude it rather than report false passes. - # Wrapper lane. - "podman_gateway_start" - ]; + podmanE2eFollowUpBinaries = [ ]; podmanE2eArchiveFilter = let excludedBinaries = map (binary: "binary(=${binary})") podmanE2eFollowUpBinaries; in - "kind(test) and not (${pkgs.lib.concatStringsSep " or " excludedBinaries})"; + if excludedBinaries == [ ] then + "kind(test)" + else + "kind(test) and not (${pkgs.lib.concatStringsSep " or " excludedBinaries})"; podmanE2eCiTests = pkgs.writeShellApplication { name = "generate-podman-e2e-ci-tests";