diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 76f534c88f..150a95494d 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -232,6 +232,17 @@ pub struct Config { /// the limit. pub grpc_rate_limit_window_secs: Option, + /// How long graceful shutdown waits for in-flight exec streams, in seconds. + /// + /// An exec rides the supervisor session this replica holds, so it cannot + /// move to another replica: once the process exits, the exec fails. While + /// draining, the gateway refuses new execs the way a replica without the + /// session does, so callers route them elsewhere, and exits as soon as the + /// last in-flight exec finishes or this deadline passes. `0` exits without + /// waiting. Keep it below the pod's termination grace period, or the + /// kubelet kills the process before it releases its liveness records. + pub shutdown_drain_secs: u64, + /// Browser-facing sandbox service routing configuration. pub service_routing: ServiceRoutingConfig, } @@ -576,6 +587,7 @@ impl Config { ssh_session_ttl_secs: default_ssh_session_ttl_secs(), grpc_rate_limit_requests: None, grpc_rate_limit_window_secs: None, + shutdown_drain_secs: 0, service_routing: ServiceRoutingConfig::default(), } } @@ -683,6 +695,13 @@ impl Config { self } + /// Set how long graceful shutdown waits for in-flight exec streams. + #[must_use] + pub const fn with_shutdown_drain_secs(mut self, secs: u64) -> Self { + self.shutdown_drain_secs = secs; + self + } + /// Set configured gateway interceptors. #[must_use] pub fn with_gateway_interceptors(mut self, interceptors: I) -> Self diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index b8b7dfd071..d44402dfb7 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -199,6 +199,11 @@ struct RunArgs { #[arg(long, env = "OPENSHELL_GRPC_RATE_LIMIT_WINDOW_SECONDS")] grpc_rate_limit_window_seconds: Option, + /// Seconds graceful shutdown waits for in-flight exec streams before + /// exiting. 0 exits without waiting. + #[arg(long, env = "OPENSHELL_SHUTDOWN_DRAIN_SECONDS", default_value_t = 0)] + shutdown_drain_seconds: u64, + /// Subject Alternative Names configured on the gateway server certificate. /// Wildcard DNS SANs also enable sandbox service URLs under that domain. #[arg( @@ -412,6 +417,7 @@ fn prepare_server_config_with_drivers( args.grpc_rate_limit_requests, args.grpc_rate_limit_window_seconds, ) + .with_shutdown_drain_secs(args.shutdown_drain_seconds) .with_gateway_interceptors( file.as_ref() .map(|f| f.openshell.gateway.interceptors.clone()) diff --git a/crates/openshell-server/src/exec_drain.rs b/crates/openshell-server/src/exec_drain.rs new file mode 100644 index 0000000000..a4df1c55ad --- /dev/null +++ b/crates/openshell-server/src/exec_drain.rs @@ -0,0 +1,115 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! In-flight exec streams, counted so graceful shutdown can wait for them. +//! +//! An exec is relayed over the supervisor session this replica holds, so it +//! cannot fail over: when the process exits, every exec it is relaying fails +//! partway through, after the command may already have had side effects. The +//! connection tasks serving those streams are detached, so nothing else keeps +//! the process alive for them. +//! +//! A handler takes its guard *before* it asks the session registry for a +//! relay. Shutdown starts draining the registry first and waits here second, +//! so every exec is either refused by the registry or counted here — there is +//! no order of the two steps in which one is admitted and not waited for. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use tokio::sync::Notify; + +/// Counter of exec streams in flight on this replica. +#[derive(Debug, Default)] +pub struct ExecDrain { + in_flight: AtomicUsize, + idle: Notify, +} + +/// Held for the life of one exec stream; releases its count on drop. +#[derive(Debug)] +pub struct ExecGuard { + drain: Arc, +} + +impl ExecDrain { + /// Count one exec until the returned guard is dropped. + pub fn track(self: &Arc) -> ExecGuard { + self.in_flight.fetch_add(1, Ordering::SeqCst); + ExecGuard { + drain: Arc::clone(self), + } + } + + pub fn in_flight(&self) -> usize { + self.in_flight.load(Ordering::SeqCst) + } + + /// Wait until no exec is in flight, or `timeout` passes. + /// + /// Returns whether the count reached zero. + pub async fn wait_idle(&self, timeout: Duration) -> bool { + tokio::time::timeout(timeout, async { + loop { + // Registered before the count is read, so a guard dropped + // between the read and the await still wakes this loop. + let notified = self.idle.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + if self.in_flight() == 0 { + return; + } + notified.await; + } + }) + .await + .is_ok() + } +} + +impl Drop for ExecGuard { + fn drop(&mut self) { + if self.drain.in_flight.fetch_sub(1, Ordering::SeqCst) == 1 { + self.drain.idle.notify_waiters(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn wait_idle_returns_at_once_with_nothing_in_flight() { + let drain = Arc::new(ExecDrain::default()); + assert!(drain.wait_idle(Duration::ZERO).await); + } + + #[tokio::test] + async fn wait_idle_returns_when_the_last_exec_finishes() { + let drain = Arc::new(ExecDrain::default()); + let first = drain.track(); + let second = drain.track(); + assert_eq!(drain.in_flight(), 2); + + let waiter = { + let drain = Arc::clone(&drain); + tokio::spawn(async move { drain.wait_idle(Duration::from_secs(5)).await }) + }; + drop(first); + tokio::task::yield_now().await; + assert!(!waiter.is_finished()); + + drop(second); + assert!(waiter.await.unwrap()); + assert_eq!(drain.in_flight(), 0); + } + + #[tokio::test] + async fn wait_idle_gives_up_at_the_deadline() { + let drain = Arc::new(ExecDrain::default()); + let _held = drain.track(); + assert!(!drain.wait_idle(Duration::from_millis(20)).await); + assert_eq!(drain.in_flight(), 1); + } +} diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 3d32aa7d00..49127e692b 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -1786,6 +1786,10 @@ pub(super) async fn handle_exec_sandbox( return Err(refusal); } + // Taken before the relay is opened, so graceful shutdown either refuses + // this exec or waits for it. See `crate::exec_drain`. + let in_flight = state.exec_drain.track(); + // Answers immediately when this replica holds no session: it cannot say // anything about the other replicas, so the caller decides whether to ask // one of them, and how long to keep asking. @@ -1813,6 +1817,7 @@ pub(super) async fn handle_exec_sandbox( let (tx, rx) = mpsc::channel::>(256); tokio::spawn(async move { + let _in_flight = in_flight; if let Err(err) = stream_exec_over_relay( tx.clone(), &sandbox_id, @@ -2318,6 +2323,10 @@ pub(super) async fn handle_exec_sandbox_interactive( return Err(refusal); } + // Taken before the relay is opened, so graceful shutdown either refuses + // this exec or waits for it. See `crate::exec_drain`. + let in_flight = state.exec_drain.track(); + let (channel_id, relay_rx) = state .supervisor_sessions .open_relay(sandbox.object_id()) @@ -2341,6 +2350,7 @@ pub(super) async fn handle_exec_sandbox_interactive( let (tx, rx) = mpsc::channel::>(256); tokio::spawn(async move { + let _in_flight = in_flight; if let Err(err) = stream_interactive_exec_over_relay( tx.clone(), &sandbox_id, diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 3eefed25a8..2879b5926e 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -20,6 +20,7 @@ mod compute; pub mod config_file; mod credentials; mod defaults; +mod exec_drain; mod gateway_listener; mod grpc; mod http; @@ -302,6 +303,9 @@ pub struct ServerState { /// distinguish expected transport closes from runtime failures. pub(crate) gateway_shutting_down: AtomicBool, + /// Exec streams in flight, which graceful shutdown waits for. + pub(crate) exec_drain: Arc, + /// Validated built-in and operator-registered supervisor middleware. pub middleware_registry: Arc, @@ -418,6 +422,7 @@ impl ServerState { settings_mutex: tokio::sync::Mutex::new(()), supervisor_sessions, gateway_shutting_down: AtomicBool::new(false), + exec_drain: Arc::default(), extension_mint_limiter: auth::extension_mint_limit::ExtensionMintLimiter::default(), middleware_registry: Arc::new(MiddlewareRegistry::default()), oidc_cache, @@ -817,6 +822,9 @@ pub(crate) async fn run_server( shutdown_signal().await; info!("Shutdown signal received; stopping gateway"); state.gateway_shutting_down.store(true, Ordering::Release); + // Before anything else, so no exec is admitted that the drain below does + // not wait for. See `exec_drain`. + state.supervisor_sessions.begin_drain(); let _ = shutdown_tx.send(true); for task in listener_tasks { @@ -854,6 +862,16 @@ pub(crate) async fn run_server( ); } + // Wait for the execs this replica is relaying. They ride connections the + // listeners already accepted, which keep serving until the process exits, + // and they cannot move to another replica. Waiting only after the records + // are withdrawn means callers are already being steered elsewhere. + drain_exec_streams( + &state.exec_drain, + Duration::from_secs(config.shutdown_drain_secs), + ) + .await; + state .compute .cleanup_on_shutdown() @@ -863,6 +881,34 @@ pub(crate) async fn run_server( Ok(()) } +async fn drain_exec_streams(drain: &exec_drain::ExecDrain, deadline: Duration) { + let in_flight = drain.in_flight(); + if in_flight == 0 { + return; + } + if deadline.is_zero() { + warn!( + in_flight, + "exiting with exec streams in flight; no shutdown drain is configured" + ); + return; + } + info!( + in_flight, + deadline_secs = deadline.as_secs(), + "waiting for in-flight exec streams before exiting" + ); + if drain.wait_idle(deadline).await { + info!("in-flight exec streams finished; continuing shutdown"); + } else { + warn!( + in_flight = drain.in_flight(), + deadline_secs = deadline.as_secs(), + "shutdown drain deadline passed; exiting with exec streams in flight" + ); + } +} + async fn serve_gateway_listener( bound_listener: BoundGatewayListener, service: MultiplexService, diff --git a/crates/openshell-server/src/supervisor_session.rs b/crates/openshell-server/src/supervisor_session.rs index f238354a87..3f928e2352 100644 --- a/crates/openshell-server/src/supervisor_session.rs +++ b/crates/openshell-server/src/supervisor_session.rs @@ -4,7 +4,7 @@ use std::collections::HashMap; use std::future::Future; use std::pin::Pin; -use std::sync::atomic::Ordering; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -83,6 +83,11 @@ pub struct SupervisorSessionRegistry { /// unit and integration tests that drive the registry without a store — /// the registry then behaves exactly as a single-replica gateway. liveness: Option>, + /// Set when graceful shutdown starts. A draining replica opens no new + /// relays and stops renewing its liveness records, so callers route new + /// work to the other replicas holding a session while the relays already + /// open here run to completion. + draining: Arc, } struct PendingRelay { @@ -124,6 +129,17 @@ impl SupervisorSessionRegistry { } } + /// Stop opening relays and renewing liveness records on this replica. + /// + /// One-way: a replica that starts draining is on its way out. + pub fn begin_drain(&self) { + self.draining.store(true, Ordering::SeqCst); + } + + fn is_draining(&self) -> bool { + self.draining.load(Ordering::SeqCst) + } + /// Claim cross-replica liveness of a session and keep the claim fresh /// for as long as the returned handle is alive. /// @@ -149,6 +165,7 @@ impl SupervisorSessionRegistry { Fut: Future + Send, { let liveness = Arc::clone(self.liveness.as_ref()?); + let draining = Arc::clone(&self.draining); let handle = tokio::spawn(async move { // Held only while this replica has a usable claim. A store error // drops it and the next pass re-announces: giving up instead would @@ -159,6 +176,12 @@ impl SupervisorSessionRegistry { let mut claim: Option = None; loop { + // A draining replica's records are withdrawn in one pass at + // shutdown; renewing or re-announcing after that would point + // callers back at a replica that refuses them. + if draining.load(Ordering::SeqCst) { + return; + } let wait = match claim.as_mut() { None => match liveness.announce(&sandbox_id, &session_id).await { Ok(fresh) => { @@ -367,7 +390,13 @@ impl SupervisorSessionRegistry { &self, sandbox_id: &str, ) -> Result, Status> { - if let Some(tx) = self.lookup_session(sandbox_id) { + // A draining replica answers as if it held no session, which is true + // of it for any new work: the refusal is reached before anything is + // dispatched, and its serving list points the caller at the replicas + // that will still be here. + if !self.is_draining() + && let Some(tx) = self.lookup_session(sandbox_id) + { return Ok(tx); } @@ -2244,6 +2273,73 @@ mod tests { ); } + /// A draining replica still holds the session, and the relays already + /// open on it keep running, but it opens no new one: it answers the way a + /// replica without the session does, naming the peers that will outlast it. + #[tokio::test] + async fn a_draining_replica_refuses_new_relays_and_names_its_peers() { + let store = store_with_sandboxes(&["sbx-drain"]).await; + let remote = liveness(&store, "replica-remote", "10-0-0-9.gw.ns.svc:8080"); + remote + .announce("sbx-drain", "session-remote") + .await + .unwrap(); + + let registry = + SupervisorSessionRegistry::with_liveness(liveness(&store, "replica-local", "local:1")); + let (tx, mut rx) = mpsc::channel(4); + registry.register( + "sbx-drain".to_string(), + "s1".to_string(), + tx, + make_shutdown(), + ); + registry + .open_relay("sbx-drain") + .await + .expect("a live replica opens the relay"); + assert!(rx.try_recv().is_ok(), "the first RelayOpen was sent"); + + registry.begin_drain(); + + let err = registry + .open_relay("sbx-drain") + .await + .expect_err("a draining replica opens no new relay"); + assert_eq!(err.code(), tonic::Code::Unavailable); + assert_eq!( + redirect_hint(&err).as_deref(), + Some("10-0-0-9.gw.ns.svc:8080") + ); + assert!( + rx.try_recv().is_err(), + "nothing may be dispatched once draining: the refusal must prove nothing ran" + ); + assert!( + registry.has_session("sbx-drain"), + "draining keeps the session for the relays already open on it" + ); + } + + #[tokio::test] + async fn a_draining_replica_does_not_announce_liveness() { + let store = store_with_sandboxes(&["sbx-quiet"]).await; + let local = liveness(&store, "replica-local", "local:1"); + let registry = SupervisorSessionRegistry::with_liveness(Arc::clone(&local)); + + registry.begin_drain(); + let renewal = registry + .spawn_liveness_record("sbx-quiet".to_string(), "s1".to_string(), |_| async {}) + .expect("liveness is configured"); + tokio::time::sleep(Duration::from_millis(50)).await; + + assert!( + local.lookup("sbx-quiet").await.unwrap().is_none(), + "a draining replica must not point callers back at itself" + ); + drop(renewal); + } + /// The contract this registry now keeps: a replica holding no session /// answers at once. It cannot observe another replica's connections, so /// waiting would only delay the same answer, and how long to keep trying diff --git a/crates/openshell-supervisor-process/src/gateway_fleet.rs b/crates/openshell-supervisor-process/src/gateway_fleet.rs index e707a65a97..c206462b07 100644 --- a/crates/openshell-supervisor-process/src/gateway_fleet.rs +++ b/crates/openshell-supervisor-process/src/gateway_fleet.rs @@ -34,6 +34,12 @@ //! The window bounds skew between two *live* views; it cannot cover a caller //! that has stopped re-resolving, so sandbox-api stops trusting an //! unboundedly old view to *narrow* the candidates (`gateway-fleet.ts`). +//! +//! A departure is held only while its session lives. Once that session +//! fails it is dropped, not redialed: a caller picking that replica would +//! reach one with no session either way, and the window is sized to a +//! gateway's whole shutdown drain, so redialing a replica that has exited +//! would spin on a dead address for hours. //! * **Never act on ignorance.** A failed or empty DNS answer leaves existing //! connections alone. Losing a working session because a resolver blipped //! would be strictly worse than routing on a slightly stale view, which @@ -55,6 +61,7 @@ //! one source of targets either way. use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock, RwLock}; use std::time::{Duration, Instant}; @@ -147,6 +154,16 @@ struct Connection { /// Set when the member has left the subset; the session is dropped once /// this passes. `None` means the member is still in the subset. drop_at: Option, + /// Shared with the session loop, which stops redialing once it is set. + departed: Arc, +} + +impl Connection { + /// A departed member whose session loop has stopped: nothing is left to + /// hold, so it can go before its drain window passes. + fn ended(&self) -> bool { + self.drop_at.is_some() && self.abort.is_finished() + } } /// Run the supervisor's gateway sessions for the lifetime of the sandbox. @@ -244,11 +261,14 @@ fn reconcile( connections: &mut HashMap, ) { for member in subset { - if let Some(connection) = connections.get_mut(member) { + if let Some(connection) = connections.get_mut(member) + && !connection.ended() + { // Already held. Clear any pending drop: a member that left the // subset and came back within the drain window keeps its session // rather than being dropped and immediately reconnected. connection.drop_at = None; + connection.departed.store(false, Ordering::SeqCst); } else { let endpoint = member_endpoint(scheme, member); info!( @@ -256,14 +276,17 @@ fn reconcile( %endpoint, "supervisor session: connecting to a new subset member" ); + let departed = Arc::new(AtomicBool::new(false)); let mut member_config = config.clone(); member_config.endpoint = endpoint; + member_config.departed = Arc::clone(&departed); let abort = sessions.spawn(run_session_loop(member_config)); connections.insert( member.clone(), Connection { abort, drop_at: None, + departed, }, ); } @@ -295,20 +318,23 @@ fn reconcile( "supervisor session: subset member departed; holding its session to drain" ); connection.drop_at = Some(deadline); + connection.departed.store(true, Ordering::SeqCst); } } } -/// Drop sessions whose drain window has passed. +/// Drop departed members whose drain window has passed or whose session has +/// already ended. fn reap_drained(connections: &mut HashMap) { let now = Instant::now(); connections.retain(|member, connection| { let expired = connection.drop_at.is_some_and(|drop_at| now >= drop_at); - if expired { + if expired || connection.ended() { debug!(%member, "supervisor session: dropping a drained subset member"); connection.abort.abort(); + return false; } - !expired + true }); } @@ -391,8 +417,9 @@ mod tests { ssh_socket_path: std::path::PathBuf::from("/nonexistent.sock"), netns_fd: None, expected_ssh_peer_pid: None, - terminating: Arc::new(std::sync::atomic::AtomicBool::new(true)), + terminating: Arc::new(AtomicBool::new(true)), instance_id: "instance-1".to_string(), + departed: Arc::new(AtomicBool::new(false)), } } @@ -531,4 +558,92 @@ mod tests { assert!(connections["a:8080"].drop_at.is_none()); assert_eq!(connections.len(), 2); } + + async fn wait_until_ended(connection: &Connection) { + tokio::time::timeout(Duration::from_secs(10), async { + while !connection.abort.is_finished() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + }) + .await + .expect("a departed member's session loop must stop once its session fails"); + } + + /// The drain window can be hours long, to cover a gateway's own shutdown + /// drain. A departed member's session is held only for the execs riding + /// it, so once that session fails (the replica exited) redialing it for + /// the rest of the window would only spin on a dead address. + #[tokio::test] + async fn a_departed_member_is_dropped_once_its_session_ends() { + let mut sessions = JoinSet::new(); + let mut connections = HashMap::new(); + let fleet = fleet(Duration::from_hours(3)); + let config = test_config("https://base:8080"); + + reconcile( + &["a:8080".to_string(), "b:8080".to_string()], + &fleet, + "https", + &config, + &mut sessions, + &mut connections, + ); + reconcile( + &["b:8080".to_string()], + &fleet, + "https", + &config, + &mut sessions, + &mut connections, + ); + wait_until_ended(&connections["a:8080"]).await; + assert!( + !connections["b:8080"].abort.is_finished(), + "a member still in the subset keeps redialing" + ); + + reap_drained(&mut connections); + assert_eq!(connections.keys().collect::>(), vec!["b:8080"]); + } + + /// A member that returns after its departed session already ended gets a + /// new session; keeping the dead entry would leave it with none. + #[tokio::test] + async fn a_returning_member_whose_session_ended_is_redialed() { + let mut sessions = JoinSet::new(); + let mut connections = HashMap::new(); + let fleet = fleet(Duration::from_hours(3)); + let config = test_config("https://base:8080"); + + reconcile( + &["a:8080".to_string()], + &fleet, + "https", + &config, + &mut sessions, + &mut connections, + ); + reconcile( + &["b:8080".to_string()], + &fleet, + "https", + &config, + &mut sessions, + &mut connections, + ); + wait_until_ended(&connections["a:8080"]).await; + + reconcile( + &["a:8080".to_string()], + &fleet, + "https", + &config, + &mut sessions, + &mut connections, + ); + let a = &connections["a:8080"]; + assert!(!a.abort.is_finished(), "the returning member is redialed"); + assert!(a.drop_at.is_none()); + assert!(!a.departed.load(Ordering::SeqCst)); + } } diff --git a/crates/openshell-supervisor-process/src/supervisor_session.rs b/crates/openshell-supervisor-process/src/supervisor_session.rs index 7823d73dfd..0bcd1af298 100644 --- a/crates/openshell-supervisor-process/src/supervisor_session.rs +++ b/crates/openshell-supervisor-process/src/supervisor_session.rs @@ -291,6 +291,7 @@ pub fn spawn( expected_ssh_peer_pid, terminating, instance_id, + departed: Arc::new(AtomicBool::new(false)), }; // One task, however many sessions it holds: callers abort this handle at // shutdown, and `gateway_fleet::run` owns its sessions in a `JoinSet` so @@ -309,10 +310,17 @@ pub(crate) struct SessionConfig { pub(crate) expected_ssh_peer_pid: Option, pub(crate) terminating: Arc, pub(crate) instance_id: String, + /// Set by the fleet loop once this session's member has left the subset. + /// A departed member is held only so the execs riding its session can + /// finish, and they die with the session, so once it ends there is + /// nothing left to hold: the loop stops rather than redialing a replica + /// that has most likely exited. + pub(crate) departed: Arc, } /// Keep one session to one gateway replica alive, reconnecting with -/// exponential backoff until the gateway closes the stream cleanly. +/// exponential backoff until the gateway closes the stream cleanly or the +/// member has departed the subset (see [`SessionConfig::departed`]). pub(crate) async fn run_session_loop(config: SessionConfig) { let mut backoff = INITIAL_BACKOFF; let mut attempt: u64 = 0; @@ -338,8 +346,15 @@ pub(crate) async fn run_session_loop(config: SessionConfig) { &e.to_string(), ); ocsf_emit!(event); + if config.departed.load(Ordering::SeqCst) { + break; + } tokio::time::sleep(backoff).await; backoff = (backoff * 2).min(MAX_BACKOFF); + // It may have departed during the backoff. + if config.departed.load(Ordering::SeqCst) { + break; + } } } }