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
19 changes: 19 additions & 0 deletions crates/openshell-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,17 @@ pub struct Config {
/// the limit.
pub grpc_rate_limit_window_secs: Option<u64>,

/// 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,
}
Expand Down Expand Up @@ -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(),
}
}
Expand Down Expand Up @@ -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<I>(mut self, interceptors: I) -> Self
Expand Down
6 changes: 6 additions & 0 deletions crates/openshell-server/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,11 @@ struct RunArgs {
#[arg(long, env = "OPENSHELL_GRPC_RATE_LIMIT_WINDOW_SECONDS")]
grpc_rate_limit_window_seconds: Option<u64>,

/// 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(
Expand Down Expand Up @@ -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())
Expand Down
115 changes: 115 additions & 0 deletions crates/openshell-server/src/exec_drain.rs
Original file line number Diff line number Diff line change
@@ -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<ExecDrain>,
}

impl ExecDrain {
/// Count one exec until the returned guard is dropped.
pub fn track(self: &Arc<Self>) -> 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);
}
}
10 changes: 10 additions & 0 deletions crates/openshell-server/src/grpc/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -1813,6 +1817,7 @@ pub(super) async fn handle_exec_sandbox(

let (tx, rx) = mpsc::channel::<Result<ExecSandboxEvent, Status>>(256);
tokio::spawn(async move {
let _in_flight = in_flight;
if let Err(err) = stream_exec_over_relay(
tx.clone(),
&sandbox_id,
Expand Down Expand Up @@ -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())
Expand All @@ -2341,6 +2350,7 @@ pub(super) async fn handle_exec_sandbox_interactive(

let (tx, rx) = mpsc::channel::<Result<ExecSandboxEvent, Status>>(256);
tokio::spawn(async move {
let _in_flight = in_flight;
if let Err(err) = stream_interactive_exec_over_relay(
tx.clone(),
&sandbox_id,
Expand Down
46 changes: 46 additions & 0 deletions crates/openshell-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ mod compute;
pub mod config_file;
mod credentials;
mod defaults;
mod exec_drain;
mod gateway_listener;
mod grpc;
mod http;
Expand Down Expand Up @@ -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<exec_drain::ExecDrain>,

/// Validated built-in and operator-registered supervisor middleware.
pub middleware_registry: Arc<MiddlewareRegistry>,

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
Expand All @@ -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,
Expand Down
Loading
Loading