Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions crates/openshell-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,22 @@ struct RunArgs {
#[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")]
compute_driver_socket: Option<PathBuf>,

/// 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<String>,

/// 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<PathBuf>,

/// 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.
Expand Down Expand Up @@ -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(),
},
})
}

Expand Down Expand Up @@ -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
Expand Down
194 changes: 192 additions & 2 deletions crates/openshell-server/src/compute/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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<usize, String> {
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.
///
Expand Down Expand Up @@ -12657,6 +12726,127 @@ mod tests {
);
}

async fn runtime_with_running_and_stopped_sandboxes(
driver: Arc<ControlledDriver>,
) -> 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<String> {
let mut ids = driver
.stop_requests()
.into_iter()
.map(|(id, _)| id)
.collect::<Vec<_>>();
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::<Sandbox>(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();
Expand Down
17 changes: 16 additions & 1 deletion crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -253,6 +254,7 @@ pub(crate) struct ServerStartupConfig {
pub guest_tls: Option<compute::driver_config::GuestTlsPaths>,
pub compute_driver: ComputeDriverSelection,
pub legacy_compute_driver_env_seen: bool,
pub shutdown_disposition: shutdown_disposition::ShutdownDispositionConfig,
}

/// Server state shared across handlers.
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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}")))?;

Expand Down
Loading