From b9d8536cbfb81c447bcb7b9043095c5f443b61ef Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 8 Nov 2026 22:36:46 +0200 Subject: [PATCH 01/18] docs(rfc): decide the per-node model in RFC 0018 Record the per-node model as the next one after the per-gateway model. Each shared supervisor proves its Pod with a pod-bound token, a per-node supervisor can claim only its own node's member ID, and a per-node sandbox never falls back to a supervisor on another node. Signed-off-by: Gal Zaidman --- rfc/0018-multi-sandbox-ha-supervisors/README.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/rfc/0018-multi-sandbox-ha-supervisors/README.md b/rfc/0018-multi-sandbox-ha-supervisors/README.md index 81dfa7a96e..e0aa85593b 100644 --- a/rfc/0018-multi-sandbox-ha-supervisors/README.md +++ b/rfc/0018-multi-sandbox-ha-supervisors/README.md @@ -6,6 +6,7 @@ links: - https://github.com/ai-openshell/openshell/issues/4311 - https://github.com/ai-openshell/openshell/issues/2385 - https://github.com/ai-openshell/openshell/pull/3661 + - https://github.com/ai-openshell/openshell/issues/6026 --- # RFC 0018 - Multi-sandbox and HA Supervisors @@ -71,7 +72,7 @@ Each deployment answers two questions: **where the supervisor runs** (per worksp | Model | One supervisor serves | Good | Hard | | --- | --- | --- | --- | | Per workspace | A pool for one workspace | Trust and quotas stay inside the workspace. Fewer Pods. | One failure hits the whole pool. Small workspaces pay for spare capacity. | -| Per node | The sandboxes on one node (DaemonSet) | Traffic stays on the node. Pod count follows node count. | One failure hits the node, possibly across workspaces. No ready standby on the node. Fits poorly with backends that move sandboxes between nodes. | +| Per node | The sandboxes on one node (DaemonSet) | Traffic stays on the node. Pod count follows node count. The kubelet's Pod limit, not a supervisor cap, bounds its sandboxes. | One failure hits the node, possibly across workspaces. No ready standby on the node. Fits poorly with backends that move sandboxes between nodes. Its resources must fit the node's Pod limit. | | Per sandbox (today) | One sandbox, with an optional warm standby | Smallest failure. Simplest isolation. | Most Pods. Slow cold start. | | Per gateway | A group tied to one gateway replica | Easy to run as a group. | Gateway rollouts and scale-in also move the group. Needs its own identity and spare capacity. | @@ -138,6 +139,7 @@ sequenceDiagram How it stays safe: - **Identity is checked.** The gateway's compute driver (for Kubernetes, `openshell-driver-kubernetes`) verifies the candidate's service account token with the Kubernetes TokenReview API and checks that the candidate may serve this sandbox; labels, namespace, and reachability prove nothing. The gateway then issues a short-lived `RecoveryGrant` bound to the candidate's key, sandbox, run, and new epoch. Launch credentials never authorize a takeover, and each candidate gets new TLS keys. +- **Each shared supervisor proves its Pod.** It presents a pod-bound token for the supervisor service account, which the gateway checks with TokenReview and a live-Pod lookup. In the per-node model the member ID must be that Pod's node. - **A missing heartbeat is not proof.** A new owner is reserved only after the old one released, its lease expired, or the runtime proved it cut the old one off. - **The runtime enforces it.** It accepts only the newer epoch, closes old channels, and stays frozen until activation. A database row alone cannot stop a live socket. - **If in doubt, stop.** If the runtime cannot freeze or verify enforcement, it stops the agent. @@ -172,6 +174,7 @@ During resume: - **The network fence needs work.** Today a Kubernetes NetworkPolicy lets only supervisors in the sandbox's own namespace reach it. A per-node or per-gateway supervisor usually lives in another namespace, so it would be blocked. Changing that policy in place stops every sandbox in the namespace, so each model needs its own reviewed policy instead. - **One IP for many sandboxes.** All traffic from a shared supervisor leaves from one Pod IP. Outside firewalls and logs can no longer tell sandboxes apart by IP. - **Sharing a process.** Each sandbox still gets its own policy, credentials, connections, logs, and limits inside the shared supervisor. A bug or compromise in that process can still reach every sandbox it serves, which a separate Pod would prevent. +- **Per node.** An attacker who controls one node can affect only that node's sandboxes. Its supervisor can claim only its own node's member ID (section 3), capacity is per member, and runtime traffic stays on the node. ### 5. Workload identity @@ -216,12 +219,13 @@ New settings choose the model, recovery mode, allowed fallbacks, spare capacity, | Workload node or runtime lost | Restart if policy allows. Process memory is lost. | | Workload node drain | Draining evicts the workload Pods too, so this is the node lost case in every model. | | Supervisor upgrade, scale-in, or drain of a supervisor-only node | Stop new assignments, hand each session over with fencing within the grace period, then stop. | +| Per-node supervisor rollout or crash | No handover. The node's sandboxes freeze and resume when the new Pod on that node attaches within the runtime's recovery timeout. | | Sandbox stop or delete, or authority revoked | Cancel grants. Cleanup wins over a pending recovery and does not touch other sessions. | Operations notes: - Draining a gateway does not drain supervisors, and the reverse. -- A per-node supervisor uses a supervisor on another node only if the operator allows it. +- A per-node sandbox never uses a supervisor on another node. - Spread supervisors across nodes and reserve resources for them. Extra Pods during an upgrade do not replace a standby for crashes. Pod disruption budgets do not prevent crashes ([Kubernetes disruptions](https://kubernetes.io/docs/concepts/workloads/pods/disruptions/)). - Show operators who owns each sandbox, how recoveries went, and spare capacity. Keep sandbox IDs out of metric labels. - Measure how long agents stay frozen, and publish recovery times for each backend. @@ -244,7 +248,7 @@ This work targets the Kubernetes driver only, and all of it sits behind a Kubern 4. Measure recovery time and noisy neighbors, then **decide which models to implement** and which is the default. Record the decision in this RFC. 5. Release the chosen models behind opt-in settings, with docs and a rollback path. -Some details are left to implementation and are out of scope for this RFC: how a per-node supervisor is bound to a sandbox, whether the lease is per replica or per sandbox, how launch material reaches a shared or replacement supervisor, and how the lease is renewed. +Some details are left to implementation and are out of scope for this RFC: whether the lease is per replica or per sandbox, how launch material reaches a shared or replacement supervisor, and how the lease is renewed. ## Risks @@ -281,4 +285,4 @@ Some details are left to implementation and are out of scope for this RFC: how a We are not picking one model over the others. Teams have different requirements for failure scope, isolation, and security, so one choice cannot fit every deployment. All four models share the safety rules in this RFC, so adding a model later does not change those rules. -Implementation starts with the per-gateway model, which is already in progress. We will add the per-node, per-workspace, or warm-standby per-sandbox models when a deployment needs them, each behind its own opt-in setting and only after it passes the failure tests. +Implementation starts with the per-gateway model, which is already in progress. The per-node model follows, for deployments that need node isolation. We will add the per-workspace or warm-standby per-sandbox models when a deployment needs them, each behind its own opt-in setting and only after it passes the failure tests. From 964f9a3b5bc2181bf9fedd83d1b43f9c729cf474 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 22 Nov 2026 22:12:31 +0200 Subject: [PATCH 02/18] feat(k8s): require a pod-bound identity for shared supervisors All shared supervisor Pods present the same gateway-minted supervisor token, so anyone holding a copy of the token Secret could attach as a supervisor. The gateway now accepts the supervisor token only beside a projected ServiceAccount token (audience openshell-supervisor) that TokenReview and a live-Pod check resolve to a Pod of shared_supervisor.service_account_name. - shared_supervisor.service_account_name is required; the driver registers it with the controller, and the gateway refuses to start the topology without it. - The supervisor sends the token from --identity-token-file in the x-openshell-host-identity-token header, re-read on every attempt. - Helm renders the supervisor ServiceAccount without RBAC, runs the supervisor as it, and mounts a 10-minute projected token. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 7 + .../openshell-driver-kubernetes/src/config.rs | 18 ++ .../openshell-driver-kubernetes/src/driver.rs | 10 +- crates/openshell-server/src/auth/peer.rs | 8 + .../src/auth/supervisor_token.rs | 212 ++++++++++++++++-- crates/openshell-server/src/lib.rs | 40 ++++ crates/openshell-server/src/multiplex.rs | 10 +- crates/openshell-supervisor-control/README.md | 11 +- .../src/controller.rs | 32 +++ .../openshell-supervisor-control/src/lib.rs | 7 +- crates/openshell-supervisor/README.md | 6 +- crates/openshell-supervisor/src/main.rs | 11 + crates/openshell-supervisor/src/shared.rs | 4 + .../openshell-supervisor/src/shared_host.rs | 31 ++- deploy/helm/openshell/README.md | 1 + deploy/helm/openshell/templates/_helpers.tpl | 2 +- .../helm/openshell/templates/peer-role.yaml | 6 +- .../templates/supervisor-serviceaccount.yaml | 18 ++ .../helm/openshell/templates/supervisor.yaml | 18 +- .../helm/openshell/tests/supervisor_test.yaml | 48 +++- deploy/helm/openshell/values.yaml | 4 + docs/kubernetes/access-control.mdx | 3 +- docs/kubernetes/high-availability.mdx | 11 + skills/debug-openshell-cluster/SKILL.md | 1 + 24 files changed, 477 insertions(+), 42 deletions(-) create mode 100644 deploy/helm/openshell/templates/supervisor-serviceaccount.yaml diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 18587b10bf..7992ea8c78 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -410,6 +410,13 @@ fails closed. `shared_supervisor.token_secret_name` Secret in `service_namespace`, which the supervisor Pod mounts, and names a missing Secret or a denied patch in the retried error. +- **Pod identity.** The driver registers + `shared_supervisor.service_account_name`, the ServiceAccount the supervisor + Pods run as, with the controller (`require_host_identity`). A projected + ServiceAccount token sent with a supervisor token must resolve to a live Pod + of that account. With `shared_supervisor.require_identity_token`, a + supervisor token without one is refused, so a copy of the token Secret alone + admits no caller. - **Create and start.** The driver creates a per-sandbox egress allowance `os-shared-control-` from the workload Pod to the Pods the shared supervisor's Service selects, on the runtime port, binds its UID and diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index ffae5119d2..7cb726dc2c 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -236,6 +236,13 @@ pub struct SharedSupervisorConfig { /// gateway-minted supervisor token (key `token`); the supervisor Pod /// mounts it and presents the token on its assignment stream. pub token_secret_name: String, + /// `ServiceAccount` in `service_namespace` the supervisor Pods run as; a + /// pod-bound token for it accompanies the supervisor token. + pub service_account_name: String, + /// Refuse a supervisor token without the pod-bound token. A present + /// token is verified either way. + #[serde(default)] + pub require_identity_token: bool, } impl SharedSupervisorConfig { @@ -251,6 +258,11 @@ impl SharedSupervisorConfig { if !is_dns_subdomain(&self.token_secret_name) { return Err("shared_supervisor token_secret_name must be a DNS subdomain name".into()); } + if !is_dns_subdomain(&self.service_account_name) { + return Err( + "shared_supervisor service_account_name must be a DNS subdomain name".into(), + ); + } Ok(()) } @@ -1317,6 +1329,8 @@ mod tests { service_namespace: "openshell".to_string(), runtime_port: 8443, token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: "openshell-supervisor".to_string(), + require_identity_token: false, }; let gateway = |shared: Option| KubernetesComputeConfig { supervisor_topology: Some(SupervisorTopology::Gateway), @@ -1348,6 +1362,10 @@ mod tests { token_secret_name: "Not_A_Secret_Name".to_string(), ..shared() }, + SharedSupervisorConfig { + service_account_name: "Not_A_Name".to_string(), + ..shared() + }, ] { assert!( gateway(Some(invalid)) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index d3e2c4720f..f77e7437c0 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -76,7 +76,7 @@ use openshell_sandbox_backend::boundary_protocol::{ generate_sandbox_tls_material, }; use openshell_supervisor_control::{ - InstanceSupervision, LaunchError, RecoverableInstance, RecoveryBaseline, + HostAccount, InstanceSupervision, LaunchError, RecoverableInstance, RecoveryBaseline, RegistrationTraceContext, SandboxInstanceRegistration, SharedSupervision, }; use serde::Deserialize; @@ -1344,6 +1344,14 @@ impl KubernetesComputeDriver { .zip(supervision.clone()) .map(|(config, supervision)| SharedSupervisor::new(config, supervision)); if let Some(shared) = &shared_supervisor { + shared + .supervision() + .controller() + .require_host_identity(HostAccount { + namespace: shared.config().service_namespace.clone(), + service_account: shared.config().service_account_name.clone(), + identity_required: shared.config().require_identity_token, + }); shared.spawn_token_secret_writer(client.clone(), shutdown_rx.clone()); } if shared_supervisor.is_some() && !config.supervisor_otlp.is_empty() { diff --git a/crates/openshell-server/src/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index 7ee198e775..bf6244a63f 100644 --- a/crates/openshell-server/src/auth/peer.rs +++ b/crates/openshell-server/src/auth/peer.rs @@ -302,6 +302,14 @@ pub struct CachingGatewayPeerResolver { entries: Mutex>, } +impl std::fmt::Debug for CachingGatewayPeerResolver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CachingGatewayPeerResolver") + .field("ttl", &self.ttl) + .finish_non_exhaustive() + } +} + impl CachingGatewayPeerResolver { pub fn new(inner: Arc, ttl: Duration) -> Self { Self { diff --git a/crates/openshell-server/src/auth/supervisor_token.rs b/crates/openshell-server/src/auth/supervisor_token.rs index b8c77ec233..651ffec7da 100644 --- a/crates/openshell-server/src/auth/supervisor_token.rs +++ b/crates/openshell-server/src/auth/supervisor_token.rs @@ -9,17 +9,23 @@ //! key, key ID, and gateway identity as the sandbox session tokens, under a //! distinct profile (`typ`, subject, claims), so no sandbox, extension, user, //! or peer credential is accepted on the stream and the supervisor token is -//! accepted nowhere else. [`SupervisorTokenAuthenticator`] slots the verifier -//! into the gateway's authenticator chain. +//! accepted nowhere else. A pod-bound token for the supervisor's +//! `ServiceAccount` that accompanies it must verify, and may be required. +//! [`SupervisorTokenAuthenticator`] slots the verifier into the gateway's +//! authenticator chain. use std::sync::Arc; use async_trait::async_trait; use jsonwebtoken::decode_header; use openshell_core::jwt::SUPERVISOR_JWT_TYPE; -use openshell_supervisor_control::HostIdentity; +use openshell_supervisor_control::{HOST_IDENTITY_TOKEN_HEADER, HostIdentity}; -use super::authenticator::{AuthRejection, Authentication, Authenticator, bearer_credential}; +use super::authenticator::{ + AuthFailureReason, AuthMechanism, AuthRejection, Authentication, Authenticator, + bearer_credential, +}; +use super::peer::GatewayPeerIdentityResolver; use super::principal::{Principal, SupervisorPrincipal}; use super::sandbox_jwt::SandboxSessionJwtAuthority; @@ -28,11 +34,83 @@ use super::sandbox_jwt::SandboxSessionJwtAuthority; /// verification ends the chain. pub struct SupervisorTokenAuthenticator { authority: Arc, + supervisor_identity: Option>, + identity_required: bool, } impl SupervisorTokenAuthenticator { pub fn new(authority: Arc) -> Self { - Self { authority } + Self { + authority, + supervisor_identity: None, + identity_required: false, + } + } + + /// Accept supervisor tokens only when the identity token in + /// [`HOST_IDENTITY_TOKEN_HEADER`] resolves through `resolver`, or, unless + /// `required`, is absent. Without a resolver, every supervisor token is + /// refused. + #[must_use] + pub fn with_identity_resolver( + mut self, + resolver: Arc, + required: bool, + ) -> Self { + self.supervisor_identity = Some(resolver); + self.identity_required = required; + self + } + + /// Resolved only after the supervisor token verified, so callers without + /// it can't trigger a `TokenReview`. + async fn resolve_identity(&self, headers: &http::HeaderMap) -> Result<(), AuthRejection> { + let refuse = |reason, message: &str| { + AuthRejection::new( + AuthMechanism::SupervisorToken, + reason, + tonic::Status::unauthenticated(message), + ) + }; + let Some(resolver) = &self.supervisor_identity else { + return Err(refuse( + AuthFailureReason::InvalidCredential, + "this gateway accepts no supervisor", + )); + }; + let Some(token) = headers + .get(HOST_IDENTITY_TOKEN_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty()) + else { + if self.identity_required { + return Err(refuse( + AuthFailureReason::MissingCredential, + "supervisor identity token is required", + )); + } + return Ok(()); + }; + resolver + .resolve(token) + .await + .map_err(|rejection| { + AuthRejection::new( + AuthMechanism::SupervisorToken, + rejection.reason, + tonic::Status::new( + rejection.status.code(), + format!("supervisor identity: {}", rejection.status.message()), + ), + ) + })? + .map(|_| ()) + .ok_or_else(|| { + refuse( + AuthFailureReason::InvalidCredential, + "supervisor identity token is invalid", + ) + }) } } @@ -61,6 +139,7 @@ impl Authenticator for SupervisorTokenAuthenticator { return Ok(Authentication::NotApplicable); } let authenticated = self.authority.verify_supervisor_token(token)?; + self.resolve_identity(headers).await?; Ok(Authentication::Accepted(Principal::Supervisor( SupervisorPrincipal { identity: HostIdentity { @@ -78,9 +157,11 @@ mod tests { use std::time::Duration; use super::*; - use crate::auth::authenticator::{AuthFailureReason, AuthMechanism}; + use crate::auth::peer::test_support::FakeGatewayPeerResolver; use openshell_bootstrap::jwt::generate_jwt_key; + const ATTACH: &str = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; + fn authority(gateway_id: &str) -> Arc { let material = generate_jwt_key().expect("jwt key"); Arc::new( @@ -104,17 +185,35 @@ mod tests { headers } + fn with_identity(token: &str) -> http::HeaderMap { + let mut headers = headers(token); + headers.insert(HOST_IDENTITY_TOKEN_HEADER, "pod-token".parse().unwrap()); + headers + } + + fn resolving() -> Arc { + Arc::new(FakeGatewayPeerResolver::returning(Ok(Some( + crate::auth::peer::ResolvedGatewayPeerIdentity { + pod_name: "openshell-supervisor-abc".to_string(), + pod_uid: "uid".to_string(), + }, + )))) + } + + fn accepting(gateway: Arc) -> SupervisorTokenAuthenticator { + SupervisorTokenAuthenticator::new(gateway).with_identity_resolver(resolving(), true) + } + #[tokio::test] async fn supervisor_tokens_authenticate_only_as_the_supervisor() { - let attach = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; let gateway = authority("test-gateway"); let minted = gateway .mint_supervisor_token(Duration::from_mins(15)) .expect("mint"); - let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()); + let authenticator = accepting(gateway.clone()); let accepted = authenticator - .authenticate(&headers(minted.token.expose_secret()), attach) + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) .await .expect("valid token"); match accepted { @@ -142,7 +241,7 @@ mod tests { ] { assert!(matches!( authenticator - .authenticate(&headers(bearer), attach) + .authenticate(&with_identity(bearer), ATTACH) .await .unwrap(), Authentication::NotApplicable @@ -162,26 +261,111 @@ mod tests { .mint_supervisor_token(Duration::from_mins(15)) .unwrap(); let rejection = authenticator - .authenticate(&headers(foreign.token.expose_secret()), attach) + .authenticate(&with_identity(foreign.token.expose_secret()), ATTACH) .await .expect_err("foreign key must be rejected"); assert_eq!(rejection.mechanism, AuthMechanism::SupervisorToken); assert_eq!(rejection.reason, AuthFailureReason::InvalidCredential); assert_eq!(rejection.status.code(), tonic::Code::Unauthenticated); let other_gateway = authority("other-gateway"); - let rejection = SupervisorTokenAuthenticator::new(other_gateway.clone()) + let rejection = accepting(other_gateway.clone()) .authenticate( - &headers( + &with_identity( other_gateway .mint_supervisor_token(Duration::from_mins(15)) .unwrap() .token .expose_secret(), ), - attach, + ATTACH, ) .await .expect("own token verifies"); assert!(matches!(rejection, Authentication::Accepted(_))); } + + #[tokio::test] + async fn supervisor_tokens_require_a_pod_identity_after_they_verify() { + let gateway = authority("test-gateway"); + let minted = gateway + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + let resolver = resolving(); + let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolver.clone(), true); + + assert!(matches!( + authenticator + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .await + .unwrap(), + Authentication::Accepted(_) + )); + assert_eq!(*resolver.seen_tokens.lock().unwrap(), ["pod-token"]); + + let missing = authenticator + .authenticate(&headers(minted.token.expose_secret()), ATTACH) + .await + .expect_err("a supervisor token alone must be refused"); + assert_eq!(missing.reason, AuthFailureReason::MissingCredential); + assert_eq!(missing.status.code(), tonic::Code::Unauthenticated); + + // Unless required, a supervisor without an identity token attaches, + // but one it sends is still verified. + let optional = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolver.clone(), false); + assert!(matches!( + optional + .authenticate(&headers(minted.token.expose_secret()), ATTACH) + .await + .unwrap(), + Authentication::Accepted(_) + )); + assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 1); + assert!( + SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver( + Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), + false + ) + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .await + .is_err() + ); + + // A forged supervisor token never reaches the resolver. + let forged = authority("test-gateway") + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + assert!( + authenticator + .authenticate(&with_identity(forged.token.expose_secret()), ATTACH) + .await + .is_err() + ); + assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn supervisor_tokens_are_refused_without_a_valid_pod_identity() { + let gateway = authority("test-gateway"); + let minted = gateway + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + let headers = with_identity(minted.token.expose_secret()); + + let unconfigured = SupervisorTokenAuthenticator::new(gateway.clone()) + .authenticate(&headers, ATTACH) + .await + .expect_err("a gateway without a supervisor account accepts no supervisor"); + assert_eq!(unconfigured.reason, AuthFailureReason::InvalidCredential); + + let unknown = SupervisorTokenAuthenticator::new(gateway) + .with_identity_resolver(Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), true) + .authenticate(&headers, ATTACH) + .await + .expect_err("an identity token for another account must be refused"); + assert_eq!(unknown.reason, AuthFailureReason::InvalidCredential); + assert_eq!(unknown.status.code(), tonic::Code::Unauthenticated); + } } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index dd0ef762cc..6d4cd6a84c 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -430,6 +430,13 @@ pub struct ServerState { /// Optional K8s `ServiceAccount` authenticator for gateway peer RPCs. pub peer_authenticator: Option>, + /// Resolves shared supervisors' identity tokens. Without it every + /// supervisor token is refused. + pub supervisor_identity_resolver: Option>, + + /// Refuse supervisor tokens that arrive without an identity token. + pub supervisor_identity_required: bool, + /// Credentials that have recently logged on, so each records one /// authentication success rather than one per request. pub(crate) logons: auth::audit::Logons, @@ -718,6 +725,8 @@ impl ServerState { compute_driver_authenticator: None, dedicated_warm_pool: None, peer_authenticator: None, + supervisor_identity_resolver: None, + supervisor_identity_required: false, logons: auth::audit::Logons::default(), grpc_rate_limiter, provider_token_rate_limiter, @@ -1065,6 +1074,37 @@ pub(crate) async fn run_server( validate_peer_endpoint_scheme(&state.config, peer_endpoint)?; } controller.set_peer_endpoint(state.peer_endpoint.clone().unwrap_or_default()); + let account = controller.host_account().ok_or_else(|| { + Error::config( + "the compute driver registered no ServiceAccount for shared supervisors, whose \ + pod-bound tokens prove their identity", + ) + })?; + let client = kube::Client::try_default().await.map_err(|error| { + Error::config(format!( + "shared supervisors prove their Pod with Kubernetes TokenReview, but the \ + in-cluster client failed: {error}" + )) + })?; + let resolver = Arc::new(auth::peer::LiveGatewayPeerResolver::new( + client, + &account.namespace, + openshell_supervisor_control::SUPERVISOR_IDENTITY_TOKEN_AUDIENCE.to_string(), + account.service_account.clone(), + Vec::new(), + )); + state.supervisor_identity_resolver = + Some(Arc::new(auth::peer::CachingGatewayPeerResolver::new( + resolver, + auth::peer::peer_token_cache_ttl_from_env(), + ))); + state.supervisor_identity_required = account.identity_required; + info!( + namespace = %account.namespace, + service_account = %account.service_account, + required = account.identity_required, + "supervisor identity verification enabled" + ); supervisor_pool::SupervisorPool::new( state.store.clone(), controller.clone(), diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 557c070996..7b81cce23b 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1157,9 +1157,13 @@ fn build_authenticator_chain(state: &ServerState) -> Option authenticators.push(driver); } if let Some(authority) = state.sandbox_session_jwt_authority.clone() { - authenticators.push(Arc::new( - crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()), - )); + let mut supervisor = + crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()); + if let Some(resolver) = state.supervisor_identity_resolver.clone() { + supervisor = + supervisor.with_identity_resolver(resolver, state.supervisor_identity_required); + } + authenticators.push(Arc::new(supervisor)); authenticators.push(Arc::new( crate::auth::sandbox_jwt::SandboxSessionJwtAuthenticator::new( authority, diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index fb6ca4c683..15d83e0ae5 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -17,9 +17,14 @@ re-implementing the control contracts. are served at once and each instance has one durable owner: a member, its process, and an ownership term. Every member names itself in its hello; a hello without a member, or with an invalid one, is refused with the - `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. One session per member: a - newer connection epoch of the same member process or a new process of the - member supersedes its stream, a delayed older hello is refused, and reports + `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. `require_host_identity` names + the `HostAccount` whose pod-bound tokens, sent in + `HOST_IDENTITY_TOKEN_HEADER` with `SUPERVISOR_IDENTITY_TOKEN_AUDIENCE`, + prove that a supervisor token's holder is a supervisor Pod; + `HostAccount.identity_required` refuses a supervisor token without one. + One session per + member: a newer connection epoch of the same member process or a new + process of the member supersedes its stream, a delayed older hello is refused, and reports from superseded streams, acks of revisions never sent, regressing acks, and oversized reports are dropped. A stream ends when the token that opened it expires; hosted instances keep running. The pool's recovery deadline diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index e9e35005e8..793d4dab5a 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -85,6 +85,13 @@ pub struct HostIdentity { pub expires_at: i64, } +/// Metadata header carrying a host's pod-bound projected `ServiceAccount` +/// token beside its host token. +pub const HOST_IDENTITY_TOKEN_HEADER: &str = "x-openshell-host-identity-token"; + +/// Audience of a supervisor's identity token. +pub const SUPERVISOR_IDENTITY_TOKEN_AUDIENCE: &str = "openshell-supervisor"; + /// The current supervisor token, as the gateway mints and renews it. /// /// A compute driver delivers it to the supervisor process by whatever means @@ -359,6 +366,18 @@ struct Inner { limits: Mutex, /// Live gateway replicas serving the pool, which scale its capacity. gateway_replicas: AtomicUsize, + /// Set by [`SupervisorHostController::require_host_identity`]. + supervisor_account: Mutex>, +} + +/// The Kubernetes `ServiceAccount` whose pod-bound tokens prove that a +/// holder of a host token is one of the host's Pods. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostAccount { + pub namespace: String, + pub service_account: String, + /// Refuse a host token that arrives without an identity token. + pub identity_required: bool, } /// Gateway-owned desired assignments and observed status of the shared @@ -412,6 +431,7 @@ impl SupervisorHostController { peer_endpoint: Mutex::new(String::new()), limits: Mutex::new(PoolLimits::default()), gateway_replicas: AtomicUsize::new(1), + supervisor_account: Mutex::new(None), }), } } @@ -443,6 +463,18 @@ impl SupervisorHostController { .max_pool_instances(self.inner.gateway_replicas.load(Ordering::Relaxed)) } + /// Verify host identity tokens as issued for `account`. Call it before + /// any host attaches. + pub fn require_host_identity(&self, account: HostAccount) { + *lock(&self.inner.supervisor_account) = Some(account); + } + + /// The account supervisor identity tokens must be issued for, when set. + #[must_use] + pub fn host_account(&self) -> Option { + lock(&self.inner.supervisor_account).clone() + } + /// Tell attaching hosts to dial their sandbox sessions to `peer_endpoint`. /// Call it before any host attaches. pub fn set_peer_endpoint(&self, peer_endpoint: String) { diff --git a/crates/openshell-supervisor-control/src/lib.rs b/crates/openshell-supervisor-control/src/lib.rs index 111b9c019f..a099810a1c 100644 --- a/crates/openshell-supervisor-control/src/lib.rs +++ b/crates/openshell-supervisor-control/src/lib.rs @@ -42,9 +42,10 @@ pub mod proto { } pub use controller::{ - AssignmentError, ConnectedMember, HostIdentity, InstanceOwner, MemberReport, MemberView, - ObservedInstance, POOL_HEARTBEAT_INTERVAL, POOL_RECOVERY_TIMEOUT_RANGE, - POOL_RECOVERY_TIMEOUT_SECS, PoolView, SupervisorCredential, SupervisorHostController, + AssignmentError, ConnectedMember, HOST_IDENTITY_TOKEN_HEADER, HostAccount, HostIdentity, + InstanceOwner, MemberReport, MemberView, ObservedInstance, POOL_HEARTBEAT_INTERVAL, + POOL_RECOVERY_TIMEOUT_RANGE, POOL_RECOVERY_TIMEOUT_SECS, PoolView, + SUPERVISOR_IDENTITY_TOKEN_AUDIENCE, SupervisorCredential, SupervisorHostController, }; pub use coordinator::{ ActivationRequest, InstancePlacement, InstanceSupervision, LaunchError, PendingWarmClaim, diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index 97f27cd129..e33074350f 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -194,7 +194,11 @@ control listener: it dials the gateway and receives its assignments from it. expired token as a reason to retry later, and the gateway ends a stream when the token that opened it expires, so the host reconnects with the renewed one. The host never acts with any other identity and has no - Kubernetes identity. The stream starts with a hello carrying a per-process + Kubernetes API access. Beside the token, the host sends its Pod's projected + `ServiceAccount` token (audience `openshell-supervisor`) from + `--identity-token-file` (`OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE`) in the + `x-openshell-host-identity-token` header, re-read on every connection + attempt; the gateway refuses the supervisor token without it. The stream starts with a hello carrying a per-process instance id and a connection epoch; the gateway supersedes an older stream of the same process and refuses a delayed older connection. - **Assignments.** The gateway owns the desired set and sends it as complete diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index a0ba6dc0f9..2dc6addb91 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -117,6 +117,16 @@ struct Args { #[arg(long, required_if_eq("mode", "shared"))] token_file: Option, + /// File holding this Pod's projected `ServiceAccount` token, audience + /// `openshell-supervisor`, sent beside the supervisor token. Re-read on + /// every connection attempt. + #[arg( + long, + env = "OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE", + required_if_eq("mode", "shared") + )] + identity_token_file: Option, + /// Listener for routed runtime-initiated Sandbox Protocol connections. #[arg(long, required_if_eq("mode", "shared"))] runtime_listen: Option, @@ -554,6 +564,7 @@ fn main() -> Result<()> { if args.gateway_endpoint.is_some() || args.address.is_some() || args.token_file.is_some() + || args.identity_token_file.is_some() || (args.runtime_listen.is_some() && args.warm_prepared_file.is_none()) || args.session_root.is_some() { diff --git a/crates/openshell-supervisor/src/shared.rs b/crates/openshell-supervisor/src/shared.rs index a1403bb5bb..818f62cb4a 100644 --- a/crates/openshell-supervisor/src/shared.rs +++ b/crates/openshell-supervisor/src/shared.rs @@ -33,6 +33,9 @@ fn run_platform(args: crate::Args) -> Result<()> { let token_file = args .token_file .ok_or_else(|| miette::miette!("--token-file is required for --mode=shared"))?; + let identity_token_file = args + .identity_token_file + .ok_or_else(|| miette::miette!("--identity-token-file is required for --mode=shared"))?; let runtime_listen = args .runtime_listen .ok_or_else(|| miette::miette!("--runtime-listen is required for --mode=shared"))?; @@ -124,6 +127,7 @@ from sandbox runtimes)", endpoint: gateway_endpoint.clone(), token_file, limits, + identity_token_file, }; let host = openshell_supervisor::shared_host::SharedHost::start( openshell_supervisor::shared_host::SharedHostConfig { diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 566de3ebd9..bba003e0b3 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -1177,9 +1177,29 @@ pub struct GatewayLink { pub token_file: PathBuf, /// Sizes the stream's message bounds; the host's limits. pub limits: PoolLimits, + /// File holding this Pod's projected `ServiceAccount` token, which proves + /// to the gateway that the supervisor token's holder is a supervisor Pod. + /// Re-read on every connection attempt, as the kubelet rotates it. + pub identity_token_file: PathBuf, } impl GatewayLink { + fn read_identity_token(&self) -> Result { + use miette::{IntoDiagnostic as _, WrapErr as _}; + + let path = &self.identity_token_file; + let contents = std::fs::read_to_string(path) + .into_diagnostic() + .wrap_err_with(|| format!("read identity token {}", path.display()))?; + let token = contents.trim(); + if token.is_empty() { + return Err(miette::miette!("the identity token file is empty")); + } + token + .parse() + .map_err(|_| miette::miette!("the identity token is not a valid header value")) + } + /// Read the current supervisor token. A missing, empty, malformed, or /// already expired token is an error; the gateway keeps the file fresh, /// so the caller retries later. @@ -1279,6 +1299,9 @@ impl GatewayConnector for GatewayLink { let token = self .read_token() .map_err(|error| format!("no usable supervisor token: {error}"))?; + let identity_token = self + .read_identity_token() + .map_err(|error| format!("no usable identity token: {error}"))?; let connect = openshell_core::grpc_client::connect_gateway_channel(endpoint); let channel = tokio::time::timeout_at(deadline, connect) .await @@ -1287,7 +1310,13 @@ impl GatewayConnector for GatewayLink { let mut client = SupervisorHostClient::with_interceptor(channel, token.interceptor()) .max_decoding_message_size(self.limits.max_gateway_message_bytes()) .max_encoding_message_size(self.limits.max_host_message_bytes()); - let attach = client.attach(tokio_stream::wrappers::ReceiverStream::new(outbound)); + let mut request = + tonic::Request::new(tokio_stream::wrappers::ReceiverStream::new(outbound)); + request.metadata_mut().insert( + openshell_supervisor_control::HOST_IDENTITY_TOKEN_HEADER, + identity_token, + ); + let attach = client.attach(request); let response = tokio::time::timeout_at(deadline, attach) .await .map_err(|_| { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index c441cb63e4..5aa5834cdf 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -853,6 +853,7 @@ for peer identity policies, multi-node registrations, and authorization. | supervisor.pool.maxMembersPerGateway | int | `32` | Most supervisors one gateway replica serves, rendered as [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a positive integer. The pool runs at most gateway replicas times maxMembersPerGateway times maxInstancesPerMember sandboxes, never more than 131072. | | supervisor.recoveryTimeoutSeconds | int | `60` | Seconds a sandbox workload stays frozen after losing its pool member's supervision before the sandbox runtime terminates it, rendered as [openshell.gateway.supervisor_pool] recovery_timeout_secs. Must be an integer from 30 to 300. Null leaves the gateway's pool default of 60 seconds. | | supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true. Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | +| supervisor.requireIdentityToken | bool | `false` | Refuse gateway-topology supervisors that attach without their pod-bound identity token. Node-topology supervisors always need it. Refer to the High Availability guide before enabling it on an upgrade. | | supervisor.resources | object | `{}` | Resources of each shared supervisor container, unset by default. Memory grows with the sandboxes a supervisor runs; for the default of 128 sandboxes, request 250m CPU and 768Mi memory, and allow for failover. Refer to Size Sandbox Capacity in the High Availability guide. | | supervisor.sandboxRuntime.boundaryPort | int | `5500` | Workload boundary TLS listener port. | | tolerations | list | `[]` | Tolerations for the gateway pod. | diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index d174315813..1c065a598b 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -832,7 +832,7 @@ like user-supplied schema-v2 fields during compatibility resolution. */}} {{- $_ := set $kubernetes "sandbox_runtime" $runtimeConfig -}} {{/* The chart owns the shared supervisor and the Secret that delivers its token. */}} {{- if include "openshell.supervisorEnabled" . -}} -{{- $_ := set $kubernetes "shared_supervisor" (dict "service_name" (include "openshell.supervisorName" .) "service_namespace" .Release.Namespace "runtime_port" 5500 "token_secret_name" (printf "%s-token" (include "openshell.supervisorName" .))) -}} +{{- $_ := set $kubernetes "shared_supervisor" (dict "service_name" (include "openshell.supervisorName" .) "service_namespace" .Release.Namespace "runtime_port" 5500 "token_secret_name" (printf "%s-token" (include "openshell.supervisorName" .)) "service_account_name" (include "openshell.supervisorName" .) "require_identity_token" (.Values.supervisor.requireIdentityToken | default false)) -}} {{- end -}} {{- toYaml $kubernetes -}} {{- end }} diff --git a/deploy/helm/openshell/templates/peer-role.yaml b/deploy/helm/openshell/templates/peer-role.yaml index d7fa148658..ca1c7c99f3 100644 --- a/deploy/helm/openshell/templates/peer-role.yaml +++ b/deploy/helm/openshell/templates/peer-role.yaml @@ -9,9 +9,9 @@ metadata: labels: {{- include "openshell.labels" . | nindent 4 }} rules: - # Gateway peer identity: TokenReview authenticates the projected token, then - # the receiver resolves the returned pod name and UID to the live gateway pod - # in the release namespace. + # Gateway peer and shared supervisor identity: TokenReview authenticates the + # projected token, then the receiver resolves the returned pod name and UID + # to the live gateway or supervisor pod in the release namespace. - apiGroups: - "" resources: diff --git a/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml new file mode 100644 index 0000000000..722ade5ab0 --- /dev/null +++ b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +{{- include "openshell.validateValues" . }} +{{- if include "openshell.supervisorEnabled" . }} +# Supervisors prove their Pod with this account's Pod-bound tokens. The +# gateway only reviews them, so bind no RBAC to it. Restrict creating Pods +# with it and `create` on its `serviceaccounts/token` to cluster +# administrators. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "openshell.supervisorName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell.labels" . | nindent 4 }} + app.kubernetes.io/component: supervisor +automountServiceAccountToken: false +{{- end }} diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index 96d4a1e687..a8fbb9b47a 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -27,7 +27,7 @@ # generation placed on it. The process dials the gateway over TLS with the # supervisor token the gateway mints for it and receives its assignments from # it; nothing but sandbox runtimes and kubelet probes connect to it. The Pod -# holds no Kubernetes identity of its own: each instance acts only with the +# holds no Kubernetes API identity of its own: each instance acts only with the # credentials the gateway issued for its generation. apiVersion: apps/v1 kind: Deployment @@ -61,6 +61,10 @@ spec: labels: {{- include "openshell.supervisorSelectorLabels" . | nindent 8 }} spec: + # The ServiceAccount has no RBAC bindings. Its projected token, bound to + # this Pod, proves to the gateway that the supervisor token's holder is + # this Pod. + serviceAccountName: {{ $name }} automountServiceAccountToken: false enableServiceLinks: false # A stopping member announces that it is leaving, and the gateway moves @@ -92,6 +96,8 @@ spec: - {{ printf "%s:5501" $listenHost | quote }} - --token-file - /etc/openshell/supervisor-token/token + - --identity-token-file + - /var/run/secrets/openshell-supervisor/token - --runtime-listen - {{ printf "%s:%v" $listenHost (get $shared "runtime_port") | quote }} - --session-root @@ -186,6 +192,9 @@ spec: - name: supervisor-token mountPath: /etc/openshell/supervisor-token readOnly: true + - name: identity + mountPath: /var/run/secrets/openshell-supervisor + readOnly: true {{- if $gatewayTls }} - name: gateway-ca mountPath: /var/run/secrets/openshell-tls @@ -204,6 +213,13 @@ spec: - name: supervisor-token secret: secretName: {{ $name }}-token + - name: identity + projected: + sources: + - serviceAccountToken: + audience: openshell-supervisor + expirationSeconds: 600 + path: token {{- if $gatewayTls }} - name: gateway-ca secret: diff --git a/deploy/helm/openshell/tests/supervisor_test.yaml b/deploy/helm/openshell/tests/supervisor_test.yaml index 717560836c..20f8666d1d 100644 --- a/deploy/helm/openshell/tests/supervisor_test.yaml +++ b/deploy/helm/openshell/tests/supervisor_test.yaml @@ -7,6 +7,7 @@ templates: - templates/supervisor-networkpolicy.yaml - templates/supervisor-token-secret.yaml - templates/supervisor-pdb.yaml + - templates/supervisor-serviceaccount.yaml - templates/gateway-config.yaml release: name: openshell @@ -43,7 +44,7 @@ tests: value: "[::]:5501" documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[8] + path: spec.template.spec.containers[0].args[10] value: "[::]:5500" documentIndex: 0 - notContains: @@ -60,22 +61,22 @@ tests: nat64_prefixes: ["2001:db8:64::/96"] asserts: - equal: - path: spec.template.spec.containers[0].args[11] + path: spec.template.spec.containers[0].args[13] value: --policy-dns-ipv6-egress documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[12] + path: spec.template.spec.containers[0].args[14] value: enabled documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[13] + path: spec.template.spec.containers[0].args[15] value: --nat64-prefix documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[14] + path: spec.template.spec.containers[0].args[16] value: 2001:db8:64::/96 documentIndex: 0 - - it: deploys the supervisor pool without Kubernetes identity in the gateway namespace + - it: deploys the supervisor pool with a Pod identity and no Kubernetes API access in the gateway namespace template: templates/supervisor.yaml set: gatewayConfig: @@ -98,6 +99,9 @@ tests: - hasDocuments: count: 1 template: templates/supervisor-pdb.yaml + - hasDocuments: + count: 1 + template: templates/supervisor-serviceaccount.yaml - equal: path: kind value: Deployment @@ -106,6 +110,28 @@ tests: path: metadata.namespace value: gateway documentIndex: 0 + - equal: + path: spec.template.spec.serviceAccountName + value: openshell-supervisor + documentIndex: 0 + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: identity + mountPath: /var/run/secrets/openshell-supervisor + readOnly: true + documentIndex: 0 + - contains: + path: spec.template.spec.volumes + content: + name: identity + projected: + sources: + - serviceAccountToken: + audience: openshell-supervisor + expirationSeconds: 600 + path: token + documentIndex: 0 - equal: path: spec.replicas value: 1 @@ -128,6 +154,8 @@ tests: - 0.0.0.0:5501 - --token-file - /etc/openshell/supervisor-token/token + - --identity-token-file + - /var/run/secrets/openshell-supervisor/token - --runtime-listen - 0.0.0.0:5500 - --session-root @@ -350,7 +378,7 @@ tests: pattern: 'supervisor_topology = "gateway"' - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - it: runs one replica as a high-availability pool by default template: templates/supervisor.yaml set: @@ -617,7 +645,7 @@ tests: template: templates/supervisor.yaml - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' template: templates/gateway-config.yaml - notMatchRegex: path: data["gateway.toml"] @@ -653,7 +681,7 @@ tests: asserts: - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - matchRegex: path: data["gateway.toml"] pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 128\nmax_members_per_gateway = 32\nrecovery_timeout_secs = 60\n' @@ -693,7 +721,7 @@ tests: pattern: '\[openshell\.gateway\.supervisor_pool\]\n(max_[a-z_]+ = [0-9]+\n)*recovery_timeout_secs = 45\n' - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - it: renders no supervisor pool without the gateway topology template: templates/gateway-config.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index e5ae3b736b..1e614e15d9 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -73,6 +73,10 @@ supervisor: digest: "" # -- Shared supervisor listener IP. Use `::` for IPv6. listenAddress: 0.0.0.0 + # -- Refuse gateway-topology supervisors that attach without their + # pod-bound identity token. Node-topology supervisors always need it. Refer + # to the High Availability guide before enabling it on an upgrade. + requireIdentityToken: false # -- Shared supervisor pool members, used only when gatewayConfig selects # supervisor_topology = "gateway". The gateway always coordinates the shared # supervisor as a high-availability pool: when a member fails or leaves, diff --git a/docs/kubernetes/access-control.mdx b/docs/kubernetes/access-control.mdx index b938c7f5aa..570c62a16a 100644 --- a/docs/kubernetes/access-control.mdx +++ b/docs/kubernetes/access-control.mdx @@ -25,7 +25,8 @@ For how the CLI resolves gateways and stores credentials, refer to [Gateway Auth Kubernetes sandbox supervisors use gateway-issued session JWTs for sandbox-specific RPCs. A dedicated supervisor reads its preissued credential bundle from a mounted Secret. A shared supervisor receives each sandbox's bundle through its assignment -stream, authenticated with a separate supervisor-host JWT. See +stream, authenticated with a separate supervisor-host JWT and a Pod-bound +token for the supervisor's ServiceAccount. See [Getting the first credential](/about/architecture#getting-the-first-credential). The separate `IssueSandboxToken` bootstrap exchange remains available. When used, diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index f2edc2952f..e14c4737a5 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -605,6 +605,17 @@ supervisor: The chart creates the supervisor Deployment and connects it to the gateway. Tune the pool through the top-level `supervisor` values. +Each supervisor authenticates with a gateway-minted supervisor token and a +Pod-bound token for the chart's `-supervisor` ServiceAccount. Allow +only cluster administrators to create Pods that use that ServiceAccount or to +`create` its `serviceaccounts/token` subresource. + +Supervisors from earlier releases send no Pod-bound token, so the gateway +admits a supervisor without one until you set +`supervisor.requireIdentityToken=true`. Set it after an upgrade finishes +rolling every supervisor Pod; from then on, a copy of the token Secret alone +can't attach as a supervisor. + The chart sets no supervisor affinity by default. The example rule places each supervisor replica on a different node, so losing one node leaves another supervisor to take over. Replace `openshell` in `app.kubernetes.io/instance` diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 663494e929..3eca3e4f7a 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1830,6 +1830,7 @@ credential failures. | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | +| A shared supervisor logs `gateway assignment stream failed` with `supervisor identity token is required`, `supervisor identity token is invalid`, a `supervisor identity:` credential refusal, or `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, or it runs as a ServiceAccount other than `shared_supervisor.service_account_name` | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | | OpenShift sandbox pod fails to start (`unable to validate against any security context constraint`) | An explicit sandbox UID/GID override or custom security context conflicts with the namespace's SCC range | Inspect pod events and the namespace's `openshift.io/sa.scc.uid-range` and `openshift.io/sa.scc.supplemental-groups` annotations; remove incompatible `sandbox_uid` / `sandbox_gid` overrides so the driver uses the namespace-assigned identity. Current sandbox pods use `restricted-v2` without a privileged SCC grant; see the [OpenShift guide](https://docs.nvidia.com/openshell/latest/kubernetes/openshift) and [RFC 0012](https://github.com/ai-openshell/openshell/blob/main/rfc/0012-isolation-backend/README.md#motivation). | | OpenShift self-hosted Vault/OpenBao credential store pod never schedules (waits time out with `no matching resources found`) | The store's Helm chart pins `runAsUser`/`fsGroup`/seccomp, which restricted-v2 rejects, so the StatefulSet controller never creates the pod | Deploy the store's chart in its OpenShift mode (`--set global.openshift=true` for the OpenBao/Vault chart) so the namespace SCC assigns a compliant security context — no manual SCC grant needed | | Vault credential driver returns HTTP 403 / `Vault Kubernetes auth denied the configured role` on provider create | Vault's `auth/kubernetes` method or the gateway login role is not provisioned, or the role is not bound to the gateway service account and namespace | In Vault: `bao auth enable kubernetes` and `bao write auth/kubernetes/config kubernetes_host=... kubernetes_ca_cert=@...`; ensure the login role's `bound_service_account_names`/`bound_service_account_namespaces` match the gateway SA and namespace and its policy grants the credential paths | From 3f7b21d77f0b1857aae69f8296ac5c87fe14d378 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 8 Nov 2026 22:48:55 +0200 Subject: [PATCH 03/18] feat(k8s): add the node supervisor topology and node identity Accept supervisor_topology = "node". The gateway records the node that a supervisor's pod identity token proves on HostIdentity, and in the node topology the driver binds pool members to nodes, so the gateway refuses host streams whose pool member ID is not that node. Launches stay refused until node-local placement lands. Signed-off-by: Gal Zaidman --- .../openshell-driver-kubernetes/src/config.rs | 25 ++++--- .../openshell-driver-kubernetes/src/driver.rs | 15 ++++- crates/openshell-server/src/auth/peer.rs | 11 ++++ .../src/auth/supervisor_token.rs | 66 +++++++++++++------ crates/openshell-server/src/multiplex.rs | 1 + crates/openshell-supervisor-control/README.md | 3 +- .../src/controller.rs | 37 ++++++++++- 7 files changed, 124 insertions(+), 34 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 7cb726dc2c..7de2c0bd86 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -220,10 +220,13 @@ where #[serde(rename_all = "snake_case")] pub enum SupervisorTopology { Gateway, + /// One shared supervisor per node, serving the sandboxes whose workload + /// Pods run on that node. + Node, Workspace, } -/// The supervisor Helm deploys for the gateway topology. +/// The supervisor Helm deploys for the gateway or node topology. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SharedSupervisorConfig { @@ -705,16 +708,23 @@ impl KubernetesComputeConfig { match self.supervisor_topology { None => { if self.shared_supervisor.is_some() { - return Err("shared_supervisor requires supervisor_topology=gateway".into()); + return Err( + "shared_supervisor requires supervisor_topology=gateway or node".into(), + ); } Ok(()) } Some(SupervisorTopology::Workspace) => { Err("supervisor_topology=workspace is not implemented".into()) } - Some(SupervisorTopology::Gateway) => { + Some(topology @ (SupervisorTopology::Gateway | SupervisorTopology::Node)) => { + let topology_name = if topology == SupervisorTopology::Node { + "node" + } else { + "gateway" + }; let shared = self.shared_supervisor.as_ref().ok_or_else(|| { - "supervisor_topology=gateway requires shared_supervisor".to_string() + format!("supervisor_topology={topology_name} requires shared_supervisor") })?; shared.validate()?; if self.sandbox_runtime.app_listener.common.enabled @@ -726,10 +736,9 @@ impl KubernetesComputeConfig { || self.proxy_auth_secret_name.is_some() || self.proxy_ca_bundle.is_some() { - return Err( - "supervisor_topology=gateway does not support upstream proxy settings" - .into(), - ); + return Err(format!( + "supervisor_topology={topology_name} does not support upstream proxy settings" + )); } Ok(()) } diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index f77e7437c0..8b7a642895 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -6,8 +6,8 @@ use crate::config::{ DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, DEFAULT_SANDBOX_UID, DEFAULT_WORKSPACE_STORAGE_SIZE, KubernetesComputeConfig, KubernetesControlConnection, OperatorNamespaceAllowlist, - WorkspaceMode, is_dns_1123_label, managed_namespace, managed_namespace_prefix, - validate_managed_namespace_name, + SupervisorTopology, WorkspaceMode, is_dns_1123_label, managed_namespace, + managed_namespace_prefix, validate_managed_namespace_name, }; use crate::isolation::{ BOUNDARY_PAIR_LABEL, BOUNDARY_ROLE_LABEL, KubernetesControlPath, @@ -1344,14 +1344,18 @@ impl KubernetesComputeDriver { .zip(supervision.clone()) .map(|(config, supervision)| SharedSupervisor::new(config, supervision)); if let Some(shared) = &shared_supervisor { + let node_topology = config.supervisor_topology == Some(SupervisorTopology::Node); shared .supervision() .controller() .require_host_identity(HostAccount { namespace: shared.config().service_namespace.clone(), service_account: shared.config().service_account_name.clone(), - identity_required: shared.config().require_identity_token, + identity_required: shared.config().require_identity_token || node_topology, }); + if node_topology { + shared.supervision().controller().bind_members_to_nodes(); + } shared.spawn_token_secret_writer(client.clone(), shutdown_rx.clone()); } if shared_supervisor.is_some() && !config.supervisor_otlp.is_empty() { @@ -4178,6 +4182,11 @@ impl KubernetesComputeDriver { .map_err(KubernetesDriverError::from_kube)?; } GenerationLaunchTarget::Shared { shared, route, .. } => { + if self.config.supervisor_topology == Some(SupervisorTopology::Node) { + return Err(KubernetesDriverError::Precondition( + "supervisor_topology=node cannot launch sandboxes yet: placement on the workload node's supervisor is not implemented".to_string(), + )); + } self.create_generation_image_pull_secrets( namespace, names, diff --git a/crates/openshell-server/src/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index bf6244a63f..f480f8fb1d 100644 --- a/crates/openshell-server/src/auth/peer.rs +++ b/crates/openshell-server/src/auth/peer.rs @@ -55,6 +55,8 @@ const POD_UID_EXTRA: &str = "authentication.kubernetes.io/pod-uid"; pub struct ResolvedGatewayPeerIdentity { pub pod_name: String, pub pod_uid: String, + /// `spec.nodeName` of the live Pod; `None` while it is unscheduled. + pub node_name: Option, } #[async_trait] @@ -279,9 +281,15 @@ impl GatewayPeerIdentityResolver for LiveGatewayPeerResolver { "validated gateway peer ServiceAccount token via TokenReview" ); + let node_name = pod + .spec + .as_ref() + .and_then(|spec| spec.node_name.clone()) + .filter(|node| !node.is_empty()); Ok(Some(ResolvedGatewayPeerIdentity { pod_name: identity.pod_name, pod_uid: identity.pod_uid, + node_name, })) } } @@ -820,6 +828,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, }, )))); let auth = PeerServiceAccountAuthenticator::new(resolver); @@ -844,6 +853,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, }, )))); let auth = PeerServiceAccountAuthenticator::new(resolver.clone()); @@ -875,6 +885,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, } } diff --git a/crates/openshell-server/src/auth/supervisor_token.rs b/crates/openshell-server/src/auth/supervisor_token.rs index 651ffec7da..9f7e908cad 100644 --- a/crates/openshell-server/src/auth/supervisor_token.rs +++ b/crates/openshell-server/src/auth/supervisor_token.rs @@ -62,9 +62,14 @@ impl SupervisorTokenAuthenticator { self } - /// Resolved only after the supervisor token verified, so callers without - /// it can't trigger a `TokenReview`. - async fn resolve_identity(&self, headers: &http::HeaderMap) -> Result<(), AuthRejection> { + /// The node the supervisor's Pod runs on, or `None` for a supervisor + /// that sent no identity token where none is required. Resolved only + /// after the supervisor token verified, so callers without it can't + /// trigger a `TokenReview`. + async fn resolve_identity( + &self, + headers: &http::HeaderMap, + ) -> Result, AuthRejection> { let refuse = |reason, message: &str| { AuthRejection::new( AuthMechanism::SupervisorToken, @@ -89,9 +94,9 @@ impl SupervisorTokenAuthenticator { "supervisor identity token is required", )); } - return Ok(()); + return Ok(None); }; - resolver + let identity = resolver .resolve(token) .await .map_err(|rejection| { @@ -104,13 +109,18 @@ impl SupervisorTokenAuthenticator { ), ) })? - .map(|_| ()) .ok_or_else(|| { refuse( AuthFailureReason::InvalidCredential, "supervisor identity token is invalid", ) - }) + })?; + identity.node_name.map(Some).ok_or_else(|| { + refuse( + AuthFailureReason::InvalidCredential, + "supervisor identity token names an unscheduled pod", + ) + }) } } @@ -139,13 +149,14 @@ impl Authenticator for SupervisorTokenAuthenticator { return Ok(Authentication::NotApplicable); } let authenticated = self.authority.verify_supervisor_token(token)?; - self.resolve_identity(headers).await?; + let node = self.resolve_identity(headers).await?; Ok(Authentication::Accepted(Principal::Supervisor( SupervisorPrincipal { identity: HostIdentity { subject: authenticated.subject, token_id: authenticated.token_id.to_string(), expires_at: authenticated.expires_at, + node, }, }, ))) @@ -191,17 +202,19 @@ mod tests { headers } - fn resolving() -> Arc { + fn resolving(node_name: Option<&str>) -> Arc { Arc::new(FakeGatewayPeerResolver::returning(Ok(Some( crate::auth::peer::ResolvedGatewayPeerIdentity { pod_name: "openshell-supervisor-abc".to_string(), pod_uid: "uid".to_string(), + node_name: node_name.map(ToString::to_string), }, )))) } fn accepting(gateway: Arc) -> SupervisorTokenAuthenticator { - SupervisorTokenAuthenticator::new(gateway).with_identity_resolver(resolving(), true) + SupervisorTokenAuthenticator::new(gateway) + .with_identity_resolver(resolving(Some("node-a")), true) } #[tokio::test] @@ -224,6 +237,7 @@ mod tests { ); assert_eq!(supervisor.identity.token_id, minted.token_id.to_string()); assert_eq!(supervisor.identity.expires_at, minted.expires_at); + assert_eq!(supervisor.identity.node.as_deref(), Some("node-a")); } other => panic!("unexpected outcome {other:?}"), } @@ -290,7 +304,7 @@ mod tests { let minted = gateway .mint_supervisor_token(Duration::from_mins(15)) .unwrap(); - let resolver = resolving(); + let resolver = resolving(Some("node-a")); let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) .with_identity_resolver(resolver.clone(), true); @@ -310,17 +324,20 @@ mod tests { assert_eq!(missing.reason, AuthFailureReason::MissingCredential); assert_eq!(missing.status.code(), tonic::Code::Unauthenticated); - // Unless required, a supervisor without an identity token attaches, - // but one it sends is still verified. + // Unless required, a supervisor without an identity token attaches + // with no node, but one it sends is still verified. let optional = SupervisorTokenAuthenticator::new(gateway.clone()) .with_identity_resolver(resolver.clone(), false); - assert!(matches!( - optional - .authenticate(&headers(minted.token.expose_secret()), ATTACH) - .await - .unwrap(), - Authentication::Accepted(_) - )); + match optional + .authenticate(&headers(minted.token.expose_secret()), ATTACH) + .await + .unwrap() + { + Authentication::Accepted(Principal::Supervisor(supervisor)) => { + assert_eq!(supervisor.identity.node, None); + } + other => panic!("unexpected outcome {other:?}"), + } assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 1); assert!( SupervisorTokenAuthenticator::new(gateway.clone()) @@ -360,12 +377,19 @@ mod tests { .expect_err("a gateway without a supervisor account accepts no supervisor"); assert_eq!(unconfigured.reason, AuthFailureReason::InvalidCredential); - let unknown = SupervisorTokenAuthenticator::new(gateway) + let unknown = SupervisorTokenAuthenticator::new(gateway.clone()) .with_identity_resolver(Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), true) .authenticate(&headers, ATTACH) .await .expect_err("an identity token for another account must be refused"); assert_eq!(unknown.reason, AuthFailureReason::InvalidCredential); assert_eq!(unknown.status.code(), tonic::Code::Unauthenticated); + + let unscheduled = SupervisorTokenAuthenticator::new(gateway) + .with_identity_resolver(resolving(None), true) + .authenticate(&headers, ATTACH) + .await + .expect_err("an unscheduled pod proves no node"); + assert_eq!(unscheduled.mechanism, AuthMechanism::SupervisorToken); } } diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 7b81cce23b..d3389dd574 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -3900,6 +3900,7 @@ mod tests { subject: "openshell-supervisor:test".to_string(), token_id: "token".to_string(), expires_at: i64::MAX, + node: None, }, }); let supervisor_chain = || { diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index 15d83e0ae5..ceaa2ac9c2 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -22,7 +22,8 @@ re-implementing the control contracts. `HOST_IDENTITY_TOKEN_HEADER` with `SUPERVISOR_IDENTITY_TOKEN_AUDIENCE`, prove that a supervisor token's holder is a supervisor Pod; `HostAccount.identity_required` refuses a supervisor token without one. - One session per + After `bind_members_to_nodes`, a supervisor's member ID must also be the + node its identity token proves (`HostIdentity.node`). One session per member: a newer connection epoch of the same member process or a new process of the member supersedes its stream, a delayed older hello is refused, and reports from superseded streams, acks of revisions never sent, regressing acks, diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 793d4dab5a..01c1c8c586 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -30,7 +30,7 @@ //! at once. use std::collections::{BTreeMap, BTreeSet}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -83,6 +83,8 @@ pub struct HostIdentity { /// `exp` of the supervisor token (Unix seconds). The gateway ends the /// stream when it passes; the host reconnects with a renewed token. pub expires_at: i64, + /// Node the host's identity token proves its Pod runs on. + pub node: Option, } /// Metadata header carrying a host's pod-bound projected `ServiceAccount` @@ -368,6 +370,8 @@ struct Inner { gateway_replicas: AtomicUsize, /// Set by [`SupervisorHostController::require_host_identity`]. supervisor_account: Mutex>, + /// Set by [`SupervisorHostController::bind_members_to_nodes`]. + members_bound_to_nodes: AtomicBool, } /// The Kubernetes `ServiceAccount` whose pod-bound tokens prove that a @@ -432,6 +436,7 @@ impl SupervisorHostController { limits: Mutex::new(PoolLimits::default()), gateway_replicas: AtomicUsize::new(1), supervisor_account: Mutex::new(None), + members_bound_to_nodes: AtomicBool::new(false), }), } } @@ -475,6 +480,20 @@ impl SupervisorHostController { lock(&self.inner.supervisor_account).clone() } + /// Accept only supervisors whose pool member ID is the node their + /// identity token proves. Call it before any host attaches. + pub fn bind_members_to_nodes(&self) { + self.inner + .members_bound_to_nodes + .store(true, Ordering::Relaxed); + } + + /// Whether [`Self::bind_members_to_nodes`] was called. + #[must_use] + pub fn members_bound_to_nodes(&self) -> bool { + self.inner.members_bound_to_nodes.load(Ordering::Relaxed) + } + /// Tell attaching hosts to dial their sandbox sessions to `peer_endpoint`. /// Call it before any host attaches. pub fn set_peer_endpoint(&self, peer_endpoint: String) { @@ -967,6 +986,9 @@ impl SupervisorHostController { return Err(Status::failed_precondition(MISSING_MEMBER)); }; validate_member(member).map_err(Status::invalid_argument)?; + if self.members_bound_to_nodes() { + validate_node(identity.node.as_deref(), &member.member_id)?; + } let member_id = member.member_id.clone(); let (tx, rx) = mpsc::channel(OUTBOUND_QUEUE); let home = home(&member_id, hello.accepts_redirect); @@ -1442,6 +1464,18 @@ pub fn redirect(peer_endpoint: String) -> HostGatewayMessage { } } +/// A node supervisor's member ID is its node name, so the node its token +/// proves must be that member. +fn validate_node(node: Option<&str>, member_id: &str) -> Result<(), Status> { + if node == Some(member_id) { + Ok(()) + } else { + Err(Status::permission_denied( + "the shared supervisor's pool member id is not the node its identity token proves", + )) + } +} + /// Check a pool member's identity, naming the setting that is wrong. fn validate_member(member: &PoolMember) -> Result<(), &'static str> { let valid = |value: &str| { @@ -1654,6 +1688,7 @@ mod tests { subject: "openshell-supervisor:test".to_string(), token_id: "token".to_string(), expires_at: i64::MAX, + node: None, } } From 1e7b22aae29ba4ef00eca27ddd86c0d443ea9769 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 8 Nov 2026 23:00:26 +0200 Subject: [PATCH 04/18] feat(k8s): pin node-topology instances to their node supervisor Carry the pool member through SharedSupervision::launch, PlacementRequest, the stored assignment record, and recovery, and restrict launch, takeover, and unowned placement of a pinned instance to that member. With members bound to nodes, the pool never places an unpinned instance: one launched under the gateway topology stays where it is until the recovery timeout ends it. In the node topology the Kubernetes driver ungates the workload Pod, waits for the scheduler to bind it, launches on that node's supervisor, records the member on the Sandbox resource for recovery, and creates the bootstrap Secret last. Supervisors started with --node-supervisor (OPENSHELL_SUPERVISOR_NODE) no longer leave the pool on shutdown, and a suspended generation forgets its member. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 23 ++ .../openshell-driver-kubernetes/src/driver.rs | 234 ++++++++++++++--- .../src/prepared_runtime/tests.rs | 2 +- .../src/shared_supervisor.rs | 4 + .../src/warm_pool/tests.rs | 6 +- .../openshell-server/src/supervisor_pool.rs | 242 +++++++++++++++--- .../src/supervisor_pool/prepared.rs | 3 + .../src/supervisor_pool/prepared_tests.rs | 2 + .../src/controller.rs | 3 +- .../src/coordinator.rs | 36 ++- crates/openshell-supervisor/README.md | 11 +- crates/openshell-supervisor/src/main.rs | 7 + crates/openshell-supervisor/src/shared.rs | 8 +- 13 files changed, 496 insertions(+), 85 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 7992ea8c78..f258523b1b 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -476,6 +476,29 @@ When the setting is removed, reconciliation suspends shared generations, and a restart creates the dedicated generation's boundary Service the shared one never had. +#### Node topology + +`supervisor_topology = "node"` runs the same shared pool with one supervisor +per node, and pins each generation to the supervisor on its workload's node. +The driver binds pool members to nodes (`bind_members_to_nodes`): the gateway +accepts a supervisor only when the Pod its identity token resolves to is +scheduled on the node it claims as its pool member ID. + +- **Placement.** The driver removes the scheduling gate before it assigns the + instance and waits up to 60 seconds for the scheduler to bind the workload + Pod to a node. A Pod that is deleted or replaced while it waits fails the + launch. The node name is the pinned member: it travels in the placement + request, the gateway's assignment record, and the + `openshell.ai/sandbox-runtime-supervisor-member` annotation on the Sandbox + resource. The workload cannot start before its bootstrap Secret exists, so + the driver creates the Secret last, and the kubelet reports a `FailedMount` + Warning for it until then. +- **Recovery and takeover.** Recovery reads the member annotation and skips a + node-topology generation that lacks one. Placement, takeover, and recovery + of a pinned instance only consider its own member, so a lost node + supervisor's instances wait for it to return. A restart clears the + annotation, and the new generation records its own node. + ## Sandbox Resource The driver works with the `agents.x-k8s.io` `Sandbox` custom resource. It diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 8b7a642895..53246e8440 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -23,8 +23,8 @@ use crate::sandbox_runtime::{ shared_instance_secret, supervisor_bootstrap_secret, supervisor_pod, workload_fence, }; use crate::shared_supervisor::{ - ANNOTATION_SUPERVISOR_SESSION, ANNOTATION_SUPERVISOR_TOPOLOGY, GATEWAY_TOPOLOGY, - SharedSupervisor, SupervisorPlacement, supervisor_placement, + ANNOTATION_SUPERVISOR_MEMBER, ANNOTATION_SUPERVISOR_SESSION, ANNOTATION_SUPERVISOR_TOPOLOGY, + GATEWAY_TOPOLOGY, SharedSupervisor, SupervisorPlacement, supervisor_placement, }; use futures::{Stream, StreamExt, TryStreamExt}; use k8s_openapi::api::authentication::v1::{ @@ -4016,6 +4016,25 @@ impl KubernetesComputeDriver { let workload_pod_name = workload_pod.metadata.name.clone().ok_or_else(|| { KubernetesDriverError::Message("workload Pod has no name".to_string()) })?; + // A node supervisor serves only its own node, so the scheduler picks + // the node first. The missing bootstrap Secret keeps the ungated Pod + // from running until the launch is placed. + let node_member = if matches!(target, GenerationLaunchTarget::Shared { .. }) + && self.config.supervisor_topology == Some(SupervisorTopology::Node) + { + remove_scheduling_gates(&pods, &workload_pod_name).await?; + Some( + wait_for_workload_node( + &pods, + &workload_pod_name, + &workload_pod_uid, + NODE_SCHEDULING_TIMEOUT, + ) + .await?, + ) + } else { + None + }; let mut annotations = serde_json::json!({ ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_pod_uid.clone(), ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID: fence_uid.clone(), @@ -4024,6 +4043,9 @@ impl KubernetesComputeDriver { if let GenerationLaunchTarget::Dedicated { pod_uid, .. } = &target { annotations[ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID] = pod_uid.clone().into(); } + if let Some(member) = &node_member { + annotations[ANNOTATION_SUPERVISOR_MEMBER] = member.clone().into(); + } if let Some(policy) = target.control_policy() { annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_UID] = policy.uid.clone().into(); annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_GENERATION] = @@ -4129,10 +4151,12 @@ impl KubernetesComputeDriver { workload_owner.clone(), ); let secrets = Api::::namespaced(self.client.clone(), namespace); - secrets - .create(&PostParams::default(), &sandbox_secret) - .await - .map_err(KubernetesDriverError::from_kube)?; + if node_member.is_none() { + secrets + .create(&PostParams::default(), &sandbox_secret) + .await + .map_err(KubernetesDriverError::from_kube)?; + } match &target { GenerationLaunchTarget::Dedicated { pod_uid, .. } => { let descriptor = provisioned @@ -4182,11 +4206,6 @@ impl KubernetesComputeDriver { .map_err(KubernetesDriverError::from_kube)?; } GenerationLaunchTarget::Shared { shared, route, .. } => { - if self.config.supervisor_topology == Some(SupervisorTopology::Node) { - return Err(KubernetesDriverError::Precondition( - "supervisor_topology=node cannot launch sandboxes yet: placement on the workload node's supervisor is not implemented".to_string(), - )); - } self.create_generation_image_pull_secrets( namespace, names, @@ -4209,22 +4228,26 @@ impl KubernetesComputeDriver { // the host without waiting for the runtime. shared .supervision() - .launch(®istration, |launch_material| async { - secrets - .create( - &PostParams::default(), - &shared_instance_secret( - namespace, - names, - sandbox_id, - launch_material, - instance_owner, - ), - ) - .await - .map(|_| ()) - .map_err(KubernetesDriverError::from_kube) - }) + .launch( + ®istration, + node_member.as_deref(), + |launch_material| async { + secrets + .create( + &PostParams::default(), + &shared_instance_secret( + namespace, + names, + sandbox_id, + launch_material, + instance_owner, + ), + ) + .await + .map(|_| ()) + .map_err(KubernetesDriverError::from_kube) + }, + ) .await .map_err(|error| match error { LaunchError::Persist(error) => error, @@ -4243,13 +4266,14 @@ impl KubernetesComputeDriver { })?; } } - pods.patch( - &workload_pod_name, - &PatchParams::default(), - &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), - ) - .await - .map_err(KubernetesDriverError::from_kube)?; + if node_member.is_some() { + secrets + .create(&PostParams::default(), &sandbox_secret) + .await + .map_err(KubernetesDriverError::from_kube)?; + } else { + remove_scheduling_gates(&pods, &workload_pod_name).await?; + } patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) }) @@ -4721,6 +4745,8 @@ impl KubernetesComputeDriver { ANNOTATION_SANDBOX_RUNTIME_CONTROL_GENERATION: generation.as_str(), ANNOTATION_SUPERVISOR_TOPOLOGY: topology, ANNOTATION_SUPERVISOR_SESSION: instance_route, + // The new generation records its own node once scheduled. + ANNOTATION_SUPERVISOR_MEMBER: serde_json::Value::Null, }); running_patch["spec"]["podTemplate"]["spec"] = restart_pod_template_spec( &volumes, @@ -5513,9 +5539,17 @@ impl KubernetesComputeDriver { .namespace .clone() .unwrap_or_else(|| self.config.namespace.clone()); + let member = object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_SUPERVISOR_MEMBER)) + .filter(|member| !member.is_empty()) + .cloned(); Some(RecoverableInstance { route, sandbox_id: sandbox_id.clone(), + member, record: SharedInstanceSecretRecord { namespace, sandbox_id, @@ -7732,6 +7766,61 @@ const SANDBOX_POD_UID_PATH: &str = "/.openshell/pod-identity/uid"; const SANDBOX_PROXY_CA_VOLUME_NAME: &str = "openshell-run"; const SANDBOX_PROXY_CA_MOUNT_PATH: &str = "/run"; const SANDBOX_BOOTSTRAP_SCHEDULING_GATE: &str = "openshell.ai/bootstrap"; +/// Longest wait for the scheduler to bind a node-topology workload Pod. +const NODE_SCHEDULING_TIMEOUT: Duration = Duration::from_mins(1); +const NODE_SCHEDULING_POLL: Duration = Duration::from_millis(500); + +async fn remove_scheduling_gates(pods: &Api, name: &str) -> Result<(), KubernetesDriverError> { + pods.patch( + name, + &PatchParams::default(), + &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), + ) + .await + .map(drop) + .map_err(KubernetesDriverError::from_kube) +} + +/// The node the scheduler bound workload Pod `name` (UID `uid`) to. Fails +/// when it isn't bound within `timeout` or the Pod is gone or replaced. +async fn wait_for_workload_node( + pods: &Api, + name: &str, + uid: &str, + timeout: Duration, +) -> Result { + let wait = async { + loop { + let pod = tokio::time::timeout(KUBE_API_TIMEOUT, pods.get_opt(name)) + .await + .map_err(|_| { + KubernetesDriverError::Message("timed out reading the workload Pod".to_string()) + })? + .map_err(KubernetesDriverError::from_kube)? + .filter(|pod| pod.metadata.uid.as_deref() == Some(uid)) + .ok_or_else(|| { + KubernetesDriverError::Precondition( + "the workload Pod was deleted or replaced before it was scheduled" + .to_string(), + ) + })?; + if let Some(node) = pod + .spec + .and_then(|spec| spec.node_name) + .filter(|node| !node.is_empty()) + { + return Ok(node); + } + tokio::time::sleep(NODE_SCHEDULING_POLL).await; + } + }; + tokio::time::timeout(timeout, wait).await.map_err(|_| { + KubernetesDriverError::Precondition(format!( + "the workload Pod was not scheduled within {} s; no node may have room for it", + timeout.as_secs() + )) + })? +} fn sandbox_bootstrap_secret_name(spec: &serde_json::Value) -> Option<&str> { spec["volumes"] @@ -9250,6 +9339,7 @@ fn sandbox_runtime_suspension_completion_patch(resource_version: &str) -> serde_ ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID: serde_json::Value::Null, ANNOTATION_SUPERVISOR_TOPOLOGY: serde_json::Value::Null, ANNOTATION_SUPERVISOR_SESSION: serde_json::Value::Null, + ANNOTATION_SUPERVISOR_MEMBER: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_GENERATION: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", @@ -9994,6 +10084,73 @@ mod tests { ) } + type QueuedResponses = Arc>>>; + + fn pod_api_answering( + responses: Vec>, + ) -> (Api, QueuedResponses) { + let responses = Arc::new(std::sync::Mutex::new(VecDeque::from(responses))); + let remaining = responses.clone(); + let service = tower::service_fn(move |request: http::Request| { + let responses = remaining.clone(); + async move { + assert_eq!(request.method(), http::Method::GET); + assert_eq!( + request.uri().path(), + "/api/v1/namespaces/openshell/pods/workload" + ); + let response = responses + .lock() + .unwrap() + .pop_front() + .expect("unexpected Kubernetes API request"); + Ok::<_, std::convert::Infallible>(response) + } + }); + let client = Client::new(service, "openshell"); + (Api::namespaced(client, "openshell"), responses) + } + + fn workload_pod_json(uid: &str, node: Option<&str>) -> http::Response { + kube_test_response( + http::StatusCode::OK, + serde_json::json!({ + "apiVersion": "v1", + "kind": "Pod", + "metadata": {"name": "workload", "namespace": "openshell", "uid": uid}, + "spec": {"containers": [], "nodeName": node}, + }), + ) + } + + #[tokio::test(start_paused = true)] + async fn node_topology_waits_for_the_scheduler_to_bind_the_workload() { + let (pods, remaining) = pod_api_answering(vec![ + workload_pod_json("uid-1", None), + workload_pod_json("uid-1", Some("node-a")), + ]); + let node = wait_for_workload_node(&pods, "workload", "uid-1", NODE_SCHEDULING_TIMEOUT) + .await + .unwrap(); + assert_eq!(node, "node-a"); + assert!(remaining.lock().unwrap().is_empty()); + + // A replaced Pod is not the one this launch validated. + let (pods, _) = pod_api_answering(vec![workload_pod_json("uid-2", Some("node-a"))]); + let error = wait_for_workload_node(&pods, "workload", "uid-1", NODE_SCHEDULING_TIMEOUT) + .await + .unwrap_err(); + assert!(error.to_string().contains("replaced"), "{error}"); + + // An unschedulable Pod fails the launch once the wait runs out. + let (pods, _) = + pod_api_answering((0..8).map(|_| workload_pod_json("uid-1", None)).collect()); + let error = wait_for_workload_node(&pods, "workload", "uid-1", Duration::from_secs(2)) + .await + .unwrap_err(); + assert!(error.to_string().contains("not scheduled"), "{error}"); + } + fn network_trust_bundle(gateway_id: &str, digest: &str) -> NetworkSupervisorTrustBundle { NetworkSupervisorTrustBundle::new( b"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n".to_vec(), @@ -10681,12 +10838,9 @@ mod tests { let annotations = &patch["metadata"]["annotations"]; assert!(annotations[ANNOTATION_SUPERVISOR_TOPOLOGY].is_null()); assert!(annotations[ANNOTATION_SUPERVISOR_SESSION].is_null()); - assert!( - annotations - .as_object() - .unwrap() - .contains_key(ANNOTATION_SUPERVISOR_SESSION) - ); + for key in [ANNOTATION_SUPERVISOR_SESSION, ANNOTATION_SUPERVISOR_MEMBER] { + assert!(annotations.as_object().unwrap().contains_key(key), "{key}"); + } } #[test] diff --git a/crates/openshell-driver-kubernetes/src/prepared_runtime/tests.rs b/crates/openshell-driver-kubernetes/src/prepared_runtime/tests.rs index 61dbb25ad8..71596d0db2 100644 --- a/crates/openshell-driver-kubernetes/src/prepared_runtime/tests.rs +++ b/crates/openshell-driver-kubernetes/src/prepared_runtime/tests.rs @@ -156,7 +156,7 @@ impl InstancePlacement for Placement { fn recorded(&self) -> PlacementFuture> { panic!("recovery") } - fn record_recovered(&self, _: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered(&self, _: SandboxInstanceAssignment, _: Option) -> PlacementFuture { panic!("recovery") } } diff --git a/crates/openshell-driver-kubernetes/src/shared_supervisor.rs b/crates/openshell-driver-kubernetes/src/shared_supervisor.rs index 850e261e34..9c92f07a2d 100644 --- a/crates/openshell-driver-kubernetes/src/shared_supervisor.rs +++ b/crates/openshell-driver-kubernetes/src/shared_supervisor.rs @@ -35,6 +35,10 @@ pub const ANNOTATION_SUPERVISOR_TOPOLOGY: &str = "openshell.ai/sandbox-runtime-s /// annotation key keeps its established `-session` name. pub const ANNOTATION_SUPERVISOR_SESSION: &str = "openshell.ai/sandbox-runtime-supervisor-session"; pub const GATEWAY_TOPOLOGY: &str = "gateway"; +/// Pool member, the node name, that alone may supervise a node-topology +/// generation. Recovery reads it from the Sandbox resource, since the +/// workload Pod may be gone. +pub const ANNOTATION_SUPERVISOR_MEMBER: &str = "openshell.ai/sandbox-runtime-supervisor-member"; /// Key of the supervisor token in `shared_supervisor.token_secret_name`. pub const TOKEN_SECRET_KEY: &str = "token"; /// Annotation recording the token's expiry (Unix seconds) for operators. diff --git a/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs b/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs index 0dd1b7f970..87829c18b2 100644 --- a/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs +++ b/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs @@ -511,7 +511,7 @@ impl InstancePlacement for Placement { fn recorded(&self) -> PlacementFuture> { panic!("unexpected recovery") } - fn record_recovered(&self, _: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered(&self, _: SandboxInstanceAssignment, _: Option) -> PlacementFuture { panic!("unexpected recovery") } } @@ -779,6 +779,8 @@ fn fixture(state: Arc>) -> KubernetesComputeDriver { service_namespace: "openshell".into(), runtime_port: 5500, token_secret_name: "token".into(), + service_account_name: "supervisor".into(), + require_identity_token: false, }; let config = KubernetesComputeConfig { namespace: "openshell".into(), @@ -930,7 +932,7 @@ impl InstancePlacement for ApiTestPlacement { fn recorded(&self) -> PlacementFuture> { panic!("unexpected recovery") } - fn record_recovered(&self, _: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered(&self, _: SandboxInstanceAssignment, _: Option) -> PlacementFuture { panic!("unexpected recovery") } } diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index b6259fda95..a291231e3c 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -296,6 +296,9 @@ struct AssignmentPayload { /// Gateway CREATE owning this reservation, captured in the claim CAS. #[serde(default, skip_serializing_if = "Option::is_none")] claim_operation_id: Option, + /// The pinned member, as [`PlacementRequest::member`] describes. + #[serde(default, skip_serializing_if = "Option::is_none")] + member_id: Option, } #[derive(Debug, Clone)] @@ -650,7 +653,8 @@ fn ring_of(members: &[LiveMember]) -> GatewayRing { /// Only members with fewer than `max_instances` routes, or already charged /// for this one, are listed; the owner change itself re-checks room /// atomically. `charges` counts the routes each member is charged for and -/// lists them. +/// lists them. With `pinned`, only that member is listed. +#[allow(clippy::too_many_arguments)] fn candidates<'a>( ring: &GatewayRing, members: &'a [LiveMember], @@ -659,12 +663,14 @@ fn candidates<'a>( charges: &BTreeMap>, same: Option<&str>, max_instances: usize, + pinned: Option<&str>, ) -> Vec<&'a LiveMember> { use std::hash::{Hash as _, Hasher as _}; let routes_of = |member: &LiveMember| charges.get(&member.member_id); let has_room = |member: &&LiveMember| { - !member.leaving + pinned.is_none_or(|pinned| member.member_id == pinned) + && !member.leaving && routes_of(member) .is_none_or(|routes| routes.contains(route) || routes.len() < max_instances) }; @@ -1720,8 +1726,9 @@ impl SupervisorPool { async fn record_assignment( &self, assignment: &SandboxInstanceAssignment, + member: Option<&str>, ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Published) + self.record_assignment_as(assignment, RecordPhase::Published, member) .await .map(|recording| recording.record) } @@ -1731,8 +1738,9 @@ impl SupervisorPool { async fn record_admitting( &self, assignment: &SandboxInstanceAssignment, + member: Option<&str>, ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Admitting) + self.record_assignment_as(assignment, RecordPhase::Admitting, member) .await } @@ -1744,14 +1752,17 @@ impl SupervisorPool { &self, assignment: &SandboxInstanceAssignment, phase: RecordPhase, + member: Option<&str>, ) -> Result { - self.record_assignment_scoped(assignment, phase, None).await + self.record_assignment_scoped(assignment, phase, member, None) + .await } async fn record_assignment_scoped( &self, assignment: &SandboxInstanceAssignment, phase: RecordPhase, + member: Option<&str>, preparation: Option<(&str, u64, &str)>, ) -> Result { let read = |error: PersistenceError| format!("read supervisor pool instance: {error}"); @@ -1843,6 +1854,7 @@ impl SupervisorPool { claim_handle: Vec::new(), pool_id: preparation.map(|(_, _, pool_id)| pool_id.to_string()), claim_operation_id: None, + member_id: member.map(str::to_string), }; let id = assignment_object_id(&payload.route, &payload.writer); let encode = |payload: &AssignmentPayload| { @@ -2247,6 +2259,7 @@ impl SupervisorPool { return Err("no shared supervisor replica is attached to the gateway".to_string()); } let ring = ring_of(&members); + let pinned = request.member.as_deref(); let max_instances = self.max_instances_per_member(); let targets = candidates( &ring, @@ -2260,10 +2273,20 @@ impl SupervisorPool { &charges, None, max_instances, + pinned, ); let no_room = || { - warn!(max_instances, "every supervisor is at its sandbox limit"); - CAPACITY_REACHED.to_string() + pinned.map_or_else( + || { + warn!(max_instances, "every supervisor is at its sandbox limit"); + CAPACITY_REACHED.to_string() + }, + |member| { + format!( + "the shared supervisor {member:?} is not attached or has no room for another sandbox" + ) + }, + ) }; if targets.is_empty() { return Err(no_room()); @@ -2272,11 +2295,12 @@ impl SupervisorPool { self.record_assignment_scoped( assignment, RecordPhase::Admitting, + pinned, preparation.map(|(workspace, pool)| (workspace, request.auth_epoch, pool)), ) .await? } else { - self.record_admitting(assignment).await? + self.record_admitting(assignment, pinned).await? }; if assignment.prepared && self.load_material(&recording.record.payload).await? != assignment.launch_material @@ -2525,8 +2549,15 @@ impl SupervisorPool { } match failure { Ok(Some(cause)) if takeovers_allowed => { - self.take_over(record, cause, &ring, &members, &charges) - .await + self.take_over( + record, + cause, + &ring, + &members, + &charges, + instance.payload.member_id.as_deref(), + ) + .await } Ok(_) => Ok(Reconciled::Unchanged), Err(error) => Err(error), @@ -2946,6 +2977,13 @@ impl SupervisorPool { if unowned_for.is_none_or(|elapsed| elapsed < self.unowned_grace) { return Ok(Reconciled::Unchanged); } + if self.refuses_unpinned(assignment.member_id.as_deref()) { + warn!( + route, + "refusing to place an instance without a node pin under supervisor_topology=node; restart the sandbox" + ); + return Ok(Reconciled::Unchanged); + } let targets = candidates( ring, members, @@ -2954,6 +2992,7 @@ impl SupervisorPool { charges, None, self.max_instances_per_member(), + assignment.member_id.as_deref(), ); if targets.is_empty() { return Ok(Reconciled::Unchanged); @@ -3028,8 +3067,16 @@ impl SupervisorPool { Ok(takeover_cause(owner, member.as_ref())) } + /// Whether an unpinned instance (launched under the gateway topology) + /// must stay put. With members bound to nodes, it would reach another + /// node's supervisor with its launch material, so it waits until the + /// recovery timeout ends it. + fn refuses_unpinned(&self, member: Option<&str>) -> bool { + member.is_none() && self.controller.members_bound_to_nodes() + } + /// Move an instance whose owner failed or left, for `cause`, to the - /// ring's choice. + /// ring's choice, or only to `pinned` when the instance is pinned. async fn take_over( &self, record: &OwnerRecord, @@ -3037,7 +3084,15 @@ impl SupervisorPool { ring: &GatewayRing, members: &[LiveMember], charges: &BTreeMap>, + pinned: Option<&str>, ) -> Result { + if self.refuses_unpinned(pinned) { + warn!( + route = %record.payload.route, + "refusing to take over an instance without a node pin under supervisor_topology=node; restart the sandbox" + ); + return Ok(Reconciled::Unchanged); + } // A member whose process restarted re-adopts its routes first: their // slots are already charged to it, so this needs no free capacity. let targets = candidates( @@ -3048,6 +3103,7 @@ impl SupervisorPool { charges, Some(&record.payload.member_id), self.max_instances_per_member(), + pinned, ); for target in targets { let intent = OwnerPayload { @@ -3544,10 +3600,16 @@ impl InstancePlacement for PoolPlacement { Box::pin(async move { pool.recorded().await }) } - fn record_recovered(&self, assignment: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered( + &self, + assignment: SandboxInstanceAssignment, + member: Option, + ) -> PlacementFuture { let pool = self.0.clone(); Box::pin(detached(async move { - pool.record_assignment(&assignment).await.map(drop) + pool.record_assignment(&assignment, member.as_deref()) + .await + .map(drop) })) } } @@ -3802,6 +3864,7 @@ mod tests { claim_handle: Vec::new(), pool_id: None, claim_operation_id: None, + member_id: None, }; self.store .put_if( @@ -3928,6 +3991,7 @@ mod tests { PlacementRequest { assignment: assignment(route, sandbox_id, generation), auth_epoch: 1, + member: None, } } @@ -3989,6 +4053,98 @@ mod tests { ); } + #[tokio::test] + async fn pinned_instances_stay_on_their_member() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture.member("m2", "p2", false).await; + let pool = fixture.replica("gw-a"); + let pinned = |route: &str, sandbox: &str, member: &str| PlacementRequest { + member: Some(member.to_string()), + ..launch(route, sandbox, "generation-1") + }; + // Pinned to m2 even where the ring prefers m1. + let ring = GatewayRing::new(["m1", "m2"]); + let sandbox = (0..64) + .map(|index| format!("sandbox-{index}")) + .find(|sandbox| ring.owner_for(sandbox) == Some("m1")) + .unwrap(); + fixture + .sandbox(&sandbox, "generation-1", SandboxPhase::Ready) + .await; + pool.place_launch(pinned("rt-route-p000", &sandbox, "m2")) + .await + .unwrap(); + assert_eq!( + fixture.owner("rt-route-p000").await.unwrap().member_id, + "m2" + ); + assert_eq!( + fixture + .instance("rt-route-p000") + .await + .unwrap() + .payload + .member_id + .as_deref(), + Some("m2") + ); + + // A member that is not attached refuses the launch instead of the + // ring choosing another. + fixture + .sandbox("sandbox-x", "generation-1", SandboxPhase::Ready) + .await; + let refused = pool + .place_launch(pinned("rt-route-x000", "sandbox-x", "node-gone")) + .await + .unwrap_err(); + assert!(refused.contains("\"node-gone\""), "{refused}"); + + // While m2 is gone the instance waits for it; its next process + // re-adopts it. + fixture.remove_member("m2").await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + assert_eq!( + fixture.owner("rt-route-p000").await.unwrap().process_id, + "p2" + ); + fixture.member("m2", "p2b", false).await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + let owner = fixture.owner("rt-route-p000").await.unwrap(); + assert_eq!( + (owner.member_id.as_str(), owner.process_id.as_str()), + ("m2", "p2b") + ); + } + + #[tokio::test] + async fn node_bound_members_never_take_an_unpinned_instance() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture + .sandbox("sandbox-a", "generation-1", SandboxPhase::Ready) + .await; + fixture + .replica("gw-a") + .place_launch(launch("rt-route-a000", "sandbox-a", "generation-1")) + .await + .unwrap(); + + // After a switch to the node topology, the gateway-topology owner is + // gone and a node supervisor is live: the instance is not moved to it. + let pool = fixture.replica("gw-b"); + pool.controller.bind_members_to_nodes(); + fixture.member("node-a", "p2", false).await; + fixture.remove_member("m1").await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + let owner = fixture.owner("rt-route-a000").await.unwrap(); + assert_eq!((owner.member_id.as_str(), owner.auth_epoch), ("m1", 1)); + } + #[tokio::test] async fn a_failed_owner_is_taken_over_once_and_fenced_everywhere() { let fixture = Fixture::new().await; @@ -4196,7 +4352,7 @@ mod tests { // recorded owners. ("rt-route-b000", "sandbox-b"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1")) + pool.record_assignment(&assignment(route, sandbox, "generation-1"), None) .await .unwrap(); } @@ -4285,7 +4441,7 @@ mod tests { ("rt-route-c000", "sandbox-c"), ("rt-route-d000", "sandbox-d"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1")) + pool.record_assignment(&assignment(route, sandbox, "generation-1"), None) .await .unwrap(); } @@ -4442,11 +4598,14 @@ mod tests { // Recording the generation again keeps the first record and material; // another generation on its route is refused. - other.record_assignment(&launched).await.unwrap(); + other.record_assignment(&launched, None).await.unwrap(); assert_eq!(fixture.credentials.stored_credential_count(), Some(1)); assert!( other - .record_assignment(&assignment("rt-route-a000", "sandbox-a", "generation-2")) + .record_assignment( + &assignment("rt-route-a000", "sandbox-a", "generation-2"), + None + ) .await .is_err() ); @@ -4477,8 +4636,8 @@ mod tests { let (first, second) = (fixture.replica("gw-a"), fixture.replica("gw-b")); let instance = assignment("rt-route-a000", "sandbox-a", "generation-1"); let results: [_; 2] = tokio::join!( - first.record_assignment(&instance), - second.record_assignment(&instance) + first.record_assignment(&instance, None), + second.record_assignment(&instance, None) ) .into(); // One recording reserves the route and publishes; the other finds the @@ -4513,7 +4672,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None).await }) }; staged.await.unwrap(); // The instance is withdrawn while it is being recorded: removing its @@ -4548,7 +4707,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None).await }) }; staged.await.unwrap(); // Staged and unpublished: material stored, candidate written, the @@ -4608,7 +4767,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None).await }) }; staged.await.unwrap(); // The recording outlives its reservation's grace: a pass fences it and @@ -4624,7 +4783,7 @@ mod tests { assert!(fixture.instance("rt-route-a000").await.is_none()); assert_eq!(fixture.credentials.stored_credential_count(), Some(0)); // The route can be recorded again. - let record = pool.record_assignment(&instance).await.unwrap(); + let record = pool.record_assignment(&instance, None).await.unwrap(); assert_eq!( pool.load_material(&record.payload).await.unwrap(), instance.launch_material @@ -4641,7 +4800,8 @@ mod tests { let record_paused = |pool: Arc| { let (staged, publish) = pool.pause_next_recording_after_staging(); let instance = instance.clone(); - let recording = tokio::spawn(async move { pool.record_assignment(&instance).await }); + let recording = + tokio::spawn(async move { pool.record_assignment(&instance, None).await }); (staged, publish, recording) }; // The first recording stalls after staging and is fenced; its @@ -5188,7 +5348,7 @@ mod tests { taking.pause_next_transition(barrier.clone()); launching.pause_next_transition(barrier); let (taken, launched) = tokio::join!( - taking.take_over(&record, "expired", &ring, &members, &charges), + taking.take_over(&record, "expired", &ring, &members, &charges, None), launching.place_launch(launch("rt-route-new0", "sandbox-new", "generation-1")), ); taken.unwrap(); @@ -6167,10 +6327,12 @@ mod tests { ) }; let order = |charges: BTreeMap>, route: &str, same| { - candidates(&ring, &members, &sandbox, route, &charges, same, MEMBER_CAP) - .into_iter() - .map(|member| member.member_id.clone()) - .collect::>() + candidates( + &ring, &members, &sandbox, route, &charges, same, MEMBER_CAP, None, + ) + .into_iter() + .map(|member| member.member_id.clone()) + .collect::>() }; let charges = |m1, m2| BTreeMap::from([routes_for("m1", m1), routes_for("m2", m2)]); // The least charged member comes first, even against the ring. @@ -6191,6 +6353,27 @@ mod tests { order(charges(MEMBER_CAP, MEMBER_CAP), "rt-m2-0", Some("m2")), ["m2"] ); + // A pinned instance lists only its member, never the ring's choice, + // and nothing when that member is full, leaving, or gone. + let pinned = |charges: BTreeMap>, member: &str| { + candidates( + &ring, + &members, + &sandbox, + "rt-new", + &charges, + None, + MEMBER_CAP, + Some(member), + ) + .into_iter() + .map(|member| member.member_id.clone()) + .collect::>() + }; + assert_eq!(pinned(charges(0, 0), "m2"), ["m2"]); + assert!(pinned(charges(0, MEMBER_CAP), "m2").is_empty()); + assert!(pinned(charges(0, 0), "m3").is_empty()); + assert!(pinned(charges(0, 0), "m4").is_empty()); } #[test] @@ -6210,6 +6393,7 @@ mod tests { charges, None, CAP, + None, ) .first() .map(|member| member.member_id.clone()) diff --git a/crates/openshell-server/src/supervisor_pool/prepared.rs b/crates/openshell-server/src/supervisor_pool/prepared.rs index 9a81063ed4..0f9aa97ec5 100644 --- a/crates/openshell-server/src/supervisor_pool/prepared.rs +++ b/crates/openshell-server/src/supervisor_pool/prepared.rs @@ -1001,6 +1001,7 @@ impl SupervisorPool { .record_assignment_scoped( &assignment, RecordPhase::Published, + None, Some(( &request.workspace, request.auth_epoch.get(), @@ -1014,6 +1015,7 @@ impl SupervisorPool { PlacementRequest { assignment, auth_epoch: request.auth_epoch.get(), + member: None, }, Some((&request.workspace, &request.pool_id)), ) @@ -1078,6 +1080,7 @@ impl SupervisorPool { claim_handle: Vec::new(), pool_id: Some(retirement.pool_id.clone()), claim_operation_id: None, + member_id: None, }; match self .store diff --git a/crates/openshell-server/src/supervisor_pool/prepared_tests.rs b/crates/openshell-server/src/supervisor_pool/prepared_tests.rs index f7f65c4ee2..8382f46d83 100644 --- a/crates/openshell-server/src/supervisor_pool/prepared_tests.rs +++ b/crates/openshell-server/src/supervisor_pool/prepared_tests.rs @@ -139,6 +139,7 @@ async fn preparation_inventory_is_scoped_durable_and_excludes_unadmitted_and_cla pool.record_assignment_scoped( &pending.registration.to_assignment().unwrap(), RecordPhase::Admitting, + None, Some(("default", 1, "test-pool")), ) .await @@ -1025,6 +1026,7 @@ async fn retirement_covers_admitting_records_but_never_a_claim_or_other_identity pool.record_assignment_scoped( &pending.registration.to_assignment().unwrap(), RecordPhase::Admitting, + None, Some(("default", 1, "test-pool")), ) .await diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 01c1c8c586..d18b069b75 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -481,7 +481,8 @@ impl SupervisorHostController { } /// Accept only supervisors whose pool member ID is the node their - /// identity token proves. Call it before any host attaches. + /// identity token proves, and keep unpinned instances off them. Call it + /// before any host attaches. pub fn bind_members_to_nodes(&self) { self.inner .members_bound_to_nodes diff --git a/crates/openshell-supervisor-control/src/coordinator.rs b/crates/openshell-supervisor-control/src/coordinator.rs index d17971ea29..4ef7866715 100644 --- a/crates/openshell-supervisor-control/src/coordinator.rs +++ b/crates/openshell-supervisor-control/src/coordinator.rs @@ -69,6 +69,9 @@ pub struct PlacementRequest { pub assignment: crate::proto::SandboxInstanceAssignment, /// Credential epoch of the launch credentials. pub auth_epoch: u64, + /// The only pool member that may supervise the instance, at launch and + /// on every takeover; `None` lets the pool choose. + pub member: Option, } impl std::fmt::Debug for PlacementRequest { @@ -79,6 +82,7 @@ impl std::fmt::Debug for PlacementRequest { .field("sandbox_id", &self.assignment.sandbox_id) .field("generation", &self.assignment.generation) .field("auth_epoch", &self.auth_epoch) + .field("member", &self.member) .finish_non_exhaustive() } } @@ -341,9 +345,10 @@ pub trait InstancePlacement: Send + Sync + std::fmt::Debug { Box::pin(async { Err("warm-pool journals are not supported".into()) }) } /// Durably record a new instance, launch material included, and the - /// owner of its launch term: the pool member the consistent-hash ring - /// prefers among live members with room, and its current process. Fails - /// when no live member has room. + /// owner of its launch term: the request's member, or else the pool + /// member the consistent-hash ring prefers among live members with room, + /// and its current process. Fails when that member, or every live + /// member, has no room. fn place_launch(&self, request: PlacementRequest) -> PlacementFuture; /// Reserve a live member and one capacity slot before releasing a warm runtime. @@ -381,10 +386,12 @@ pub trait InstancePlacement: Send + Sync + std::fmt::Debug { /// Durably record an instance a driver recovery found without a record, /// such as one launched before the host became a pool; the pool places - /// it, fencing whichever process may supervise it. + /// it, fencing whichever process may supervise it, on `member` only when + /// one is given. fn record_recovered( &self, assignment: crate::proto::SandboxInstanceAssignment, + member: Option, ) -> PlacementFuture; } @@ -404,6 +411,8 @@ pub struct RecoveryBaseline { pub struct RecoverableInstance { pub route: String, pub sandbox_id: String, + /// The pool member the instance was launched on, when it is pinned. + pub member: Option, pub record: R, } @@ -783,10 +792,13 @@ impl SharedSupervision { /// every gateway replica, on a live member with room; without one the /// launch fails as [`LaunchError::Unplaced`], and beyond the pool's /// capacity as [`LaunchError::Refused`], so the caller fails its create - /// before the workload runs. An identical assignment changes nothing. + /// before the workload runs. `member` pins the instance, as + /// [`PlacementRequest::member`] describes. An identical assignment + /// changes nothing. pub async fn launch( &self, registration: &SandboxInstanceRegistration, + member: Option<&str>, persist: impl FnOnce(Vec) -> F + Send, ) -> Result<(), LaunchError> where @@ -810,6 +822,7 @@ impl SharedSupervision { .place_launch(PlacementRequest { assignment: assignment.clone(), auth_epoch: registration.auth.auth_epoch.get(), + member: member.map(str::to_string), }) .await { @@ -912,7 +925,11 @@ impl SharedSupervision { } }; let recorded = match assignment { - Ok(assignment) => placement.record_recovered(assignment).await, + Ok(assignment) => { + placement + .record_recovered(assignment, candidate.member.clone()) + .await + } Err(error) => Err(error.to_string()), }; if let Err(error) = recorded { @@ -1079,7 +1096,11 @@ mod tests { Box::pin(async move { Ok(recorded) }) } - fn record_recovered(&self, assignment: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered( + &self, + assignment: SandboxInstanceAssignment, + _member: Option, + ) -> PlacementFuture { self.recovered.lock().unwrap().push(assignment.route); Box::pin(async { Ok(()) }) } @@ -1089,6 +1110,7 @@ mod tests { RecoverableInstance { route: route.to_string(), sandbox_id: sandbox_id.to_string(), + member: None, record: if route.starts_with("rt-unreadable") { "unreadable" } else { diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index e33074350f..da02d3db52 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -198,9 +198,14 @@ control listener: it dials the gateway and receives its assignments from it. `ServiceAccount` token (audience `openshell-supervisor`) from `--identity-token-file` (`OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE`) in the `x-openshell-host-identity-token` header, re-read on every connection - attempt; the gateway refuses the supervisor token without it. The stream starts with a hello carrying a per-process - instance id and a connection epoch; the gateway supersedes an older stream - of the same process and refuses a delayed older connection. + attempt. The gateway verifies it, and refuses the supervisor token without + it under `require_identity_token` or the node topology. With + `--node-supervisor` (`OPENSHELL_SUPERVISOR_NODE`), the host serves only its + node's sandboxes, and the gateway requires its member ID to be the node its + identity token proves. The stream starts + with a hello carrying a per-process instance id and a connection epoch; the + gateway supersedes an older stream of the same process and refuses a delayed + older connection. - **Assignments.** The gateway owns the desired set and sends it as complete `AssignmentSnapshot`s with session-scoped revisions. `shared_host::SharedHost::reconcile` validates the snapshot as a whole (at most 256 instances, no route twice), diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index 2dc6addb91..c4fad93561 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -127,6 +127,12 @@ struct Args { )] identity_token_file: Option, + /// Serve only this node's sandboxes, as one supervisor per node: the + /// pool member ID must be the node name, and the supervisor doesn't leave + /// the pool on shutdown, since no other member may take its instances. + #[arg(long, env = "OPENSHELL_SUPERVISOR_NODE")] + node_supervisor: bool, + /// Listener for routed runtime-initiated Sandbox Protocol connections. #[arg(long, required_if_eq("mode", "shared"))] runtime_listen: Option, @@ -565,6 +571,7 @@ fn main() -> Result<()> { || args.address.is_some() || args.token_file.is_some() || args.identity_token_file.is_some() + || args.node_supervisor || (args.runtime_listen.is_some() && args.warm_prepared_file.is_none()) || args.session_root.is_some() { diff --git a/crates/openshell-supervisor/src/shared.rs b/crates/openshell-supervisor/src/shared.rs index 818f62cb4a..5b03ac91a9 100644 --- a/crates/openshell-supervisor/src/shared.rs +++ b/crates/openshell-supervisor/src/shared.rs @@ -36,6 +36,7 @@ fn run_platform(args: crate::Args) -> Result<()> { let identity_token_file = args .identity_token_file .ok_or_else(|| miette::miette!("--identity-token-file is required for --mode=shared"))?; + let node_supervisor = args.node_supervisor; let runtime_listen = args .runtime_listen .ok_or_else(|| miette::miette!("--runtime-listen is required for --mode=shared"))?; @@ -170,8 +171,11 @@ from sandbox runtimes)", _ = interrupt.recv() => {} } // A pool member hands its instances to other members while it still - // hears from the gateway. - host.leave(POOL_LEAVE_TIMEOUT).await; + // hears from the gateway. A node supervisor's instances are pinned to + // its node, so leaving would only wait for moves that never happen. + if !node_supervisor { + host.leave(POOL_LEAVE_TIMEOUT).await; + } stop.send_replace(true); let _ = probes.await; let _ = attachment.await; From fba5d2c8c85d46797c60f7973545e67f435d5f52 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 8 Nov 2026 23:10:59 +0200 Subject: [PATCH 05/18] feat(helm): run the shared supervisor as a per-node DaemonSet With supervisor_topology = "node", the chart renders the supervisor as a DaemonSet on every node, started with --node-supervisor and with the node name as each Pod's pool member ID. The Service keeps runtimes on their own node with internalTrafficPolicy: Local, and the node topology renders no PodDisruptionBudget or HPA. supervisor.tolerations and supervisor.nodeSelector place supervisors on tainted or selected sandbox nodes, such as GPU nodes. Adds the e2e:kubernetes:shared-supervisor-node task on a two-node k3d cluster, and documents the topology, its platform preconditions, and that switching topologies ends running shared sandboxes. Signed-off-by: Gal Zaidman --- .agents/skills/helm-dev-environment/SKILL.md | 4 + .config/nextest.toml | 8 +- .../openshell-supervisor/src/shared_host.rs | 4 +- deploy/helm/openshell/README.md | 12 +- deploy/helm/openshell/README.md.gotmpl | 4 + .../openshell/ci/values-supervisor-node.yaml | 11 + deploy/helm/openshell/templates/_helpers.tpl | 43 ++- .../templates/_supervisor-autoscaling.tpl | 2 +- .../openshell/templates/supervisor-pdb.yaml | 2 +- .../templates/supervisor-service.yaml | 4 + .../templates/supervisor-serviceaccount.yaml | 8 +- .../helm/openshell/templates/supervisor.yaml | 37 ++- .../helm/openshell/tests/supervisor_test.yaml | 179 +++++++++++- deploy/helm/openshell/values.yaml | 28 +- docs/how-it-works/gateways/configuration.mdx | 25 +- docs/kubernetes/high-availability.mdx | 56 +++- e2e/rust/Cargo.toml | 2 + .../kubernetes_shared_supervisor_node.rs | 270 ++++++++++++++++++ e2e/rust/tests/kubernetes_warm_pool.rs | 2 + e2e/rust/tests/shared_supervisor/mod.rs | 70 +++-- skills/debug-openshell-cluster/SKILL.md | 22 +- tasks/test.toml | 8 + 22 files changed, 717 insertions(+), 84 deletions(-) create mode 100644 deploy/helm/openshell/ci/values-supervisor-node.yaml create mode 100644 e2e/rust/tests/kubernetes_shared_supervisor_node.rs diff --git a/.agents/skills/helm-dev-environment/SKILL.md b/.agents/skills/helm-dev-environment/SKILL.md index 170bdd7c16..5fc3661e20 100644 --- a/.agents/skills/helm-dev-environment/SKILL.md +++ b/.agents/skills/helm-dev-environment/SKILL.md @@ -143,6 +143,10 @@ shared process namespace. The sidecar sends SIGKILL to the supervisor as the same UID; it needs no host PID namespace, capabilities, or runtime socket. The default k3d/kind test continues to kill through the node container runtime. +`mise run e2e:kubernetes:shared-supervisor-node` runs the +`supervisor_topology: node` e2e (`ci/values-supervisor-node.yaml`) on a +two-node k3d cluster. + ### Shared supervisor high availability `mise run e2e:kubernetes:shared-supervisor-spiffe-node-local` validates direct diff --git a/.config/nextest.toml b/.config/nextest.toml index c5a25293b4..2d045e5c11 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -32,7 +32,7 @@ test-group = "kubernetes-ha" # they kill members or gateways, or scale the pool. Never run them at once. # Test names, not binary(), for the reason above. [[profile.e2e-kubernetes.overrides]] -filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways)$/)" +filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways|each_workload_is_served_by_its_own_nodes_supervisor|a_supervisor_claiming_another_nodes_member_id_is_refused)$/)" test-group = "kubernetes-shared-supervisor-pool" # Scaling the pool runs two bounded Helm upgrades (up to 6 minutes each), waits @@ -59,6 +59,12 @@ slow-timeout = { period = "60s", terminate-after = 15 } filter = "test(/^supervisors_spread_evenly_across_gateways$/)" slow-timeout = { period = "60s", terminate-after = 20 } +# Restarting a node supervisor waits for its replacement to receive the +# supervisor token, attach, and re-adopt the node's instances. +[[profile.e2e-kubernetes.overrides]] +filter = "test(/^each_workload_is_served_by_its_own_nodes_supervisor$/)" +slow-timeout = { period = "60s", terminate-after = 12 } + # Relative to the profile store dir (`e2e/rust/target/nextest/e2e-kubernetes/`). [profile.e2e-kubernetes.junit] path = "../../../../../results/e2e-kubernetes.xml" diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index bba003e0b3..ee6ec3647e 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -1722,7 +1722,7 @@ async fn run_stream( let mut inbound = match opened { Ok(inbound) => inbound, Err(error) => { - tracing::warn!(%error, "could not open the supervisor host stream"); + tracing::warn!("could not open the supervisor host stream: {error}"); return lost(false); } }; @@ -1751,7 +1751,7 @@ async fn run_stream( let payload = match message { Some(Ok(message)) => message.payload, Some(Err(status)) => { - tracing::warn!(%status, "gateway assignment stream failed"); + tracing::warn!("gateway assignment stream failed: {status}"); break lost(accepted); } None => break lost(accepted), diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 5aa5834cdf..8531572c68 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -522,6 +522,10 @@ explicitly. Existing sandboxes stay on their owners when scaling up, and memory-based scaling does not guarantee spare capacity for handoff. See the [shared supervisor autoscaling guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#autoscale-shared-supervisors-by-memory). +Set `supervisor_topology: node` in `gatewayConfig.openshell.drivers.kubernetes` +to run one shared supervisor per node as a DaemonSet. See the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). + ## Secure metrics scraping Metrics are enabled by default on `service.metricsPort: 9090`. Set @@ -830,7 +834,7 @@ for peer identity policies, multi-node registrations, and authorization. | serviceAccount.create | bool | `true` | Create a service account for the gateway. | | serviceAccount.name | string | `""` | Existing service account name to use when serviceAccount.create is false. | | storageClass.preflight.enabled | bool | `false` | On a fresh StatefulSet install with no server.dataStorageClass, check for a default StorageClass. The Helm identity must be allowed to list StorageClasses. | -| supervisor.affinity | object | `{}` | Affinity rules for the shared supervisor pod, rendered only when gatewayConfig selects supervisor_topology = "gateway". Top-level affinity applies only to the gateway pod. | +| supervisor.affinity | object | `{}` | Affinity rules for the shared supervisor pod, rendered only when gatewayConfig selects supervisor_topology = "gateway" or "node". Top-level affinity applies only to the gateway pod. | | supervisor.autoscaling.behavior | object | `{"scaleDown":{"policies":[{"periodSeconds":120,"type":"Pods","value":1}],"stabilizationWindowSeconds":300}}` | HPA scaling behavior. Remove at most one member every two minutes, after a five-minute stabilization window, to allow ownership handoff. | | supervisor.autoscaling.enabled | bool | `false` | Enable memory-based autoscaling of the shared supervisor Deployment. Requires supervisor_topology = "gateway" and the Kubernetes resource metrics API (usually Metrics Server). When enabled, the HPA owns the replica count and supervisor.replicas is ignored. | | supervisor.autoscaling.maxReplicas | int | `4` | Maximum supervisor replicas. Must not exceed the gateway replica count * supervisor.pool.maxMembersPerGateway. | @@ -843,19 +847,21 @@ for peer identity policies, multi-node registrations, and authorization. | supervisor.image.tag | string | `""` | Supervisor image tag. Defaults to the chart appVersion when empty. | | supervisor.listenAddress | string | `"0.0.0.0"` | Shared supervisor listener IP. Use `::` for IPv6. | | supervisor.network.additionalCaConfigMapName | string | `""` | Name of an operator-owned ConfigMap with a `ca.crt` key containing additional destination CA certificates for sandbox supervisors. Empty disables additional destination trust. | +| supervisor.nodeSelector | object | `{}` | Node selector for the shared supervisor pod. With supervisor_topology = "node", it must cover every node that can host sandboxes. | | supervisor.podDisruptionBudget.enabled | bool | `true` | Render a PodDisruptionBudget with maxUnavailable 1 for the shared supervisor, used only when gatewayConfig selects supervisor_topology = "gateway". Disable it only when maintenance must evict more than one supervisor Pod at a time, or evict a member while another is unavailable. | | supervisor.podSecurityContext.fsGroup | int | `65534` | fsGroup assigned to the shared supervisor pod. | | supervisor.podSecurityContext.runAsGroup | int | `65534` | Primary GID assigned to the shared supervisor pod. | | supervisor.podSecurityContext.runAsNonRoot | bool | `true` | Require the shared supervisor to run as a non-root user. | | supervisor.podSecurityContext.runAsUser | int | `65534` | UID assigned to the shared supervisor pod. | | supervisor.podSecurityContext.seccompProfile.type | string | `"RuntimeDefault"` | Seccomp profile applied to the shared supervisor pod. | -| supervisor.pool.maxInstancesPerMember | int | `128` | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. | +| supervisor.pool.maxInstancesPerMember | int | `128` | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. Ignored with supervisor_topology = "node", which uses 1024. | | supervisor.pool.maxMembersPerGateway | int | `32` | Most supervisors one gateway replica serves, rendered as [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a positive integer. The pool runs at most gateway replicas times maxMembersPerGateway times maxInstancesPerMember sandboxes, never more than 131072. | | supervisor.recoveryTimeoutSeconds | int | `60` | Seconds a sandbox workload stays frozen after losing its pool member's supervision before the sandbox runtime terminates it, rendered as [openshell.gateway.supervisor_pool] recovery_timeout_secs. Must be an integer from 30 to 300. Null leaves the gateway's pool default of 60 seconds. | -| supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true. Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | +| supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true or supervisor_topology = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | | supervisor.requireIdentityToken | bool | `false` | Refuse gateway-topology supervisors that attach without their pod-bound identity token. Node-topology supervisors always need it. Refer to the High Availability guide before enabling it on an upgrade. | | supervisor.resources | object | `{}` | Resources of each shared supervisor container, unset by default. Memory grows with the sandboxes a supervisor runs; for the default of 128 sandboxes, request 250m CPU and 768Mi memory, and allow for failover. Refer to Size Sandbox Capacity in the High Availability guide. | | supervisor.sandboxRuntime.boundaryPort | int | `5500` | Workload boundary TLS listener port. | +| supervisor.tolerations | list | `[]` | Tolerations for the shared supervisor pod. With supervisor_topology = "node", tolerate every taint a sandbox template tolerates, such as `nvidia.com/gpu` on GPU nodes. | | tolerations | list | `[]` | Tolerations for the gateway pod. | | topologySpreadConstraints | list | `[]` | Topology spread constraints for the gateway pod, used to spread replicas across zones or nodes. Empty = omit the field. | | upstreamProxy | object | `{"authAllowInsecure":false,"authSecret":{"key":"","name":""},"caBundle":{"configMapName":"","key":"ca.crt"},"connectByHostname":false,"noProxy":"","url":""}` | Operator-owned corporate forward proxy for policy-approved TLS egress from Kubernetes sandboxes. The workload cannot select or override it. | diff --git a/deploy/helm/openshell/README.md.gotmpl b/deploy/helm/openshell/README.md.gotmpl index 4441c571d3..d5eeac22d4 100644 --- a/deploy/helm/openshell/README.md.gotmpl +++ b/deploy/helm/openshell/README.md.gotmpl @@ -523,6 +523,10 @@ explicitly. Existing sandboxes stay on their owners when scaling up, and memory-based scaling does not guarantee spare capacity for handoff. See the [shared supervisor autoscaling guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#autoscale-shared-supervisors-by-memory). +Set `supervisor_topology: node` in `gatewayConfig.openshell.drivers.kubernetes` +to run one shared supervisor per node as a DaemonSet. See the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). + ## Secure metrics scraping Metrics are enabled by default on `service.metricsPort: 9090`. Set diff --git a/deploy/helm/openshell/ci/values-supervisor-node.yaml b/deploy/helm/openshell/ci/values-supervisor-node.yaml new file mode 100644 index 0000000000..35b030832c --- /dev/null +++ b/deploy/helm/openshell/ci/values-supervisor-node.yaml @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# E2E overlay: supervise new sandbox generations with one shared supervisor per +# node. Each generation is pinned to the supervisor on its workload's node. +gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + +supervisor: + recoveryTimeoutSeconds: 60 diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index 1c065a598b..ac7f1bfaba 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -359,12 +359,21 @@ flag — so the default value works for any release name or namespace without override. */}} {{/* -Whether the gateway supervisor topology is enabled. Read from the -raw gateway configuration so openshell.effectiveKubernetesConfig can use it. +Whether a shared supervisor topology (gateway or node) is enabled. Read from +the raw gateway configuration so openshell.effectiveKubernetesConfig can use it. */}} {{- define "openshell.supervisorEnabled" -}} {{- $kubernetes := get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict -}} -{{- if eq (get $kubernetes "supervisor_topology" | default "") "gateway" -}}true{{- end -}} +{{- if has (get $kubernetes "supervisor_topology" | default "") (list "gateway" "node") -}}true{{- end -}} +{{- end }} + +{{/* +Whether the shared supervisor runs one Pod per node (a DaemonSet) instead of a +replicated Deployment. +*/}} +{{- define "openshell.supervisorNodeTopology" -}} +{{- $kubernetes := get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict -}} +{{- if eq (get $kubernetes "supervisor_topology" | default "") "node" -}}true{{- end -}} {{- end }} {{/* @@ -514,9 +523,17 @@ key, default, and optionally max. {{- end -}} {{- end }} -{{/* Most sandboxes one supervisor runs (supervisor.pool.maxInstancesPerMember). */}} +{{/* +Most sandboxes one supervisor runs (supervisor.pool.maxInstancesPerMember). +A node supervisor takes every sandbox the kubelet admits on its node, so the +node topology always uses the largest cap. +*/}} {{- define "openshell.supervisorMaxInstancesPerMember" -}} +{{- if include "openshell.supervisorNodeTopology" . -}} +1024 +{{- else -}} {{- include "openshell.supervisorPoolLimit" (dict "root" . "key" "maxInstancesPerMember" "max" 1024 "default" 128) -}} +{{- end -}} {{- end }} {{/* Most supervisors one gateway replica serves (supervisor.pool.maxMembersPerGateway). */}} @@ -563,7 +580,9 @@ TOML form. {{- fail "supervisor_pool is rendered by the chart; set supervisor.replicas, supervisor.pool, and supervisor.recoveryTimeoutSeconds" -}} {{- end -}} {{- if include "openshell.supervisorEnabled" . -}} +{{- if not (include "openshell.supervisorNodeTopology" .) -}} {{- include "openshell.validateSupervisorMembers" . -}} +{{- end -}} {{- $table := dict "max_instances_per_member" (int64 (include "openshell.supervisorMaxInstancesPerMember" .)) "max_members_per_gateway" (int64 (include "openshell.supervisorMaxMembersPerGateway" .)) -}} {{- $recoveryTimeout := include "openshell.supervisorRecoveryTimeoutSeconds" . -}} {{- if $recoveryTimeout -}} @@ -845,8 +864,8 @@ Validate chart values that Helm would otherwise accept silently. {{- $kubernetes := include "openshell.effectiveKubernetesConfig" . | fromYaml -}} {{- if hasKey $kubernetes "supervisor_topology" -}} {{- $topology := get $kubernetes "supervisor_topology" -}} -{{- if not (has $topology (list "gateway" "workspace")) -}} -{{- fail "supervisor_topology must be gateway or workspace; omit it to disable the shared supervisor" -}} +{{- if not (has $topology (list "gateway" "node" "workspace")) -}} +{{- fail "supervisor_topology must be gateway, node, or workspace; omit it to disable the shared supervisor" -}} {{- end -}} {{- if eq $topology "workspace" -}} {{- fail "supervisor_topology=workspace is not implemented" -}} @@ -856,22 +875,22 @@ Validate chart values that Helm would otherwise accept silently. {{- fail "supervisor_topology requires the kubernetes compute driver" -}} {{- end -}} {{- if or (get $kubernetes "https_proxy") (get $kubernetes "proxy_ca_bundle") (get $kubernetes "proxy_auth_secret_name") -}} -{{- fail "supervisor_topology=gateway does not support upstream proxy settings" -}} +{{- fail (printf "supervisor_topology=%s does not support upstream proxy settings" $topology) -}} {{- end -}} {{- if .Values.server.disableTls -}} -{{- fail "supervisor_topology=gateway requires gateway TLS; the supervisor token travels only over TLS" -}} +{{- fail (printf "supervisor_topology=%s requires gateway TLS; the supervisor token travels only over TLS" $topology) -}} {{- end -}} {{- if and (eq (get $kubernetes "workspace_mode" | default "shared") "operator") (not (regexMatch "^[A-Za-z0-9][-A-Za-z0-9_./]*==?[-A-Za-z0-9_.]*$" (get $kubernetes "operator_namespace_label" | default ""))) -}} -{{- fail "supervisor_topology=gateway in operator workspace mode requires operator_namespace_label of the form key=value" -}} +{{- fail (printf "supervisor_topology=%s in operator workspace mode requires operator_namespace_label of the form key=value" $topology) -}} {{- end -}} {{- end -}} {{- $broker := get (.Values.gatewayConfig | default dict) "openshell.gateway.spiffe_broker" | default dict -}} -{{- if and (eq (get $kubernetes "supervisor_topology" | default "") "gateway") (get $kubernetes "provider_spiffe_workload_api_socket_path") (empty $broker) -}} +{{- if and (include "openshell.supervisorEnabled" .) (get $kubernetes "provider_spiffe_workload_api_socket_path") (empty $broker) -}} {{- fail "shared supervisor SPIFFE grants require spiffe_broker; remove provider_spiffe_workload_api_socket_path from the shared supervisor" -}} {{- end -}} {{- if $broker -}} -{{- if ne (get $kubernetes "supervisor_topology" | default "") "gateway" -}} -{{- fail "spiffe_broker requires supervisor_topology=gateway" -}} +{{- if not (include "openshell.supervisorEnabled" .) -}} +{{- fail "spiffe_broker requires supervisor_topology=gateway or node" -}} {{- end -}} {{- include "openshell.validateSpiffeBroker" (dict "broker" $broker) -}} {{- end -}} diff --git a/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl b/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl index 3d25ebcf09..99f7a3955c 100644 --- a/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl +++ b/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl @@ -16,7 +16,7 @@ {{- fail "supervisor.autoscaling.enabled must be a boolean" -}} {{- end -}} {{- if eq (include "openshell.supervisorAutoscalingEnabled" .) "true" -}} -{{- if not (include "openshell.supervisorEnabled" .) -}} +{{- if or (not (include "openshell.supervisorEnabled" .)) (include "openshell.supervisorNodeTopology" .) -}} {{- fail "supervisor.autoscaling.enabled requires supervisor_topology = gateway" -}} {{- end -}} {{- $min := include "openshell.wholeNumber" (get $a "minReplicas") -}} diff --git a/deploy/helm/openshell/templates/supervisor-pdb.yaml b/deploy/helm/openshell/templates/supervisor-pdb.yaml index ab1f8bc37d..75d7074a62 100644 --- a/deploy/helm/openshell/templates/supervisor-pdb.yaml +++ b/deploy/helm/openshell/templates/supervisor-pdb.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 {{- include "openshell.validateValues" . }} -{{- if and (include "openshell.supervisorEnabled" .) (eq (include "openshell.supervisorPodDisruptionBudgetEnabled" .) "true") }} +{{- if and (include "openshell.supervisorEnabled" .) (not (include "openshell.supervisorNodeTopology" .)) (eq (include "openshell.supervisorPodDisruptionBudgetEnabled" .) "true") }} # Voluntary disruptions, such as node drains, evict one member at a time, so # the remaining members can take over its instances. apiVersion: policy/v1 diff --git a/deploy/helm/openshell/templates/supervisor-service.yaml b/deploy/helm/openshell/templates/supervisor-service.yaml index e91832afd1..78e68408ab 100644 --- a/deploy/helm/openshell/templates/supervisor-service.yaml +++ b/deploy/helm/openshell/templates/supervisor-service.yaml @@ -13,6 +13,10 @@ metadata: {{- include "openshell.labels" . | nindent 4 }} app.kubernetes.io/component: supervisor spec: + {{- if include "openshell.supervisorNodeTopology" . }} + # A runtime that dials the Service reaches its own node's supervisor. + internalTrafficPolicy: Local + {{- end }} selector: {{- include "openshell.supervisorSelectorLabels" . | nindent 4 }} ports: diff --git a/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml index 722ade5ab0..14c2bf5cd4 100644 --- a/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml +++ b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml @@ -2,10 +2,10 @@ # SPDX-License-Identifier: Apache-2.0 {{- include "openshell.validateValues" . }} {{- if include "openshell.supervisorEnabled" . }} -# Supervisors prove their Pod with this account's Pod-bound tokens. The -# gateway only reviews them, so bind no RBAC to it. Restrict creating Pods -# with it and `create` on its `serviceaccounts/token` to cluster -# administrators. +# Supervisors prove their Pod, and in the node topology their node, with +# this account's Pod-bound tokens. The gateway only reviews them, so bind no +# RBAC to it. Restrict creating Pods with it and `create` on its +# `serviceaccounts/token` to cluster administrators. apiVersion: v1 kind: ServiceAccount metadata: diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index a8fbb9b47a..695838315c 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -23,6 +23,7 @@ {{- $endpoint := get $kubernetes "grpc_endpoint" }} {{- $endpointUrl := urlParse $endpoint }} {{- $gatewayTls := and (not .Values.server.disableTls) .Values.server.tls.clientTlsSecretName }} +{{- $node := include "openshell.supervisorNodeTopology" . }} # One supervisor process per replica hosts a sandbox instance for each sandbox # generation placed on it. The process dials the gateway over TLS with the # supervisor token the gateway mints for it and receives its assignments from @@ -30,7 +31,7 @@ # holds no Kubernetes API identity of its own: each instance acts only with the # credentials the gateway issued for its generation. apiVersion: apps/v1 -kind: Deployment +kind: {{ ternary "DaemonSet" "Deployment" (eq $node "true") }} metadata: name: {{ $name }} namespace: {{ .Release.Namespace }} @@ -38,6 +39,15 @@ metadata: {{- include "openshell.labels" . | nindent 4 }} app.kubernetes.io/component: supervisor spec: + {{- if $node }} + # No surge: two live members with one node's ID would keep superseding each + # other. + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 + {{- else }} # The replicas form a high-availability pool. Each instance lives in the # process hosting it; the pool rolls one member at a time, starting a new # member before an old one leaves, and the gateway hands a failed or leaving @@ -53,6 +63,7 @@ spec: rollingUpdate: maxSurge: 1 maxUnavailable: 0 + {{- end }} selector: matchLabels: {{- include "openshell.supervisorSelectorLabels" . | nindent 6 }} @@ -61,14 +72,13 @@ spec: labels: {{- include "openshell.supervisorSelectorLabels" . | nindent 8 }} spec: - # The ServiceAccount has no RBAC bindings. Its projected token, bound to - # this Pod, proves to the gateway that the supervisor token's holder is - # this Pod. serviceAccountName: {{ $name }} automountServiceAccountToken: false enableServiceLinks: false + {{- if not $node }} # A stopping member announces that it is leaving, and the gateway moves # its instances to the remaining members before it exits. + {{- end }} terminationGracePeriodSeconds: 60 {{- with ($imagePullSecrets | uniq) }} imagePullSecrets: @@ -84,6 +94,14 @@ spec: affinity: {{- toYaml . | nindent 8 }} {{- end }} + {{- with .Values.supervisor.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.supervisor.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} containers: - name: supervisor image: {{ get $kubernetes "supervisor_image" | quote }} @@ -110,6 +128,9 @@ spec: - --nat64-prefix - {{ . | quote }} {{- end }} + {{- if $node }} + - --node-supervisor + {{- end }} env: {{- if get $app "enabled" }} - name: OPENSHELL_APP_LISTENER_ENABLED @@ -135,13 +156,13 @@ spec: - name: OPENSHELL_GATEWAY_TLS_SERVER_NAME value: {{ get $endpointUrl "hostname" | quote }} {{- end }} - # Pool membership: the Pod name is this member's stable ID, and - # other members redirect the runtimes of its instances to its Pod - # IP. + # Pool membership: the Pod name (the node name in the node + # topology) is this member's stable ID, and other members redirect + # the runtimes of its instances to its Pod IP. - name: OPENSHELL_SUPERVISOR_POOL_MEMBER_ID valueFrom: fieldRef: - fieldPath: metadata.name + fieldPath: {{ ternary "spec.nodeName" "metadata.name" (eq $node "true") }} - name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP valueFrom: fieldRef: diff --git a/deploy/helm/openshell/tests/supervisor_test.yaml b/deploy/helm/openshell/tests/supervisor_test.yaml index 20f8666d1d..cc2c38c27a 100644 --- a/deploy/helm/openshell/tests/supervisor_test.yaml +++ b/deploy/helm/openshell/tests/supervisor_test.yaml @@ -799,6 +799,26 @@ tests: value: 512Mi template: templates/supervisor.yaml documentIndex: 0 + - it: gives node supervisors the largest per-member cap + set: + supervisor: + pool: + maxInstancesPerMember: 16 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 1024\n' + template: templates/gateway-config.yaml + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES + value: "1024" + template: templates/supervisor.yaml + documentIndex: 0 - it: accepts a per-member cap of one sandbox template: templates/supervisor.yaml set: @@ -879,6 +899,20 @@ tests: asserts: - failedTemplate: errorMessage: supervisor.replicas (3) exceeds replicaCount (1) * supervisor.pool.maxMembersPerGateway (2) = 2; add gateway replicas or raise maxMembersPerGateway + - it: ignores supervisor.replicas when counting node-topology members + template: templates/supervisor.yaml + set: + supervisor: + replicas: 3 + pool: + maxMembersPerGateway: 2 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - isKind: + of: DaemonSet + documentIndex: 0 - it: rejects a supervisor HPA maximum above what the gateways serve template: templates/supervisor.yaml set: @@ -1022,7 +1056,7 @@ tests: supervisor_topology: invalid asserts: - failedTemplate: - errorMessage: supervisor_topology must be gateway or workspace; omit it to disable the shared supervisor + errorMessage: supervisor_topology must be gateway, node, or workspace; omit it to disable the shared supervisor - it: rejects enabled topology for another compute driver template: templates/supervisor.yaml set: @@ -1034,3 +1068,146 @@ tests: asserts: - failedTemplate: errorMessage: supervisor_topology requires the kubernetes compute driver + - it: runs one supervisor per node bound to its node in the node topology + template: templates/supervisor.yaml + set: + supervisor: + replicas: 3 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: kind + value: DaemonSet + - notExists: + path: spec.replicas + - notExists: + path: spec.strategy + - equal: + path: spec.updateStrategy + value: + type: RollingUpdate + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 + - equal: + path: spec.template.spec.serviceAccountName + value: openshell-supervisor + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - notExists: + path: spec.template.spec.nodeSelector + - notExists: + path: spec.template.spec.tolerations + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_MEMBER_ID + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - contains: + path: spec.template.spec.containers[0].args + content: --node-supervisor + - contains: + path: spec.template.spec.containers[0].args + content: /var/run/secrets/openshell-supervisor/token + - it: places node supervisors on tainted and selected nodes + template: templates/supervisor.yaml + set: + supervisor: + nodeSelector: + openshell.ai/sandbox-pool: gpu + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: kind + value: DaemonSet + - equal: + path: spec.template.spec.nodeSelector + value: + openshell.ai/sandbox-pool: gpu + - equal: + path: spec.template.spec.tolerations + value: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + - it: keeps node-topology runtimes on their node and renders no disruption budget + template: templates/supervisor-service.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.internalTrafficPolicy + value: Local + template: templates/supervisor-service.yaml + - hasDocuments: + count: 0 + template: templates/supervisor-pdb.yaml + - hasDocuments: + count: 1 + template: templates/supervisor-serviceaccount.yaml + - equal: + path: automountServiceAccountToken + value: false + template: templates/supervisor-serviceaccount.yaml + - matchRegex: + path: data["gateway.toml"] + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + template: templates/gateway-config.yaml + - matchRegex: + path: data["gateway.toml"] + pattern: 'supervisor_topology = "node"' + template: templates/gateway-config.yaml + - it: keeps the gateway topology a Deployment unbound to nodes + template: templates/supervisor.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: gateway + asserts: + - equal: + path: kind + value: Deployment + template: templates/supervisor.yaml + - notContains: + path: spec.template.spec.containers[0].args + content: --node-supervisor + template: templates/supervisor.yaml + - notExists: + path: spec.internalTrafficPolicy + template: templates/supervisor-service.yaml + - it: rejects autoscaling in the node topology + template: templates/supervisor.yaml + set: + supervisor: + autoscaling: + enabled: true + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorMessage: supervisor.autoscaling.enabled requires supervisor_topology = gateway + - it: names the node topology in its refusals + template: templates/supervisor.yaml + set: + upstreamProxy: + url: http://proxy.example:3128 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorMessage: supervisor_topology=node does not support upstream proxy settings diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 1e614e15d9..65602f7fd6 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -84,14 +84,15 @@ supervisor: # workloads. 1 has no failover; use 2 or more to survive losing a member. # Only the supervisor Deployment's replica count depends on this value, so # changing it neither restarts the gateway nor replaces running members. - # Ignored when supervisor.autoscaling.enabled is true. Must not exceed - # replicaCount * supervisor.pool.maxMembersPerGateway. + # Ignored when supervisor.autoscaling.enabled is true or supervisor_topology + # = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. replicas: 1 pool: # -- Most sandboxes one supervisor runs, rendered as # [openshell.gateway.supervisor_pool] max_instances_per_member and passed # to each supervisor. Must be an integer from 1 to 1024. The gateway - # refuses a sandbox when every supervisor is full. + # refuses a sandbox when every supervisor is full. Ignored with + # supervisor_topology = "node", which uses 1024. maxInstancesPerMember: 128 # -- Most supervisors one gateway replica serves, rendered as # [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a @@ -141,10 +142,11 @@ supervisor: # integer from 30 to 300. Null leaves the gateway's pool default of 60 # seconds. recoveryTimeoutSeconds: 60 - # Pod security context for the shared supervisor Deployment, rendered only - # when gatewayConfig selects supervisor_topology = "gateway". On OpenShift, - # set the user and group IDs to null so the restricted-v2 SCC can assign the - # namespace range; ci/values-openshift-scc.yaml does this. + # Pod security context for the shared supervisor Deployment or DaemonSet, + # rendered only when gatewayConfig selects supervisor_topology = "gateway" or + # "node". On OpenShift, set the user and group IDs to null so the + # restricted-v2 SCC can assign the namespace range; + # ci/values-openshift-scc.yaml does this. podSecurityContext: # -- Require the shared supervisor to run as a non-root user. runAsNonRoot: true @@ -158,9 +160,17 @@ supervisor: # -- Seccomp profile applied to the shared supervisor pod. type: RuntimeDefault # -- Affinity rules for the shared supervisor pod, rendered only when - # gatewayConfig selects supervisor_topology = "gateway". Top-level affinity - # applies only to the gateway pod. + # gatewayConfig selects supervisor_topology = "gateway" or "node". Top-level + # affinity applies only to the gateway pod. affinity: {} + # -- Node selector for the shared supervisor pod. With + # supervisor_topology = "node", it must cover every node that can host + # sandboxes. + nodeSelector: {} + # -- Tolerations for the shared supervisor pod. With + # supervisor_topology = "node", tolerate every taint a sandbox template + # tolerates, such as `nvidia.com/gpu` on GPU nodes. + tolerations: [] network: # -- Name of an operator-owned ConfigMap with a `ca.crt` key containing additional destination CA certificates for sandbox supervisors. Empty disables additional destination trust. additionalCaConfigMapName: "" diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index c42bfd01e5..ad1f06988a 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -909,7 +909,7 @@ On SQLite, writers are serialized regardless of pool size, so a larger ceiling b ## Shared Supervisor Pool -`[openshell.gateway.supervisor_pool]` tunes the shared supervisor pool used with the Kubernetes driver's `supervisor_topology = "gateway"`. The Helm chart renders this table from `supervisor.*` values and rejects a hand-written one. +`[openshell.gateway.supervisor_pool]` tunes the shared supervisor pool used with the Kubernetes driver's `supervisor_topology = "gateway"` or `"node"`. The Helm chart renders this table from `supervisor.*` values and rejects a hand-written one. ```toml [openshell.gateway.supervisor_pool] @@ -924,7 +924,7 @@ max_members_per_gateway = 32 | `max_instances_per_member` | `128` | `1` to `1024` | `supervisor.pool.maxInstancesPerMember` | | `max_members_per_gateway` | `32` | `1` or more | `supervisor.pool.maxMembersPerGateway` | -The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. Values outside the ranges fail at startup. +The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. With `supervisor_topology = "node"`, the chart sets `1024`; see [Run one supervisor per node](/kubernetes/high-availability#run-one-supervisor-per-node). Values outside the ranges fail at startup. ## OCSF JSONL Output @@ -1585,7 +1585,7 @@ The Kubernetes, Docker, Podman, and MicroVM driver tables accept two keys that t - `policy_dns_ipv6_egress` sets how mediated policy DNS answers AAAA queries: `auto` (default), `enabled`, or `disabled`. `auto` answers AAAA only when the supervisor network namespace has an IPv6 default route and no IPv4 default route. `disabled` answers AAAA with an empty response so dual-stack clients fall back to IPv4. - `nat64_prefixes` lists the NAT64 prefixes of the sandbox network as RFC 6052 CIDRs (`/32`, `/40`, `/48`, `/56`, `/64`, or `/96`). The supervisor applies the IPv4 SSRF rules to the IPv4 address embedded in any destination inside these prefixes. It always recognizes the well-known prefix `64:ff9b::/96` and also discovers the network prefix through `ipv4only.arpa` (RFC 7050), so set this key when the network uses a prefix that discovery cannot find. -With `supervisor_topology = "gateway"`, the Helm chart passes the Kubernetes keys to the shared supervisors. +With `supervisor_topology = "gateway"` or `"node"`, the Helm chart passes the Kubernetes keys to the shared supervisors. The gateway rejects an unknown mode or a malformed prefix at startup. @@ -1761,6 +1761,25 @@ provider_spiffe_workload_api_socket_path = "/spiffe-workload-api/spire-agent.soc # (hot-reloaded on change, e.g. via ConfigMap volume mount). # operator_namespace_file = "/etc/openshell/workspace-namespaces.json" +# Shared supervisor topology for new sandbox generations: "gateway" runs a +# replicated pool, and "node" runs one supervisor per node that hosts the +# sandboxes scheduled to its node. Omit it for a supervisor Pod per sandbox. +# Only the in-process Kubernetes driver supports it. Helm renders the +# shared_supervisor table and refuses a hand-written one. +# supervisor_topology = "node" +# [openshell.drivers.kubernetes.shared_supervisor] +# service_name = "openshell-supervisor" +# service_namespace = "openshell" +# runtime_port = 5500 +# token_secret_name = "openshell-supervisor-token" +# The ServiceAccount the supervisors run as in service_namespace. The gateway +# verifies the pod-bound token for it that accompanies the supervisor token, +# and in the "node" topology that token proves each supervisor's node. +# service_account_name = "openshell-supervisor" +# Refuse supervisors that attach without the pod-bound token. Helm renders +# supervisor.requireIdentityToken here; the "node" topology always requires it. +# require_identity_token = false + [openshell.drivers.kubernetes.managed_ssh_ingress] enabled = true gateway_namespace = "openshell" diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index e14c4737a5..e20f039587 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -586,7 +586,7 @@ replicas so sandboxes can fail over: gatewayConfig: openshell.drivers.kubernetes: # Creates a supervisor Deployment alongside the gateway. - # Per-workspace and per-node supervisor options are planned. + # Use supervisor_topology: node for one supervisor per node. supervisor_topology: gateway supervisor: @@ -739,6 +739,60 @@ helm install openshell ./openshell -n openshell \ -f openshell/values-scale-10k.yaml --set server.externalDbSecret= ``` +### Run one supervisor per node + +With `supervisor_topology: node`, the chart runs the shared supervisor as a +DaemonSet, and each sandbox is served by the supervisor on its workload's node. +The scheduler picks the node. A sandbox never moves to another node's +supervisor. + +```yaml +gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node +``` + +Each supervisor's Pod-bound token also proves its node: the gateway accepts a +supervisor only for the node that the token's Pod runs on. Your cluster must +meet these conditions: + +- The ServiceAccount restriction above holds. Anyone who can create its Pods + or tokens can claim any node. +- Only principals that can already create Pods in the sandbox namespace can + create Secrets there. A node-topology workload Pod is scheduled before its + bootstrap Secret exists, so a Secret created first under that name is + mounted until the gateway's own create fails and rolls back the sandbox. + +We recommend running the API server with the `Node` authorizer and the +`NodeRestriction` admission plugin, so a compromised node's kubelet cannot +obtain tokens for another node's supervisor. + +Sandbox creation waits up to 60 seconds for the scheduler to place the +workload, and fails if that node has no attached supervisor. If sandbox +templates tolerate node taints, set the same tolerations in +`supervisor.tolerations`; if they select a node pool, cover it with +`supervisor.nodeSelector`. GPU nodes usually need: + +```yaml +supervisor: + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule +``` + +The chart renders no PodDisruptionBudget or HPA for the DaemonSet and ignores +`supervisor.replicas`. It also ignores `supervisor.pool.maxInstancesPerMember` +and sets each supervisor's cap to 1024, so a supervisor accepts every sandbox +the kubelet admits on its node. Size `supervisor.resources` for the kubelet's +`maxPods` on your sandbox nodes. When a node's supervisor restarts, its sandboxes pause +until the replacement attaches within `supervisor.recoveryTimeoutSeconds`. +A lost node takes its sandboxes with it. + +Switching `supervisor_topology` between `gateway` and `node` terminates +running shared sandboxes at the recovery timeout. Restart them to run under +the new topology. + ## Next Steps - To expose the gateway through a highly available data path, refer to diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 33464ed903..4ef051c71b 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -46,6 +46,8 @@ e2e-kubernetes-shared-supervisor-ha = ["e2e-kubernetes", "e2e-host-gateway"] # Scaling a one-member high-availability pool of shared supervisors to two # members and back. It upgrades the release, so it runs on its own release. e2e-kubernetes-shared-supervisor-scaling = ["e2e-kubernetes", "e2e-host-gateway"] +# One shared supervisor per node on a cluster of at least two nodes. +e2e-kubernetes-shared-supervisor-node = ["e2e-kubernetes", "e2e-host-gateway"] e2e-podman = ["e2e", "e2e-host-gateway", "e2e-local-container-driver"] e2e-podman-gpu = ["e2e-podman", "e2e-gpu"] e2e-oidc-pkce = [] diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_node.rs b/e2e/rust/tests/kubernetes_shared_supervisor_node.rs new file mode 100644 index 0000000000..60a129e70c --- /dev/null +++ b/e2e/rust/tests/kubernetes_shared_supervisor_node.rs @@ -0,0 +1,270 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-kubernetes-shared-supervisor-node")] + +//! One shared supervisor per node (`supervisor_topology = "node"`) on a +//! cluster of at least two nodes. + +mod shared_supervisor; + +use std::collections::{BTreeMap, BTreeSet}; +use std::process::Stdio; +use std::time::Duration; + +use shared_supervisor::{ + ATTACH_TIMEOUT, ATTACHED, HostEndpoint, call_host, counts_past, create, generation, kubectl, + kubectl_command, kubectl_json, main_process, owner_of, policy, release_namespace, + supervisor_logs, supervisor_pod_items, wait_for_owner, wait_until_attached, +}; + +/// Bound on a deleted node supervisor's replacement starting, attaching, and +/// re-adopting its node's instances. +const READOPT_DEADLINE: Duration = Duration::from_mins(3); +/// What the gateway answers a supervisor whose member ID is not its node. +const MEMBER_MISMATCH: &str = "is not the node its identity token proves"; +const FORGED_POD: &str = "openshell-e2e-forged-supervisor"; + +/// Running supervisor Pods by name, with the node each runs on. +async fn supervisor_nodes() -> BTreeMap { + supervisor_pod_items() + .await + .iter() + .filter(|pod| { + pod["metadata"]["deletionTimestamp"].is_null() && pod["status"]["phase"] == "Running" + }) + .filter_map(|pod| { + Some(( + pod["metadata"]["name"].as_str()?.to_string(), + pod["spec"]["nodeName"].as_str()?.to_string(), + )) + }) + .collect() +} + +/// [`kubectl_command`] run to completion, for use in `Drop`. +fn blocking_kubectl(args: &[&str]) { + let _ = kubectl_command() + .into_std() + .args(args) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); +} + +/// Keeps new Pods off a node until dropped. +struct Cordoned(String); + +impl Cordoned { + async fn new(node: &str) -> Self { + kubectl(&["cordon", node]).await; + Self(node.to_string()) + } +} + +impl Drop for Cordoned { + fn drop(&mut self) { + blocking_kubectl(&["uncordon", &self.0]); + } +} + +/// Deletes a test-created Pod when dropped. +struct TestPod(String); + +impl Drop for TestPod { + fn drop(&mut self) { + blocking_kubectl(&[ + "-n", + &release_namespace(), + "delete", + "pod", + &self.0, + "--ignore-not-found", + "--wait=false", + ]); + } +} + +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn each_workload_is_served_by_its_own_nodes_supervisor() { + let nodes = supervisor_nodes().await; + let distinct: BTreeSet<&String> = nodes.values().collect(); + assert!( + distinct.len() >= 2, + "the node topology needs supervisors on at least two nodes: {nodes:?}" + ); + wait_until_attached(&nodes.keys().cloned().collect::>()).await; + let endpoint = HostEndpoint::start().await; + let policy = policy(endpoint.port); + + // The first sandbox lands wherever the scheduler puts it; the second is + // kept off that node so the two run on different nodes. + let mut first = create(&policy).await; + let first_generation = generation(&first.name).await; + let first_node = first_generation + .workload_node + .clone() + .expect("the first workload is scheduled"); + let mut second = { + let _cordoned = Cordoned::new(&first_node).await; + create(&policy).await + }; + let second_generation = generation(&second.name).await; + let second_node = second_generation + .workload_node + .clone() + .expect("the second workload is scheduled"); + assert_ne!(first_node, second_node); + + let mut owners = Vec::new(); + for (sandbox, sandbox_generation, node) in [ + (&first, &first_generation, &first_node), + (&second, &second_generation, &second_node), + ] { + assert_eq!( + sandbox_generation.member.as_ref(), + Some(node), + "{} records its workload's node as its member", + sandbox.name + ); + let owner = wait_for_owner(&sandbox_generation.route).await; + assert_eq!( + nodes.get(&owner), + Some(node), + "{} is served by {owner}, not by the supervisor on {node}", + sandbox.name + ); + assert_eq!(call_host(sandbox, endpoint.port).await, "HA_OK"); + owners.push(owner); + } + let [first_owner, second_owner] = owners.as_slice() else { + unreachable!() + }; + + // Restarting the first node's supervisor re-adopts its running workload + // on the same node; the other node's sandbox keeps its owner. + let before = main_process(&first).await.expect("main process before"); + kubectl(&[ + "-n", + &release_namespace(), + "delete", + "pod", + first_owner, + "--wait=false", + ]) + .await; + let replacement = tokio::time::timeout(READOPT_DEADLINE, async { + loop { + if let Some((pod, _)) = supervisor_nodes() + .await + .into_iter() + .find(|(pod, node)| pod != first_owner && *node == first_node) + { + return pod; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("no supervisor replaced {first_owner} on {first_node}")); + wait_until_attached(std::slice::from_ref(&replacement)).await; + let adopted = tokio::time::timeout(READOPT_DEADLINE, async { + loop { + if owner_of(&first_generation.route).await.as_ref() == Some(&replacement) { + return; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }) + .await; + assert!( + adopted.is_ok(), + "{replacement} did not re-adopt {} within {READOPT_DEADLINE:?}", + first_generation.route + ); + counts_past(&first, &before).await; + assert_eq!(generation(&first.name).await, first_generation); + assert_eq!(call_host(&first, endpoint.port).await, "HA_OK"); + assert_eq!( + owner_of(&second_generation.route).await.as_ref(), + Some(second_owner) + ); + + first.cleanup().await; + second.cleanup().await; +} + +#[tokio::test] +async fn a_supervisor_claiming_another_nodes_member_id_is_refused() { + let nodes = supervisor_nodes().await; + let mut by_node: BTreeMap<&String, &String> = BTreeMap::new(); + for (pod, node) in &nodes { + by_node.entry(node).or_insert(pod); + } + let mut pairs = by_node.into_iter(); + let (Some((node, pod)), Some((other_node, other_pod))) = (pairs.next(), pairs.next()) else { + panic!("the node topology needs supervisors on at least two nodes: {nodes:?}"); + }; + wait_until_attached(&[pod.clone(), other_pod.clone()]).await; + + // A copy of the genuine supervisor Pod on `node`: the same ServiceAccount, + // shared supervisor token, and identity token, but the other node's + // member ID and labels no Service or DaemonSet selects. + let mut forged = + kubectl_json(&["-n", &release_namespace(), "get", "pod", pod, "-o", "json"]).await; + forged["metadata"] = serde_json::json!({ + "name": FORGED_POD, + "namespace": release_namespace(), + "labels": {"app.kubernetes.io/name": FORGED_POD}, + }); + forged.as_object_mut().expect("Pod object").remove("status"); + let env = forged["spec"]["containers"][0]["env"] + .as_array_mut() + .expect("supervisor env"); + let member = env + .iter_mut() + .find(|entry| entry["name"] == "OPENSHELL_SUPERVISOR_POOL_MEMBER_ID") + .expect("pool member ID env"); + *member = serde_json::json!({ + "name": "OPENSHELL_SUPERVISOR_POOL_MEMBER_ID", + "value": other_node, + }); + let mut manifest = tempfile::Builder::new() + .suffix(".json") + .tempfile() + .expect("create Pod manifest"); + std::io::Write::write_all(&mut manifest, forged.to_string().as_bytes()) + .expect("write Pod manifest"); + let _forged = TestPod(FORGED_POD.to_string()); + kubectl(&[ + "-n", + &release_namespace(), + "create", + "-f", + manifest.path().to_str().expect("UTF-8 manifest path"), + ]) + .await; + + let refused = tokio::time::timeout(ATTACH_TIMEOUT, async { + loop { + let logs = supervisor_logs(FORGED_POD).await.unwrap_or_default(); + assert!( + !logs.contains(ATTACHED), + "the gateway accepted a supervisor on {node} claiming {other_node}:\n{logs}" + ); + if logs.contains(MEMBER_MISMATCH) { + return; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + }) + .await; + assert!( + refused.is_ok(), + "the forged supervisor was not refused within {ATTACH_TIMEOUT:?}:\n{}", + supervisor_logs(FORGED_POD).await.unwrap_or_default() + ); + // The genuine member of the claimed node stays attached. + wait_until_attached(std::slice::from_ref(other_pod)).await; +} diff --git a/e2e/rust/tests/kubernetes_warm_pool.rs b/e2e/rust/tests/kubernetes_warm_pool.rs index c7692ca7a6..b588e26116 100644 --- a/e2e/rust/tests/kubernetes_warm_pool.rs +++ b/e2e/rust/tests/kubernetes_warm_pool.rs @@ -29,6 +29,8 @@ async fn generation(name: &str) -> shared_supervisor::Generation { .as_str() .unwrap() .to_string(), + workload_node: None, + member: None, } } diff --git a/e2e/rust/tests/shared_supervisor/mod.rs b/e2e/rust/tests/shared_supervisor/mod.rs index 6a3f4d4081..181ca18fc6 100644 --- a/e2e/rust/tests/shared_supervisor/mod.rs +++ b/e2e/rust/tests/shared_supervisor/mod.rs @@ -20,6 +20,7 @@ pub const TEST_HOST: &str = "host.openshell.internal"; pub const SUPERVISOR_COMPONENT: &str = "app.kubernetes.io/component=supervisor"; const INSTANCE_ROUTE_ANNOTATION: &str = "openshell.ai/sandbox-runtime-supervisor-session"; const GENERATION_ANNOTATION: &str = "openshell.ai/sandbox-runtime-generation"; +const MEMBER_ANNOTATION: &str = "openshell.ai/sandbox-runtime-supervisor-member"; /// The workload's main process: it records its PID once and a counter that /// lives only in its memory every second. A restarted process would start /// counting from one again. @@ -42,7 +43,7 @@ const RELEASES: [&str; 3] = [ ]; /// What a supervisor logs when the gateway accepts its stream, and when any /// stream ends; the later of the two says whether it is attached now. -const ATTACHED: &str = "gateway accepted the supervisor host"; +pub const ATTACHED: &str = "gateway accepted the supervisor host"; const DETACHED: &str = "gateway assignment stream lost"; /// Bound on a supervisor attaching to the gateway. A Pod is TCP-ready before /// it can authenticate: on a fresh install the gateway writes the supervisor @@ -350,6 +351,10 @@ pub struct Generation { pub route: String, pub runtime: String, pub workload_pod_uid: String, + /// Node the workload Pod is scheduled to. + pub workload_node: Option, + /// Pool member the generation is pinned to (node topology only). + pub member: Option, } pub async fn generation(name: &str) -> Generation { @@ -397,6 +402,8 @@ pub async fn generation(name: &str) -> Generation { .as_str() .expect("workload Pod UID") .to_string(), + workload_node: workload["spec"]["nodeName"].as_str().map(str::to_string), + member: annotations[MEMBER_ANNOTATION].as_str().map(str::to_string), } } @@ -488,53 +495,42 @@ pub fn is_takeover(line: &str, route: &str, from: &str, cause: &str) -> bool { /// each running member logged about it last. pub async fn owner_of(route: &str) -> Option { for pod in supervisor_pods().await { - let Ok(Ok(logs)) = tokio::time::timeout( - Duration::from_secs(30), - kubectl_command() - .args([ - "-n", - &release_namespace(), - "logs", - &pod, - "-c", - SUPERVISOR_CONTAINER, - ]) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .output(), - ) - .await + let Ok(Some(logs)) = + tokio::time::timeout(Duration::from_secs(30), supervisor_logs(&pod)).await else { continue; }; - if supervises(&String::from_utf8_lossy(&logs.stdout), route) { + if supervises(&logs, route) { return Some(pod); } } None } +/// The logs of `pod`'s supervisor container. +pub async fn supervisor_logs(pod: &str) -> Option { + let output = kubectl_command() + .args([ + "-n", + &release_namespace(), + "logs", + pod, + "-c", + SUPERVISOR_CONTAINER, + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .output() + .await + .ok()?; + Some(String::from_utf8_lossy(&output.stdout).into_owned()) +} + /// The latest attach or detach line `pod`'s supervisor logged, if any. async fn attachment(pod: &str) -> Option { - let output = tokio::time::timeout( - Duration::from_secs(30), - kubectl_command() - .args([ - "-n", - &release_namespace(), - "logs", - pod, - "-c", - SUPERVISOR_CONTAINER, - ]) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .output(), - ) - .await - .ok()? - .ok()?; - String::from_utf8_lossy(&output.stdout) + tokio::time::timeout(Duration::from_secs(30), supervisor_logs(pod)) + .await + .ok()?? .lines() .rev() .find(|line| line.contains(ATTACHED) || line.contains(DETACHED)) diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 3eca3e4f7a..f7a2ed840d 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1553,6 +1553,24 @@ kubectl -n logs -l openshell.ai/sandbox-id=,open --tail=200 | grep -E 'sandbox-supervisor-|Supervisor takeover' ``` +With `supervisor_topology = "node"`, `-supervisor` is a DaemonSet +and each Pod's member ID is its node name; see the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). +A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. +The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation +records its node. Create launches before it writes the bootstrap Secret, so a +workload Pod in `ContainerCreating` with a +`FailedMount ... secret "os-sandbox-..." not found` Warning is normal for a few +seconds. + +```bash +kubectl -n openshell get daemonset,pod -l app.kubernetes.io/component=supervisor -o wide +kubectl get sandboxes.agents.x-k8s.io -A \ + -o custom-columns=NAME:.metadata.name,MEMBER:'.metadata.annotations.openshell\.ai/sandbox-runtime-supervisor-member' +kubectl -n openshell logs daemonset/-supervisor --prefix --tail=200 \ + | grep -E 'gateway accepted the supervisor host|could not open the supervisor host stream|gateway assignment stream failed' +``` + Each sandbox instance runs on one member, and a live owner keeps it. A member's console log names an instance by its route (the Sandbox's `openshell.ai/sandbox-runtime-supervisor-session` annotation) at the end of @@ -1827,10 +1845,12 @@ credential failures. | OpenShift gateway pod fails to start with an SCC/`runAsUser` error (e.g. `unable to validate against any security context constraint`) | Chart's default `podSecurityContext`/`securityContext` hardcodes `runAsUser`/`fsGroup`, which the restricted-v2 SCC rejects; it must instead inject the namespace-assigned UID/GID range | `oc -n openshell describe pod `; deploy with `podSecurityContext: null` and clear `securityContext.runAsUser` (see `deploy/helm/openshell/ci/values-openshift-scc.yaml`) | | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | +| A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | +| Sandbox create fails with `not scheduled within 60 s` or `the shared supervisor "" is not attached or has no room` (`supervisor_topology = "node"`) | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, not yet attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | -| A shared supervisor logs `gateway assignment stream failed` with `supervisor identity token is required`, `supervisor identity token is invalid`, a `supervisor identity:` credential refusal, or `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, or it runs as a ServiceAccount other than `shared_supervisor.service_account_name` | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | +| A shared supervisor logs `could not open the supervisor host stream` with `supervisor identity token is required`, `supervisor identity token is invalid`, or a `supervisor identity:` credential refusal, or logs `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, or it runs as a ServiceAccount other than `shared_supervisor.service_account_name` | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | | OpenShift sandbox pod fails to start (`unable to validate against any security context constraint`) | An explicit sandbox UID/GID override or custom security context conflicts with the namespace's SCC range | Inspect pod events and the namespace's `openshift.io/sa.scc.uid-range` and `openshift.io/sa.scc.supplemental-groups` annotations; remove incompatible `sandbox_uid` / `sandbox_gid` overrides so the driver uses the namespace-assigned identity. Current sandbox pods use `restricted-v2` without a privileged SCC grant; see the [OpenShift guide](https://docs.nvidia.com/openshell/latest/kubernetes/openshift) and [RFC 0012](https://github.com/ai-openshell/openshell/blob/main/rfc/0012-isolation-backend/README.md#motivation). | | OpenShift self-hosted Vault/OpenBao credential store pod never schedules (waits time out with `no matching resources found`) | The store's Helm chart pins `runAsUser`/`fsGroup`/seccomp, which restricted-v2 rejects, so the StatefulSet controller never creates the pod | Deploy the store's chart in its OpenShift mode (`--set global.openshift=true` for the OpenBao/Vault chart) so the namespace SCC assigns a compliant security context — no manual SCC grant needed | | Vault credential driver returns HTTP 403 / `Vault Kubernetes auth denied the configured role` on provider create | Vault's `auth/kubernetes` method or the gateway login role is not provisioned, or the role is not bound to the gateway service account and namespace | In Vault: `bao auth enable kubernetes` and `bao write auth/kubernetes/config kubernetes_host=... kubernetes_ca_cert=@...`; ensure the login role's `bound_service_account_names`/`bound_service_account_namespaces` match the gateway SA and namespace and its policy grants the credential paths | diff --git a/tasks/test.toml b/tasks/test.toml index ca254eec4d..466c256c37 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -343,6 +343,14 @@ description = "Run node-local SPIFFE Broker coverage with gateway relocation acr env = { HELM_K3S_AGENT_COUNT = "2", OPENSHELL_E2E_SPIRE_MIN_AGENTS = "3", OPENSHELL_E2E_KUBE_SPIRE_NODE_LOCAL = "1", OPENSHELL_E2E_KUBE_EXTERNAL_POSTGRES_SECRET = "e2e-spiffe-postgres", OPENSHELL_E2E_KUBE_SPIRE_BROKER = "1", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor_spiffe", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-shared-supervisor-spiffe" } run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor-spiffe-node-local.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' +["e2e:kubernetes:shared-supervisor-node"] +description = "Run Kubernetes e2e for one shared supervisor per node on a two-node cluster" +env = { HELM_K3S_AGENT_COUNT = "1", OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor_node", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-shared-supervisor-node" } +# The ephemeral k3d cluster gets one agent beside its server node; an existing +# context must already have two schedulable nodes. The shared supervisor +# requires gateway TLS, which the Skaffold values turn off. +run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor-node.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' + ["e2e:kubernetes:workspace-operator"] description = "Run Kubernetes e2e with operator workspace mode (pre-provisioned per-workspace namespaces)" env = { OPENSHELL_E2E_KUBE_EXTRA_VALUES = "deploy/helm/openshell/ci/values-workspace-operator.yaml", OPENSHELL_E2E_KUBE_TEST = "workspace_namespace_operator", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-kubernetes,e2e-kubernetes-workspace-operator" } From c73fd5877cb22f8770282d940982aa1e33d132bc Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Wed, 18 Nov 2026 22:09:06 +0200 Subject: [PATCH 06/18] feat(k8s): launch node-topology sandboxes once scheduled With supervisor_topology = "node", create and restart now return after the driver removes the scheduling gate. The bootstrap launches on the node once the scheduler binds the workload Pod, and a failed launch or a Pod that isn't scheduled within runtime_bootstrap_grace_seconds is logged and rolls the bootstrap back like any stale bootstrap. A shared supervisor now marks its boundary as stopping on every requested stop, so stopping a workload that is already gone no longer waits for a reconnect to time out and stall later instance removals. Update the Kubernetes HA docs, the driver README, and the debug-openshell-cluster skill to match. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 19 +- .../openshell-driver-kubernetes/src/driver.rs | 712 ++++++++++++++---- crates/openshell-supervisor/src/lib.rs | 8 +- docs/kubernetes/high-availability.mdx | 29 +- skills/debug-openshell-cluster/SKILL.md | 8 +- 5 files changed, 601 insertions(+), 175 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index f258523b1b..3e8f236869 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -484,15 +484,16 @@ The driver binds pool members to nodes (`bind_members_to_nodes`): the gateway accepts a supervisor only when the Pod its identity token resolves to is scheduled on the node it claims as its pool member ID. -- **Placement.** The driver removes the scheduling gate before it assigns the - instance and waits up to 60 seconds for the scheduler to bind the workload - Pod to a node. A Pod that is deleted or replaced while it waits fails the - launch. The node name is the pinned member: it travels in the placement - request, the gateway's assignment record, and the - `openshell.ai/sandbox-runtime-supervisor-member` annotation on the Sandbox - resource. The workload cannot start before its bootstrap Secret exists, so - the driver creates the Secret last, and the kubelet reports a `FailedMount` - Warning for it until then. +- **Placement.** The driver removes the scheduling gate and returns from + create or restart before it assigns the instance. The bootstrap task watches + the workload Pod and launches on the node in its `spec.nodeName`. A Pod that + is deleted or replaced, or a node supervisor that refuses the instance, rolls + the bootstrap back. So does a Pod that isn't scheduled within + `runtime_bootstrap_grace_seconds`. + The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation + records the pinned node. The bootstrap Secret exists before the gate is removed; until the + launch places the route, the supervisor refuses the runtime's dials and the + workload does not start. - **Recovery and takeover.** Recovery reads the member annotation and skips a node-topology generation that lacks one. Placement, takeover, and recovery of a pinned instance only consider its own member, so a lost node diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 53246e8440..19e8940c77 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -440,6 +440,25 @@ impl GenerationLaunchTarget { } } +/// A generation whose bootstrap Secret exists, ready to launch once its node +/// is known. +struct PreparedGeneration { + namespace: String, + cr_name: String, + sandbox_api: AgentSandboxApi, + sandbox_id: String, + cr_uid: String, + names: SandboxRuntimeNames, + launch_authentication: openshell_core::jwt::SandboxLaunchAuthentication, + staged: StagedBootstrapMaterial, + runtime_descriptor: openshell_sandbox_backend::boundary_protocol::SandboxRuntimeDescriptor, + proxy_ca: crate::sandbox_runtime::ProxyCaMaterial, + target: GenerationLaunchTarget, + admission_object: DynamicObject, + workload_pod_uid: String, + workload_pod_name: String, +} + /// Where workload runtimes reach the gateway's shared supervisor. struct SharedSupervisorTarget { namespace: String, @@ -735,6 +754,7 @@ const POD_UID_EXTRA: &str = "authentication.kubernetes.io/pod-uid"; const GPU_RESOURCE_NAME: &str = "nvidia.com/gpu"; const SPIFFE_WORKLOAD_API_VOLUME_NAME: &str = "spiffe-workload-api"; +#[derive(Clone)] struct AgentSandboxApi { api: Api, resource: ApiResource, @@ -4016,25 +4036,6 @@ impl KubernetesComputeDriver { let workload_pod_name = workload_pod.metadata.name.clone().ok_or_else(|| { KubernetesDriverError::Message("workload Pod has no name".to_string()) })?; - // A node supervisor serves only its own node, so the scheduler picks - // the node first. The missing bootstrap Secret keeps the ungated Pod - // from running until the launch is placed. - let node_member = if matches!(target, GenerationLaunchTarget::Shared { .. }) - && self.config.supervisor_topology == Some(SupervisorTopology::Node) - { - remove_scheduling_gates(&pods, &workload_pod_name).await?; - Some( - wait_for_workload_node( - &pods, - &workload_pod_name, - &workload_pod_uid, - NODE_SCHEDULING_TIMEOUT, - ) - .await?, - ) - } else { - None - }; let mut annotations = serde_json::json!({ ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_pod_uid.clone(), ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID: fence_uid.clone(), @@ -4043,9 +4044,6 @@ impl KubernetesComputeDriver { if let GenerationLaunchTarget::Dedicated { pod_uid, .. } = &target { annotations[ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID] = pod_uid.clone().into(); } - if let Some(member) = &node_member { - annotations[ANNOTATION_SUPERVISOR_MEMBER] = member.clone().into(); - } if let Some(policy) = target.control_policy() { annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_UID] = policy.uid.clone().into(); annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_GENERATION] = @@ -4119,8 +4117,8 @@ impl KubernetesComputeDriver { workload_pod_uid: workload_pod_uid.clone(), workload_pod_uid_path: PathBuf::from(SANDBOX_POD_UID_PATH), supervisor: supervisor_claim, - egress_policy_uid: fence_uid.clone(), - egress_policy_resource_version: fence_resource_version.clone(), + egress_policy_uid: fence_uid, + egress_policy_resource_version: fence_resource_version, control_path, sandbox_tls: SandboxTlsServerConfig { certificate_chain_path: PathBuf::from(BOUNDARY_CERTIFICATE_PATH), @@ -4137,7 +4135,6 @@ impl KubernetesComputeDriver { .provision() .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; let workload_owner = runtime_pod_owner(&workload_pod_name, &workload_pod_uid); - let instance_owner = workload_owner.clone(); let sandbox_secret = sandbox_bootstrap_secret( namespace, names, @@ -4150,17 +4147,195 @@ impl KubernetesComputeDriver { tls.private_key_pem.into_bytes(), workload_owner.clone(), ); - let secrets = Api::::namespaced(self.client.clone(), namespace); - if node_member.is_none() { - secrets - .create(&PostParams::default(), &sandbox_secret) + Api::::namespaced(self.client.clone(), namespace) + .create(&PostParams::default(), &sandbox_secret) + .await + .map_err(KubernetesDriverError::from_kube)?; + if matches!(target, GenerationLaunchTarget::Shared { .. }) { + self.create_generation_image_pull_secrets( + namespace, + names, + sandbox_id, + vec![workload_owner], + ) + .await?; + } + + let generation = PreparedGeneration { + namespace: namespace.to_string(), + cr_name: cr_name.to_string(), + sandbox_api: sandbox_api.clone(), + sandbox_id: sandbox_id.to_string(), + cr_uid: cr_uid.to_string(), + names: names.clone(), + launch_authentication: launch_authentication.clone(), + staged, + runtime_descriptor: provisioned.runtime_descriptor, + proxy_ca, + target, + admission_object, + workload_pod_uid, + workload_pod_name, + }; + // A node supervisor serves only its own node, so the scheduler picks + // the node first. Until the launch places the route there, the + // runtime's dials are refused and the workload doesn't start. + if let GenerationLaunchTarget::Shared { route, .. } = &generation.target + && self.config.supervisor_topology == Some(SupervisorTopology::Node) + { + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; + remove_scheduling_gates(&pods, &generation.workload_pod_name).await?; + tokio::spawn(Box::pin( + self.clone().launch_on_scheduled_node(generation, placement), + )); + return Ok(()); + } + Box::pin(self.launch_sandbox_runtime_generation(generation, None)).await + } + + /// Finish a node-topology launch once the scheduler binds the workload + /// Pod. A failed launch rolls the bootstrap back as a stale one would be. + async fn launch_on_scheduled_node( + self, + generation: PreparedGeneration, + placement: SupervisorPlacement, + ) { + let bootstrap_grace = Duration::from_secs(self.config.runtime_bootstrap_grace_seconds); + let deadline = tokio::time::Instant::now() + bootstrap_grace; + let sandbox_api = generation.sandbox_api.clone(); + let cr_name = generation.cr_name.clone(); + let cr_uid = generation.cr_uid.clone(); + let workload_pod_uid = generation.workload_pod_uid.clone(); + let pods = Api::::namespaced(self.client.clone(), &generation.namespace); + let scheduled_or_replaced = + |pod: Option<&Pod>| workload_pod_scheduled_or_replaced(pod, &workload_pod_uid); + let pod = loop { + match tokio::time::timeout_at( + deadline, + await_condition( + pods.clone(), + &generation.workload_pod_name, + scheduled_or_replaced, + ), + ) + .await + { + Ok(Ok(pod)) => break pod, + Err(_) => { + warn!( + sandbox = cr_name, + "the workload Pod was not scheduled within the bootstrap grace; the stale bootstrap will be rolled back" + ); + return; + } + Ok(Err(error)) => { + debug!(%error, sandbox = cr_name, "workload Pod scheduling watch failed; retrying"); + tokio::time::sleep_until( + deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), + ) + .await; + } + } + }; + // A deleted or replaced Pod leaves its bootstrap to the reaper. + let Some(node) = pod + .filter(|pod| pod.metadata.uid.as_deref() == Some(workload_pod_uid.as_str())) + .and_then(|pod| pod.spec?.node_name) + else { + return; + }; + let _guard = self + .lifecycle_gates + .gate_for(&generation.sandbox_id) + .lock_owned() + .await; + // A stop, delete, reaper, or newer attempt may have run while the + // Pod waited for a node, and the reaper rolls back a stale bootstrap. + let read_awaiting = || async { + tokio::time::timeout(KUBE_API_TIMEOUT, sandbox_api.api.get_opt(&cr_name)) .await - .map_err(KubernetesDriverError::from_kube)?; + .ok() + .and_then(Result::ok) + .flatten() + .filter(|object| { + sandbox_runtime_awaits_launch(object, &cr_uid, &workload_pod_uid) + && !sandbox_runtime_bootstrap_is_stale( + object, + SystemTime::now(), + bootstrap_grace, + ) + }) + }; + if read_awaiting().await.is_none() { + return; } + let launch = Box::pin(self.launch_sandbox_runtime_generation(generation, Some(node))).await; + if let Err(error) = launch { + warn!(sandbox = cr_name, %error, "sandbox-runtime launch on the scheduled node failed; rolling back"); + self.remove_shared_instance(&placement); + if let Some(object) = read_awaiting().await { + self.roll_back_sandbox_runtime_bootstrap(&sandbox_api, &object) + .await; + } + } + } + + /// Install the parts of a generation that depend on its node: the + /// supervisor launch and the workload's release. `node_member` is the + /// scheduled node in the node topology. + async fn launch_sandbox_runtime_generation( + &self, + generation: PreparedGeneration, + node_member: Option, + ) -> Result<(), KubernetesDriverError> { + let PreparedGeneration { + namespace, + cr_name, + sandbox_api, + sandbox_id, + cr_uid, + names, + launch_authentication, + staged, + runtime_descriptor, + proxy_ca, + target, + admission_object, + workload_pod_uid, + workload_pod_name, + } = generation; + let (namespace, cr_name, sandbox_id, cr_uid, names) = ( + namespace.as_str(), + cr_name.as_str(), + sandbox_id.as_str(), + cr_uid.as_str(), + &names, + ); + let launch_authentication = &launch_authentication; + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(member) = &node_member { + patch_dynamic_object_with_resource_version_retry( + &sandbox_api.api, + cr_name, + |version| { + serde_json::json!({ + "metadata": { + "resourceVersion": version, + "annotations": {ANNOTATION_SUPERVISOR_MEMBER: member}, + } + }) + }, + ) + .await?; + } + + let workload_owner = runtime_pod_owner(&workload_pod_name, &workload_pod_uid); + let secrets = Api::::namespaced(self.client.clone(), namespace); match &target { GenerationLaunchTarget::Dedicated { pod_uid, .. } => { - let descriptor = provisioned - .runtime_descriptor + let descriptor = runtime_descriptor .backend_descriptor() .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; let supervisor_owner = runtime_pod_owner(&names.supervisor_pod, pod_uid); @@ -4206,18 +4381,11 @@ impl KubernetesComputeDriver { .map_err(KubernetesDriverError::from_kube)?; } GenerationLaunchTarget::Shared { shared, route, .. } => { - self.create_generation_image_pull_secrets( - namespace, - names, - sandbox_id, - vec![workload_owner], - ) - .await?; let registration = shared_instance_registration( &admission_object, route, sandbox_id, - provisioned.runtime_descriptor, + runtime_descriptor, launch_authentication, proxy_ca, )?; @@ -4240,7 +4408,7 @@ impl KubernetesComputeDriver { names, sandbox_id, launch_material, - instance_owner, + workload_owner, ), ) .await @@ -4266,12 +4434,7 @@ impl KubernetesComputeDriver { })?; } } - if node_member.is_some() { - secrets - .create(&PostParams::default(), &sandbox_secret) - .await - .map_err(KubernetesDriverError::from_kube)?; - } else { + if node_member.is_none() { remove_scheduling_gates(&pods, &workload_pod_name).await?; } patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { @@ -5841,6 +6004,16 @@ impl KubernetesComputeDriver { ) { return; } + self.roll_back_sandbox_runtime_bootstrap(lookup_api, object) + .await; + } + + /// Delete a failed create, or suspend a failed restart. + async fn roll_back_sandbox_runtime_bootstrap( + &self, + lookup_api: &AgentSandboxApi, + object: &DynamicObject, + ) { if sandbox_runtime_bootstrap_operation(object) != Some("create") { warn!( sandbox = object.metadata.name.as_deref().unwrap_or(""), @@ -7766,9 +7939,6 @@ const SANDBOX_POD_UID_PATH: &str = "/.openshell/pod-identity/uid"; const SANDBOX_PROXY_CA_VOLUME_NAME: &str = "openshell-run"; const SANDBOX_PROXY_CA_MOUNT_PATH: &str = "/run"; const SANDBOX_BOOTSTRAP_SCHEDULING_GATE: &str = "openshell.ai/bootstrap"; -/// Longest wait for the scheduler to bind a node-topology workload Pod. -const NODE_SCHEDULING_TIMEOUT: Duration = Duration::from_mins(1); -const NODE_SCHEDULING_POLL: Duration = Duration::from_millis(500); async fn remove_scheduling_gates(pods: &Api, name: &str) -> Result<(), KubernetesDriverError> { pods.patch( @@ -7781,45 +7951,35 @@ async fn remove_scheduling_gates(pods: &Api, name: &str) -> Result<(), Kube .map_err(KubernetesDriverError::from_kube) } -/// The node the scheduler bound workload Pod `name` (UID `uid`) to. Fails -/// when it isn't bound within `timeout` or the Pod is gone or replaced. -async fn wait_for_workload_node( - pods: &Api, - name: &str, - uid: &str, - timeout: Duration, -) -> Result { - let wait = async { - loop { - let pod = tokio::time::timeout(KUBE_API_TIMEOUT, pods.get_opt(name)) - .await - .map_err(|_| { - KubernetesDriverError::Message("timed out reading the workload Pod".to_string()) - })? - .map_err(KubernetesDriverError::from_kube)? - .filter(|pod| pod.metadata.uid.as_deref() == Some(uid)) - .ok_or_else(|| { - KubernetesDriverError::Precondition( - "the workload Pod was deleted or replaced before it was scheduled" - .to_string(), - ) - })?; - if let Some(node) = pod +/// Whether workload Pod `uid` is bound to a node, or was deleted or replaced, +/// which the launch then reports. +fn workload_pod_scheduled_or_replaced(pod: Option<&Pod>, uid: &str) -> bool { + pod.is_none_or(|pod| { + pod.metadata.uid.as_deref() != Some(uid) + || pod .spec - .and_then(|spec| spec.node_name) - .filter(|node| !node.is_empty()) - { - return Ok(node); - } - tokio::time::sleep(NODE_SCHEDULING_POLL).await; - } - }; - tokio::time::timeout(timeout, wait).await.map_err(|_| { - KubernetesDriverError::Precondition(format!( - "the workload Pod was not scheduled within {} s; no node may have room for it", - timeout.as_secs() - )) - })? + .as_ref() + .and_then(|spec| spec.node_name.as_deref()) + .is_some_and(|node| !node.is_empty()) + }) +} + +/// Whether `object` is still the bootstrap attempt that prepared workload Pod +/// `workload_pod_uid`, waiting for its node-dependent launch. +fn sandbox_runtime_awaits_launch( + object: &DynamicObject, + cr_uid: &str, + workload_pod_uid: &str, +) -> bool { + object.metadata.uid.as_deref() == Some(cr_uid) + && sandbox_runtime_bootstrap_phase(object) == Some(SandboxRuntimeBootstrapPhase::Preparing) + && object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID)) + .map(String::as_str) + == Some(workload_pod_uid) } fn sandbox_bootstrap_secret_name(spec: &serde_json::Value) -> Option<&str> { @@ -10084,71 +10244,343 @@ mod tests { ) } - type QueuedResponses = Arc>>>; + const SCHEDULED_SANDBOX_PATH: &str = + "/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes/sandbox-cr"; + const WORKLOAD_PODS_PATH: &str = "/api/v1/namespaces/openshell/pods"; - fn pod_api_answering( - responses: Vec>, - ) -> (Api, QueuedResponses) { - let responses = Arc::new(std::sync::Mutex::new(VecDeque::from(responses))); - let remaining = responses.clone(); - let service = tower::service_fn(move |request: http::Request| { - let responses = remaining.clone(); - async move { - assert_eq!(request.method(), http::Method::GET); - assert_eq!( - request.uri().path(), - "/api/v1/namespaces/openshell/pods/workload" - ); - let response = responses - .lock() - .unwrap() - .pop_front() - .expect("unexpected Kubernetes API request"); - Ok::<_, std::convert::Infallible>(response) - } - }); - let client = Client::new(service, "openshell"); - (Api::namespaced(client, "openshell"), responses) + fn scheduled_sandbox(phase: SandboxRuntimeBootstrapPhase, started_at_ms: i64) -> DynamicObject { + serde_json::from_value(serde_json::json!({ + "apiVersion": "agents.x-k8s.io/v1beta1", + "kind": "Sandbox", + "metadata": { + "name": "sandbox-cr", + "namespace": "openshell", + "uid": "cr-uid", + "resourceVersion": "7", + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase.as_str(), + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "create", + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: started_at_ms.to_string(), + ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: "pod-uid", + LABEL_SANDBOX_NAME: "sandbox-name", + ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC: + openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec(None) + .unwrap(), + }, + }, + })) + .unwrap() } - fn workload_pod_json(uid: &str, node: Option<&str>) -> http::Response { + fn scheduled_sandbox_json( + phase: SandboxRuntimeBootstrapPhase, + started_at_ms: i64, + ) -> http::Response { + kube_test_response( + http::StatusCode::OK, + serde_json::to_value(scheduled_sandbox(phase, started_at_ms)).unwrap(), + ) + } + + fn bound_workload_pods_json() -> http::Response { kube_test_response( http::StatusCode::OK, serde_json::json!({ "apiVersion": "v1", - "kind": "Pod", - "metadata": {"name": "workload", "namespace": "openshell", "uid": uid}, - "spec": {"containers": [], "nodeName": node}, + "kind": "PodList", + "metadata": {"resourceVersion": "1"}, + "items": [{ + "metadata": {"name": "workload", "namespace": "openshell", "uid": "pod-uid"}, + "spec": {"containers": [], "nodeName": "node-a"}, + }], }), ) } - #[tokio::test(start_paused = true)] - async fn node_topology_waits_for_the_scheduler_to_bind_the_workload() { - let (pods, remaining) = pod_api_answering(vec![ - workload_pod_json("uid-1", None), - workload_pod_json("uid-1", Some("node-a")), - ]); - let node = wait_for_workload_node(&pods, "workload", "uid-1", NODE_SCHEDULING_TIMEOUT) - .await - .unwrap(); - assert_eq!(node, "node-a"); - assert!(remaining.lock().unwrap().is_empty()); + /// A shared generation of `sandbox-cr`, prepared but not yet launched. + fn scheduled_generation(driver: &KubernetesComputeDriver) -> PreparedGeneration { + let route = openshell_sandbox_backend::runtime_routed::new_route_handle(); + let session_id = openshell_core::SandboxSessionId::new(); + let launch_authentication = openshell_core::jwt::SandboxLaunchAuthentication { + supervisor: openshell_core::jwt::SupervisorAuthBundle { + session_id, + runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( + "generation-1", + ) + .unwrap(), + session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), + auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + gateway_token: openshell_core::jwt::SecretJwt::parse("gateway.token.value") + .unwrap(), + gateway_expires_at: i64::MAX, + sandbox_token: openshell_core::jwt::SecretJwt::parse("sandbox.token.value") + .unwrap(), + sandbox_expires_at: i64::MAX, + ssh_host_private_key: None, + traces_otlp_headers: None, + ocsf_otlp_headers: None, + agent_otlp_headers: None, + otlp_tls: Vec::new(), + traces_otlp_tls: None, + ocsf_otlp_tls: None, + agent_otlp_tls: None, + }, + gateway_id: "gateway-a".to_string(), + verification_keys: vec![openshell_core::jwt::SessionVerificationKey { + key_id: "key-1".to_string(), + public_key_pem: b"public-key".to_vec(), + }], + }; + let target = SharedSupervisorTarget { + namespace: "openshell".to_string(), + authority: "openshell-supervisor.openshell.svc:5500".to_string(), + address: "10.43.0.9:5500".parse().unwrap(), + selector: BTreeMap::new(), + }; + let tls = generate_sandbox_tls_material(session_id).unwrap(); + let provisioned = KubernetesSandboxRuntimeBoundarySpec { + boundary_id: "sandbox-id".to_string(), + generation: "generation-1".to_string(), + session_id, + session_rotation: launch_authentication.supervisor.session_rotation, + auth_epoch: launch_authentication.supervisor.auth_epoch, + gateway_id: launch_authentication.gateway_id.clone(), + verification_keys: gateway_verification_keys(&launch_authentication.verification_keys) + .unwrap(), + namespace_uid: "namespace-uid".to_string(), + sandbox_resource_uid: "cr-uid".to_string(), + workload_pod_uid: "pod-uid".to_string(), + workload_pod_uid_path: PathBuf::from(SANDBOX_POD_UID_PATH), + supervisor: KubernetesSupervisorClaim::SandboxInstance(route.clone()), + egress_policy_uid: "fence-uid".to_string(), + egress_policy_resource_version: "1".to_string(), + control_path: KubernetesControlPath::RuntimeInitiatedShared { + control_authority: target.authority.clone(), + supervisor_address: target.address, + supervisor_namespace: target.namespace.clone(), + route: route.clone(), + control_policy_uid: "control-uid".to_string(), + control_policy_resource_version: "1".to_string(), + }, + sandbox_tls: SandboxTlsServerConfig { + certificate_chain_path: PathBuf::from(BOUNDARY_CERTIFICATE_PATH), + private_key_path: PathBuf::from(BOUNDARY_PRIVATE_KEY_PATH), + }, + supervisor_tls: SandboxTlsClientConfig { + server_name: tls.server_name, + trust_anchor_pem: tls.trust_anchor_pem, + }, + host_gateway_ip: None, + workload_identity: ResolvedWorkloadIdentity::new( + 1000, + 1000, + Vec::new(), + "kubernetes-config".to_string(), + "sandbox:cr-uid".to_string(), + ) + .unwrap(), + child_env: std::collections::HashMap::new(), + } + .provision() + .unwrap(); + let shared = SharedSupervisor::new( + crate::config::SharedSupervisorConfig { + service_name: "openshell-supervisor".to_string(), + service_namespace: "openshell".to_string(), + runtime_port: 5500, + token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: "openshell-supervisor".to_string(), + require_identity_token: true, + }, + SharedSupervision::new(), + ); + PreparedGeneration { + namespace: "openshell".to_string(), + cr_name: "sandbox-cr".to_string(), + sandbox_api: KubernetesComputeDriver::agent_sandbox_api( + driver.client.clone(), + "v1beta1", + "openshell", + ), + sandbox_id: "sandbox-id".to_string(), + cr_uid: "cr-uid".to_string(), + names: SandboxRuntimeNames::new("sandbox-id"), + launch_authentication, + staged: StagedBootstrapMaterial { + upstream_proxy_ca_bundle: None, + client_tls: None, + }, + runtime_descriptor: provisioned.runtime_descriptor, + proxy_ca: generate_proxy_ca_material().unwrap(), + target: GenerationLaunchTarget::Shared { + shared, + route, + target, + control_policy: VerifiedControlPolicy { + uid: "control-uid".to_string(), + resource_version: "1".to_string(), + generation: 1, + }, + }, + admission_object: scheduled_sandbox( + SandboxRuntimeBootstrapPhase::Preparing, + openshell_core::time::now_ms(), + ), + workload_pod_uid: "pod-uid".to_string(), + workload_pod_name: "workload".to_string(), + } + } - // A replaced Pod is not the one this launch validated. - let (pods, _) = pod_api_answering(vec![workload_pod_json("uid-2", Some("node-a"))]); - let error = wait_for_workload_node(&pods, "workload", "uid-1", NODE_SCHEDULING_TIMEOUT) - .await - .unwrap_err(); - assert!(error.to_string().contains("replaced"), "{error}"); + #[tokio::test] + async fn scheduled_launch_the_pool_cannot_place_is_rolled_back() { + let awaiting = || { + scheduled_sandbox_json( + SandboxRuntimeBootstrapPhase::Preparing, + openshell_core::time::now_ms(), + ) + }; + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::POST, + "/api/v1/namespaces/openshell/secrets", + kube_test_response( + http::StatusCode::CREATED, + serde_json::json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": {"name": "instance", "namespace": "openshell"}, + }), + ), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::DELETE, + SCHEDULED_SANDBOX_PATH, + kube_test_response(http::StatusCode::OK, serde_json::json!({})), + ), + ], + ); + let generation = scheduled_generation(&driver); + let GenerationLaunchTarget::Shared { route, .. } = &generation.target else { + unreachable!(); + }; + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; + Box::pin( + driver + .clone() + .launch_on_scheduled_node(generation, placement), + ) + .await; + assert!(steps.lock().unwrap().is_empty()); + let bodies = bodies.lock().unwrap(); + let delete = bodies.last().unwrap(); + assert_eq!(delete["preconditions"]["uid"], "cr-uid"); + assert_eq!(delete["preconditions"]["resourceVersion"], "7"); + } - // An unschedulable Pod fails the launch once the wait runs out. - let (pods, _) = - pod_api_answering((0..8).map(|_| workload_pod_json("uid-1", None)).collect()); - let error = wait_for_workload_node(&pods, "workload", "uid-1", Duration::from_secs(2)) - .await - .unwrap_err(); - assert!(error.to_string().contains("not scheduled"), "{error}"); + #[tokio::test] + async fn scheduled_launch_skips_a_sandbox_that_moved_on_or_went_stale() { + let now = openshell_core::time::now_ms(); + for sandbox in [ + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now), + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, 0), + ] { + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, sandbox), + ], + ); + let generation = scheduled_generation(&driver); + Box::pin( + driver + .clone() + .launch_on_scheduled_node(generation, SupervisorPlacement::Dedicated), + ) + .await; + assert!(steps.lock().unwrap().is_empty()); + assert!(bodies.lock().unwrap().is_empty()); + } + } + + #[test] + fn scheduled_launch_runs_only_for_the_attempt_that_prepared_it() { + let sandbox = |uid: &str, phase: &str, workload_uid: &str| { + serde_json::from_value::(serde_json::json!({ + "apiVersion": "agents.x-k8s.io/v1beta1", + "kind": "Sandbox", + "metadata": { + "name": "sandbox-cr", + "namespace": "openshell", + "uid": uid, + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase, + ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_uid, + }, + }, + })) + .unwrap() + }; + let preparing = SandboxRuntimeBootstrapPhase::Preparing.as_str(); + assert!(sandbox_runtime_awaits_launch( + &sandbox("cr-1", preparing, "pod-1"), + "cr-1", + "pod-1" + )); + // Stopped or suspended while it waited. + assert!(!sandbox_runtime_awaits_launch( + &sandbox( + "cr-1", + SandboxRuntimeBootstrapPhase::Suspending.as_str(), + "pod-1" + ), + "cr-1", + "pod-1" + )); + // A retried or newer attempt prepared another workload Pod. + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-1", preparing, "pod-2"), + "cr-1", + "pod-1" + )); + // Already launched, or a stop is releasing it. + for phase in [ + SandboxRuntimeBootstrapPhase::Released, + SandboxRuntimeBootstrapPhase::Releasing, + ] { + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-1", phase.as_str(), "pod-1"), + "cr-1", + "pod-1" + )); + } + // The bootstrap completed and its annotations were cleared. + let mut completed = sandbox("cr-1", preparing, "pod-1"); + completed.metadata.annotations = None; + assert!(!sandbox_runtime_awaits_launch(&completed, "cr-1", "pod-1")); + // Deleted and recreated under the same name. + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-2", preparing, "pod-1"), + "cr-1", + "pod-1" + )); } fn network_trust_bundle(gateway_id: &str, digest: &str) -> NetworkSupervisorTrustBundle { diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index b9e6327d15..c93e5efd45 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -1033,8 +1033,8 @@ pub struct SandboxInstanceControls { /// Completes when the owner asks the instance to stop its workload. It is /// first polled once the workload has started. pub shutdown: Pin + Send>>, - /// True when `shutdown` also ends this process, so its boundary may be - /// stopping too and a lost connection is not worth recovering. + /// True when `shutdown` also ends this process, so the whole stop must + /// finish within the process shutdown deadline. pub shutdown_ends_process: bool, /// Requests to suspend only this instance. A failed suspension can be /// retried by sending another request. Closing the stream disables it. @@ -1848,9 +1848,11 @@ pub async fn run_sandbox_instance( )); } () = &mut shutdown_requested => { + // A workload that is already gone must not hold the stop + // until a reconnect to it times out. + running.begin_stop(); if shutdown_ends_process { shutdown_deadline = Some(tokio::time::Instant::now() + SHUTDOWN_TIMEOUT); - running.begin_stop(); } let wait = async { let _ = agent diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index e20f039587..87ca5cfa67 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -753,24 +753,17 @@ gatewayConfig: ``` Each supervisor's Pod-bound token also proves its node: the gateway accepts a -supervisor only for the node that the token's Pod runs on. Your cluster must -meet these conditions: - -- The ServiceAccount restriction above holds. Anyone who can create its Pods - or tokens can claim any node. -- Only principals that can already create Pods in the sandbox namespace can - create Secrets there. A node-topology workload Pod is scheduled before its - bootstrap Secret exists, so a Secret created first under that name is - mounted until the gateway's own create fails and rolls back the sandbox. - -We recommend running the API server with the `Node` authorizer and the -`NodeRestriction` admission plugin, so a compromised node's kubelet cannot -obtain tokens for another node's supervisor. - -Sandbox creation waits up to 60 seconds for the scheduler to place the -workload, and fails if that node has no attached supervisor. If sandbox -templates tolerate node taints, set the same tolerations in -`supervisor.tolerations`; if they select a node pool, cover it with +supervisor only for the node that the token's Pod runs on. The ServiceAccount +restriction above still applies: anyone who can create its Pods or tokens can +claim any node. We recommend running the API server with the `Node` authorizer +and the `NodeRestriction` admission plugin, so a compromised node's kubelet +cannot obtain tokens for another node's supervisor. + +If the scheduler places a workload on a node without an attached supervisor, +or no node accepts it within `runtime_bootstrap_grace_seconds`, the gateway +deletes the new sandbox or stops the restarted one. A supervisor must run on +every node that can host a sandbox. If sandbox templates tolerate node taints, +set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with `supervisor.nodeSelector`. GPU nodes usually need: ```yaml diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index f7a2ed840d..ee3953bf0a 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1558,10 +1558,8 @@ and each Pod's member ID is its node name; see the [per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation -records its node. Create launches before it writes the bootstrap Secret, so a -workload Pod in `ContainerCreating` with a -`FailedMount ... secret "os-sandbox-..." not found` Warning is normal for a few -seconds. +records its node. Until the workload Pod is scheduled, the runtime logs +`Runtime-initiated control cannot reach the supervisor; retrying`. ```bash kubectl -n openshell get daemonset,pod -l app.kubernetes.io/component=supervisor -o wide @@ -1846,7 +1844,7 @@ credential failures. | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | | A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | -| Sandbox create fails with `not scheduled within 60 s` or `the shared supervisor "" is not attached or has no room` (`supervisor_topology = "node"`) | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, not yet attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room`), or, once `runtime_bootstrap_grace_seconds` passes, `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart) | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, not yet attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | From 0bee35d9cda6de63d5305708ee11cce827ec7c98 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:36:26 +0200 Subject: [PATCH 07/18] fix(k8s): keep a stopped sandbox stopped when its deferred launch finishes The node-topology launch runs after create returns, outside the gateway's lifecycle lock. Its member and release writes now re-check on every conflict retry that the sandbox still awaits this launch, so a stop, delete, or newer attempt served by another replica is never overwritten; the existing failure path then withdraws the placed instance. A transient error reading the sandbox before the launch is retried until the bootstrap grace instead of abandoning the launch. Signed-off-by: Gal Zaidman --- .../openshell-driver-kubernetes/src/driver.rs | 354 ++++++++++++++++-- 1 file changed, 314 insertions(+), 40 deletions(-) diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 19e8940c77..6a57d9476f 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -571,20 +571,40 @@ async fn patch_dynamic_object_with_resource_version_retry( name: &str, mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, ) -> Result { + patch_dynamic_object_if(api, name, |_, resource_version| { + Some(patch_for_resource_version(resource_version)) + }) + .await? + .ok_or(KubernetesDriverError::NotFound) +} + +/// Merge-patch `name` with the patch `patch_for` builds from the current +/// object and its resourceVersion, retrying resourceVersion conflicts. `None` +/// from `patch_for` declines the patch. Returns the patched object, or `None` +/// when declined or the object is not found when read. +async fn patch_dynamic_object_if( + api: &Api, + name: &str, + mut patch_for: impl FnMut(&DynamicObject, &str) -> Option, +) -> Result, KubernetesDriverError> { let operation = async { loop { - let current = api.get(name).await?; + let Some(current) = api.get_opt(name).await? else { + return Ok(None); + }; let resource_version = current .metadata .resource_version .as_deref() .unwrap_or_default(); - let patch = patch_for_resource_version(resource_version); + let Some(patch) = patch_for(¤t, resource_version) else { + return Ok(None); + }; match api .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) .await { - Ok(updated) => return Ok(updated), + Ok(updated) => return Ok(Some(updated)), Err(error) if is_kube_resource_version_conflict(&error) => { tokio::task::yield_now().await; } @@ -4254,28 +4274,41 @@ impl KubernetesComputeDriver { // A stop, delete, reaper, or newer attempt may have run while the // Pod waited for a node, and the reaper rolls back a stale bootstrap. let read_awaiting = || async { - tokio::time::timeout(KUBE_API_TIMEOUT, sandbox_api.api.get_opt(&cr_name)) + let object = tokio::time::timeout(KUBE_API_TIMEOUT, sandbox_api.api.get_opt(&cr_name)) .await - .ok() - .and_then(Result::ok) - .flatten() - .filter(|object| { - sandbox_runtime_awaits_launch(object, &cr_uid, &workload_pod_uid) - && !sandbox_runtime_bootstrap_is_stale( - object, - SystemTime::now(), - bootstrap_grace, - ) - }) + .map_err(|_| "timed out".to_string())? + .map_err(|error| error.to_string())?; + Ok::<_, String>(object.filter(|object| { + sandbox_runtime_awaits_launch(object, &cr_uid, &workload_pod_uid) + && !sandbox_runtime_bootstrap_is_stale( + object, + SystemTime::now(), + bootstrap_grace, + ) + })) }; - if read_awaiting().await.is_none() { - return; + loop { + match read_awaiting().await { + Ok(Some(_)) => break, + Ok(None) => return, + Err(error) if tokio::time::Instant::now() >= deadline => { + warn!(sandbox = cr_name, %error, "could not read the sandbox within the bootstrap grace; the stale bootstrap will be rolled back"); + return; + } + Err(error) => { + debug!(%error, sandbox = cr_name, "reading the sandbox before its launch failed; retrying"); + tokio::time::sleep_until( + deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), + ) + .await; + } + } } let launch = Box::pin(self.launch_sandbox_runtime_generation(generation, Some(node))).await; if let Err(error) = launch { warn!(sandbox = cr_name, %error, "sandbox-runtime launch on the scheduled node failed; rolling back"); self.remove_shared_instance(&placement); - if let Some(object) = read_awaiting().await { + if let Ok(Some(object)) = read_awaiting().await { self.roll_back_sandbox_runtime_bootstrap(&sandbox_api, &object) .await; } @@ -4315,20 +4348,29 @@ impl KubernetesComputeDriver { ); let launch_authentication = &launch_authentication; let pods = Api::::namespaced(self.client.clone(), namespace); + // A deferred launch runs outside the gateway's lifecycle lock, so its + // writes yield to a stop, delete, or newer attempt that got there first. + let awaits_launch = |object: &DynamicObject| { + sandbox_runtime_awaits_launch(object, cr_uid, &workload_pod_uid) + }; + let superseded = || { + KubernetesDriverError::Precondition( + "the sandbox was stopped or replaced before its launch completed".to_string(), + ) + }; if let Some(member) = &node_member { - patch_dynamic_object_with_resource_version_retry( - &sandbox_api.api, - cr_name, - |version| { + patch_dynamic_object_if(&sandbox_api.api, cr_name, |object, version| { + awaits_launch(object).then(|| { serde_json::json!({ "metadata": { "resourceVersion": version, "annotations": {ANNOTATION_SUPERVISOR_MEMBER: member}, } }) - }, - ) - .await?; + }) + }) + .await? + .ok_or_else(superseded)?; } let workload_owner = runtime_pod_owner(&workload_pod_name, &workload_pod_uid); @@ -4434,13 +4476,20 @@ impl KubernetesComputeDriver { })?; } } + let released = |version: &str| { + sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) + }; if node_member.is_none() { remove_scheduling_gates(&pods, &workload_pod_name).await?; + patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, released) + .await?; + } else { + patch_dynamic_object_if(&sandbox_api.api, cr_name, |object, version| { + awaits_launch(object).then(|| released(version)) + }) + .await? + .ok_or_else(superseded)?; } - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { - sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) - }) - .await?; let control = match target { GenerationLaunchTarget::Dedicated { .. } => BootstrapControl::SupervisorPod { pods, @@ -10297,6 +10346,116 @@ mod tests { ) } + fn scheduled_shared_supervisor() -> SharedSupervisor { + SharedSupervisor::new( + crate::config::SharedSupervisorConfig { + service_name: "openshell-supervisor".to_string(), + service_namespace: "openshell".to_string(), + runtime_port: 5500, + token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: "openshell-supervisor".to_string(), + require_identity_token: true, + }, + SharedSupervision::new(), + ) + } + + /// Durable pool records that accept every launch. + #[derive(Debug)] + struct AcceptingPlacement; + + impl openshell_supervisor_control::InstancePlacement for AcceptingPlacement { + fn place_launch( + &self, + _request: openshell_supervisor_control::PlacementRequest, + ) -> openshell_supervisor_control::PlacementFuture { + Box::pin(async { Ok(()) }) + } + + fn recorded(&self) -> openshell_supervisor_control::PlacementFuture> { + Box::pin(async { Ok(BTreeMap::new()) }) + } + + fn record_recovered( + &self, + _assignment: openshell_supervisor_control::proto::SandboxInstanceAssignment, + _member: Option, + ) -> openshell_supervisor_control::PlacementFuture { + Box::pin(async { Ok(()) }) + } + + fn prepare_runtime( + &self, + _: openshell_supervisor_control::PreparationRequest, + ) -> openshell_supervisor_control::PlacementFuture { + unreachable!("deferred launches prepare no warm runtime") + } + + fn prepared_runtimes( + &self, + _: String, + _: Vec, + ) -> openshell_supervisor_control::PlacementFuture< + Vec, + > { + unreachable!("deferred launches list no warm runtime") + } + + fn release_preparation( + &self, + _: openshell_supervisor_control::PreparationRevision, + ) -> openshell_supervisor_control::PlacementFuture< + openshell_supervisor_control::PreparationRelease, + > { + unreachable!("deferred launches release no warm runtime") + } + + fn retire_preparation( + &self, + _: openshell_supervisor_control::PreparationRetirement, + ) -> openshell_supervisor_control::PlacementFuture< + openshell_supervisor_control::PreparationRelease, + > { + unreachable!("deferred launches retire no warm runtime") + } + + fn activate_runtime( + &self, + _: openshell_supervisor_control::ActivationRequest, + ) -> openshell_supervisor_control::PlacementFuture< + openshell_supervisor_control::proto::SandboxInstanceAssignment, + > { + unreachable!("deferred launches activate no warm runtime") + } + } + + fn instance_secret_created() -> http::Response { + kube_test_response( + http::StatusCode::CREATED, + serde_json::json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": {"name": "instance", "namespace": "openshell"}, + }), + ) + } + + /// Run the deferred launch of `generation` to completion. + async fn launch_scheduled(driver: &KubernetesComputeDriver, generation: PreparedGeneration) { + let GenerationLaunchTarget::Shared { route, .. } = &generation.target else { + unreachable!(); + }; + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; + Box::pin( + driver + .clone() + .launch_on_scheduled_node(generation, placement), + ) + .await; + } + /// A shared generation of `sandbox-cr`, prepared but not yet launched. fn scheduled_generation(driver: &KubernetesComputeDriver) -> PreparedGeneration { let route = openshell_sandbox_backend::runtime_routed::new_route_handle(); @@ -10383,17 +10542,10 @@ mod tests { } .provision() .unwrap(); - let shared = SharedSupervisor::new( - crate::config::SharedSupervisorConfig { - service_name: "openshell-supervisor".to_string(), - service_namespace: "openshell".to_string(), - runtime_port: 5500, - token_secret_name: "openshell-supervisor-token".to_string(), - service_account_name: "openshell-supervisor".to_string(), - require_identity_token: true, - }, - SharedSupervision::new(), - ); + let shared = driver + .shared_supervisor + .clone() + .unwrap_or_else(scheduled_shared_supervisor); PreparedGeneration { namespace: "openshell".to_string(), cr_name: "sandbox-cr".to_string(), @@ -10490,6 +10642,128 @@ mod tests { assert_eq!(delete["preconditions"]["resourceVersion"], "7"); } + #[tokio::test] + async fn scheduled_launch_yields_to_a_stop_before_its_member_write() { + let now = openshell_core::time::now_ms(); + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now), + ), + // A stop on another replica lands before the member write. + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now), + ), + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now), + ), + ], + ); + let generation = scheduled_generation(&driver); + launch_scheduled(&driver, generation).await; + assert!(steps.lock().unwrap().is_empty()); + // Nothing was written, created, or rolled back. + assert!(bodies.lock().unwrap().is_empty()); + } + + #[tokio::test] + async fn scheduled_launch_yields_to_a_stop_before_release() { + let now = openshell_core::time::now_ms(); + let awaiting = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now); + let stopping = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now); + let (mut driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::POST, + "/api/v1/namespaces/openshell/secrets", + instance_secret_created(), + ), + // A stop on another replica lands before the release. + (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), + ], + ); + let shared = scheduled_shared_supervisor(); + shared + .supervision() + .controller() + .install_placement(Arc::new(AcceptingPlacement)); + driver.shared_supervisor = Some(shared.clone()); + let generation = scheduled_generation(&driver); + launch_scheduled(&driver, generation).await; + assert!(steps.lock().unwrap().is_empty()); + // The placed instance was withdrawn, the stop's phase was never + // overwritten, and nothing was rolled back. + assert!(shared.supervision().controller().assignments().is_empty()); + let bodies = bodies.lock().unwrap(); + assert_eq!(bodies.len(), 2); + assert!( + bodies[0]["metadata"]["annotations"][ANNOTATION_SUPERVISOR_MEMBER] == "node-a", + "{:?}", + bodies[0] + ); + } + + #[tokio::test(start_paused = true)] + async fn scheduled_launch_retries_a_failed_sandbox_read() { + let now = openshell_core::time::now_ms(); + let (driver, steps, _bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + kube_test_response( + http::StatusCode::INTERNAL_SERVER_ERROR, + serde_json::json!({ + "apiVersion": "v1", + "kind": "Status", + "status": "Failure", + "message": "etcdserver: request timed out", + "reason": "InternalError", + "code": 500 + }), + ), + ), + // The retry finds the sandbox moved on, so the launch ends. + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Releasing, now), + ), + ], + ); + let generation = scheduled_generation(&driver); + launch_scheduled(&driver, generation).await; + assert!(steps.lock().unwrap().is_empty()); + } + #[tokio::test] async fn scheduled_launch_skips_a_sandbox_that_moved_on_or_went_stale() { let now = openshell_core::time::now_ms(); From 11cedcb05c766f4fc9c87c6d45dc5e8fe0615a3b Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:38:25 +0200 Subject: [PATCH 08/18] fix(k8s): wait for the node's supervisor before a deferred launch On a new node the workload Pod and the node's supervisor start together, so a launch that runs as soon as the Pod is bound found no pool member and rolled the sandbox back. The deferred launch now waits, within the bootstrap grace, until the gateway's pool view has the node's supervisor live and not leaving. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 11 ++- .../openshell-driver-kubernetes/src/driver.rs | 99 +++++++++++++++++++ .../src/controller.rs | 15 +++ docs/kubernetes/high-availability.mdx | 6 +- skills/debug-openshell-cluster/SKILL.md | 2 +- 5 files changed, 125 insertions(+), 8 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 3e8f236869..4c65e55363 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -486,10 +486,13 @@ scheduled on the node it claims as its pool member ID. - **Placement.** The driver removes the scheduling gate and returns from create or restart before it assigns the instance. The bootstrap task watches - the workload Pod and launches on the node in its `spec.nodeName`. A Pod that - is deleted or replaced, or a node supervisor that refuses the instance, rolls - the bootstrap back. So does a Pod that isn't scheduled within - `runtime_bootstrap_grace_seconds`. + the workload Pod, waits for the supervisor of the node in its `spec.nodeName` + to join the pool, and launches there. A Pod that is deleted or replaced, or a + node supervisor that refuses the instance, rolls the bootstrap back. So does + a Pod that isn't scheduled, or a node supervisor that doesn't join, within + `runtime_bootstrap_grace_seconds`. Each launch write re-checks that the + Sandbox still awaits this launch, so a stop, delete, or newer attempt served + by another gateway replica wins. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation records the pinned node. The bootstrap Secret exists before the gate is removed; until the launch places the route, the supervisor refuses the runtime's dials and the diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 6a57d9476f..39d9d8a276 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -4266,6 +4266,28 @@ impl KubernetesComputeDriver { else { return; }; + // The node's supervisor may start with the workload, as on a new node. + if let GenerationLaunchTarget::Shared { shared, .. } = &generation.target { + let controller = shared.supervision().controller(); + while !controller.pool_view().is_some_and(|view| { + view.members + .iter() + .any(|member| member.member_id == node && !member.leaving) + }) { + if tokio::time::Instant::now() >= deadline { + warn!( + sandbox = cr_name, + node, + "no supervisor attached on the node within the bootstrap grace; the stale bootstrap will be rolled back" + ); + return; + } + tokio::time::sleep_until( + deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), + ) + .await; + } + } let _guard = self .lifecycle_gates .gate_for(&generation.sandbox_id) @@ -10360,6 +10382,26 @@ mod tests { ) } + /// Make the pool view hold exactly the supervisors of `nodes`. + fn attach_node_supervisors(shared: &SharedSupervisor, nodes: &[&str]) { + let members = nodes + .iter() + .map(|node| openshell_supervisor_control::MemberView { + member_id: (*node).to_string(), + process_id: format!("{node}-process"), + runtime_address: "10.0.0.1:5500".to_string(), + leaving: false, + }) + .collect(); + shared.supervision().controller().update_pool( + openshell_supervisor_control::PoolView { + members, + ..Default::default() + }, + tokio::time::Instant::now(), + ); + } + /// Durable pool records that accept every launch. #[derive(Debug)] struct AcceptingPlacement; @@ -10546,6 +10588,7 @@ mod tests { .shared_supervisor .clone() .unwrap_or_else(scheduled_shared_supervisor); + attach_node_supervisors(&shared, &["node-a"]); PreparedGeneration { namespace: "openshell".to_string(), cr_name: "sandbox-cr".to_string(), @@ -10764,6 +10807,62 @@ mod tests { assert!(steps.lock().unwrap().is_empty()); } + #[tokio::test(start_paused = true)] + async fn scheduled_launch_waits_for_its_node_supervisor() { + let now = openshell_core::time::now_ms(); + let (driver, steps, _bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Releasing, now), + ), + ], + ); + let generation = scheduled_generation(&driver); + let GenerationLaunchTarget::Shared { shared, .. } = &generation.target else { + unreachable!(); + }; + let shared = shared.clone(); + attach_node_supervisors(&shared, &["node-b"]); + let launch = tokio::spawn({ + let driver = driver.clone(); + async move { launch_scheduled(&driver, generation).await } + }); + tokio::time::sleep(Duration::from_secs(30)).await; + // Still waiting: the sandbox was not read yet. + assert_eq!(steps.lock().unwrap().len(), 1); + attach_node_supervisors(&shared, &["node-a", "node-b"]); + launch.await.unwrap(); + assert!(steps.lock().unwrap().is_empty()); + } + + #[tokio::test(start_paused = true)] + async fn scheduled_launch_leaves_a_node_without_supervisor_to_the_reaper() { + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + )], + ); + let generation = scheduled_generation(&driver); + let GenerationLaunchTarget::Shared { shared, .. } = &generation.target else { + unreachable!(); + }; + attach_node_supervisors(shared, &[]); + launch_scheduled(&driver, generation).await; + assert!(steps.lock().unwrap().is_empty()); + assert!(bodies.lock().unwrap().is_empty()); + } + #[tokio::test] async fn scheduled_launch_skips_a_sandbox_that_moved_on_or_went_stale() { let now = openshell_core::time::now_ms(); diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index d18b069b75..8b6ff8b973 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -1756,6 +1756,21 @@ mod tests { assert!(changes.has_changed().unwrap(), "the member's stream ended"); } + #[tokio::test] + async fn pool_members_are_known_once_live_and_not_leaving() { + let controller = SupervisorHostController::new(); + assert!(!controller.has_pool_member("node-a")); + let mut leaving = member_view("node-b", "p2"); + leaving.leaving = true; + controller.update_pool( + loaded_view(vec![member_view("node-a", "p1"), leaving], []), + tokio::time::Instant::now(), + ); + assert!(controller.has_pool_member("node-a")); + assert!(!controller.has_pool_member("node-b")); + assert!(!controller.has_pool_member("node-c")); + } + #[tokio::test] async fn a_member_snapshot_does_not_grow_with_the_pool() { use prost::Message as _; diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index 87ca5cfa67..3defcf5733 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -759,9 +759,9 @@ claim any node. We recommend running the API server with the `Node` authorizer and the `NodeRestriction` admission plugin, so a compromised node's kubelet cannot obtain tokens for another node's supervisor. -If the scheduler places a workload on a node without an attached supervisor, -or no node accepts it within `runtime_bootstrap_grace_seconds`, the gateway -deletes the new sandbox or stops the restarted one. A supervisor must run on +If no node accepts the workload, or its node's supervisor does not attach, +within `runtime_bootstrap_grace_seconds`, the gateway deletes the new sandbox +or stops the restarted one. A supervisor must run on every node that can host a sandbox. If sandbox templates tolerate node taints, set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with `supervisor.nodeSelector`. GPU nodes usually need: diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index ee3953bf0a..f51c390124 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1844,7 +1844,7 @@ credential failures. | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | | A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | -| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room`), or, once `runtime_bootstrap_grace_seconds` passes, `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart) | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, not yet attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | From db542a4c781cd2efb05ec5079d3ea5082bb3c25d Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:44:13 +0200 Subject: [PATCH 09/18] fix(server): place node-pinned instances only on a supervisor proven on that node Only node-topology replicas check a supervisor's claimed node at attach, so during a topology switch a supervisor attached through a gateway-topology replica could claim any node and be granted that node's pinned instances. Every session already carries the node its Pod identity token proves; the membership record now stores it, and launch, recovery placement, and takeover grant a pinned instance only to a member whose record proves that node. Signed-off-by: Gal Zaidman --- .../openshell-server/src/supervisor_pool.rs | 122 ++++++++++-------- .../openshell-server/src/supervisor_spread.rs | 1 + .../src/controller.rs | 18 +-- skills/debug-openshell-cluster/SKILL.md | 2 +- 4 files changed, 74 insertions(+), 69 deletions(-) diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index a291231e3c..555f1de0d4 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -185,6 +185,10 @@ struct MemberPayload { #[serde(default)] connected_at_ms: i64, gateway_replica: String, + /// The node the member's identity token proved, on whichever replica + /// serves its stream. + #[serde(default, skip_serializing_if = "Option::is_none")] + node: Option, } /// A pool member whose record is live. @@ -195,6 +199,8 @@ pub struct LiveMember { pub runtime_address: String, pub leaving: bool, pub gateway_replica: String, + /// The node the member's identity token proved. + pub node: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -653,7 +659,8 @@ fn ring_of(members: &[LiveMember]) -> GatewayRing { /// Only members with fewer than `max_instances` routes, or already charged /// for this one, are listed; the owner change itself re-checks room /// atomically. `charges` counts the routes each member is charged for and -/// lists them. With `pinned`, only that member is listed. +/// lists them. With `pinned`, only that member is listed, and only when its +/// identity token proved it runs on that node. #[allow(clippy::too_many_arguments)] fn candidates<'a>( ring: &GatewayRing, @@ -669,8 +676,9 @@ fn candidates<'a>( let routes_of = |member: &LiveMember| charges.get(&member.member_id); let has_room = |member: &&LiveMember| { - pinned.is_none_or(|pinned| member.member_id == pinned) - && !member.leaving + pinned.is_none_or(|pinned| { + member.member_id == pinned && member.node.as_deref() == Some(pinned) + }) && !member.leaving && routes_of(member) .is_none_or(|routes| routes.contains(route) || routes.len() < max_instances) }; @@ -1163,6 +1171,7 @@ impl SupervisorPool { leaving: member.leaving, connected_at_ms: member.connected_at_ms, gateway_replica: self.replica_id.clone(), + node: member.node.clone(), }; let bytes = serde_json::to_vec(&payload) .map_err(|error| PersistenceError::Encode(error.to_string()))?; @@ -1319,6 +1328,7 @@ impl SupervisorPool { runtime_address: payload.runtime_address, leaving: payload.leaving, gateway_replica: payload.gateway_replica, + node: payload.node, }); } members.sort_by(|left, right| left.member_id.cmp(&right.member_id)); @@ -1726,24 +1736,12 @@ impl SupervisorPool { async fn record_assignment( &self, assignment: &SandboxInstanceAssignment, - member: Option<&str>, ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Published, member) + self.record_assignment_as(assignment, RecordPhase::Published) .await .map(|recording| recording.record) } - /// Record a launched instance as [`RecordPhase::Admitting`], for its - /// launch to admit onto a member. - async fn record_admitting( - &self, - assignment: &SandboxInstanceAssignment, - member: Option<&str>, - ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Admitting, member) - .await - } - /// [`Self::record_assignment`], publishing the record as `phase` /// ([`RecordPhase::Published`] or [`RecordPhase::Admitting`]). An /// admitting record keeps its material candidate, which this recording @@ -1752,9 +1750,8 @@ impl SupervisorPool { &self, assignment: &SandboxInstanceAssignment, phase: RecordPhase, - member: Option<&str>, ) -> Result { - self.record_assignment_scoped(assignment, phase, member, None) + self.record_assignment_scoped(assignment, phase, None, None) .await } @@ -2276,32 +2273,25 @@ impl SupervisorPool { pinned, ); let no_room = || { - pinned.map_or_else( - || { - warn!(max_instances, "every supervisor is at its sandbox limit"); - CAPACITY_REACHED.to_string() - }, - |member| { - format!( - "the shared supervisor {member:?} is not attached or has no room for another sandbox" - ) - }, - ) + if let Some(member) = pinned { + return format!( + "the shared supervisor {member:?} is not attached or has no room for another sandbox" + ); + } + warn!(max_instances, "every supervisor is at its sandbox limit"); + CAPACITY_REACHED.to_string() }; if targets.is_empty() { return Err(no_room()); } - let recording = if preparation.is_some() { - self.record_assignment_scoped( + let recording = self + .record_assignment_scoped( assignment, RecordPhase::Admitting, pinned, preparation.map(|(workspace, pool)| (workspace, request.auth_epoch, pool)), ) - .await? - } else { - self.record_admitting(assignment, pinned).await? - }; + .await?; if assignment.prepared && self.load_material(&recording.record.payload).await? != assignment.launch_material { @@ -3063,6 +3053,7 @@ impl SupervisorPool { runtime_address: payload.runtime_address, leaving: payload.leaving, gateway_replica: payload.gateway_replica, + node: payload.node, }); Ok(takeover_cause(owner, member.as_ref())) } @@ -3607,9 +3598,14 @@ impl InstancePlacement for PoolPlacement { ) -> PlacementFuture { let pool = self.0.clone(); Box::pin(detached(async move { - pool.record_assignment(&assignment, member.as_deref()) - .await - .map(drop) + pool.record_assignment_scoped( + &assignment, + RecordPhase::Published, + member.as_deref(), + None, + ) + .await + .map(drop) })) } } @@ -3809,6 +3805,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving, connected_at_ms: now_ms(), + node: Some(member_id.to_string()), }) .await .unwrap(); @@ -4352,7 +4349,7 @@ mod tests { // recorded owners. ("rt-route-b000", "sandbox-b"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1"), None) + pool.record_assignment(&assignment(route, sandbox, "generation-1")) .await .unwrap(); } @@ -4441,7 +4438,7 @@ mod tests { ("rt-route-c000", "sandbox-c"), ("rt-route-d000", "sandbox-d"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1"), None) + pool.record_assignment(&assignment(route, sandbox, "generation-1")) .await .unwrap(); } @@ -4598,14 +4595,11 @@ mod tests { // Recording the generation again keeps the first record and material; // another generation on its route is refused. - other.record_assignment(&launched, None).await.unwrap(); + other.record_assignment(&launched).await.unwrap(); assert_eq!(fixture.credentials.stored_credential_count(), Some(1)); assert!( other - .record_assignment( - &assignment("rt-route-a000", "sandbox-a", "generation-2"), - None - ) + .record_assignment(&assignment("rt-route-a000", "sandbox-a", "generation-2")) .await .is_err() ); @@ -4636,8 +4630,8 @@ mod tests { let (first, second) = (fixture.replica("gw-a"), fixture.replica("gw-b")); let instance = assignment("rt-route-a000", "sandbox-a", "generation-1"); let results: [_; 2] = tokio::join!( - first.record_assignment(&instance, None), - second.record_assignment(&instance, None) + first.record_assignment(&instance), + second.record_assignment(&instance) ) .into(); // One recording reserves the route and publishes; the other finds the @@ -4672,7 +4666,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance, None).await }) + tokio::spawn(async move { pool.record_assignment(&instance).await }) }; staged.await.unwrap(); // The instance is withdrawn while it is being recorded: removing its @@ -4707,7 +4701,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance, None).await }) + tokio::spawn(async move { pool.record_assignment(&instance).await }) }; staged.await.unwrap(); // Staged and unpublished: material stored, candidate written, the @@ -4767,7 +4761,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance, None).await }) + tokio::spawn(async move { pool.record_assignment(&instance).await }) }; staged.await.unwrap(); // The recording outlives its reservation's grace: a pass fences it and @@ -4783,7 +4777,7 @@ mod tests { assert!(fixture.instance("rt-route-a000").await.is_none()); assert_eq!(fixture.credentials.stored_credential_count(), Some(0)); // The route can be recorded again. - let record = pool.record_assignment(&instance, None).await.unwrap(); + let record = pool.record_assignment(&instance).await.unwrap(); assert_eq!( pool.load_material(&record.payload).await.unwrap(), instance.launch_material @@ -4800,8 +4794,7 @@ mod tests { let record_paused = |pool: Arc| { let (staged, publish) = pool.pause_next_recording_after_staging(); let instance = instance.clone(); - let recording = - tokio::spawn(async move { pool.record_assignment(&instance, None).await }); + let recording = tokio::spawn(async move { pool.record_assignment(&instance).await }); (staged, publish, recording) }; // The first recording stalls after staging and is fenced; its @@ -5762,6 +5755,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving: false, connected_at_ms, + node: Some(member_id.to_string()), } } @@ -6282,6 +6276,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving, gateway_replica: String::new(), + node: None, }; assert_eq!(takeover_cause(&owner, None), Some("expired")); assert_eq!( @@ -6306,6 +6301,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving, gateway_replica: String::new(), + node: Some(id.to_string()), } } @@ -6374,6 +6370,26 @@ mod tests { assert!(pinned(charges(0, MEMBER_CAP), "m2").is_empty()); assert!(pinned(charges(0, 0), "m3").is_empty()); assert!(pinned(charges(0, 0), "m4").is_empty()); + // A member that proved no node, or another one, never receives the + // node's instances. + for node in [None, Some("m1".to_string())] { + let members = [LiveMember { + node, + ..live_member("m2", false) + }]; + let empty = BTreeMap::new(); + let listed = candidates( + &ring, + &members, + &sandbox, + "rt-new", + &empty, + None, + MEMBER_CAP, + Some("m2"), + ); + assert!(listed.is_empty()); + } } #[test] diff --git a/crates/openshell-server/src/supervisor_spread.rs b/crates/openshell-server/src/supervisor_spread.rs index 264435a42b..f5aa238df6 100644 --- a/crates/openshell-server/src/supervisor_spread.rs +++ b/crates/openshell-server/src/supervisor_spread.rs @@ -121,6 +121,7 @@ mod tests { runtime_address: String::new(), leaving: false, gateway_replica: gateway_replica.to_string(), + node: None, } } diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 8b6ff8b973..7de5722664 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -234,6 +234,8 @@ pub struct ConnectedMember { /// When this stream was accepted (Unix milliseconds); a newer stream of a /// member supersedes an older one on another gateway replica. pub connected_at_ms: i64, + /// The node the stream's identity token proved its Pod runs on. + pub node: Option, } struct Assigned { @@ -850,6 +852,7 @@ impl SupervisorHostController { runtime_address: session.member.runtime_address.clone(), leaving: session.status.as_ref().is_some_and(|status| status.leaving), connected_at_ms: session.connected_at_ms, + node: session.identity.node.clone(), }) .collect() } @@ -1756,21 +1759,6 @@ mod tests { assert!(changes.has_changed().unwrap(), "the member's stream ended"); } - #[tokio::test] - async fn pool_members_are_known_once_live_and_not_leaving() { - let controller = SupervisorHostController::new(); - assert!(!controller.has_pool_member("node-a")); - let mut leaving = member_view("node-b", "p2"); - leaving.leaving = true; - controller.update_pool( - loaded_view(vec![member_view("node-a", "p1"), leaving], []), - tokio::time::Instant::now(), - ); - assert!(controller.has_pool_member("node-a")); - assert!(!controller.has_pool_member("node-b")); - assert!(!controller.has_pool_member("node-c")); - } - #[tokio::test] async fn a_member_snapshot_does_not_grow_with_the_pool() { use prost::Message as _; diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index f51c390124..010c353df1 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1844,7 +1844,7 @@ credential failures. | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | | A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | -| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full, or its membership record has no proven node because it attached through a replica that resolved no identity token), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | From 857e935ab59db711645dab8cb606edbd4d510386 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:48:02 +0200 Subject: [PATCH 10/18] fix(server): end supervisor streams when the Pod identity token expires The gateway checked a supervisor's Pod identity token once per stream and ended the stream only when the supervisor token expired, up to an hour later, so a stream outlived the Pod that proved its node. The stream now ends at the earlier expiry of the two tokens; the host already re-reads both on every reconnect, and its sandboxes keep running across it. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 3 +- .../src/auth/supervisor_token.rs | 69 ++++++++++++++++--- crates/openshell-supervisor-control/README.md | 5 +- .../src/controller.rs | 7 +- crates/openshell-supervisor/README.md | 4 +- skills/debug-openshell-cluster/SKILL.md | 4 +- 6 files changed, 73 insertions(+), 19 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 4c65e55363..d58886c7a9 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -454,7 +454,8 @@ fails closed. - **Isolation.** The supervisor token is a profile of its own, separate from every instance's credentials; the gateway refuses it on every other RPC and refuses every other identity on the assignment stream, and ends a stream - when the token that opened it expires. Sandboxes cannot reach the stream, + when the token or the Pod identity token that opened it expires. Sandboxes + cannot reach the stream, and the routing preface only selects which generation-pinned TLS identity the supervisor demands. - **Workload identity.** The gateway owns SPIFFE Broker API identity acquisition and provider-token diff --git a/crates/openshell-server/src/auth/supervisor_token.rs b/crates/openshell-server/src/auth/supervisor_token.rs index 9f7e908cad..77e6cc89f1 100644 --- a/crates/openshell-server/src/auth/supervisor_token.rs +++ b/crates/openshell-server/src/auth/supervisor_token.rs @@ -62,14 +62,14 @@ impl SupervisorTokenAuthenticator { self } - /// The node the supervisor's Pod runs on, or `None` for a supervisor - /// that sent no identity token where none is required. Resolved only - /// after the supervisor token verified, so callers without it can't - /// trigger a `TokenReview`. + /// The node the supervisor's Pod runs on and when its identity token + /// expires, or `None` for a supervisor that sent no identity token where + /// none is required. Resolved only after the supervisor token verified, + /// so callers without it can't trigger a `TokenReview`. async fn resolve_identity( &self, headers: &http::HeaderMap, - ) -> Result, AuthRejection> { + ) -> Result)>, AuthRejection> { let refuse = |reason, message: &str| { AuthRejection::new( AuthMechanism::SupervisorToken, @@ -115,12 +115,14 @@ impl SupervisorTokenAuthenticator { "supervisor identity token is invalid", ) })?; - identity.node_name.map(Some).ok_or_else(|| { + let node = identity.node_name.ok_or_else(|| { refuse( AuthFailureReason::InvalidCredential, "supervisor identity token names an unscheduled pod", ) - }) + })?; + // The resolver verified this token, so its `exp` is the API server's. + Ok(Some((node, openshell_core::jwt::parse_exp_secs(token)))) } } @@ -149,14 +151,22 @@ impl Authenticator for SupervisorTokenAuthenticator { return Ok(Authentication::NotApplicable); } let authenticated = self.authority.verify_supervisor_token(token)?; - let node = self.resolve_identity(headers).await?; + let identity = self.resolve_identity(headers).await?; + // The stream ends when either token expires, so it never outlives + // the Pod that proved the node. + let expires_at = identity + .as_ref() + .and_then(|(_, identity_expires_at)| *identity_expires_at) + .map_or(authenticated.expires_at, |identity_expires_at| { + authenticated.expires_at.min(identity_expires_at) + }); Ok(Authentication::Accepted(Principal::Supervisor( SupervisorPrincipal { identity: HostIdentity { subject: authenticated.subject, token_id: authenticated.token_id.to_string(), - expires_at: authenticated.expires_at, - node, + expires_at, + node: identity.map(|(node, _)| node), }, }, ))) @@ -363,6 +373,45 @@ mod tests { assert_eq!(resolver.seen_tokens.lock().unwrap().len(), 1); } + #[tokio::test] + async fn supervisor_streams_end_when_the_pod_identity_expires() { + use base64::Engine as _; + + let gateway = authority("test-gateway"); + let minted = gateway + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + let identity_token = |exp: i64| { + let encode = |value: serde_json::Value| { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value.to_string()) + }; + format!( + "{}.{}.signature", + encode(serde_json::json!({"alg": "RS256"})), + encode(serde_json::json!({"exp": exp})) + ) + }; + let expires_at = |exp: i64| { + let mut headers = headers(minted.token.expose_secret()); + headers.insert( + HOST_IDENTITY_TOKEN_HEADER, + identity_token(exp).parse().unwrap(), + ); + let authenticator = accepting(gateway.clone()); + async move { + match authenticator.authenticate(&headers, ATTACH).await.unwrap() { + Authentication::Accepted(Principal::Supervisor(supervisor)) => { + supervisor.identity.expires_at + } + other => panic!("unexpected outcome {other:?}"), + } + } + }; + let earlier = minted.expires_at - 300; + assert_eq!(expires_at(earlier).await, earlier); + assert_eq!(expires_at(minted.expires_at + 300).await, minted.expires_at); + } + #[tokio::test] async fn supervisor_tokens_are_refused_without_a_valid_pod_identity() { let gateway = authority("test-gateway"); diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index ceaa2ac9c2..5898ec94b0 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -27,8 +27,9 @@ re-implementing the control contracts. member: a newer connection epoch of the same member process or a new process of the member supersedes its stream, a delayed older hello is refused, and reports from superseded streams, acks of revisions never sent, regressing acks, - and oversized reports are dropped. A stream ends when the token that opened - it expires; hosted instances keep running. The pool's recovery deadline + and oversized reports are dropped. A stream ends when the supervisor token + or the Pod identity token that opened it expires; hosted instances keep + running. The pool's recovery deadline defaults to `POOL_RECOVERY_TIMEOUT_SECS` (`set_recovery_timeout_secs` overrides it). The gateway's pool reconciler replaces the `PoolView` as a whole (`update_pool`): the desired set from the gateway's durable records, the diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 7de5722664..edbc8fd6b5 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -80,8 +80,9 @@ pub struct HostIdentity { pub subject: String, /// `jti` of the supervisor token. pub token_id: String, - /// `exp` of the supervisor token (Unix seconds). The gateway ends the - /// stream when it passes; the host reconnects with a renewed token. + /// The earlier `exp` of the supervisor token and the identity token + /// (Unix seconds). The gateway ends the stream when it passes; the host + /// reconnects with renewed tokens. pub expires_at: i64, /// Node the host's identity token proves its Pod runs on. pub node: Option, @@ -1445,7 +1446,7 @@ impl SupervisorHostController { } _ = superseded.changed() => return, () = &mut credential_expiry => { - tracing::info!(session = session_id, "supervisor token expired; closing the stream for reconnection"); + tracing::info!(session = session_id, "supervisor credential expired; closing the stream for reconnection"); return; } } diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index da02d3db52..c07fef17d7 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -192,8 +192,8 @@ control listener: it dials the gateway and receives its assignments from it. user, operator, and peer credentials are refused on it. The host re-reads the file on every connection attempt and treats a missing, malformed, or expired token as a reason to retry later, and the gateway ends a stream - when the token that opened it expires, so the host reconnects with the - renewed one. The host never acts with any other identity and has no + when the token or the Pod identity token that opened it expires, so the + host reconnects with the renewed ones. The host never acts with any other identity and has no Kubernetes API access. Beside the token, the host sends its Pod's projected `ServiceAccount` token (audience `openshell-supervisor`) from `--identity-token-file` (`OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE`) in the diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 010c353df1..cb31fa7d13 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1559,7 +1559,9 @@ and each Pod's member ID is its node name; see the A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation records its node. Until the workload Pod is scheduled, the runtime logs -`Runtime-initiated control cannot reach the supervisor; retrying`. +`Runtime-initiated control cannot reach the supervisor; retrying`. Shared +supervisors in either topology reconnect about every 8 minutes, when their +Pod identity token rotates; a repeated `gateway accepted the supervisor host` is expected. ```bash kubectl -n openshell get daemonset,pod -l app.kubernetes.io/component=supervisor -o wide From 161c7a6fefa5cdecf3c458e7d6b40577be703ff0 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:51:33 +0200 Subject: [PATCH 11/18] feat(helm): default node supervisors to 300 sandboxes and add rollout and priority settings The node topology forced every supervisor's cap to 1024, sizing each gateway message for that many sandboxes. It now defaults to 300, above the kubelet's default maxPods, and an explicit supervisor.pool.maxInstancesPerMember overrides it in either topology. supervisor.updateStrategy.maxUnavailable sets how many node supervisors a rollout replaces at once, and supervisor.priorityClassName sets the supervisor Pods' PriorityClass; system-node-critical is recommended for the node topology. Signed-off-by: Gal Zaidman --- deploy/helm/openshell/README.md | 8 +- deploy/helm/openshell/templates/_helpers.tpl | 11 +-- .../helm/openshell/templates/supervisor.yaml | 7 +- .../helm/openshell/tests/supervisor_test.yaml | 99 +++++++++++-------- deploy/helm/openshell/values.yaml | 24 +++-- docs/how-it-works/gateways/configuration.mdx | 2 +- docs/kubernetes/high-availability.mdx | 18 ++-- skills/debug-openshell-cluster/SKILL.md | 7 ++ 8 files changed, 107 insertions(+), 69 deletions(-) diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 8531572c68..e8dfae7359 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -854,14 +854,16 @@ for peer identity policies, multi-node registrations, and authorization. | supervisor.podSecurityContext.runAsNonRoot | bool | `true` | Require the shared supervisor to run as a non-root user. | | supervisor.podSecurityContext.runAsUser | int | `65534` | UID assigned to the shared supervisor pod. | | supervisor.podSecurityContext.seccompProfile.type | string | `"RuntimeDefault"` | Seccomp profile applied to the shared supervisor pod. | -| supervisor.pool.maxInstancesPerMember | int | `128` | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. Ignored with supervisor_topology = "node", which uses 1024. | +| supervisor.pool.maxInstancesPerMember | int | 128, or 300 with supervisor_topology = "node" | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. With supervisor_topology = "node", set it to at least the kubelet maxPods of your sandbox nodes. | | supervisor.pool.maxMembersPerGateway | int | `32` | Most supervisors one gateway replica serves, rendered as [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a positive integer. The pool runs at most gateway replicas times maxMembersPerGateway times maxInstancesPerMember sandboxes, never more than 131072. | +| supervisor.priorityClassName | string | `""` | PriorityClass of the shared supervisor Pods, such as system-node-critical for node supervisors; empty omits it. | | supervisor.recoveryTimeoutSeconds | int | `60` | Seconds a sandbox workload stays frozen after losing its pool member's supervision before the sandbox runtime terminates it, rendered as [openshell.gateway.supervisor_pool] recovery_timeout_secs. Must be an integer from 30 to 300. Null leaves the gateway's pool default of 60 seconds. | | supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true or supervisor_topology = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | -| supervisor.requireIdentityToken | bool | `false` | Refuse gateway-topology supervisors that attach without their pod-bound identity token. Node-topology supervisors always need it. Refer to the High Availability guide before enabling it on an upgrade. | +| supervisor.requireIdentityToken | bool | `false` | Refuse gateway-topology supervisors that attach without their pod-bound identity token. The node topology always requires it. | | supervisor.resources | object | `{}` | Resources of each shared supervisor container, unset by default. Memory grows with the sandboxes a supervisor runs; for the default of 128 sandboxes, request 250m CPU and 768Mi memory, and allow for failover. Refer to Size Sandbox Capacity in the High Availability guide. | | supervisor.sandboxRuntime.boundaryPort | int | `5500` | Workload boundary TLS listener port. | -| supervisor.tolerations | list | `[]` | Tolerations for the shared supervisor pod. With supervisor_topology = "node", tolerate every taint a sandbox template tolerates, such as `nvidia.com/gpu` on GPU nodes. | +| supervisor.tolerations | list | `[]` | Tolerations for the shared supervisor pod. With supervisor_topology = "node", tolerate every taint sandboxes tolerate. | +| supervisor.updateStrategy.maxUnavailable | int | `1` | Most node supervisors replaced at once during a rollout, used only with supervisor_topology = "node": an integer or a percentage such as "10%". Sandboxes on a node pause while its supervisor is replaced. | | tolerations | list | `[]` | Tolerations for the gateway pod. | | topologySpreadConstraints | list | `[]` | Topology spread constraints for the gateway pod, used to spread replicas across zones or nodes. Empty = omit the field. | | upstreamProxy | object | `{"authAllowInsecure":false,"authSecret":{"key":"","name":""},"caBundle":{"configMapName":"","key":"ca.crt"},"connectByHostname":false,"noProxy":"","url":""}` | Operator-owned corporate forward proxy for policy-approved TLS egress from Kubernetes sandboxes. The workload cannot select or override it. | diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index ac7f1bfaba..5e3d9e230f 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -525,15 +525,12 @@ key, default, and optionally max. {{/* Most sandboxes one supervisor runs (supervisor.pool.maxInstancesPerMember). -A node supervisor takes every sandbox the kubelet admits on its node, so the -node topology always uses the largest cap. +A node supervisor takes the sandboxes the kubelet admits on its node, so the +node topology defaults to more than the kubelet's default maxPods. */}} {{- define "openshell.supervisorMaxInstancesPerMember" -}} -{{- if include "openshell.supervisorNodeTopology" . -}} -1024 -{{- else -}} -{{- include "openshell.supervisorPoolLimit" (dict "root" . "key" "maxInstancesPerMember" "max" 1024 "default" 128) -}} -{{- end -}} +{{- $default := ternary 300 128 (eq (include "openshell.supervisorNodeTopology" .) "true") -}} +{{- include "openshell.supervisorPoolLimit" (dict "root" . "key" "maxInstancesPerMember" "max" 1024 "default" $default) -}} {{- end }} {{/* Most supervisors one gateway replica serves (supervisor.pool.maxMembersPerGateway). */}} diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index 695838315c..5f66ea4916 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -46,7 +46,7 @@ spec: type: RollingUpdate rollingUpdate: maxSurge: 0 - maxUnavailable: 1 + maxUnavailable: {{ .Values.supervisor.updateStrategy.maxUnavailable }} {{- else }} # The replicas form a high-availability pool. Each instance lives in the # process hosting it; the pool rolls one member at a time, starting a new @@ -75,10 +75,8 @@ spec: serviceAccountName: {{ $name }} automountServiceAccountToken: false enableServiceLinks: false - {{- if not $node }} # A stopping member announces that it is leaving, and the gateway moves # its instances to the remaining members before it exits. - {{- end }} terminationGracePeriodSeconds: 60 {{- with ($imagePullSecrets | uniq) }} imagePullSecrets: @@ -102,6 +100,9 @@ spec: tolerations: {{- toYaml . | nindent 8 }} {{- end }} + {{- with .Values.supervisor.priorityClassName }} + priorityClassName: {{ . }} + {{- end }} containers: - name: supervisor image: {{ get $kubernetes "supervisor_image" | quote }} diff --git a/deploy/helm/openshell/tests/supervisor_test.yaml b/deploy/helm/openshell/tests/supervisor_test.yaml index cc2c38c27a..962e5e5d30 100644 --- a/deploy/helm/openshell/tests/supervisor_test.yaml +++ b/deploy/helm/openshell/tests/supervisor_test.yaml @@ -90,6 +90,9 @@ tests: - hasDocuments: count: 1 template: templates/supervisor-service.yaml + - notExists: + path: spec.internalTrafficPolicy + template: templates/supervisor-service.yaml - hasDocuments: count: 1 template: templates/supervisor-networkpolicy.yaml @@ -799,24 +802,41 @@ tests: value: 512Mi template: templates/supervisor.yaml documentIndex: 0 - - it: gives node supervisors the largest per-member cap + - it: defaults node supervisors to a cap of 300 + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 300\n' + template: templates/gateway-config.yaml + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES + value: "300" + template: templates/supervisor.yaml + documentIndex: 0 + - it: keeps an explicit per-member cap in the node topology set: supervisor: pool: - maxInstancesPerMember: 16 + maxInstancesPerMember: 1000 gatewayConfig: openshell.drivers.kubernetes: supervisor_topology: node asserts: - matchRegex: path: data["gateway.toml"] - pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 1024\n' + pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 1000\n' template: templates/gateway-config.yaml - contains: path: spec.template.spec.containers[0].env content: name: OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES - value: "1024" + value: "1000" template: templates/supervisor.yaml documentIndex: 0 - it: accepts a per-member cap of one sandbox @@ -899,20 +919,6 @@ tests: asserts: - failedTemplate: errorMessage: supervisor.replicas (3) exceeds replicaCount (1) * supervisor.pool.maxMembersPerGateway (2) = 2; add gateway replicas or raise maxMembersPerGateway - - it: ignores supervisor.replicas when counting node-topology members - template: templates/supervisor.yaml - set: - supervisor: - replicas: 3 - pool: - maxMembersPerGateway: 2 - gatewayConfig: - openshell.drivers.kubernetes: - supervisor_topology: node - asserts: - - isKind: - of: DaemonSet - documentIndex: 0 - it: rejects a supervisor HPA maximum above what the gateways serve template: templates/supervisor.yaml set: @@ -1072,7 +1078,10 @@ tests: template: templates/supervisor.yaml set: supervisor: + # The node topology ignores replicas, which exceed the member limit. replicas: 3 + pool: + maxMembersPerGateway: 2 gatewayConfig: openshell.drivers.kubernetes: supervisor_topology: node @@ -1101,6 +1110,8 @@ tests: path: spec.template.spec.nodeSelector - notExists: path: spec.template.spec.tolerations + - notExists: + path: spec.template.spec.priorityClassName - contains: path: spec.template.spec.containers[0].env content: @@ -1114,6 +1125,36 @@ tests: - contains: path: spec.template.spec.containers[0].args content: /var/run/secrets/openshell-supervisor/token + - it: replaces the configured share of node supervisors at once + template: templates/supervisor.yaml + set: + supervisor: + updateStrategy: + maxUnavailable: 10% + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.updateStrategy.rollingUpdate + value: + maxSurge: 0 + maxUnavailable: 10% + - it: sets the node supervisor priority class + template: templates/supervisor.yaml + set: + supervisor: + priorityClassName: system-node-critical + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: kind + value: DaemonSet + - equal: + path: spec.template.spec.priorityClassName + value: system-node-critical - it: places node supervisors on tainted and selected nodes template: templates/supervisor.yaml set: @@ -1162,32 +1203,10 @@ tests: path: automountServiceAccountToken value: false template: templates/supervisor-serviceaccount.yaml - - matchRegex: - path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - template: templates/gateway-config.yaml - matchRegex: path: data["gateway.toml"] pattern: 'supervisor_topology = "node"' template: templates/gateway-config.yaml - - it: keeps the gateway topology a Deployment unbound to nodes - template: templates/supervisor.yaml - set: - gatewayConfig: - openshell.drivers.kubernetes: - supervisor_topology: gateway - asserts: - - equal: - path: kind - value: Deployment - template: templates/supervisor.yaml - - notContains: - path: spec.template.spec.containers[0].args - content: --node-supervisor - template: templates/supervisor.yaml - - notExists: - path: spec.internalTrafficPolicy - template: templates/supervisor-service.yaml - it: rejects autoscaling in the node topology template: templates/supervisor.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 65602f7fd6..646696a045 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -74,8 +74,7 @@ supervisor: # -- Shared supervisor listener IP. Use `::` for IPv6. listenAddress: 0.0.0.0 # -- Refuse gateway-topology supervisors that attach without their - # pod-bound identity token. Node-topology supervisors always need it. Refer - # to the High Availability guide before enabling it on an upgrade. + # pod-bound identity token. The node topology always requires it. requireIdentityToken: false # -- Shared supervisor pool members, used only when gatewayConfig selects # supervisor_topology = "gateway". The gateway always coordinates the shared @@ -88,12 +87,14 @@ supervisor: # = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. replicas: 1 pool: - # -- Most sandboxes one supervisor runs, rendered as + # -- (int) Most sandboxes one supervisor runs, rendered as # [openshell.gateway.supervisor_pool] max_instances_per_member and passed # to each supervisor. Must be an integer from 1 to 1024. The gateway - # refuses a sandbox when every supervisor is full. Ignored with - # supervisor_topology = "node", which uses 1024. - maxInstancesPerMember: 128 + # refuses a sandbox when every supervisor is full. With + # supervisor_topology = "node", set it to at least the kubelet maxPods of + # your sandbox nodes. + # @default -- 128, or 300 with supervisor_topology = "node" + maxInstancesPerMember: null # -- Most supervisors one gateway replica serves, rendered as # [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a # positive integer. The pool runs at most gateway replicas times @@ -136,6 +137,14 @@ supervisor: # "gateway". Disable it only when maintenance must evict more than one # supervisor Pod at a time, or evict a member while another is unavailable. enabled: true + updateStrategy: + # -- Most node supervisors replaced at once during a rollout, used only + # with supervisor_topology = "node": an integer or a percentage such as + # "10%". Sandboxes on a node pause while its supervisor is replaced. + maxUnavailable: 1 + # -- PriorityClass of the shared supervisor Pods, such as + # system-node-critical for node supervisors; empty omits it. + priorityClassName: "" # -- Seconds a sandbox workload stays frozen after losing its pool member's # supervision before the sandbox runtime terminates it, rendered as # [openshell.gateway.supervisor_pool] recovery_timeout_secs. Must be an @@ -168,8 +177,7 @@ supervisor: # sandboxes. nodeSelector: {} # -- Tolerations for the shared supervisor pod. With - # supervisor_topology = "node", tolerate every taint a sandbox template - # tolerates, such as `nvidia.com/gpu` on GPU nodes. + # supervisor_topology = "node", tolerate every taint sandboxes tolerate. tolerations: [] network: # -- Name of an operator-owned ConfigMap with a `ca.crt` key containing additional destination CA certificates for sandbox supervisors. Empty disables additional destination trust. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index ad1f06988a..5837575a99 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -924,7 +924,7 @@ max_members_per_gateway = 32 | `max_instances_per_member` | `128` | `1` to `1024` | `supervisor.pool.maxInstancesPerMember` | | `max_members_per_gateway` | `32` | `1` or more | `supervisor.pool.maxMembersPerGateway` | -The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. With `supervisor_topology = "node"`, the chart sets `1024`; see [Run one supervisor per node](/kubernetes/high-availability#run-one-supervisor-per-node). Values outside the ranges fail at startup. +The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. With `supervisor_topology = "node"`, the chart defaults to `300`; see [Run one supervisor per node](/kubernetes/high-availability#run-one-supervisor-per-node). Values outside the ranges fail at startup. ## OCSF JSONL Output diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index 3defcf5733..522cfe2d04 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -696,7 +696,7 @@ Three values set how many sandboxes the cluster can run: | Value | Default | Range | Meaning | |---|---|---|---| -| `supervisor.pool.maxInstancesPerMember` | `128` | `1` to `1024` | Sandboxes one supervisor runs. | +| `supervisor.pool.maxInstancesPerMember` | `128` (`300` with `supervisor_topology: node`) | `1` to `1024` | Sandboxes one supervisor runs. | | `supervisor.pool.maxMembersPerGateway` | `32` | `1` or more | Supervisors one gateway replica serves. | | `replicaCount` | `1` | | Gateway replicas. | @@ -775,12 +775,16 @@ supervisor: ``` The chart renders no PodDisruptionBudget or HPA for the DaemonSet and ignores -`supervisor.replicas`. It also ignores `supervisor.pool.maxInstancesPerMember` -and sets each supervisor's cap to 1024, so a supervisor accepts every sandbox -the kubelet admits on its node. Size `supervisor.resources` for the kubelet's -`maxPods` on your sandbox nodes. When a node's supervisor restarts, its sandboxes pause -until the replacement attaches within `supervisor.recoveryTimeoutSeconds`. -A lost node takes its sandboxes with it. +`supervisor.replicas`. Each supervisor accepts +`supervisor.pool.maxInstancesPerMember` sandboxes, 300 by default in this +topology; set it to at least the kubelet `maxPods` of your sandbox nodes +(default 110; managed services set their own limit). Switching an existing +release with `--reuse-values` keeps the earlier chart's 128; use +`--reset-then-reuse-values`. Size `supervisor.resources` for the sandboxes +per node. When a node's supervisor restarts, its sandboxes pause until the +replacement attaches within `supervisor.recoveryTimeoutSeconds`. A rollout +replaces `supervisor.updateStrategy.maxUnavailable` supervisors at once, +default 1. A lost node takes its sandboxes with it. Switching `supervisor_topology` between `gateway` and `node` terminates running shared sandboxes at the recovery timeout. Restart them to run under diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index cb31fa7d13..f6c05d88ee 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1557,6 +1557,13 @@ With `supervisor_topology = "node"`, `-supervisor` is a DaemonSet and each Pod's member ID is its node name; see the [per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. +Each node supervisor accepts `supervisor.pool.maxInstancesPerMember` +sandboxes, 300 unless set; a release switched to this topology with +`--reuse-values` keeps the earlier chart's 128 (`max_instances_per_member` in +`gateway.toml` shows it). `supervisor.updateStrategy.maxUnavailable` sets how +many supervisors a rollout replaces at once, and +`supervisor.priorityClassName: system-node-critical` has other Pods preempted +or evicted before the supervisor. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation records its node. Until the workload Pod is scheduled, the runtime logs `Runtime-initiated control cannot reach the supervisor; retrying`. Shared From ab0a456d8ca61faee94c6b818c25eaaf194b794b Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 15:51:45 +0200 Subject: [PATCH 12/18] docs(kubernetes): document settings for dense sandbox nodes List the limits that bound how many sandboxes one node runs in the node supervisor topology: the node's Pod address range, the pool cap, and the supervisor's PriorityClass. Signed-off-by: Gal Zaidman --- docs/kubernetes/high-availability.mdx | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index 522cfe2d04..ee2667854e 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -784,7 +784,18 @@ release with `--reuse-values` keeps the earlier chart's 128; use per node. When a node's supervisor restarts, its sandboxes pause until the replacement attaches within `supervisor.recoveryTimeoutSeconds`. A rollout replaces `supervisor.updateStrategy.maxUnavailable` supervisors at once, -default 1. A lost node takes its sandboxes with it. +default 1. A lost node takes its sandboxes with it. Set +`supervisor.priorityClassName: system-node-critical` so other Pods are +preempted or evicted before the supervisor. Clusters that limit critical +priority classes to `kube-system` need a ResourceQuota that allows it in the +release namespace. + +To run many sandboxes per node, also check these limits: + +- If your CNI allocates from each node's Pod CIDR, a `/24` holds about 250 + Pods. +- Each node runs one pool member, so keep `replicaCount` × + `supervisor.pool.maxMembersPerGateway` at or above your sandbox node count. Switching `supervisor_topology` between `gateway` and `node` terminates running shared sandboxes at the recovery timeout. Restart them to run under From c0edf0aec1520333f05d87a2c0459179fe11c8c1 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 17:26:06 +0200 Subject: [PATCH 13/18] fix(k8s): report why a node-topology create failed before deleting it A create in the node topology returns before its launch, so a later failure deleted the sandbox with no reason the creator could see. The launch now records the cause in openshell.ai/sandbox-runtime-launch-failure, which the driver reports as Ready=False SandboxRuntimeLaunchFailed so the gateway shows the create as failed. The reaper deletes such a sandbox on its next pass, and gives a stale node-topology create a generic cause first. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 5 +- .../openshell-driver-kubernetes/src/driver.rs | 734 +++++++++++------- .../openshell-server/src/supervisor_pool.rs | 2 + docs/kubernetes/high-availability.mdx | 6 +- skills/debug-openshell-cluster/SKILL.md | 2 +- 5 files changed, 462 insertions(+), 287 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index d58886c7a9..ff552bd364 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -491,7 +491,10 @@ scheduled on the node it claims as its pool member ID. to join the pool, and launches there. A Pod that is deleted or replaced, or a node supervisor that refuses the instance, rolls the bootstrap back. So does a Pod that isn't scheduled, or a node supervisor that doesn't join, within - `runtime_bootstrap_grace_seconds`. Each launch write re-checks that the + `runtime_bootstrap_grace_seconds`. A failed create first records its cause + in `openshell.ai/sandbox-runtime-launch-failure`, reported as a terminal + `Ready=False` (`SandboxRuntimeLaunchFailed`), and the reaper deletes it on + its next pass. Each launch write re-checks that the Sandbox still awaits this launch, so a stop, delete, or newer attempt served by another gateway replica wins. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 39d9d8a276..3f23ccb653 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -109,6 +109,10 @@ const ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: &str = "openshell.ai/sandbox-runtime-bootstrap-phase"; const ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_SESSION: &str = "openshell.ai/sandbox-runtime-bootstrap-session"; +/// Why a create launched after scheduling failed, reported as its Ready +/// condition until the rollback deletes the sandbox. +const ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE: &str = + "openshell.ai/sandbox-runtime-launch-failure"; const ANNOTATION_SANDBOX_RUNTIME_GENERATION: &str = "openshell.ai/sandbox-runtime-generation"; const ANNOTATION_SANDBOX_RUNTIME_READINESS: &str = "openshell.ai/sandbox-runtime-readiness"; const ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: &str = "openshell.ai/sandbox-runtime-workload-uid"; @@ -4200,16 +4204,11 @@ impl KubernetesComputeDriver { // A node supervisor serves only its own node, so the scheduler picks // the node first. Until the launch places the route there, the // runtime's dials are refused and the workload doesn't start. - if let GenerationLaunchTarget::Shared { route, .. } = &generation.target + if matches!(generation.target, GenerationLaunchTarget::Shared { .. }) && self.config.supervisor_topology == Some(SupervisorTopology::Node) { - let placement = SupervisorPlacement::Shared { - route: route.clone(), - }; remove_scheduling_gates(&pods, &generation.workload_pod_name).await?; - tokio::spawn(Box::pin( - self.clone().launch_on_scheduled_node(generation, placement), - )); + tokio::spawn(Box::pin(self.clone().launch_on_scheduled_node(generation))); return Ok(()); } Box::pin(self.launch_sandbox_runtime_generation(generation, None)).await @@ -4217,17 +4216,39 @@ impl KubernetesComputeDriver { /// Finish a node-topology launch once the scheduler binds the workload /// Pod. A failed launch rolls the bootstrap back as a stale one would be. - async fn launch_on_scheduled_node( - self, - generation: PreparedGeneration, - placement: SupervisorPlacement, - ) { + async fn launch_on_scheduled_node(self, generation: PreparedGeneration) { + let GenerationLaunchTarget::Shared { shared, route, .. } = &generation.target else { + return; + }; + let controller = shared.supervision().controller().clone(); + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; let bootstrap_grace = Duration::from_secs(self.config.runtime_bootstrap_grace_seconds); let deadline = tokio::time::Instant::now() + bootstrap_grace; let sandbox_api = generation.sandbox_api.clone(); let cr_name = generation.cr_name.clone(); let cr_uid = generation.cr_uid.clone(); let workload_pod_uid = generation.workload_pod_uid.clone(); + let pause = || { + tokio::time::sleep_until( + deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), + ) + }; + let give_up = async |cause: String| { + warn!( + sandbox = cr_name, + cause, "the stale bootstrap will be rolled back" + ); + record_sandbox_runtime_launch_failure( + &sandbox_api.api, + &cr_name, + &cr_uid, + &workload_pod_uid, + &cause, + ) + .await; + }; let pods = Api::::namespaced(self.client.clone(), &generation.namespace); let scheduled_or_replaced = |pod: Option<&Pod>| workload_pod_scheduled_or_replaced(pod, &workload_pod_uid); @@ -4244,18 +4265,13 @@ impl KubernetesComputeDriver { { Ok(Ok(pod)) => break pod, Err(_) => { - warn!( - sandbox = cr_name, - "the workload Pod was not scheduled within the bootstrap grace; the stale bootstrap will be rolled back" - ); + let secs = bootstrap_grace.as_secs(); + give_up(format!("the workload Pod was not scheduled within {secs}s")).await; return; } Ok(Err(error)) => { debug!(%error, sandbox = cr_name, "workload Pod scheduling watch failed; retrying"); - tokio::time::sleep_until( - deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), - ) - .await; + pause().await; } } }; @@ -4267,26 +4283,20 @@ impl KubernetesComputeDriver { return; }; // The node's supervisor may start with the workload, as on a new node. - if let GenerationLaunchTarget::Shared { shared, .. } = &generation.target { - let controller = shared.supervision().controller(); - while !controller.pool_view().is_some_and(|view| { - view.members - .iter() - .any(|member| member.member_id == node && !member.leaving) - }) { - if tokio::time::Instant::now() >= deadline { - warn!( - sandbox = cr_name, - node, - "no supervisor attached on the node within the bootstrap grace; the stale bootstrap will be rolled back" - ); - return; - } - tokio::time::sleep_until( - deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), - ) + while !controller.pool_view().is_some_and(|view| { + view.members + .iter() + .any(|member| member.member_id == node && !member.leaving) + }) { + if tokio::time::Instant::now() >= deadline { + let secs = bootstrap_grace.as_secs(); + give_up(format!( + "no supervisor attached on node {node} within {secs}s" + )) .await; + return; } + pause().await; } let _guard = self .lifecycle_gates @@ -4319,10 +4329,7 @@ impl KubernetesComputeDriver { } Err(error) => { debug!(%error, sandbox = cr_name, "reading the sandbox before its launch failed; retrying"); - tokio::time::sleep_until( - deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), - ) - .await; + pause().await; } } } @@ -4330,7 +4337,17 @@ impl KubernetesComputeDriver { if let Err(error) = launch { warn!(sandbox = cr_name, %error, "sandbox-runtime launch on the scheduled node failed; rolling back"); self.remove_shared_instance(&placement); - if let Ok(Some(object)) = read_awaiting().await { + if let Ok(Some(object)) = read_awaiting().await + && record_sandbox_runtime_launch_failure( + &sandbox_api.api, + &cr_name, + &cr_uid, + &workload_pod_uid, + &error.to_string(), + ) + .await + .is_none() + { self.roll_back_sandbox_runtime_bootstrap(&sandbox_api, &object) .await; } @@ -4436,13 +4453,7 @@ impl KubernetesComputeDriver { // the gateway refuses that combination fail-closed. self.ensure_network_additional_ca_config_map(namespace) .await?; - pods.patch( - &names.supervisor_pod, - &PatchParams::default(), - &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), - ) - .await - .map_err(KubernetesDriverError::from_kube)?; + remove_scheduling_gates(&pods, &names.supervisor_pod).await?; } GenerationLaunchTarget::Shared { shared, route, .. } => { let registration = shared_instance_registration( @@ -5778,7 +5789,6 @@ impl KubernetesComputeDriver { .annotations .as_ref() .and_then(|annotations| annotations.get(ANNOTATION_SUPERVISOR_MEMBER)) - .filter(|member| !member.is_empty()) .cloned(); Some(RecoverableInstance { route, @@ -6068,13 +6078,50 @@ impl KubernetesComputeDriver { lookup_api: &AgentSandboxApi, object: &DynamicObject, ) { - if !sandbox_runtime_bootstrap_is_stale( - object, - SystemTime::now(), - Duration::from_secs(self.config.runtime_bootstrap_grace_seconds), - ) { + let failed = sandbox_runtime_launch_failure(object).is_some(); + let grace = Duration::from_secs(self.config.runtime_bootstrap_grace_seconds); + if !failed && !sandbox_runtime_bootstrap_is_stale(object, SystemTime::now(), grace) { return; } + // A create launched after scheduling reports why it failed before its + // deletion, which waits for the next pass so the gateway can show it. + if !failed + && sandbox_runtime_bootstrap_operation(object) == Some("create") + && self.config.supervisor_topology == Some(SupervisorTopology::Node) + && let Some(name) = object.metadata.name.as_deref() + { + let namespace = object + .metadata + .namespace + .as_deref() + .unwrap_or(&self.config.namespace); + let api = Self::agent_sandbox_api( + self.client.clone(), + &lookup_api.resource.version, + namespace, + ); + let patch = sandbox_runtime_launch_failure_patch( + object + .metadata + .resource_version + .as_deref() + .unwrap_or_default(), + &format!("the sandbox did not launch within {}s", grace.as_secs()), + ); + match tokio::time::timeout( + KUBE_API_TIMEOUT, + api.api + .patch(name, &PatchParams::default(), &Patch::Merge(&patch)), + ) + .await + { + Ok(Ok(_)) => return, + Ok(Err(KubeError::Api(error))) if error.code == 404 || error.code == 409 => { + return; + } + Ok(Err(_)) | Err(_) => {} + } + } self.roll_back_sandbox_runtime_bootstrap(lookup_api, object) .await; } @@ -6686,6 +6733,51 @@ fn sandbox_runtime_bootstrap_operation(object: &DynamicObject) -> Option<&str> { .map(String::as_str) } +/// Why this create's launch failed, while its rollback is pending. +fn sandbox_runtime_launch_failure(object: &DynamicObject) -> Option<&str> { + if !sandbox_runtime_bootstrap_in_progress(object) + || sandbox_runtime_bootstrap_operation(object) != Some("create") + { + return None; + } + object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE)) + .map(String::as_str) +} + +fn sandbox_runtime_launch_failure_patch(resource_version: &str, cause: &str) -> serde_json::Value { + serde_json::json!({ + "metadata": { + "resourceVersion": resource_version, + "annotations": {ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE: cause}, + } + }) +} + +/// Record why a create launched after scheduling failed, unless a stop or a +/// newer attempt replaced it. Returns the updated sandbox. +async fn record_sandbox_runtime_launch_failure( + api: &Api, + name: &str, + cr_uid: &str, + workload_pod_uid: &str, + cause: &str, +) -> Option { + patch_dynamic_object_if(api, name, |object, version| { + (sandbox_runtime_awaits_launch(object, cr_uid, workload_pod_uid) + && sandbox_runtime_bootstrap_operation(object) == Some("create")) + .then(|| sandbox_runtime_launch_failure_patch(version, cause)) + }) + .await + .unwrap_or_else(|error| { + debug!(sandbox = name, %error, "could not record the sandbox launch failure"); + None + }) +} + fn sandbox_runtime_bootstrap_is_ready_to_complete(object: &DynamicObject) -> bool { sandbox_runtime_bootstrap_in_progress(object) && sandbox_runtime_bootstrap_phase(object) == Some(SandboxRuntimeBootstrapPhase::Released) @@ -7742,7 +7834,7 @@ async fn sandbox_from_object_with_sandbox_runtime_readiness( .clone() .unwrap_or_else(|| namespace.to_string()); let (name, mut sandbox) = sandbox_from_object_with_bootstrap_state(namespace, &obj)?; - if !sandbox_id.is_empty() { + if !sandbox_id.is_empty() && sandbox_runtime_launch_failure(&obj).is_none() { let dependencies = Box::pin(generation_control_availability( client, shared, @@ -7788,6 +7880,8 @@ fn sandbox_from_object_with_bootstrap_state( if sandbox_runtime_bootstrap_in_progress(obj) { if sandbox_runtime_bootstrap_operation(obj) == Some("stop") { mark_sandbox_runtime_stopping(&mut sandbox); + } else if let Some(cause) = sandbox_runtime_launch_failure(obj) { + mark_sandbox_runtime_launch_failed(&mut sandbox, cause); } else { mark_sandbox_runtime_bootstrapping(&mut sandbox); } @@ -7818,6 +7912,14 @@ fn mark_sandbox_runtime_bootstrapping(sandbox: &mut Sandbox) { mark_sandbox_runtime_control_unavailable(sandbox); } +/// A terminal Ready reason, so the gateway reports the create as failed +/// before the rollback deletes it. +fn mark_sandbox_runtime_launch_failed(sandbox: &mut Sandbox, cause: &str) { + clear_sandbox_runtime_operation_conditions(sandbox); + sandbox.status.get_or_insert_with(Default::default); + mark_sandbox_not_ready(sandbox, "SandboxRuntimeLaunchFailed", cause); +} + fn clear_sandbox_runtime_operation_conditions(sandbox: &mut Sandbox) { if let Some(status) = sandbox.status.as_mut() { status.conditions.retain(|condition| { @@ -7827,8 +7929,14 @@ fn clear_sandbox_runtime_operation_conditions(sandbox: &mut Sandbox) { } fn mark_sandbox_runtime_control_unavailable(sandbox: &mut Sandbox) { - const REASON: &str = "DependenciesNotReady"; - const MESSAGE: &str = "sandbox-runtime enforcement dependencies are not ready"; + mark_sandbox_not_ready( + sandbox, + "DependenciesNotReady", + "sandbox-runtime enforcement dependencies are not ready", + ); +} + +fn mark_sandbox_not_ready(sandbox: &mut Sandbox, reason: &str, message: &str) { let Some(status) = sandbox.status.as_mut() else { return; }; @@ -7838,14 +7946,14 @@ fn mark_sandbox_runtime_control_unavailable(sandbox: &mut Sandbox) { .find(|condition| condition.r#type == "Ready") { ready.status = "False".to_string(); - ready.reason = REASON.to_string(); - ready.message = MESSAGE.to_string(); + ready.reason = reason.to_string(); + ready.message = message.to_string(); } else { status.conditions.push(SandboxCondition { r#type: "Ready".to_string(), status: "False".to_string(), - reason: REASON.to_string(), - message: MESSAGE.to_string(), + reason: reason.to_string(), + message: message.to_string(), transition_time: None, }); } @@ -10402,34 +10510,30 @@ mod tests { ); } + use openshell_supervisor_control as control; + /// Durable pool records that accept every launch. #[derive(Debug)] struct AcceptingPlacement; - impl openshell_supervisor_control::InstancePlacement for AcceptingPlacement { - fn place_launch( - &self, - _request: openshell_supervisor_control::PlacementRequest, - ) -> openshell_supervisor_control::PlacementFuture { + impl control::InstancePlacement for AcceptingPlacement { + fn place_launch(&self, _request: control::PlacementRequest) -> control::PlacementFuture { Box::pin(async { Ok(()) }) } - fn recorded(&self) -> openshell_supervisor_control::PlacementFuture> { + fn recorded(&self) -> control::PlacementFuture> { Box::pin(async { Ok(BTreeMap::new()) }) } fn record_recovered( &self, - _assignment: openshell_supervisor_control::proto::SandboxInstanceAssignment, + _assignment: control::proto::SandboxInstanceAssignment, _member: Option, - ) -> openshell_supervisor_control::PlacementFuture { + ) -> control::PlacementFuture { Box::pin(async { Ok(()) }) } - fn prepare_runtime( - &self, - _: openshell_supervisor_control::PreparationRequest, - ) -> openshell_supervisor_control::PlacementFuture { + fn prepare_runtime(&self, _: control::PreparationRequest) -> control::PlacementFuture { unreachable!("deferred launches prepare no warm runtime") } @@ -10437,36 +10541,28 @@ mod tests { &self, _: String, _: Vec, - ) -> openshell_supervisor_control::PlacementFuture< - Vec, - > { + ) -> control::PlacementFuture> { unreachable!("deferred launches list no warm runtime") } fn release_preparation( &self, - _: openshell_supervisor_control::PreparationRevision, - ) -> openshell_supervisor_control::PlacementFuture< - openshell_supervisor_control::PreparationRelease, - > { + _: control::PreparationRevision, + ) -> control::PlacementFuture { unreachable!("deferred launches release no warm runtime") } fn retire_preparation( &self, - _: openshell_supervisor_control::PreparationRetirement, - ) -> openshell_supervisor_control::PlacementFuture< - openshell_supervisor_control::PreparationRelease, - > { + _: control::PreparationRetirement, + ) -> control::PlacementFuture { unreachable!("deferred launches retire no warm runtime") } fn activate_runtime( &self, - _: openshell_supervisor_control::ActivationRequest, - ) -> openshell_supervisor_control::PlacementFuture< - openshell_supervisor_control::proto::SandboxInstanceAssignment, - > { + _: control::ActivationRequest, + ) -> control::PlacementFuture { unreachable!("deferred launches activate no warm runtime") } } @@ -10482,20 +10578,13 @@ mod tests { ) } + fn scheduled_sandbox_api(driver: &KubernetesComputeDriver) -> AgentSandboxApi { + KubernetesComputeDriver::agent_sandbox_api(driver.client.clone(), "v1beta1", "openshell") + } + /// Run the deferred launch of `generation` to completion. async fn launch_scheduled(driver: &KubernetesComputeDriver, generation: PreparedGeneration) { - let GenerationLaunchTarget::Shared { route, .. } = &generation.target else { - unreachable!(); - }; - let placement = SupervisorPlacement::Shared { - route: route.clone(), - }; - Box::pin( - driver - .clone() - .launch_on_scheduled_node(generation, placement), - ) - .await; + Box::pin(driver.clone().launch_on_scheduled_node(generation)).await; } /// A shared generation of `sandbox-cr`, prepared but not yet launched. @@ -10592,11 +10681,7 @@ mod tests { PreparedGeneration { namespace: "openshell".to_string(), cr_name: "sandbox-cr".to_string(), - sandbox_api: KubernetesComputeDriver::agent_sandbox_api( - driver.client.clone(), - "v1beta1", - "openshell", - ), + sandbox_api: scheduled_sandbox_api(driver), sandbox_id: "sandbox-id".to_string(), cr_uid: "cr-uid".to_string(), names: SandboxRuntimeNames::new("sandbox-id"), @@ -10626,63 +10711,48 @@ mod tests { } } + /// A deferred launch's requests through its instance Secret: the bound + /// Pod, the sandbox read, the member write, and the Secret. + fn launch_steps_through_secret(now: i64) -> Vec { + let awaiting = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now); + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::POST, + "/api/v1/namespaces/openshell/secrets", + instance_secret_created(), + ), + ] + } + #[tokio::test] - async fn scheduled_launch_the_pool_cannot_place_is_rolled_back() { - let awaiting = || { - scheduled_sandbox_json( - SandboxRuntimeBootstrapPhase::Preparing, - openshell_core::time::now_ms(), - ) - }; - let (driver, steps, bodies) = scripted_driver( - managed_config(&[]), - vec![ - ( - http::Method::GET, - WORKLOAD_PODS_PATH, - bound_workload_pods_json(), - ), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), - (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), - ( - http::Method::POST, - "/api/v1/namespaces/openshell/secrets", - kube_test_response( - http::StatusCode::CREATED, - serde_json::json!({ - "apiVersion": "v1", - "kind": "Secret", - "metadata": {"name": "instance", "namespace": "openshell"}, - }), - ), - ), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), - ( - http::Method::DELETE, - SCHEDULED_SANDBOX_PATH, - kube_test_response(http::StatusCode::OK, serde_json::json!({})), - ), - ], - ); - let generation = scheduled_generation(&driver); - let GenerationLaunchTarget::Shared { route, .. } = &generation.target else { - unreachable!(); - }; - let placement = SupervisorPlacement::Shared { - route: route.clone(), - }; - Box::pin( - driver - .clone() - .launch_on_scheduled_node(generation, placement), - ) - .await; + async fn scheduled_launch_the_pool_cannot_place_reports_its_failure() { + let now = openshell_core::time::now_ms(); + let awaiting = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now); + let mut script = launch_steps_through_secret(now); + script.extend([ + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ]); + let (driver, steps, bodies) = scripted_driver(managed_config(&[]), script); + launch_scheduled(&driver, scheduled_generation(&driver)).await; assert!(steps.lock().unwrap().is_empty()); + // The reaper deletes it on its next pass, after the gateway shows why. let bodies = bodies.lock().unwrap(); - let delete = bodies.last().unwrap(); - assert_eq!(delete["preconditions"]["uid"], "cr-uid"); - assert_eq!(delete["preconditions"]["resourceVersion"], "7"); + let failure = &bodies.last().unwrap()["metadata"]; + assert_eq!(failure["resourceVersion"], "7"); + assert_eq!( + failure["annotations"][ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE], + "the supervisor pool is not ready to place sandbox instances" + ); } #[tokio::test] @@ -10714,8 +10784,7 @@ mod tests { ), ], ); - let generation = scheduled_generation(&driver); - launch_scheduled(&driver, generation).await; + launch_scheduled(&driver, scheduled_generation(&driver)).await; assert!(steps.lock().unwrap().is_empty()); // Nothing was written, created, or rolled back. assert!(bodies.lock().unwrap().is_empty()); @@ -10724,47 +10793,30 @@ mod tests { #[tokio::test] async fn scheduled_launch_yields_to_a_stop_before_release() { let now = openshell_core::time::now_ms(); - let awaiting = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now); let stopping = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now); - let (mut driver, steps, bodies) = scripted_driver( - managed_config(&[]), - vec![ - ( - http::Method::GET, - WORKLOAD_PODS_PATH, - bound_workload_pods_json(), - ), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), - (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), - ( - http::Method::POST, - "/api/v1/namespaces/openshell/secrets", - instance_secret_created(), - ), - // A stop on another replica lands before the release. - (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), - ], - ); + let mut script = launch_steps_through_secret(now); + // A stop on another replica lands before the release. + script.extend([ + (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, stopping()), + ]); + let (mut driver, steps, bodies) = scripted_driver(managed_config(&[]), script); let shared = scheduled_shared_supervisor(); shared .supervision() .controller() .install_placement(Arc::new(AcceptingPlacement)); driver.shared_supervisor = Some(shared.clone()); - let generation = scheduled_generation(&driver); - launch_scheduled(&driver, generation).await; + launch_scheduled(&driver, scheduled_generation(&driver)).await; assert!(steps.lock().unwrap().is_empty()); // The placed instance was withdrawn, the stop's phase was never // overwritten, and nothing was rolled back. assert!(shared.supervision().controller().assignments().is_empty()); let bodies = bodies.lock().unwrap(); assert_eq!(bodies.len(), 2); - assert!( - bodies[0]["metadata"]["annotations"][ANNOTATION_SUPERVISOR_MEMBER] == "node-a", - "{:?}", - bodies[0] + assert_eq!( + bodies[0]["metadata"]["annotations"][ANNOTATION_SUPERVISOR_MEMBER], + "node-a" ); } @@ -10784,14 +10836,7 @@ mod tests { SCHEDULED_SANDBOX_PATH, kube_test_response( http::StatusCode::INTERNAL_SERVER_ERROR, - serde_json::json!({ - "apiVersion": "v1", - "kind": "Status", - "status": "Failure", - "message": "etcdserver: request timed out", - "reason": "InternalError", - "code": 500 - }), + serde_json::json!({"kind": "Status", "code": 500}), ), ), // The retry finds the sandbox moved on, so the launch ends. @@ -10802,8 +10847,7 @@ mod tests { ), ], ); - let generation = scheduled_generation(&driver); - launch_scheduled(&driver, generation).await; + launch_scheduled(&driver, scheduled_generation(&driver)).await; assert!(steps.lock().unwrap().is_empty()); } @@ -10844,14 +10888,78 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn scheduled_launch_leaves_a_node_without_supervisor_to_the_reaper() { + async fn scheduled_launch_reports_a_workload_pod_never_scheduled() { + use http_body_util::BodyExt as _; + let now = openshell_core::time::now_ms(); + let patches = Arc::new(std::sync::Mutex::new(Vec::::new())); + let recorded = patches.clone(); + let service = tower::service_fn(move |request: http::Request| { + let recorded = recorded.clone(); + async move { + let watch = request.uri().query().is_some_and(|q| q.contains("watch")); + let (method, path) = (request.method().clone(), request.uri().path().to_owned()); + let response = match (method, path.as_str()) { + // The Pod stays Pending, so no watch event arrives. + (http::Method::GET, WORKLOAD_PODS_PATH) if watch => { + futures::future::pending().await + } + (http::Method::GET, WORKLOAD_PODS_PATH) => kube_test_response( + http::StatusCode::OK, + serde_json::json!({ + "apiVersion": "v1", + "kind": "PodList", + "metadata": {"resourceVersion": "1"}, + "items": [{ + "metadata": {"name": "workload", "namespace": "openshell", "uid": "pod-uid"}, + "spec": {"containers": []}, + }], + }), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH) => { + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now) + } + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH) => { + let body = request.into_body().collect().await.unwrap().to_bytes(); + recorded + .lock() + .unwrap() + .push(serde_json::from_slice(&body).unwrap()); + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now) + } + (method, path) => panic!("unexpected Kubernetes API request {method} {path}"), + }; + Ok::<_, std::convert::Infallible>(response) + } + }); + let (mut driver, _, _) = scripted_driver(managed_config(&[]), Vec::new()); + driver.client = Client::new(service, "openshell"); + launch_scheduled(&driver, scheduled_generation(&driver)).await; + let patches = patches.lock().unwrap(); + assert_eq!(patches.len(), 1); + assert_eq!( + patches[0]["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE], + format!( + "the workload Pod was not scheduled within {}s", + driver.config.runtime_bootstrap_grace_seconds + ) + ); + } + + #[tokio::test(start_paused = true)] + async fn scheduled_launch_reports_a_node_without_supervisor() { + let now = openshell_core::time::now_ms(); + let awaiting = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, now); let (driver, steps, bodies) = scripted_driver( managed_config(&[]), - vec![( - http::Method::GET, - WORKLOAD_PODS_PATH, - bound_workload_pods_json(), - )], + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ], ); let generation = scheduled_generation(&driver); let GenerationLaunchTarget::Shared { shared, .. } = &generation.target else { @@ -10860,100 +10968,127 @@ mod tests { attach_node_supervisors(shared, &[]); launch_scheduled(&driver, generation).await; assert!(steps.lock().unwrap().is_empty()); - assert!(bodies.lock().unwrap().is_empty()); + // Only the cause is written; the reaper deletes the sandbox. + let bodies = bodies.lock().unwrap(); + assert_eq!(bodies.len(), 1); + assert_eq!( + bodies[0]["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE], + format!( + "no supervisor attached on node node-a within {}s", + driver.config.runtime_bootstrap_grace_seconds + ) + ); } #[tokio::test] - async fn scheduled_launch_skips_a_sandbox_that_moved_on_or_went_stale() { + async fn reaper_deletes_a_failed_create_without_waiting_for_the_grace() { let now = openshell_core::time::now_ms(); - for sandbox in [ - scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now), - scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, 0), - ] { - let (driver, steps, bodies) = scripted_driver( - managed_config(&[]), - vec![ - ( - http::Method::GET, - WORKLOAD_PODS_PATH, - bound_workload_pods_json(), - ), - (http::Method::GET, SCHEDULED_SANDBOX_PATH, sandbox), - ], - ); - let generation = scheduled_generation(&driver); - Box::pin( - driver - .clone() - .launch_on_scheduled_node(generation, SupervisorPlacement::Dedicated), + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![( + http::Method::DELETE, + SCHEDULED_SANDBOX_PATH, + kube_test_response(http::StatusCode::OK, serde_json::json!({})), + )], + ); + let mut object = scheduled_sandbox(SandboxRuntimeBootstrapPhase::Preparing, now); + let annotations = object.metadata.annotations.as_mut().unwrap(); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), + "true".to_string(), + ); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE.to_string(), + "refused".to_string(), + ); + driver + .reap_stale_sandbox_runtime_bootstrap(&scheduled_sandbox_api(&driver), &object) + .await; + assert!(steps.lock().unwrap().is_empty()); + assert_eq!( + bodies.lock().unwrap()[0]["preconditions"]["resourceVersion"], + "7" + ); + } + + #[tokio::test] + async fn reaper_reports_a_stale_node_create_before_deleting_it() { + let mut config = managed_config(&[]); + config.supervisor_topology = Some(SupervisorTopology::Node); + let (driver, steps, bodies) = scripted_driver( + config, + vec![( + http::Method::PATCH, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, 0), + )], + ); + driver + .reap_stale_sandbox_runtime_bootstrap( + &scheduled_sandbox_api(&driver), + &scheduled_sandbox(SandboxRuntimeBootstrapPhase::Preparing, 0), ) .await; - assert!(steps.lock().unwrap().is_empty()); - assert!(bodies.lock().unwrap().is_empty()); - } + assert!(steps.lock().unwrap().is_empty()); + let bodies = bodies.lock().unwrap(); + assert_eq!(bodies.len(), 1); + assert_eq!(bodies[0]["metadata"]["resourceVersion"], "7"); + assert!( + bodies[0]["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE] + .is_string() + ); + } + + #[tokio::test] + async fn scheduled_launch_leaves_a_stale_sandbox_to_the_reaper() { + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + ( + http::Method::GET, + SCHEDULED_SANDBOX_PATH, + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, 0), + ), + ], + ); + launch_scheduled(&driver, scheduled_generation(&driver)).await; + assert!(steps.lock().unwrap().is_empty()); + assert!(bodies.lock().unwrap().is_empty()); } #[test] fn scheduled_launch_runs_only_for_the_attempt_that_prepared_it() { - let sandbox = |uid: &str, phase: &str, workload_uid: &str| { - serde_json::from_value::(serde_json::json!({ - "apiVersion": "agents.x-k8s.io/v1beta1", - "kind": "Sandbox", - "metadata": { - "name": "sandbox-cr", - "namespace": "openshell", - "uid": uid, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase, - ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_uid, - }, - }, - })) - .unwrap() - }; - let preparing = SandboxRuntimeBootstrapPhase::Preparing.as_str(); + let preparing = || scheduled_sandbox(SandboxRuntimeBootstrapPhase::Preparing, 0); assert!(sandbox_runtime_awaits_launch( - &sandbox("cr-1", preparing, "pod-1"), - "cr-1", - "pod-1" + &preparing(), + "cr-uid", + "pod-uid" )); - // Stopped or suspended while it waited. - assert!(!sandbox_runtime_awaits_launch( - &sandbox( - "cr-1", - SandboxRuntimeBootstrapPhase::Suspending.as_str(), - "pod-1" - ), - "cr-1", - "pod-1" - )); - // A retried or newer attempt prepared another workload Pod. - assert!(!sandbox_runtime_awaits_launch( - &sandbox("cr-1", preparing, "pod-2"), - "cr-1", - "pod-1" - )); - // Already launched, or a stop is releasing it. + // Stopped, already launched, or a stop is releasing it. for phase in [ + SandboxRuntimeBootstrapPhase::Suspending, SandboxRuntimeBootstrapPhase::Released, SandboxRuntimeBootstrapPhase::Releasing, ] { - assert!(!sandbox_runtime_awaits_launch( - &sandbox("cr-1", phase.as_str(), "pod-1"), - "cr-1", - "pod-1" - )); + let object = scheduled_sandbox(phase, 0); + assert!(!sandbox_runtime_awaits_launch(&object, "cr-uid", "pod-uid")); } - // The bootstrap completed and its annotations were cleared. - let mut completed = sandbox("cr-1", preparing, "pod-1"); + // A newer attempt prepared another workload Pod, the bootstrap + // completed, or the sandbox was recreated under the same name. + let mut completed = preparing(); completed.metadata.annotations = None; - assert!(!sandbox_runtime_awaits_launch(&completed, "cr-1", "pod-1")); - // Deleted and recreated under the same name. - assert!(!sandbox_runtime_awaits_launch( - &sandbox("cr-2", preparing, "pod-1"), - "cr-1", - "pod-1" - )); + for (object, cr_uid, pod_uid) in [ + (preparing(), "cr-uid", "pod-2"), + (completed, "cr-uid", "pod-uid"), + (preparing(), "cr-2", "pod-uid"), + ] { + assert!(!sandbox_runtime_awaits_launch(&object, cr_uid, pod_uid)); + } } fn network_trust_bundle(gateway_id: &str, digest: &str) -> NetworkSupervisorTrustBundle { @@ -16143,6 +16278,39 @@ mod tests { } } + #[test] + fn failed_create_snapshots_report_their_cause() { + let ready_reason = |operation| { + let mut object = sandbox_cr_mid_operation(Some(operation)); + object.metadata.annotations.as_mut().unwrap().insert( + ANNOTATION_SANDBOX_RUNTIME_LAUNCH_FAILURE.to_string(), + "no supervisor attached on node node-a within 300s".to_string(), + ); + let (_, sandbox) = + sandbox_from_object_with_bootstrap_state("default", &object).unwrap(); + assert!(!has_condition(&sandbox, "Bootstrapping", "True")); + sandbox + .status + .unwrap() + .conditions + .into_iter() + .find(|condition| condition.r#type == "Ready") + .map(|condition| (condition.reason, condition.message)) + }; + assert_eq!( + ready_reason("create"), + Some(( + "SandboxRuntimeLaunchFailed".to_string(), + "no supervisor attached on node node-a within 300s".to_string(), + )) + ); + // A later stop or restart is not the failed create. + assert_ne!( + ready_reason("stop").map(|(reason, _)| reason), + Some("SandboxRuntimeLaunchFailed".to_string()) + ); + } + #[test] fn completed_sandbox_runtime_bootstrap_preserves_real_suspension() { let sandbox = Sandbox { diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index 555f1de0d4..6052dd8c46 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -1733,6 +1733,7 @@ impl SupervisorPool { /// [`Self::remove_stale_candidates`]). A recording whose reservation is /// fenced or withdrawn first fails and deletes its own material; a /// failure to do so leaves the candidate for collection to retry. + #[cfg(test)] async fn record_assignment( &self, assignment: &SandboxInstanceAssignment, @@ -1746,6 +1747,7 @@ impl SupervisorPool { /// ([`RecordPhase::Published`] or [`RecordPhase::Admitting`]). An /// admitting record keeps its material candidate, which this recording /// reports; a published one releases it. + #[cfg(test)] async fn record_assignment_as( &self, assignment: &SandboxInstanceAssignment, diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index ee2667854e..bb039974df 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -760,8 +760,10 @@ and the `NodeRestriction` admission plugin, so a compromised node's kubelet cannot obtain tokens for another node's supervisor. If no node accepts the workload, or its node's supervisor does not attach, -within `runtime_bootstrap_grace_seconds`, the gateway deletes the new sandbox -or stops the restarted one. A supervisor must run on +within `runtime_bootstrap_grace_seconds`, the gateway stops the restarted +sandbox. A new sandbox, or one its node's supervisor refuses, enters `Error` +with the cause, which `openshell sandbox create` reports, and is deleted +within 30 seconds. A supervisor must run on every node that can host a sandbox. If sandbox templates tolerate node taints, set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with `supervisor.nodeSelector`. GPU nodes usually need: diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index f6c05d88ee..842d31780d 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1853,7 +1853,7 @@ credential failures. | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | | A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | -| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full, or its membership record has no proven node because it attached through a replica that resolved no identity token), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| Create fails with `SandboxRuntimeLaunchFailed: ` and the sandbox is deleted within 30 seconds, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full, or its membership record has no proven node because it attached through a replica that resolved no identity token), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | From edb5dd7b036fad5391d3e90f8463f406cec6f01e Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Thu, 3 Dec 2026 20:07:57 +0200 Subject: [PATCH 14/18] ci(e2e): run the per-node shared supervisor lane on a multi-node kind cluster Signed-off-by: Gal Zaidman --- .github/actions/setup-e2e-kind/action.yml | 22 +++++++++++++++++++--- .github/workflows/branch-e2e.yml | 18 +++++++++++++++++- .github/workflows/e2e-kubernetes-test.yml | 6 ++++++ TESTING.md | 1 + 4 files changed, 43 insertions(+), 4 deletions(-) diff --git a/.github/actions/setup-e2e-kind/action.yml b/.github/actions/setup-e2e-kind/action.yml index a4a98d52fb..1884043d61 100644 --- a/.github/actions/setup-e2e-kind/action.yml +++ b/.github/actions/setup-e2e-kind/action.yml @@ -30,6 +30,10 @@ inputs: description: Replace kindnet with pinned Calico for NetworkPolicy assertions required: false default: "false" + worker-nodes: + description: Worker nodes beside the control plane, which kind then taints NoSchedule + required: false + default: "0" runs: using: composite @@ -46,20 +50,32 @@ runs: REGISTRY_PASSWORD: ${{ inputs.registry-password }} run: echo "$REGISTRY_PASSWORD" | docker login "${REGISTRY%%/*}" -u "$REGISTRY_USERNAME" --password-stdin - - name: Configure policy-enforcing kind network + - name: Configure kind cluster id: kind-config - if: inputs.enforce-network-policy == 'true' + if: inputs.enforce-network-policy == 'true' || inputs.worker-nodes != '0' shell: bash + env: + ENFORCE_NETWORK_POLICY: ${{ inputs.enforce-network-policy }} + WORKER_NODES: ${{ inputs.worker-nodes }} run: | set -euo pipefail - config="$RUNNER_TEMP/kind-network-policy.yaml" + config="$RUNNER_TEMP/kind-config.yaml" cat > "$config" <<'YAML' kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 + nodes: + - role: control-plane + YAML + for ((worker = 0; worker < WORKER_NODES; worker++)); do + echo " - role: worker" >> "$config" + done + if [ "$ENFORCE_NETWORK_POLICY" = true ]; then + cat >> "$config" <<'YAML' networking: disableDefaultCNI: true podSubnet: 10.244.0.0/16 YAML + fi echo "path=$config" >> "$GITHUB_OUTPUT" # kind comes from mise (pinned in mise.lock) rather than a fresh download. diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 87d9a38db7..d0b0ff4972 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -799,6 +799,22 @@ jobs: kubernetes-features: e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-ha use-envoy-gateway: true + kubernetes-shared-supervisor-node-e2e: + needs: [pr_metadata, build-binaries-linux, build-conformance, build-images] + if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_ha_e2e == 'true' + permissions: + actions: read + contents: read + packages: read + uses: ./.github/workflows/e2e-kubernetes-test.yml + with: + checkout-ref: ${{ needs.pr_metadata.outputs.sha }} + prebuilt-conformance: true + image-tag: ${{ needs.pr_metadata.outputs.sha }} + job-name: Kubernetes E2E (shared supervisor per node) + e2e-task: e2e:kubernetes:shared-supervisor-node + worker-nodes: 2 + kubernetes-credential-drivers-e2e: needs: [pr_metadata, build-binaries-linux, build-conformance, build-images] if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_credential_drivers_e2e == 'true' @@ -849,7 +865,7 @@ jobs: kubernetes-ha-e2e-result: name: Kubernetes HA E2E result - needs: [pr_metadata, build-binaries-macos, kubernetes-ha-e2e] + needs: [pr_metadata, build-binaries-macos, kubernetes-ha-e2e, kubernetes-shared-supervisor-node-e2e] if: always() && needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_ha_e2e == 'true' runs-on: ubuntu-latest steps: diff --git a/.github/workflows/e2e-kubernetes-test.yml b/.github/workflows/e2e-kubernetes-test.yml index 340beb81f7..7734604df8 100644 --- a/.github/workflows/e2e-kubernetes-test.yml +++ b/.github/workflows/e2e-kubernetes-test.yml @@ -87,6 +87,11 @@ on: required: false type: boolean default: false + worker-nodes: + description: "kind worker nodes beside the control plane" + required: false + type: number + default: 0 listener-topology: required: false type: string @@ -153,6 +158,7 @@ jobs: registry-password: ${{ secrets.GITHUB_TOKEN }} mise-version: ${{ inputs.mise-version }} enforce-network-policy: ${{ inputs.enforce-network-policy }} + worker-nodes: ${{ inputs.worker-nodes }} - name: Preload listener workload and client fixture if: inputs.e2e-task == 'e2e:kubernetes:app-listener' diff --git a/TESTING.md b/TESTING.md index 5cf0592fd0..015e61588e 100644 --- a/TESTING.md +++ b/TESTING.md @@ -981,6 +981,7 @@ Available task variants: | `e2e:kubernetes:shared-supervisor` | One-member shared supervisor pool for the gateway's sandboxes (gateway TLS through the port-forward) | | `e2e:kubernetes:shared-supervisor-ha` | Two-replica shared supervisor pool behind two gateway replicas on PostgreSQL: kills the member that owns a sandbox and checks the sandbox is adopted, not restarted; crashes and restarts gateways and checks each sandbox's session stays on its supervisor's gateway | | `e2e:kubernetes:shared-supervisor-scaling` | One-member shared supervisor pool: scales it to two members and back with `helm upgrade`, checking sandboxes stay running and the removed member hands its sandboxes off | +| `e2e:kubernetes:shared-supervisor-node` | One shared supervisor per node on two schedulable nodes: checks each sandbox runs under its node's supervisor, a replaced supervisor re-adopts its node's sandboxes, and a supervisor claiming another node is refused | | `e2e:kubernetes:tracing` | Deploys a Jaeger collector, exports gateway traces to it, and fails unless Jaeger receives gateway and Kubernetes compute-driver spans for a new sandbox. The only Kubernetes lane that exports traces | Kubernetes e2e environment variables: From 0f78e67041c48e5f73aaa4bfd9323a4cd61158ea Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Fri, 4 Dec 2026 20:24:13 +0200 Subject: [PATCH 15/18] docs(kubernetes): note raising the bootstrap grace for autoscaled sandbox nodes Signed-off-by: Gal Zaidman --- docs/kubernetes/high-availability.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index bb039974df..b0e481e6ea 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -763,8 +763,10 @@ If no node accepts the workload, or its node's supervisor does not attach, within `runtime_bootstrap_grace_seconds`, the gateway stops the restarted sandbox. A new sandbox, or one its node's supervisor refuses, enters `Error` with the cause, which `openshell sandbox create` reports, and is deleted -within 30 seconds. A supervisor must run on -every node that can host a sandbox. If sandbox templates tolerate node taints, +within 30 seconds. The window, 300 seconds by default, includes adding a node +and starting its supervisor, so raise it if a cluster autoscaler adds sandbox +nodes slower than that. A supervisor must run on every node that can host a +sandbox. If sandbox templates tolerate node taints, set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with `supervisor.nodeSelector`. GPU nodes usually need: From 564df1cf318b97ef12c8229c7b629d84f5200ce8 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Fri, 4 Dec 2026 21:39:08 +0200 Subject: [PATCH 16/18] fix(server): refuse warm pool preparation in the node supervisor topology A warm spare reserves shared supervisor capacity before its Pod is scheduled, so it carries no node pin. With supervisor_topology = "node" any node's supervisor could take it, the Pod could then run on another node, and recovery refuses unpinned instances there. Node-topology replicas now refuse unpinned placement, which warm preparation uses. Signed-off-by: Gal Zaidman --- crates/openshell-server/src/supervisor_pool.rs | 6 ++++++ .../src/supervisor_pool/prepared_tests.rs | 18 ++++++++++++++++++ docs/how-it-works/gateways/configuration.mdx | 2 ++ 3 files changed, 26 insertions(+) diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index 6052dd8c46..3d56f3b21e 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -2232,6 +2232,12 @@ impl SupervisorPool { preparation: Option<(&str, &str)>, ) -> Result<(), String> { let assignment = &request.assignment; + // A warm runtime is reserved before the scheduler picks its node. + if self.refuses_unpinned(request.member.as_deref()) { + return Err( + "supervisor_topology = \"node\" places only instances pinned to their node's supervisor; warm pools are not supported in this topology".into(), + ); + } let members = self .live_members() .await diff --git a/crates/openshell-server/src/supervisor_pool/prepared_tests.rs b/crates/openshell-server/src/supervisor_pool/prepared_tests.rs index 8382f46d83..5e4678e284 100644 --- a/crates/openshell-server/src/supervisor_pool/prepared_tests.rs +++ b/crates/openshell-server/src/supervisor_pool/prepared_tests.rs @@ -192,6 +192,24 @@ async fn preparation_inventory_is_scoped_durable_and_excludes_unadmitted_and_cla ); } +#[tokio::test] +async fn node_bound_pools_refuse_warm_preparation() { + let fixture = Fixture::new().await; + fixture.member("node-a", "p1", false).await; + let pool = fixture.replica("gateway-a"); + pool.controller.bind_members_to_nodes(); + let prepared = preparation(&fixture, "rt-prepared-0123456789").await; + + let error = pool.prepare_runtime(prepared.clone()).await.unwrap_err(); + assert!(error.contains("warm pools are not supported"), "{error}"); + assert!( + pool.assignment(&prepared.registration.route) + .await + .unwrap() + .is_none() + ); +} + #[tokio::test] async fn preparation_inventory_reports_the_original_process_availability() { let (fixture, pool, prepared) = setup().await; diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 5837575a99..88cf6ab386 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1900,6 +1900,8 @@ until claimed. The response supplies the assigned identity and credentials, so claims do not wait for Kubernetes Secret projection. The runtime makes no bootstrap request to the gateway. Shared supervisors receive claims through their existing assignment stream. Drain warm pools before changing supervisor topology. +Warm pools are not supported with `supervisor_topology = "node"`: the gateway +refuses to prepare a spare before the scheduler picks its node. A claim keeps the existing Pod and supervisor connection. Policy, credentials, and the main process are assigned at claim time. A stopped sandbox starts with From e505af1c02681b2c15e8fad02340d8b98851e9c3 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Fri, 4 Dec 2026 22:00:59 +0200 Subject: [PATCH 17/18] fix(kubernetes): keep gateway-topology shared supervisor config without a service account working A shared_supervisor table written before service_account_name existed failed to load after upgrade. The gateway topology now accepts it without the account and verifies only the supervisor token, refusing a pod-bound identity token it has no account to verify. The node topology and require_identity_token still require the account. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 4 +- .../openshell-driver-kubernetes/src/config.rs | 67 +++++++++- .../openshell-driver-kubernetes/src/driver.rs | 24 ++-- .../src/warm_pool/tests.rs | 2 +- crates/openshell-server/src/auth/peer.rs | 8 -- .../src/auth/supervisor_token.rs | 115 ++++++++---------- crates/openshell-server/src/lib.rs | 71 ++++++----- crates/openshell-server/src/multiplex.rs | 12 +- crates/openshell-supervisor-control/README.md | 17 +-- crates/openshell-supervisor/README.md | 23 ++-- crates/openshell-supervisor/src/main.rs | 26 +++- crates/openshell-supervisor/src/shared.rs | 4 +- .../openshell-supervisor/src/shared_host.rs | 19 +-- docs/how-it-works/gateways/configuration.mdx | 16 ++- skills/debug-openshell-cluster/SKILL.md | 11 +- 15 files changed, 229 insertions(+), 190 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index ff552bd364..09b5896bed 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -416,7 +416,9 @@ fails closed. ServiceAccount token sent with a supervisor token must resolve to a live Pod of that account. With `shared_supervisor.require_identity_token`, a supervisor token without one is refused, so a copy of the token Secret alone - admits no caller. + admits no caller. The gateway topology may omit the account, which validation + refuses with the node topology or `require_identity_token`; the gateway then + accepts the supervisor token alone and refuses a projected token. - **Create and start.** The driver creates a per-sandbox egress allowance `os-shared-control-` from the workload Pod to the Pods the shared supervisor's Service selects, on the runtime port, binds its UID and diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 7de2c0bd86..2be87c5a53 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -240,8 +240,11 @@ pub struct SharedSupervisorConfig { /// mounts it and presents the token on its assignment stream. pub token_secret_name: String, /// `ServiceAccount` in `service_namespace` the supervisor Pods run as; a - /// pod-bound token for it accompanies the supervisor token. - pub service_account_name: String, + /// pod-bound token for it accompanies the supervisor token. Unset, the + /// gateway topology accepts the supervisor token alone and refuses a + /// pod-bound token it cannot verify. + #[serde(default)] + pub service_account_name: Option, /// Refuse a supervisor token without the pod-bound token. A present /// token is verified either way. #[serde(default)] @@ -261,7 +264,11 @@ impl SharedSupervisorConfig { if !is_dns_subdomain(&self.token_secret_name) { return Err("shared_supervisor token_secret_name must be a DNS subdomain name".into()); } - if !is_dns_subdomain(&self.service_account_name) { + if self + .service_account_name + .as_deref() + .is_some_and(|name| !is_dns_subdomain(name)) + { return Err( "shared_supervisor service_account_name must be a DNS subdomain name".into(), ); @@ -727,6 +734,14 @@ impl KubernetesComputeConfig { format!("supervisor_topology={topology_name} requires shared_supervisor") })?; shared.validate()?; + if shared.service_account_name.is_none() { + if topology == SupervisorTopology::Node { + return Err("supervisor_topology=node requires shared_supervisor.service_account_name; the pod-bound token for it proves each supervisor's node".into()); + } + if shared.require_identity_token { + return Err("shared_supervisor.require_identity_token requires shared_supervisor.service_account_name".into()); + } + } if self.sandbox_runtime.app_listener.common.enabled && self.sandbox_runtime.app_listener.common.port == shared.runtime_port { @@ -1338,7 +1353,7 @@ mod tests { service_namespace: "openshell".to_string(), runtime_port: 8443, token_secret_name: "openshell-supervisor-token".to_string(), - service_account_name: "openshell-supervisor".to_string(), + service_account_name: Some("openshell-supervisor".to_string()), require_identity_token: false, }; let gateway = |shared: Option| KubernetesComputeConfig { @@ -1372,7 +1387,7 @@ mod tests { ..shared() }, SharedSupervisorConfig { - service_account_name: "Not_A_Name".to_string(), + service_account_name: Some("Not_A_Name".to_string()), ..shared() }, ] { @@ -1400,6 +1415,48 @@ mod tests { assert!(workspace.validate_supervisor_topology().is_err()); } + #[test] + fn shared_supervisor_account_is_required_only_to_verify_pod_identity() { + let legacy: KubernetesComputeConfig = toml::from_str( + r#" + supervisor_topology = "gateway" + + [shared_supervisor] + service_name = "openshell-supervisor" + service_namespace = "openshell" + runtime_port = 5500 + token_secret_name = "openshell-supervisor-token" + "#, + ) + .expect("a shared_supervisor table without the account parses"); + let shared = legacy.shared_supervisor.clone().unwrap(); + assert_eq!(shared.service_account_name, None); + assert!(legacy.validate_supervisor_topology().is_ok()); + + let node = KubernetesComputeConfig { + supervisor_topology: Some(SupervisorTopology::Node), + ..legacy.clone() + }; + assert!( + node.validate_supervisor_topology() + .unwrap_err() + .contains("service_account_name") + ); + let enforced = KubernetesComputeConfig { + shared_supervisor: Some(SharedSupervisorConfig { + require_identity_token: true, + ..shared + }), + ..legacy + }; + assert!( + enforced + .validate_supervisor_topology() + .unwrap_err() + .contains("service_account_name") + ); + } + #[test] fn image_pull_policy_accepts_config_and_kubernetes_spellings() { for (value, expected) in [ diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 3f23ccb653..6e9471a759 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -1389,14 +1389,20 @@ impl KubernetesComputeDriver { .map(|(config, supervision)| SharedSupervisor::new(config, supervision)); if let Some(shared) = &shared_supervisor { let node_topology = config.supervisor_topology == Some(SupervisorTopology::Node); - shared - .supervision() - .controller() - .require_host_identity(HostAccount { - namespace: shared.config().service_namespace.clone(), - service_account: shared.config().service_account_name.clone(), - identity_required: shared.config().require_identity_token || node_topology, - }); + if let Some(service_account) = shared.config().service_account_name.clone() { + shared + .supervision() + .controller() + .require_host_identity(HostAccount { + namespace: shared.config().service_namespace.clone(), + service_account, + identity_required: shared.config().require_identity_token || node_topology, + }); + } else { + warn!( + "shared_supervisor.service_account_name is unset; the gateway accepts supervisor tokens without verifying the supervisor Pod" + ); + } if node_topology { shared.supervision().controller().bind_members_to_nodes(); } @@ -10483,7 +10489,7 @@ mod tests { service_namespace: "openshell".to_string(), runtime_port: 5500, token_secret_name: "openshell-supervisor-token".to_string(), - service_account_name: "openshell-supervisor".to_string(), + service_account_name: Some("openshell-supervisor".to_string()), require_identity_token: true, }, SharedSupervision::new(), diff --git a/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs b/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs index 87829c18b2..eec77c0c4e 100644 --- a/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs +++ b/crates/openshell-driver-kubernetes/src/warm_pool/tests.rs @@ -779,7 +779,7 @@ fn fixture(state: Arc>) -> KubernetesComputeDriver { service_namespace: "openshell".into(), runtime_port: 5500, token_secret_name: "token".into(), - service_account_name: "supervisor".into(), + service_account_name: Some("supervisor".into()), require_identity_token: false, }; let config = KubernetesComputeConfig { diff --git a/crates/openshell-server/src/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index f480f8fb1d..64734ae732 100644 --- a/crates/openshell-server/src/auth/peer.rs +++ b/crates/openshell-server/src/auth/peer.rs @@ -310,14 +310,6 @@ pub struct CachingGatewayPeerResolver { entries: Mutex>, } -impl std::fmt::Debug for CachingGatewayPeerResolver { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("CachingGatewayPeerResolver") - .field("ttl", &self.ttl) - .finish_non_exhaustive() - } -} - impl CachingGatewayPeerResolver { pub fn new(inner: Arc, ttl: Duration) -> Self { Self { diff --git a/crates/openshell-server/src/auth/supervisor_token.rs b/crates/openshell-server/src/auth/supervisor_token.rs index 77e6cc89f1..f324df9d8f 100644 --- a/crates/openshell-server/src/auth/supervisor_token.rs +++ b/crates/openshell-server/src/auth/supervisor_token.rs @@ -39,6 +39,8 @@ pub struct SupervisorTokenAuthenticator { } impl SupervisorTokenAuthenticator { + /// Accept supervisor tokens alone, with no node, and refuse an identity + /// token, which nothing can verify. pub fn new(authority: Arc) -> Self { Self { authority, @@ -49,8 +51,7 @@ impl SupervisorTokenAuthenticator { /// Accept supervisor tokens only when the identity token in /// [`HOST_IDENTITY_TOKEN_HEADER`] resolves through `resolver`, or, unless - /// `required`, is absent. Without a resolver, every supervisor token is - /// refused. + /// `required`, is absent. #[must_use] pub fn with_identity_resolver( mut self, @@ -77,17 +78,20 @@ impl SupervisorTokenAuthenticator { tonic::Status::unauthenticated(message), ) }; - let Some(resolver) = &self.supervisor_identity else { - return Err(refuse( - AuthFailureReason::InvalidCredential, - "this gateway accepts no supervisor", - )); - }; - let Some(token) = headers + let token = headers .get(HOST_IDENTITY_TOKEN_HEADER) .and_then(|value| value.to_str().ok()) - .filter(|value| !value.is_empty()) - else { + .filter(|value| !value.is_empty()); + let Some(resolver) = &self.supervisor_identity else { + if token.is_some() { + return Err(refuse( + AuthFailureReason::InvalidCredential, + "this gateway has no supervisor ServiceAccount to verify the identity token", + )); + } + return Ok(None); + }; + let Some(token) = token else { if self.identity_required { return Err(refuse( AuthFailureReason::MissingCredential, @@ -178,11 +182,10 @@ mod tests { use std::time::Duration; use super::*; + use crate::auth::authenticator::{AuthFailureReason, AuthMechanism}; use crate::auth::peer::test_support::FakeGatewayPeerResolver; use openshell_bootstrap::jwt::generate_jwt_key; - const ATTACH: &str = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; - fn authority(gateway_id: &str) -> Arc { let material = generate_jwt_key().expect("jwt key"); Arc::new( @@ -206,6 +209,8 @@ mod tests { headers } + const ATTACH: &str = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; + fn with_identity(token: &str) -> http::HeaderMap { let mut headers = headers(token); headers.insert(HOST_IDENTITY_TOKEN_HEADER, "pod-token".parse().unwrap()); @@ -222,21 +227,17 @@ mod tests { )))) } - fn accepting(gateway: Arc) -> SupervisorTokenAuthenticator { - SupervisorTokenAuthenticator::new(gateway) - .with_identity_resolver(resolving(Some("node-a")), true) - } - #[tokio::test] async fn supervisor_tokens_authenticate_only_as_the_supervisor() { + let attach = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; let gateway = authority("test-gateway"); let minted = gateway .mint_supervisor_token(Duration::from_mins(15)) .expect("mint"); - let authenticator = accepting(gateway.clone()); + let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()); let accepted = authenticator - .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .authenticate(&headers(minted.token.expose_secret()), attach) .await .expect("valid token"); match accepted { @@ -247,10 +248,16 @@ mod tests { ); assert_eq!(supervisor.identity.token_id, minted.token_id.to_string()); assert_eq!(supervisor.identity.expires_at, minted.expires_at); - assert_eq!(supervisor.identity.node.as_deref(), Some("node-a")); + assert_eq!(supervisor.identity.node, None); } other => panic!("unexpected outcome {other:?}"), } + // Without a resolver, nothing can verify an identity token. + let unverifiable = authenticator + .authenticate(&with_identity(minted.token.expose_secret()), attach) + .await + .expect_err("an identity token nothing can verify must be refused"); + assert_eq!(unverifiable.reason, AuthFailureReason::InvalidCredential); // Session tokens of the same authority, opaque bearers, and non-JWT // bearers fall through to the other authenticators. @@ -265,7 +272,7 @@ mod tests { ] { assert!(matches!( authenticator - .authenticate(&with_identity(bearer), ATTACH) + .authenticate(&headers(bearer), attach) .await .unwrap(), Authentication::NotApplicable @@ -285,23 +292,23 @@ mod tests { .mint_supervisor_token(Duration::from_mins(15)) .unwrap(); let rejection = authenticator - .authenticate(&with_identity(foreign.token.expose_secret()), ATTACH) + .authenticate(&headers(foreign.token.expose_secret()), attach) .await .expect_err("foreign key must be rejected"); assert_eq!(rejection.mechanism, AuthMechanism::SupervisorToken); assert_eq!(rejection.reason, AuthFailureReason::InvalidCredential); assert_eq!(rejection.status.code(), tonic::Code::Unauthenticated); let other_gateway = authority("other-gateway"); - let rejection = accepting(other_gateway.clone()) + let rejection = SupervisorTokenAuthenticator::new(other_gateway.clone()) .authenticate( - &with_identity( + &headers( other_gateway .mint_supervisor_token(Duration::from_mins(15)) .unwrap() .token .expose_secret(), ), - ATTACH, + attach, ) .await .expect("own token verifies"); @@ -318,13 +325,16 @@ mod tests { let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) .with_identity_resolver(resolver.clone(), true); - assert!(matches!( - authenticator - .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) - .await - .unwrap(), - Authentication::Accepted(_) - )); + match authenticator + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .await + .unwrap() + { + Authentication::Accepted(Principal::Supervisor(supervisor)) => { + assert_eq!(supervisor.identity.node.as_deref(), Some("node-a")); + } + other => panic!("unexpected outcome {other:?}"), + } assert_eq!(*resolver.seen_tokens.lock().unwrap(), ["pod-token"]); let missing = authenticator @@ -359,6 +369,12 @@ mod tests { .await .is_err() ); + let unscheduled = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolving(None), true) + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .await + .expect_err("an unscheduled pod proves no node"); + assert_eq!(unscheduled.mechanism, AuthMechanism::SupervisorToken); // A forged supervisor token never reaches the resolver. let forged = authority("test-gateway") @@ -397,7 +413,8 @@ mod tests { HOST_IDENTITY_TOKEN_HEADER, identity_token(exp).parse().unwrap(), ); - let authenticator = accepting(gateway.clone()); + let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolving(Some("node-a")), true); async move { match authenticator.authenticate(&headers, ATTACH).await.unwrap() { Authentication::Accepted(Principal::Supervisor(supervisor)) => { @@ -411,34 +428,4 @@ mod tests { assert_eq!(expires_at(earlier).await, earlier); assert_eq!(expires_at(minted.expires_at + 300).await, minted.expires_at); } - - #[tokio::test] - async fn supervisor_tokens_are_refused_without_a_valid_pod_identity() { - let gateway = authority("test-gateway"); - let minted = gateway - .mint_supervisor_token(Duration::from_mins(15)) - .unwrap(); - let headers = with_identity(minted.token.expose_secret()); - - let unconfigured = SupervisorTokenAuthenticator::new(gateway.clone()) - .authenticate(&headers, ATTACH) - .await - .expect_err("a gateway without a supervisor account accepts no supervisor"); - assert_eq!(unconfigured.reason, AuthFailureReason::InvalidCredential); - - let unknown = SupervisorTokenAuthenticator::new(gateway.clone()) - .with_identity_resolver(Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), true) - .authenticate(&headers, ATTACH) - .await - .expect_err("an identity token for another account must be refused"); - assert_eq!(unknown.reason, AuthFailureReason::InvalidCredential); - assert_eq!(unknown.status.code(), tonic::Code::Unauthenticated); - - let unscheduled = SupervisorTokenAuthenticator::new(gateway) - .with_identity_resolver(resolving(None), true) - .authenticate(&headers, ATTACH) - .await - .expect_err("an unscheduled pod proves no node"); - assert_eq!(unscheduled.mechanism, AuthMechanism::SupervisorToken); - } } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 6d4cd6a84c..7a1d8ef332 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -430,12 +430,9 @@ pub struct ServerState { /// Optional K8s `ServiceAccount` authenticator for gateway peer RPCs. pub peer_authenticator: Option>, - /// Resolves shared supervisors' identity tokens. Without it every + /// Authenticates the shared supervisor's tokens. Without it every /// supervisor token is refused. - pub supervisor_identity_resolver: Option>, - - /// Refuse supervisor tokens that arrive without an identity token. - pub supervisor_identity_required: bool, + pub supervisor_authenticator: Option>, /// Credentials that have recently logged on, so each records one /// authentication success rather than one per request. @@ -725,8 +722,7 @@ impl ServerState { compute_driver_authenticator: None, dedicated_warm_pool: None, peer_authenticator: None, - supervisor_identity_resolver: None, - supervisor_identity_required: false, + supervisor_authenticator: None, logons: auth::audit::Logons::default(), grpc_rate_limiter, provider_token_rate_limiter, @@ -1074,37 +1070,40 @@ pub(crate) async fn run_server( validate_peer_endpoint_scheme(&state.config, peer_endpoint)?; } controller.set_peer_endpoint(state.peer_endpoint.clone().unwrap_or_default()); - let account = controller.host_account().ok_or_else(|| { - Error::config( - "the compute driver registered no ServiceAccount for shared supervisors, whose \ - pod-bound tokens prove their identity", - ) - })?; - let client = kube::Client::try_default().await.map_err(|error| { - Error::config(format!( - "shared supervisors prove their Pod with Kubernetes TokenReview, but the \ - in-cluster client failed: {error}" - )) - })?; - let resolver = Arc::new(auth::peer::LiveGatewayPeerResolver::new( - client, - &account.namespace, - openshell_supervisor_control::SUPERVISOR_IDENTITY_TOKEN_AUDIENCE.to_string(), - account.service_account.clone(), - Vec::new(), - )); - state.supervisor_identity_resolver = - Some(Arc::new(auth::peer::CachingGatewayPeerResolver::new( + if let Some(account) = controller.host_account() { + let client = kube::Client::try_default().await.map_err(|error| { + Error::config(format!( + "shared supervisors prove their Pod with Kubernetes TokenReview, but the \ + in-cluster client failed: {error}" + )) + })?; + let resolver = Arc::new(auth::peer::LiveGatewayPeerResolver::new( + client, + &account.namespace, + openshell_supervisor_control::SUPERVISOR_IDENTITY_TOKEN_AUDIENCE.to_string(), + account.service_account.clone(), + Vec::new(), + )); + let resolver = Arc::new(auth::peer::CachingGatewayPeerResolver::new( resolver, auth::peer::peer_token_cache_ttl_from_env(), - ))); - state.supervisor_identity_required = account.identity_required; - info!( - namespace = %account.namespace, - service_account = %account.service_account, - required = account.identity_required, - "supervisor identity verification enabled" - ); + )); + state.supervisor_authenticator = Some(Arc::new( + auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()) + .with_identity_resolver(resolver, account.identity_required), + )); + info!( + namespace = %account.namespace, + service_account = %account.service_account, + required = account.identity_required, + "supervisor identity verification enabled" + ); + } else if controller.members_bound_to_nodes() { + return Err(Error::config( + "the node supervisor topology proves each supervisor's node with its pod-bound \ + token, but the compute driver registered no ServiceAccount for shared supervisors", + )); + } supervisor_pool::SupervisorPool::new( state.store.clone(), controller.clone(), diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index d3389dd574..40db89b4b6 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1157,13 +1157,11 @@ fn build_authenticator_chain(state: &ServerState) -> Option authenticators.push(driver); } if let Some(authority) = state.sandbox_session_jwt_authority.clone() { - let mut supervisor = - crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()); - if let Some(resolver) = state.supervisor_identity_resolver.clone() { - supervisor = - supervisor.with_identity_resolver(resolver, state.supervisor_identity_required); - } - authenticators.push(Arc::new(supervisor)); + authenticators.push(state.supervisor_authenticator.clone().unwrap_or_else(|| { + Arc::new( + crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()), + ) + })); authenticators.push(Arc::new( crate::auth::sandbox_jwt::SandboxSessionJwtAuthenticator::new( authority, diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index 5898ec94b0..c74bf773e3 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -18,18 +18,13 @@ re-implementing the control contracts. process, and an ownership term. Every member names itself in its hello; a hello without a member, or with an invalid one, is refused with the `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. `require_host_identity` names - the `HostAccount` whose pod-bound tokens, sent in - `HOST_IDENTITY_TOKEN_HEADER` with `SUPERVISOR_IDENTITY_TOKEN_AUDIENCE`, - prove that a supervisor token's holder is a supervisor Pod; - `HostAccount.identity_required` refuses a supervisor token without one. - After `bind_members_to_nodes`, a supervisor's member ID must also be the - node its identity token proves (`HostIdentity.node`). One session per - member: a newer connection epoch of the same member process or a new - process of the member supersedes its stream, a delayed older hello is refused, and reports + the `HostAccount` whose pod-bound tokens prove a supervisor Pod; after + `bind_members_to_nodes`, a member ID must be the node its token proves. + One session per member: a newer connection epoch of the same member process or a new process of the + member supersedes its stream, a delayed older hello is refused, and reports from superseded streams, acks of revisions never sent, regressing acks, - and oversized reports are dropped. A stream ends when the supervisor token - or the Pod identity token that opened it expires; hosted instances keep - running. The pool's recovery deadline + and oversized reports are dropped. A stream ends when the token that opened + it expires; hosted instances keep running. The pool's recovery deadline defaults to `POOL_RECOVERY_TIMEOUT_SECS` (`set_recovery_timeout_secs` overrides it). The gateway's pool reconciler replaces the `PoolView` as a whole (`update_pool`): the desired set from the gateway's durable records, the diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index c07fef17d7..19086f0d99 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -192,20 +192,15 @@ control listener: it dials the gateway and receives its assignments from it. user, operator, and peer credentials are refused on it. The host re-reads the file on every connection attempt and treats a missing, malformed, or expired token as a reason to retry later, and the gateway ends a stream - when the token or the Pod identity token that opened it expires, so the - host reconnects with the renewed ones. The host never acts with any other identity and has no - Kubernetes API access. Beside the token, the host sends its Pod's projected - `ServiceAccount` token (audience `openshell-supervisor`) from - `--identity-token-file` (`OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE`) in the - `x-openshell-host-identity-token` header, re-read on every connection - attempt. The gateway verifies it, and refuses the supervisor token without - it under `require_identity_token` or the node topology. With - `--node-supervisor` (`OPENSHELL_SUPERVISOR_NODE`), the host serves only its - node's sandboxes, and the gateway requires its member ID to be the node its - identity token proves. The stream starts - with a hello carrying a per-process instance id and a connection epoch; the - gateway supersedes an older stream of the same process and refuses a delayed - older connection. + when the token that opened it expires, so the host reconnects with the + renewed one. The host never acts with any other identity and has no + Kubernetes API access. With `--identity-token-file`, the host also sends + its Pod's projected `ServiceAccount` token, which the gateway verifies and + which ends the stream when it expires. `--node-supervisor` requires it: the + host serves only its node's sandboxes, as the member named after the node. + The stream starts with a hello carrying a per-process + instance id and a connection epoch; the gateway supersedes an older stream + of the same process and refuses a delayed older connection. - **Assignments.** The gateway owns the desired set and sends it as complete `AssignmentSnapshot`s with session-scoped revisions. `shared_host::SharedHost::reconcile` validates the snapshot as a whole (at most 256 instances, no route twice), diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index c4fad93561..6f49853b9b 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -120,17 +120,17 @@ struct Args { /// File holding this Pod's projected `ServiceAccount` token, audience /// `openshell-supervisor`, sent beside the supervisor token. Re-read on /// every connection attempt. - #[arg( - long, - env = "OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE", - required_if_eq("mode", "shared") - )] + #[arg(long, env = "OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE")] identity_token_file: Option, /// Serve only this node's sandboxes, as one supervisor per node: the /// pool member ID must be the node name, and the supervisor doesn't leave /// the pool on shutdown, since no other member may take its instances. - #[arg(long, env = "OPENSHELL_SUPERVISOR_NODE")] + #[arg( + long, + env = "OPENSHELL_SUPERVISOR_NODE", + requires = "identity_token_file" + )] node_supervisor: bool, /// Listener for routed runtime-initiated Sandbox Protocol connections. @@ -1205,6 +1205,20 @@ mod tests { assert_eq!(supervisor_exit(Ok(143)).unwrap(), 143); } + #[test] + fn node_supervisors_require_an_identity_token_file() { + assert!(Args::try_parse_from(["openshell-supervisor", "--node-supervisor"]).is_err()); + assert!( + Args::try_parse_from([ + "openshell-supervisor", + "--node-supervisor", + "--identity-token-file", + "/var/run/identity/token", + ]) + .is_ok() + ); + } + #[test] fn telemetry_names_the_sandbox_and_its_gateway() { let args = Args::try_parse_from([ diff --git a/crates/openshell-supervisor/src/shared.rs b/crates/openshell-supervisor/src/shared.rs index 5b03ac91a9..9e860fe7cc 100644 --- a/crates/openshell-supervisor/src/shared.rs +++ b/crates/openshell-supervisor/src/shared.rs @@ -33,9 +33,7 @@ fn run_platform(args: crate::Args) -> Result<()> { let token_file = args .token_file .ok_or_else(|| miette::miette!("--token-file is required for --mode=shared"))?; - let identity_token_file = args - .identity_token_file - .ok_or_else(|| miette::miette!("--identity-token-file is required for --mode=shared"))?; + let identity_token_file = args.identity_token_file; let node_supervisor = args.node_supervisor; let runtime_listen = args .runtime_listen diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index ee6ec3647e..757a14bf14 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -1180,14 +1180,16 @@ pub struct GatewayLink { /// File holding this Pod's projected `ServiceAccount` token, which proves /// to the gateway that the supervisor token's holder is a supervisor Pod. /// Re-read on every connection attempt, as the kubelet rotates it. - pub identity_token_file: PathBuf, + pub identity_token_file: Option, } impl GatewayLink { - fn read_identity_token(&self) -> Result { + fn read_identity_token(&self) -> Result> { use miette::{IntoDiagnostic as _, WrapErr as _}; - let path = &self.identity_token_file; + let Some(path) = &self.identity_token_file else { + return Ok(None); + }; let contents = std::fs::read_to_string(path) .into_diagnostic() .wrap_err_with(|| format!("read identity token {}", path.display()))?; @@ -1197,6 +1199,7 @@ impl GatewayLink { } token .parse() + .map(Some) .map_err(|_| miette::miette!("the identity token is not a valid header value")) } @@ -1312,10 +1315,12 @@ impl GatewayConnector for GatewayLink { .max_encoding_message_size(self.limits.max_host_message_bytes()); let mut request = tonic::Request::new(tokio_stream::wrappers::ReceiverStream::new(outbound)); - request.metadata_mut().insert( - openshell_supervisor_control::HOST_IDENTITY_TOKEN_HEADER, - identity_token, - ); + if let Some(identity_token) = identity_token { + request.metadata_mut().insert( + openshell_supervisor_control::HOST_IDENTITY_TOKEN_HEADER, + identity_token, + ); + } let attach = client.attach(request); let response = tokio::time::timeout_at(deadline, attach) .await diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 88cf6ab386..bdde817c62 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -924,7 +924,7 @@ max_members_per_gateway = 32 | `max_instances_per_member` | `128` | `1` to `1024` | `supervisor.pool.maxInstancesPerMember` | | `max_members_per_gateway` | `32` | `1` or more | `supervisor.pool.maxMembersPerGateway` | -The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. With `supervisor_topology = "node"`, the chart defaults to `300`; see [Run one supervisor per node](/kubernetes/high-availability#run-one-supervisor-per-node). Values outside the ranges fail at startup. +The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. Values outside the ranges fail at startup. ## OCSF JSONL Output @@ -1762,9 +1762,8 @@ provider_spiffe_workload_api_socket_path = "/spiffe-workload-api/spire-agent.soc # operator_namespace_file = "/etc/openshell/workspace-namespaces.json" # Shared supervisor topology for new sandbox generations: "gateway" runs a -# replicated pool, and "node" runs one supervisor per node that hosts the -# sandboxes scheduled to its node. Omit it for a supervisor Pod per sandbox. -# Only the in-process Kubernetes driver supports it. Helm renders the +# replicated pool, and "node" runs one supervisor per node for the sandboxes +# scheduled there. Omit it for a supervisor Pod per sandbox. Helm renders the # shared_supervisor table and refuses a hand-written one. # supervisor_topology = "node" # [openshell.drivers.kubernetes.shared_supervisor] @@ -1772,12 +1771,11 @@ provider_spiffe_workload_api_socket_path = "/spiffe-workload-api/spire-agent.soc # service_namespace = "openshell" # runtime_port = 5500 # token_secret_name = "openshell-supervisor-token" -# The ServiceAccount the supervisors run as in service_namespace. The gateway -# verifies the pod-bound token for it that accompanies the supervisor token, -# and in the "node" topology that token proves each supervisor's node. +# The ServiceAccount the supervisors run as. The gateway verifies its +# pod-bound token, which in the "node" topology proves each supervisor's node. +# Without it, the "gateway" topology accepts the supervisor token alone. # service_account_name = "openshell-supervisor" -# Refuse supervisors that attach without the pod-bound token. Helm renders -# supervisor.requireIdentityToken here; the "node" topology always requires it. +# Refuse supervisors without the pod-bound token (supervisor.requireIdentityToken). # require_identity_token = false [openshell.drivers.kubernetes.managed_ssh_ingress] diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 842d31780d..20e53ab7d7 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -1557,13 +1557,6 @@ With `supervisor_topology = "node"`, `-supervisor` is a DaemonSet and each Pod's member ID is its node name; see the [per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. -Each node supervisor accepts `supervisor.pool.maxInstancesPerMember` -sandboxes, 300 unless set; a release switched to this topology with -`--reuse-values` keeps the earlier chart's 128 (`max_instances_per_member` in -`gateway.toml` shows it). `supervisor.updateStrategy.maxUnavailable` sets how -many supervisors a rollout replaces at once, and -`supervisor.priorityClassName: system-node-critical` has other Pods preempted -or evicted before the supervisor. The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation records its node. Until the workload Pod is scheduled, the runtime logs `Runtime-initiated control cannot reach the supervisor; retrying`. Shared @@ -1853,11 +1846,11 @@ credential failures. | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | | A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | -| Create fails with `SandboxRuntimeLaunchFailed: ` and the sandbox is deleted within 30 seconds, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full, or its membership record has no proven node because it attached through a replica that resolved no identity token), or, once `runtime_bootstrap_grace_seconds` passes, `no supervisor attached on the node within the bootstrap grace` and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| Create fails with `SandboxRuntimeLaunchFailed: ` and the sandbox is deleted within 30 seconds, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room` when the node's supervisor is full), or, once `runtime_bootstrap_grace_seconds` passes, `the stale bootstrap will be rolled back` with `the workload Pod was not scheduled within s` or `no supervisor attached on node within s`, and then `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart); until then the sandbox stays provisioning | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, never attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | -| A shared supervisor logs `could not open the supervisor host stream` with `supervisor identity token is required`, `supervisor identity token is invalid`, or a `supervisor identity:` credential refusal, or logs `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, or it runs as a ServiceAccount other than `shared_supervisor.service_account_name` | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | +| A shared supervisor logs `could not open the supervisor host stream` with `supervisor identity token is required`, `supervisor identity token is invalid`, `has no supervisor ServiceAccount`, or a `supervisor identity:` credential refusal, or logs `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, it runs as a ServiceAccount other than `shared_supervisor.service_account_name`, or the gateway config omits that account | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | | OpenShift sandbox pod fails to start (`unable to validate against any security context constraint`) | An explicit sandbox UID/GID override or custom security context conflicts with the namespace's SCC range | Inspect pod events and the namespace's `openshift.io/sa.scc.uid-range` and `openshift.io/sa.scc.supplemental-groups` annotations; remove incompatible `sandbox_uid` / `sandbox_gid` overrides so the driver uses the namespace-assigned identity. Current sandbox pods use `restricted-v2` without a privileged SCC grant; see the [OpenShift guide](https://docs.nvidia.com/openshell/latest/kubernetes/openshift) and [RFC 0012](https://github.com/ai-openshell/openshell/blob/main/rfc/0012-isolation-backend/README.md#motivation). | | OpenShift self-hosted Vault/OpenBao credential store pod never schedules (waits time out with `no matching resources found`) | The store's Helm chart pins `runAsUser`/`fsGroup`/seccomp, which restricted-v2 rejects, so the StatefulSet controller never creates the pod | Deploy the store's chart in its OpenShift mode (`--set global.openshift=true` for the OpenBao/Vault chart) so the namespace SCC assigns a compliant security context — no manual SCC grant needed | | Vault credential driver returns HTTP 403 / `Vault Kubernetes auth denied the configured role` on provider create | Vault's `auth/kubernetes` method or the gateway login role is not provisioned, or the role is not bound to the gateway service account and namespace | In Vault: `bao auth enable kubernetes` and `bao write auth/kubernetes/config kubernetes_host=... kubernetes_ca_cert=@...`; ensure the login role's `bound_service_account_names`/`bound_service_account_namespaces` match the gateway SA and namespace and its policy grants the credential paths | From 788712fd0f5aed453ef94081e874f130eab368e3 Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Fri, 4 Dec 2026 22:19:27 +0200 Subject: [PATCH 18/18] feat(kubernetes): schedule node-topology sandboxes only on nodes running a supervisor In the node supervisor topology, each generation's workload Pod now requires Pod affinity, on kubernetes.io/hostname, to a Pod the supervisor Service selects. The scheduler no longer places a sandbox on a node without a supervisor, where it would wait out the bootstrap grace and fail. A restart outside the node topology clears the rule. The gateway topology and dedicated supervisors are unchanged. Signed-off-by: Gal Zaidman --- crates/openshell-driver-kubernetes/README.md | 13 ++-- .../openshell-driver-kubernetes/src/driver.rs | 68 ++++++++++++++++- docs/kubernetes/high-availability.mdx | 73 +++++++++---------- 3 files changed, 108 insertions(+), 46 deletions(-) diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 09b5896bed..c1cc3090a5 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -457,9 +457,8 @@ fails closed. every instance's credentials; the gateway refuses it on every other RPC and refuses every other identity on the assignment stream, and ends a stream when the token or the Pod identity token that opened it expires. Sandboxes - cannot reach the stream, - and the routing preface only selects which generation-pinned TLS identity - the supervisor demands. + cannot reach the stream, and the routing preface only selects which + generation-pinned TLS identity the supervisor demands. - **Workload identity.** The gateway owns SPIFFE Broker API identity acquisition and provider-token exchange when `openshell.gateway.spiffe_broker` is configured. Shared supervisors receive final access tokens through their authenticated @@ -487,8 +486,12 @@ The driver binds pool members to nodes (`bind_members_to_nodes`): the gateway accepts a supervisor only when the Pod its identity token resolves to is scheduled on the node it claims as its pool member ID. -- **Placement.** The driver removes the scheduling gate and returns from - create or restart before it assigns the instance. The bootstrap task watches +- **Placement.** Each generation's workload Pod requires Pod affinity, on + `kubernetes.io/hostname`, to a Pod the supervisor Service selects in + `service_namespace`, so the scheduler only picks nodes running a supervisor; + a restart outside this topology clears it. The driver removes the + scheduling gate and returns from create or restart before it assigns the + instance. The bootstrap task watches the workload Pod, waits for the supervisor of the node in its `spec.nodeName` to join the pool, and launches there. A Pod that is deleted or replaced, or a node supervisor that refuses the instance, rolls the bootstrap back. So does diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 6e9471a759..9858becfba 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -2838,6 +2838,9 @@ impl KubernetesComputeDriver { let kube_name = self.config.kube_resource_name(workspace, name); let mut data = sandbox_to_k8s_spec(sandbox.spec.as_ref(), ¶ms) .map_err(KubernetesDriverError::InvalidArgument)?; + if let Some(affinity) = self.node_supervisor_affinity().await? { + data["spec"]["podTemplate"]["spec"]["affinity"] = affinity; + } self.create_sandbox_runtime_fence(&target_namespace, &proxy_names) .await?; // A missing bootstrap Secret keeps both pods inert as defense in @@ -3864,6 +3867,18 @@ impl KubernetesComputeDriver { )) } + /// The workload Pod affinity of a new generation: in the node topology, + /// only nodes already running a supervisor Pod; `None` otherwise. + async fn node_supervisor_affinity( + &self, + ) -> Result, KubernetesDriverError> { + if self.config.supervisor_topology != Some(SupervisorTopology::Node) { + return Ok(None); + } + let (_, target) = self.shared_supervisor_target().await?; + Ok(Some(node_supervisor_pod_affinity(&target))) + } + /// Create or validate this sandbox's egress allowance to the shared /// supervisor and return the stored coordinates bound into its evidence. async fn ensure_sandbox_runtime_shared_control_policy( @@ -4820,6 +4835,7 @@ impl KubernetesComputeDriver { let control_connection = KubernetesControlConnection::RuntimeInitiated; let placement = self.new_generation_placement(); + let affinity = self.node_supervisor_affinity().await?; let names = SandboxRuntimeNames::for_generation(sandbox_id, generation.as_str()); self.create_sandbox_runtime_fence(&namespace, &names) .await?; @@ -5003,6 +5019,7 @@ impl KubernetesComputeDriver { &volumes, &init_containers, &image_pull_secrets, + affinity.clone(), ); // A claimed warm Pod used a physical pair ID. A subsequent // cold generation uses the logical Sandbox's new fences. @@ -7112,16 +7129,32 @@ fn runtime_pod_owner(name: &str, uid: &str) -> OwnerReference { } /// Pod template fields replaced when a stopped sandbox starts a new runtime -/// generation. +/// generation. A null `affinity` clears the node topology's rule. fn restart_pod_template_spec( volumes: &[serde_json::Value], init_containers: &[serde_json::Value], image_pull_secrets: &[String], + affinity: Option, ) -> serde_json::Value { serde_json::json!({ "volumes": volumes, "initContainers": init_containers, "imagePullSecrets": image_pull_secret_refs(image_pull_secrets), + "affinity": affinity, + }) +} + +/// Required affinity to the supervisor Pods `target`'s Service selects on the +/// same node. The driver sets no other workload Pod affinity. +fn node_supervisor_pod_affinity(target: &SharedSupervisorTarget) -> serde_json::Value { + serde_json::json!({ + "podAffinity": { + "requiredDuringSchedulingIgnoredDuringExecution": [{ + "labelSelector": {"matchLabels": target.selector}, + "namespaces": [target.namespace], + "topologyKey": "kubernetes.io/hostname", + }], + }, }) } @@ -15556,6 +15589,7 @@ mod tests { &volumes, &init_containers, &["os-pull-sandbox-1-gen7-0".to_string()], + None, ); assert_eq!(spec["volumes"], serde_json::json!(volumes)); assert_eq!(spec["initContainers"], serde_json::json!(init_containers)); @@ -15563,6 +15597,38 @@ mod tests { spec["imagePullSecrets"], serde_json::json!([{"name": "os-pull-sandbox-1-gen7-0"}]) ); + // The merge patch clears a node topology rule from an earlier generation. + assert_eq!(spec.get("affinity"), Some(&serde_json::Value::Null)); + } + + #[test] + fn node_topology_workloads_require_a_supervisor_pod_on_their_node() { + let target = SharedSupervisorTarget { + namespace: "openshell".to_string(), + authority: "openshell-supervisor.openshell.svc:5500".to_string(), + address: "10.0.0.1:5500".parse().unwrap(), + selector: BTreeMap::from([( + "app.kubernetes.io/component".to_string(), + "supervisor".to_string(), + )]), + }; + let affinity = node_supervisor_pod_affinity(&target); + assert_eq!( + affinity, + serde_json::json!({ + "podAffinity": { + "requiredDuringSchedulingIgnoredDuringExecution": [{ + "labelSelector": { + "matchLabels": {"app.kubernetes.io/component": "supervisor"} + }, + "namespaces": ["openshell"], + "topologyKey": "kubernetes.io/hostname", + }], + }, + }) + ); + let spec = restart_pod_template_spec(&[], &[], &[], Some(affinity.clone())); + assert_eq!(spec["affinity"], affinity); } #[test] diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index b0e481e6ea..1c92c334b1 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -743,8 +743,7 @@ helm install openshell ./openshell -n openshell \ With `supervisor_topology: node`, the chart runs the shared supervisor as a DaemonSet, and each sandbox is served by the supervisor on its workload's node. -The scheduler picks the node. A sandbox never moves to another node's -supervisor. +A sandbox never moves to another node's supervisor. ```yaml gatewayConfig: @@ -752,23 +751,16 @@ gatewayConfig: supervisor_topology: node ``` -Each supervisor's Pod-bound token also proves its node: the gateway accepts a -supervisor only for the node that the token's Pod runs on. The ServiceAccount -restriction above still applies: anyone who can create its Pods or tokens can -claim any node. We recommend running the API server with the `Node` authorizer -and the `NodeRestriction` admission plugin, so a compromised node's kubelet -cannot obtain tokens for another node's supervisor. - -If no node accepts the workload, or its node's supervisor does not attach, -within `runtime_bootstrap_grace_seconds`, the gateway stops the restarted -sandbox. A new sandbox, or one its node's supervisor refuses, enters `Error` -with the cause, which `openshell sandbox create` reports, and is deleted -within 30 seconds. The window, 300 seconds by default, includes adding a node -and starting its supervisor, so raise it if a cluster autoscaler adds sandbox -nodes slower than that. A supervisor must run on every node that can host a -sandbox. If sandbox templates tolerate node taints, -set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with -`supervisor.nodeSelector`. GPU nodes usually need: +Each supervisor's Pod-bound token also proves its node, so the gateway accepts +a supervisor only for its own node. Anyone who can create Pods or tokens for +the supervisor ServiceAccount can still claim any node. We recommend the +`Node` authorizer and the `NodeRestriction` admission plugin, so a compromised +node's kubelet can't obtain tokens for another node's supervisor. + +Sandbox Pods require a supervisor Pod on their node, so run a supervisor on +every node that can host a sandbox. If sandbox templates tolerate node taints, +set the same tolerations in `supervisor.tolerations`; if they select a node +pool, cover it with `supervisor.nodeSelector`. GPU nodes usually need: ```yaml supervisor: @@ -778,28 +770,29 @@ supervisor: effect: NoSchedule ``` +If a sandbox's workload isn't scheduled, or its node's supervisor doesn't +attach, within `runtime_bootstrap_grace_seconds` (300 seconds by default), a +new sandbox enters `Error` with the cause and is deleted, and a restarted one +stops. The window includes adding a node and starting its supervisor, so raise +it if a cluster autoscaler adds sandbox nodes more slowly. + +Each supervisor accepts `supervisor.pool.maxInstancesPerMember` sandboxes, 300 +by default in this topology; set it to at least the kubelet `maxPods` of your +sandbox nodes. Switching an existing release with `--reuse-values` keeps the +earlier default of 128; use `--reset-then-reuse-values`. Size +`supervisor.resources` for the sandboxes per node, and keep `replicaCount` × +`supervisor.pool.maxMembersPerGateway` at or above your sandbox node count. If +your CNI allocates from each node's Pod CIDR, a `/24` holds about 250 Pods. + The chart renders no PodDisruptionBudget or HPA for the DaemonSet and ignores -`supervisor.replicas`. Each supervisor accepts -`supervisor.pool.maxInstancesPerMember` sandboxes, 300 by default in this -topology; set it to at least the kubelet `maxPods` of your sandbox nodes -(default 110; managed services set their own limit). Switching an existing -release with `--reuse-values` keeps the earlier chart's 128; use -`--reset-then-reuse-values`. Size `supervisor.resources` for the sandboxes -per node. When a node's supervisor restarts, its sandboxes pause until the -replacement attaches within `supervisor.recoveryTimeoutSeconds`. A rollout -replaces `supervisor.updateStrategy.maxUnavailable` supervisors at once, -default 1. A lost node takes its sandboxes with it. Set -`supervisor.priorityClassName: system-node-critical` so other Pods are -preempted or evicted before the supervisor. Clusters that limit critical -priority classes to `kube-system` need a ResourceQuota that allows it in the -release namespace. - -To run many sandboxes per node, also check these limits: - -- If your CNI allocates from each node's Pod CIDR, a `/24` holds about 250 - Pods. -- Each node runs one pool member, so keep `replicaCount` × - `supervisor.pool.maxMembersPerGateway` at or above your sandbox node count. +`supervisor.replicas`. A rollout replaces +`supervisor.updateStrategy.maxUnavailable` supervisors at once, default 1. When +a node's supervisor restarts, its sandboxes pause until the replacement +attaches within `supervisor.recoveryTimeoutSeconds`. A lost node takes its +sandboxes with it. Set `supervisor.priorityClassName: system-node-critical` so +other Pods are preempted or evicted before the supervisor. Clusters that limit +critical priority classes to `kube-system` need a ResourceQuota that allows it +in the release namespace. Switching `supervisor_topology` between `gateway` and `node` terminates running shared sandboxes at the recovery timeout. Restart them to run under