diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index ba5a5d2ff8..558c8eb57c 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -150,6 +150,22 @@ struct RunArgs { #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] compute_driver_socket: Option, + /// What graceful shutdown does with running sandboxes: + /// `stop-running-sandboxes` (default) or `retain-running-sandboxes`. + /// + /// Retain skips only the shutdown stop sweep so the next gateway can + /// re-adopt live sandboxes; all other shutdown cleanup still runs. Any + /// other value selects the stop sweep. + #[arg(long, env = "OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION")] + shutdown_disposition: Option, + + /// File holding the shutdown disposition, read when the shutdown signal + /// arrives so a host can choose per shutdown. When set it replaces + /// `--shutdown-disposition`; a missing, unreadable or unknown file + /// selects the stop sweep. + #[arg(long, env = "OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION_FILE")] + shutdown_disposition_file: Option, + /// Disable TLS entirely — listen on plaintext HTTP. /// Use this when the gateway sits behind a reverse proxy or tunnel /// (e.g. Cloudflare Tunnel) that terminates TLS at the edge. @@ -583,6 +599,10 @@ fn prepare_server_config_with_drivers( guest_tls, compute_driver, legacy_compute_driver_env_seen, + shutdown_disposition: crate::shutdown_disposition::ShutdownDispositionConfig { + value: args.shutdown_disposition.clone(), + file: args.shutdown_disposition_file.clone(), + }, }) } @@ -1471,6 +1491,52 @@ mod tests { assert!(!cli.run.enable_loopback_service_http); } + #[test] + fn command_reads_shutdown_disposition_from_flags_and_env() { + use crate::shutdown_disposition::ShutdownDisposition; + + let _lock = ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _value = EnvVarGuard::remove("OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION"); + let _file = EnvVarGuard::remove("OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION_FILE"); + + let cli = + Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"]).unwrap(); + assert_eq!(cli.run.shutdown_disposition, None); + assert_eq!(cli.run.shutdown_disposition_file, None); + + // Unknown values are accepted by the parser and resolve to the sweep. + let cli = Cli::try_parse_from([ + "openshell-gateway", + "--db-url", + "sqlite::memory:", + "--shutdown-disposition", + "not-a-mode", + ]) + .unwrap(); + assert_eq!(cli.run.shutdown_disposition.as_deref(), Some("not-a-mode")); + + let _value = EnvVarGuard::set( + "OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION", + ShutdownDisposition::RETAIN, + ); + let _file = EnvVarGuard::set( + "OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION_FILE", + "/run/openshell/disposition", + ); + let cli = + Cli::try_parse_from(["openshell-gateway", "--db-url", "sqlite::memory:"]).unwrap(); + assert_eq!( + cli.run.shutdown_disposition.as_deref(), + Some(ShutdownDisposition::RETAIN) + ); + assert_eq!( + cli.run.shutdown_disposition_file, + Some(std::path::PathBuf::from("/run/openshell/disposition")) + ); + } + #[test] fn command_parses_oidc_insecure_http_acknowledgement_value() { let _lock = ENV_LOCK diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index ddbb2400d8..50ad91cac7 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -16,6 +16,7 @@ use crate::persistence::{ }; use crate::sandbox_index::SandboxIndex; use crate::sandbox_watch::SandboxWatchBus; +use crate::shutdown_disposition::{ResolvedDisposition, ShutdownDisposition}; use crate::supervisor_owner::{OWNER_TTL, SupervisorOwnerIndex}; use crate::supervisor_session::SupervisorSessionRegistry; use crate::tracing_bus::TracingLogBus; @@ -2706,8 +2707,57 @@ impl ComputeRuntime { } } - pub async fn cleanup_on_shutdown(&self) -> Result<(), String> { - let stop_result = self.stop_persisted_sandboxes_on_shutdown().await; + /// Run graceful-shutdown compute cleanup. + /// + /// `disposition` selects only whether the sandbox stop sweep runs. The + /// managed driver process is shut down in both modes, and one bounded + /// `CK_gateway_shutdown_disposition` receipt records the mode and the + /// number of running-intent sandboxes left for the next gateway. + pub async fn cleanup_on_shutdown( + &self, + disposition: ResolvedDisposition, + ) -> Result<(), String> { + let stop_result = match disposition.mode { + ShutdownDisposition::StopRunningSandboxes => { + let result = self.stop_persisted_sandboxes_on_shutdown().await; + info!( + code = "CK_gateway_shutdown_disposition", + mode = disposition.mode.as_str(), + source = disposition.source.as_str(), + retained = 0usize, + sweep_ok = result.is_ok(), + "Gateway shutdown stopped running sandboxes" + ); + result + } + ShutdownDisposition::RetainRunningSandboxes => { + match self.count_running_intent_sandboxes().await { + Ok(retained) => { + info!( + code = "CK_gateway_shutdown_disposition", + mode = disposition.mode.as_str(), + source = disposition.source.as_str(), + retained, + "Gateway shutdown retained running sandboxes for re-adoption" + ); + Ok(()) + } + // Counting is for the receipt only; retain never stops a + // sandbox, so a store error does not fail shutdown. + Err(err) => { + warn!( + code = "CK_gateway_shutdown_disposition", + mode = disposition.mode.as_str(), + source = disposition.source.as_str(), + retained = "unknown", + error = %err, + "Gateway shutdown retained running sandboxes; count unavailable" + ); + Ok(()) + } + } + } + }; #[cfg(unix)] let process_result = if let Some(process) = &self.driver_process { @@ -2729,6 +2779,25 @@ impl ComputeRuntime { } } + /// Count persisted sandboxes whose phase carries running intent, the + /// set the stop sweep would have stopped. + async fn count_running_intent_sandboxes(&self) -> Result { + let records = self + .store + .collect_records(Sandbox::object_type(), ObjectListQuery::AllWorkspaces) + .await + .map_err(|err| format!("failed to list sandboxes for gateway shutdown: {err}"))?; + Ok(records + .iter() + .filter_map(|record| Sandbox::decode(record.payload.as_slice()).ok()) + .filter(|sandbox| { + sandbox_phase_should_be_running( + SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown), + ) + }) + .count()) + } + /// Stop local compute during graceful gateway shutdown without changing /// persisted lifecycle intent. /// @@ -12657,6 +12726,127 @@ mod tests { ); } + async fn runtime_with_running_and_stopped_sandboxes( + driver: Arc, + ) -> ComputeRuntime { + let runtime = + test_runtime_with_gateway_managed_lifecycle(driver.clone(), "arbitrary").await; + for (id, name, phase) in [ + ("sb-ready", "ready", SandboxPhase::Ready), + ("sb-prov", "prov", SandboxPhase::Provisioning), + ("sb-stopped", "stopped", SandboxPhase::Stopped), + ] { + runtime + .store + .put_message(&sandbox_record(id, name, phase)) + .await + .unwrap(); + } + runtime + } + + fn disposition(value: Option<&str>) -> ResolvedDisposition { + crate::shutdown_disposition::ShutdownDispositionConfig { + value: value.map(str::to_owned), + file: None, + } + .resolve() + } + + fn sorted_stop_ids(driver: &ControlledDriver) -> Vec { + let mut ids = driver + .stop_requests() + .into_iter() + .map(|(id, _)| id) + .collect::>(); + ids.sort(); + ids + } + + #[tokio::test] + async fn cleanup_on_shutdown_default_disposition_runs_stop_sweep() { + let driver = ControlledDriver::new(); + let runtime = runtime_with_running_and_stopped_sandboxes(driver.clone()).await; + + runtime + .cleanup_on_shutdown(disposition(None)) + .await + .unwrap(); + + assert_eq!( + sorted_stop_ids(&driver), + vec!["sb-prov".to_string(), "sb-ready".to_string()], + "an unset disposition must keep the historical stop sweep" + ); + } + + #[tokio::test] + async fn cleanup_on_shutdown_unknown_disposition_runs_stop_sweep() { + for raw in ["", "retain", "skip-cleanup", "Retain-Running-Sandboxes"] { + let driver = ControlledDriver::new(); + let runtime = runtime_with_running_and_stopped_sandboxes(driver.clone()).await; + + runtime + .cleanup_on_shutdown(disposition(Some(raw))) + .await + .unwrap(); + + assert_eq!( + sorted_stop_ids(&driver), + vec!["sb-prov".to_string(), "sb-ready".to_string()], + "unknown disposition {raw:?} must select the stop sweep" + ); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn cleanup_on_shutdown_retain_skips_only_the_stop_sweep() { + let driver = ControlledDriver::new(); + let mut runtime = runtime_with_running_and_stopped_sandboxes(driver.clone()).await; + + // A managed driver process must still be shut down in retain mode. + let dir = tempfile::tempdir().unwrap(); + let child = tokio::process::Command::new("sleep") + .arg("30") + .kill_on_drop(true) + .spawn() + .unwrap(); + let pid = child.id().unwrap(); + runtime.driver_process = Some(Arc::new(ManagedDriverProcess::new( + child, + dir.path().join("driver.sock"), + ))); + + runtime + .cleanup_on_shutdown(disposition(Some("retain-running-sandboxes"))) + .await + .unwrap(); + + assert_eq!(driver.stop_calls(), 0, "retain must not stop any sandbox"); + for (id, phase) in [ + ("sb-ready", SandboxPhase::Ready), + ("sb-prov", SandboxPhase::Provisioning), + ] { + let stored = runtime + .store + .get_message::(id) + .await + .unwrap() + .unwrap(); + assert_eq!( + SandboxPhase::try_from(stored.phase()).unwrap(), + phase, + "retain must keep running intent for {id}" + ); + } + assert!( + nix::sys::signal::kill(nix::unistd::Pid::from_raw(pid.cast_signed()), None).is_err(), + "retain must still shut down the managed driver process" + ); + assert_eq!(runtime.count_running_intent_sandboxes().await.unwrap(), 2); + } + #[tokio::test] async fn shutdown_stop_sweep_continues_after_driver_errors() { let driver = ControlledDriver::new(); diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index cd4b20cd83..0c4ff4331c 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -36,6 +36,7 @@ mod readiness; mod sandbox_index; mod sandbox_watch; mod service_routing; +pub(crate) mod shutdown_disposition; mod ssh_sessions; mod storage_proto; mod supervisor_owner; @@ -253,6 +254,7 @@ pub(crate) struct ServerStartupConfig { pub guest_tls: Option, pub compute_driver: ComputeDriverSelection, pub legacy_compute_driver_env_seen: bool, + pub shutdown_disposition: shutdown_disposition::ShutdownDispositionConfig, } /// Server state shared across handlers. @@ -531,6 +533,7 @@ pub(crate) async fn run_server( guest_tls, compute_driver, legacy_compute_driver_env_seen: _, + shutdown_disposition, } = startup; let (shutdown_tx, shutdown_rx) = watch::channel(false); @@ -1041,9 +1044,21 @@ pub(crate) async fn run_server( warn!(error = %err, "Gateway listener task failed during shutdown"); } + // Resolve after the signal so a disposition file carries the host's + // choice for this shutdown. Anything but an exact known value sweeps. + let disposition = shutdown_disposition.resolve(); + if let Some(fallback) = disposition.fallback { + warn!( + code = "CK_gateway_shutdown_disposition_fallback", + source = disposition.source.as_str(), + reason = fallback.as_str(), + mode = disposition.mode.as_str(), + "Shutdown disposition unusable; stopping running sandboxes" + ); + } state .compute - .cleanup_on_shutdown() + .cleanup_on_shutdown(disposition) .await .map_err(|err| Error::execution(format!("gateway shutdown cleanup failed: {err}")))?; diff --git a/crates/openshell-server/src/shutdown_disposition.rs b/crates/openshell-server/src/shutdown_disposition.rs new file mode 100644 index 0000000000..fd8ed7381f --- /dev/null +++ b/crates/openshell-server/src/shutdown_disposition.rs @@ -0,0 +1,302 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! What a graceful gateway shutdown does with running sandboxes. +//! +//! The default, [`ShutdownDisposition::StopRunningSandboxes`], is the +//! historical behaviour: the gateway sends a driver stop to every persisted +//! sandbox with running intent before it exits. An embedded host that +//! restarts its gateway can instead select +//! [`ShutdownDisposition::RetainRunningSandboxes`], so the next gateway can +//! re-adopt the live sandboxes. Retain skips only that stop sweep; listener +//! shutdown, the managed driver process and every other cleanup still run. +//! +//! The disposition is separate from the driver's `gateway_manages_lifecycle` +//! capability, which also gates startup reconciliation and must stay on for +//! re-adoption to work. +//! +//! Two sources select it: +//! +//! - a static value (`--shutdown-disposition`, +//! `OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION`), and +//! - a disposition file (`--shutdown-disposition-file`, +//! `OPENSHELL_GATEWAY_SHUTDOWN_DISPOSITION_FILE`) read when the shutdown +//! signal arrives, so a host can pick the mode per shutdown. When a file is +//! configured it is the only source. +//! +//! Anything other than an exact, known value selects the stop sweep: an +//! unset value, an unknown value, a missing, unreadable or oversized file. + +use std::io::Read; +use std::path::{Path, PathBuf}; + +/// Largest disposition file the gateway reads. Valid values are short tokens. +const MAX_DISPOSITION_FILE_BYTES: u64 = 64; + +/// What graceful shutdown does with sandboxes that have running intent. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum ShutdownDisposition { + /// Stop every persisted sandbox with running intent (the default). + #[default] + StopRunningSandboxes, + /// Leave running sandboxes in place for the next gateway to re-adopt. + RetainRunningSandboxes, +} + +impl ShutdownDisposition { + pub const STOP: &'static str = "stop-running-sandboxes"; + pub const RETAIN: &'static str = "retain-running-sandboxes"; + + /// Parse an exact disposition token. Surrounding whitespace is ignored; + /// anything else, including case variants, is unknown. + pub fn parse(raw: &str) -> Option { + match raw.trim() { + Self::STOP => Some(Self::StopRunningSandboxes), + Self::RETAIN => Some(Self::RetainRunningSandboxes), + _ => None, + } + } + + pub const fn as_str(self) -> &'static str { + match self { + Self::StopRunningSandboxes => Self::STOP, + Self::RetainRunningSandboxes => Self::RETAIN, + } + } +} + +/// Where a resolved disposition came from, for the shutdown receipt. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DispositionSource { + /// Nothing was configured. + Default, + /// The static flag or environment value. + Static, + /// The disposition file. + File, +} + +impl DispositionSource { + pub const fn as_str(self) -> &'static str { + match self { + Self::Default => "default", + Self::Static => "static", + Self::File => "file", + } + } +} + +/// Why a configured source fell back to the stop sweep. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DispositionFallback { + Unknown, + Missing, + Unreadable, + Oversized, +} + +impl DispositionFallback { + pub const fn as_str(self) -> &'static str { + match self { + Self::Unknown => "unknown", + Self::Missing => "missing", + Self::Unreadable => "unreadable", + Self::Oversized => "oversized", + } + } +} + +/// A disposition with its provenance. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResolvedDisposition { + pub mode: ShutdownDisposition, + pub source: DispositionSource, + /// Set when a configured source could not be used and the stop sweep was + /// selected instead. + pub fallback: Option, +} + +/// Configured disposition sources. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ShutdownDispositionConfig { + pub value: Option, + pub file: Option, +} + +impl ShutdownDispositionConfig { + /// Resolve the disposition now. Call when the shutdown signal arrives so + /// a disposition file reflects the host's latest choice. + pub fn resolve(&self) -> ResolvedDisposition { + if let Some(path) = &self.file { + return match read_disposition_file(path) { + Ok(raw) => from_token(&raw, DispositionSource::File), + Err(fallback) => stop(DispositionSource::File, Some(fallback)), + }; + } + self.value.as_deref().map_or_else( + || stop(DispositionSource::Default, None), + |raw| from_token(raw, DispositionSource::Static), + ) + } +} + +const fn stop( + source: DispositionSource, + fallback: Option, +) -> ResolvedDisposition { + ResolvedDisposition { + mode: ShutdownDisposition::StopRunningSandboxes, + source, + fallback, + } +} + +fn from_token(raw: &str, source: DispositionSource) -> ResolvedDisposition { + ShutdownDisposition::parse(raw).map_or_else( + || stop(source, Some(DispositionFallback::Unknown)), + |mode| ResolvedDisposition { + mode, + source, + fallback: None, + }, + ) +} + +fn read_disposition_file(path: &Path) -> Result { + let file = std::fs::File::open(path).map_err(|err| { + if err.kind() == std::io::ErrorKind::NotFound { + DispositionFallback::Missing + } else { + DispositionFallback::Unreadable + } + })?; + let mut bytes = Vec::new(); + file.take(MAX_DISPOSITION_FILE_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|_| DispositionFallback::Unreadable)?; + if bytes.len() as u64 > MAX_DISPOSITION_FILE_BYTES { + return Err(DispositionFallback::Oversized); + } + String::from_utf8(bytes).map_err(|_| DispositionFallback::Unknown) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(value: Option<&str>, file: Option) -> ShutdownDispositionConfig { + ShutdownDispositionConfig { + value: value.map(str::to_owned), + file, + } + } + + #[test] + fn missing_disposition_defaults_to_stop_sweep() { + assert_eq!( + config(None, None).resolve(), + ResolvedDisposition { + mode: ShutdownDisposition::StopRunningSandboxes, + source: DispositionSource::Default, + fallback: None, + } + ); + } + + #[test] + fn known_static_values_parse_exactly() { + assert_eq!( + config(Some("retain-running-sandboxes"), None) + .resolve() + .mode, + ShutdownDisposition::RetainRunningSandboxes + ); + assert_eq!( + config(Some(" stop-running-sandboxes\n"), None) + .resolve() + .mode, + ShutdownDisposition::StopRunningSandboxes + ); + } + + #[test] + fn unknown_static_value_defaults_to_stop_sweep() { + for raw in [ + "", + "retain", + "RETAIN-RUNNING-SANDBOXES", + "skip-cleanup", + "retain-running-sandboxes,extra", + ] { + assert_eq!( + config(Some(raw), None).resolve(), + ResolvedDisposition { + mode: ShutdownDisposition::StopRunningSandboxes, + source: DispositionSource::Static, + fallback: Some(DispositionFallback::Unknown), + }, + "{raw:?} must select the stop sweep" + ); + } + } + + #[test] + fn disposition_file_is_read_at_resolve_time() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("disposition"); + let cfg = config(Some("retain-running-sandboxes"), Some(path.clone())); + + let missing = cfg.resolve(); + assert_eq!( + missing, + ResolvedDisposition { + mode: ShutdownDisposition::StopRunningSandboxes, + source: DispositionSource::File, + fallback: Some(DispositionFallback::Missing), + }, + "a configured but missing file must not fall back to the static value" + ); + + std::fs::write(&path, "retain-running-sandboxes\n").unwrap(); + assert_eq!( + cfg.resolve(), + ResolvedDisposition { + mode: ShutdownDisposition::RetainRunningSandboxes, + source: DispositionSource::File, + fallback: None, + } + ); + + std::fs::write(&path, "stop-running-sandboxes").unwrap(); + assert_eq!( + cfg.resolve().mode, + ShutdownDisposition::StopRunningSandboxes + ); + } + + #[test] + fn unknown_or_oversized_disposition_file_defaults_to_stop_sweep() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("disposition"); + let cfg = config(None, Some(path.clone())); + + std::fs::write(&path, "keep-everything").unwrap(); + assert_eq!(cfg.resolve().fallback, Some(DispositionFallback::Unknown)); + + std::fs::write(&path, [0xff, 0xfe]).unwrap(); + assert_eq!(cfg.resolve().fallback, Some(DispositionFallback::Unknown)); + + let mut oversized = "retain-running-sandboxes".to_string(); + oversized.push_str(&" ".repeat(64)); + std::fs::write(&path, oversized).unwrap(); + let resolved = cfg.resolve(); + assert_eq!(resolved.mode, ShutdownDisposition::StopRunningSandboxes); + assert_eq!(resolved.fallback, Some(DispositionFallback::Oversized)); + + assert_eq!( + config(None, Some(dir.path().to_path_buf())).resolve().mode, + ShutdownDisposition::StopRunningSandboxes, + "a directory is not a disposition file" + ); + } +} diff --git a/e2e/rust/src/harness/gateway.rs b/e2e/rust/src/harness/gateway.rs index 8400371b3a..f4e74a8171 100644 --- a/e2e/rust/src/harness/gateway.rs +++ b/e2e/rust/src/harness/gateway.rs @@ -58,6 +58,12 @@ impl ManagedGateway { /// Start the gateway if it is not already running. pub fn start(&self) -> Result<(), String> { + self.start_with_args(&[]) + } + + /// Start the gateway with `extra` appended to the wrapper's arguments, if + /// it is not already running. A later [`Self::start`] drops them again. + pub fn start_with_args(&self, extra: &[&str]) -> Result<(), String> { if let Some(pid) = self.current_pid()? { if process_running(pid)? { return Ok(()); @@ -65,7 +71,8 @@ impl ManagedGateway { let _ = fs::remove_file(&self.pid_file); } - let args = self.gateway_args()?; + let mut args = self.gateway_args()?; + args.extend(extra.iter().map(|arg| (*arg).to_string())); let mut log = OpenOptions::new() .create(true) .append(true) @@ -122,6 +129,40 @@ impl ManagedGateway { Ok(()) } + /// Send `SIGTERM` and wait for the gateway's graceful shutdown to finish. + /// + /// Unlike [`Self::stop`], this never escalates to `SIGKILL`: a gateway + /// that does not exit within `timeout` is an error, so callers can rely + /// on graceful shutdown cleanup having run. Only the PID recorded by this + /// e2e run is signalled. + pub fn terminate(&self, timeout: Duration) -> Result<(), String> { + let Some(pid) = self.current_pid()? else { + return Err("gateway is not running".to_string()); + }; + if !process_running(pid)? { + let _ = fs::remove_file(&self.pid_file); + return Err(format!("gateway process {pid} already exited")); + } + send_signal(pid, None)?; + let deadline = std::time::Instant::now() + timeout; + while std::time::Instant::now() < deadline { + if !process_running(pid)? { + let _ = fs::remove_file(&self.pid_file); + return Ok(()); + } + thread::sleep(Duration::from_millis(250)); + } + Err(format!( + "gateway process {pid} did not exit within {}s of SIGTERM", + timeout.as_secs() + )) + } + + /// The gateway log shared by every start in this e2e run. + pub fn log_path(&self) -> &std::path::Path { + &self.log + } + /// Kill the gateway with `SIGKILL`, skipping graceful shutdown. /// /// This models an embedded gateway whose host process dies: running diff --git a/e2e/rust/tests/docker_gateway_restart_readopt.rs b/e2e/rust/tests/docker_gateway_restart_readopt.rs index 67ccb71aff..a7ef1c59cc 100644 --- a/e2e/rust/tests/docker_gateway_restart_readopt.rs +++ b/e2e/rust/tests/docker_gateway_restart_readopt.rs @@ -4,7 +4,8 @@ #![cfg(feature = "e2e")] //! E2E coverage for re-adopting a live Docker sandbox across repeated -//! ungraceful gateway restarts. +//! ungraceful gateway restarts, and across a graceful restart whose shutdown +//! disposition retains running sandboxes. //! //! An embedded gateway can die without running its graceful shutdown sweep, //! so the sandbox container keeps running. The next gateway start removes the @@ -25,8 +26,12 @@ use openshell_e2e::harness::cli::{ use openshell_e2e::harness::gateway::ManagedGateway; use openshell_e2e::harness::output::strip_ansi; use openshell_e2e::harness::sandbox::SandboxGuard; +use tokio::sync::Mutex; use tokio::time::sleep; +/// Both tests restart the one wrapper-owned gateway, so they run one at a time. +static GATEWAY_RESTARTS: Mutex<()> = Mutex::const_new(()); + const READY_MARKER: &str = "gateway-readopt-ready"; const STATE_FILE: &str = "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/sandbox/gateway-readopt-state"; const RESTARTS: usize = 3; @@ -270,6 +275,7 @@ async fn sandbox_phase(sandbox_name: &str) -> String { #[tokio::test] #[allow(clippy::too_many_lines)] async fn docker_gateway_restarts_readopt_live_sandbox() { + let _restarts = GATEWAY_RESTARTS.lock().await; let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") else { eprintln!("Skipping gateway re-adopt test: e2e gateway is not managed by this test run"); @@ -437,3 +443,244 @@ async fn docker_gateway_restarts_readopt_live_sandbox() { "sandbox delete should remove its volumes, found {leftovers:?}" ); } + +const RETAIN: &str = "retain-running-sandboxes"; +const RETAIN_MARKER: &str = "gateway-retain-ready"; +const RETAIN_STATE_FILE: &str = "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/sandbox/gateway-retain-state"; + +/// The gateway log lines carrying the shutdown disposition receipt. +fn disposition_receipts(gateway: &ManagedGateway) -> Vec { + std::fs::read_to_string(gateway.log_path()) + .unwrap_or_default() + .lines() + .filter(|line| line.contains("CK_gateway_shutdown_disposition")) + .map(strip_ansi) + .collect() +} + +async fn wait_until_not_running(container_id: &str, timeout: Duration) -> Result<(), String> { + let deadline = Instant::now() + timeout; + let mut last = String::new(); + while Instant::now() < deadline { + match container_state(container_id) { + Ok(state) if !state.running => return Ok(()), + Ok(state) => last = format!("{state:?}"), + Err(err) => return Err(err), + } + sleep(Duration::from_millis(500)).await; + } + Err(format!( + "container {container_id} still running after {}s: {last}", + timeout.as_secs() + )) +} + +/// A graceful `SIGTERM` with the retain disposition leaves the sandbox +/// running with its running intent, and the next gateway re-adopts it through +/// a supervisor generation handover. The disposition is selected through a +/// disposition file, read at shutdown: once the file is removed, the next +/// graceful shutdown of the same gateway falls back to the stop sweep. +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn docker_gateway_graceful_retain_restart_readopts_live_sandbox() { + let _restarts = GATEWAY_RESTARTS.lock().await; + let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") + else { + eprintln!("Skipping graceful retain test: e2e gateway is not managed by this test run"); + return; + }; + let Some(namespace) = std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") + .ok() + .filter(|value| !value.trim().is_empty()) + else { + eprintln!("Skipping graceful retain test: Docker e2e sandbox namespace is unavailable"); + return; + }; + + let disposition_dir = tempfile::tempdir().expect("disposition dir"); + let disposition_file = disposition_dir.path().join("shutdown-disposition"); + std::fs::write(&disposition_file, format!("{RETAIN}\n")).expect("write disposition"); + let disposition_path = disposition_file + .to_str() + .expect("utf-8 disposition path") + .to_string(); + let retain_args = ["--shutdown-disposition-file", disposition_path.as_str()]; + + // Relaunch the wrapper's gateway with the disposition file. No sandbox + // of this test exists yet, so the default sweep of this stop is moot. + gateway.stop().expect("stop wrapper gateway"); + gateway + .start_with_args(&retain_args) + .expect("start gateway with disposition file"); + wait_for_healthy(Duration::from_secs(120)) + .await + .expect("gateway with disposition file should start healthy"); + + let script = format!( + "echo before-retain > {RETAIN_STATE_FILE}; echo {RETAIN_MARKER}; while true; do sleep 1; done" + ); + let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], RETAIN_MARKER) + .await + .expect("create long-running sandbox"); + wait_for_sandbox_phase(&sandbox.name, "Ready", Duration::from_secs(120)) + .await + .expect("sandbox should be Ready before the graceful restart"); + let container_id = + single_container(&namespace, &sandbox.name, "sandbox").expect("sandbox container"); + let sandbox_id = sandbox_id_label(&container_id).expect("sandbox id label"); + let initial_state = container_state(&container_id).expect("sandbox container state"); + assert!(initial_state.running, "sandbox container should be running"); + let initial_volumes = sandbox_volumes(&sandbox_id).expect("list sandbox volumes"); + let supervisor_id = + wait_for_healthy_supervisor(&namespace, &sandbox.name, Duration::from_secs(60)) + .await + .expect("initial supervisor should be healthy"); + wait_for_sandbox_exec_contains( + &sandbox.name, + &["cat", RETAIN_STATE_FILE], + "before-retain", + Duration::from_secs(120), + ) + .await + .expect("sandbox exec should work before the graceful restart"); + + // Graceful SIGTERM in retain mode. + let receipts_before = disposition_receipts(&gateway).len(); + gateway + .terminate(Duration::from_secs(60)) + .expect("gateway should exit gracefully on SIGTERM"); + let receipts = disposition_receipts(&gateway); + let receipt = receipts + .get(receipts_before..) + .and_then(<[String]>::last) + .cloned() + .unwrap_or_else(|| panic!("no shutdown disposition receipt; receipts: {receipts:?}")); + eprintln!("gateway retain: shutdown receipt: {receipt}"); + assert!( + receipt.contains(RETAIN) && receipt.contains("retained=1") && receipt.contains("file"), + "retain receipt must carry the mode, source and retained count: {receipt}" + ); + sleep(Duration::from_secs(3)).await; + let state = container_state(&container_id).expect("sandbox state after graceful exit"); + assert!( + state.running, + "graceful retain shutdown must leave the sandbox running" + ); + assert_eq!( + (state.started_at.as_str(), state.restart_count.as_str()), + ( + initial_state.started_at.as_str(), + initial_state.restart_count.as_str() + ), + "graceful retain shutdown must not restart the sandbox workload" + ); + + // The next gateway re-adopts the sandbox. + gateway + .start_with_args(&retain_args) + .expect("restart gateway after graceful retain"); + wait_for_healthy(Duration::from_secs(120)) + .await + .expect("gateway should be healthy after graceful retain restart"); + let replacement = + wait_for_healthy_supervisor(&namespace, &sandbox.name, Duration::from_secs(120)) + .await + .unwrap_or_else(|err| { + panic!( + "{err}\nboundary log:\n{}", + boundary_log_summary(&container_id) + ) + }); + assert_ne!( + replacement, supervisor_id, + "gateway startup should replace the stale supervisor sidecar" + ); + if let Err(err) = wait_for_sandbox_phase(&sandbox.name, "Ready", Duration::from_secs(120)).await + { + panic!( + "sandbox did not return to Ready after graceful retain (phase {}): {err}\nboundary log:\n{}", + sandbox_phase(&sandbox.name).await, + boundary_log_summary(&container_id) + ); + } + wait_for_sandbox_exec_contains( + &sandbox.name, + &["cat", RETAIN_STATE_FILE], + "before-retain", + Duration::from_secs(120), + ) + .await + .unwrap_or_else(|err| { + panic!( + "sandbox exec failed after graceful retain: {err}\nboundary log:\n{}", + boundary_log_summary(&container_id) + ) + }); + assert_eq!( + single_container(&namespace, &sandbox.name, "sandbox").expect("sandbox container"), + container_id, + "the same sandbox container must be retained" + ); + assert_eq!( + sandbox_field(&sandbox.name, "id").await, + sandbox_id, + "the gateway must re-adopt the same sandbox id" + ); + let state = container_state(&container_id).expect("sandbox state after re-adopt"); + assert_eq!( + ( + state.running, + state.started_at.as_str(), + state.restart_count.as_str() + ), + ( + true, + initial_state.started_at.as_str(), + initial_state.restart_count.as_str() + ), + "re-adoption after graceful retain must not restart the sandbox workload" + ); + assert_eq!( + sandbox_volumes(&sandbox_id).expect("list sandbox volumes"), + initial_volumes, + "sandbox volumes must be retained" + ); + let handover = handover_log_line(&container_id, 2).unwrap_or_else(|err| panic!("{err}")); + eprintln!("gateway retain: boundary log: {handover}"); + + // A missing disposition file selects the stop sweep on the same gateway. + std::fs::remove_file(&disposition_file).expect("remove disposition file"); + let receipts_before = disposition_receipts(&gateway).len(); + gateway + .terminate(Duration::from_secs(90)) + .expect("gateway should exit gracefully on SIGTERM"); + let receipts = disposition_receipts(&gateway); + let receipt = receipts + .get(receipts_before..) + .and_then(<[String]>::last) + .cloned() + .unwrap_or_else(|| panic!("no sweep receipt; receipts: {receipts:?}")); + eprintln!("gateway retain: fallback receipt: {receipt}"); + assert!( + receipt.contains("stop-running-sandboxes"), + "a missing disposition file must select the stop sweep: {receipt}" + ); + wait_until_not_running(&container_id, Duration::from_secs(60)) + .await + .expect("the stop sweep should stop the sandbox container"); + + // Back to the wrapper's own arguments for cleanup and later tests. + gateway.start().expect("restart wrapper gateway"); + wait_for_healthy(Duration::from_secs(120)) + .await + .expect("wrapper gateway should be healthy"); + sandbox.cleanup().await; + let leftovers = sandbox_volumes(&sandbox_id).unwrap_or_default(); + for volume in &leftovers { + let _ = docker(&["volume", "rm", "-f", volume]); + } + assert!( + leftovers.is_empty(), + "sandbox delete should remove its volumes, found {leftovers:?}" + ); +}