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/.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: diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 18587b10bf..c1cc3090a5 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -410,6 +410,15 @@ 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. 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 @@ -447,9 +456,9 @@ 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, - and the routing preface only selects which generation-pinned TLS identity - the supervisor demands. + 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 exchange when `openshell.gateway.spiffe_broker` is configured. Shared supervisors receive final access tokens through their authenticated @@ -469,6 +478,40 @@ 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.** 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 + a Pod that isn't scheduled, or a node supervisor that doesn't join, within + `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 + 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 + 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/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index ffae5119d2..2be87c5a53 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 { @@ -236,6 +239,16 @@ 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. 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)] + pub require_identity_token: bool, } impl SharedSupervisorConfig { @@ -251,6 +264,15 @@ 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 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(), + ); + } Ok(()) } @@ -693,18 +715,33 @@ 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 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 { @@ -714,10 +751,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(()) } @@ -1317,6 +1353,8 @@ mod tests { service_namespace: "openshell".to_string(), runtime_port: 8443, token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: Some("openshell-supervisor".to_string()), + require_identity_token: false, }; let gateway = |shared: Option| KubernetesComputeConfig { supervisor_topology: Some(SupervisorTopology::Gateway), @@ -1348,6 +1386,10 @@ mod tests { token_secret_name: "Not_A_Secret_Name".to_string(), ..shared() }, + SharedSupervisorConfig { + service_account_name: Some("Not_A_Name".to_string()), + ..shared() + }, ] { assert!( gateway(Some(invalid)) @@ -1373,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 d3e2c4720f..9858becfba 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, @@ -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::{ @@ -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; @@ -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"; @@ -440,6 +444,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, @@ -552,20 +575,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; } @@ -735,6 +778,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, @@ -1344,6 +1388,24 @@ 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); + 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(); + } shared.spawn_token_secret_writer(client.clone(), shutdown_rx.clone()); } if shared_supervisor.is_some() && !config.supervisor_otlp.is_empty() { @@ -2776,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 @@ -3802,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( @@ -4085,8 +4162,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), @@ -4103,7 +4180,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, @@ -4116,15 +4192,252 @@ impl KubernetesComputeDriver { tls.private_key_pem.into_bytes(), workload_owner.clone(), ); - let secrets = Api::::namespaced(self.client.clone(), namespace); - secrets + 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 matches!(generation.target, GenerationLaunchTarget::Shared { .. }) + && self.config.supervisor_topology == Some(SupervisorTopology::Node) + { + remove_scheduling_gates(&pods, &generation.workload_pod_name).await?; + tokio::spawn(Box::pin(self.clone().launch_on_scheduled_node(generation))); + 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) { + 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); + 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(_) => { + 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"); + pause().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; + }; + // The node's supervisor may start with the workload, as on a new node. + 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 + .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 { + let object = tokio::time::timeout(KUBE_API_TIMEOUT, sandbox_api.api.get_opt(&cr_name)) + .await + .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, + ) + })) + }; + 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"); + pause().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 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; + } + } + } + + /// 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); + // 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_if(&sandbox_api.api, cr_name, |object, version| { + awaits_launch(object).then(|| { + serde_json::json!({ + "metadata": { + "resourceVersion": version, + "annotations": {ANNOTATION_SUPERVISOR_MEMBER: member}, + } + }) + }) + }) + .await? + .ok_or_else(superseded)?; + } + + 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); @@ -4161,27 +4474,14 @@ 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, .. } => { - 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, )?; @@ -4192,22 +4492,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, + workload_owner, + ), + ) + .await + .map(|_| ()) + .map_err(KubernetesDriverError::from_kube) + }, + ) .await .map_err(|error| match error { LaunchError::Persist(error) => error, @@ -4226,17 +4530,20 @@ impl KubernetesComputeDriver { })?; } } - pods.patch( - &workload_pod_name, - &PatchParams::default(), - &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), - ) - .await - .map_err(KubernetesDriverError::from_kube)?; - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { + let released = |version: &str| { sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) - }) - .await?; + }; + 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)?; + } let control = match target { GenerationLaunchTarget::Dedicated { .. } => BootstrapControl::SupervisorPod { pods, @@ -4528,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?; @@ -4704,11 +5012,14 @@ 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, &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. @@ -5496,9 +5807,16 @@ 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)) + .cloned(); Some(RecoverableInstance { route, sandbox_id: sandbox_id.clone(), + member, record: SharedInstanceSecretRecord { namespace, sandbox_id, @@ -5783,13 +6101,60 @@ 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; + } + + /// 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(""), @@ -6391,6 +6756,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) @@ -6719,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", + }], + }, }) } @@ -7447,7 +7873,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, @@ -7493,6 +7919,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); } @@ -7523,6 +7951,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| { @@ -7532,8 +7968,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; }; @@ -7543,14 +7985,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, }); } @@ -7716,6 +8158,48 @@ 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"; +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) +} + +/// 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 + .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> { spec["volumes"] .as_array()? @@ -9233,6 +9717,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", @@ -9977,23 +10462,691 @@ mod tests { ) } - fn network_trust_bundle(gateway_id: &str, digest: &str) -> NetworkSupervisorTrustBundle { - NetworkSupervisorTrustBundle::new( - b"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n".to_vec(), - 1, - digest, - PathBuf::from(format!("/gateway-state/{gateway_id}.crt")), - ) - } + 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"; - #[test] - fn destination_trust_config_map_is_immutable_content_addressed_and_retained() { - let digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; - let bundle = network_trust_bundle("gateway-a", digest); - let expected = network_additional_ca_config_map("workspace-a", "gateway-a", &bundle) - .expect("normalized PEM must be valid UTF-8"); - let name = expected.metadata.name.as_deref().expect("ConfigMap name"); - assert_eq!(name.len(), 63); + 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 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": "PodList", + "metadata": {"resourceVersion": "1"}, + "items": [{ + "metadata": {"name": "workload", "namespace": "openshell", "uid": "pod-uid"}, + "spec": {"containers": [], "nodeName": "node-a"}, + }], + }), + ) + } + + 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: Some("openshell-supervisor".to_string()), + require_identity_token: true, + }, + SharedSupervision::new(), + ) + } + + /// 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(), + ); + } + + use openshell_supervisor_control as control; + + /// Durable pool records that accept every launch. + #[derive(Debug)] + struct AcceptingPlacement; + + impl control::InstancePlacement for AcceptingPlacement { + fn place_launch(&self, _request: control::PlacementRequest) -> control::PlacementFuture { + Box::pin(async { Ok(()) }) + } + + fn recorded(&self) -> control::PlacementFuture> { + Box::pin(async { Ok(BTreeMap::new()) }) + } + + fn record_recovered( + &self, + _assignment: control::proto::SandboxInstanceAssignment, + _member: Option, + ) -> control::PlacementFuture { + Box::pin(async { Ok(()) }) + } + + fn prepare_runtime(&self, _: control::PreparationRequest) -> control::PlacementFuture { + unreachable!("deferred launches prepare no warm runtime") + } + + fn prepared_runtimes( + &self, + _: String, + _: Vec, + ) -> control::PlacementFuture> { + unreachable!("deferred launches list no warm runtime") + } + + fn release_preparation( + &self, + _: control::PreparationRevision, + ) -> control::PlacementFuture { + unreachable!("deferred launches release no warm runtime") + } + + fn retire_preparation( + &self, + _: control::PreparationRetirement, + ) -> control::PlacementFuture { + unreachable!("deferred launches retire no warm runtime") + } + + fn activate_runtime( + &self, + _: control::ActivationRequest, + ) -> control::PlacementFuture { + 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"}, + }), + ) + } + + 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) { + Box::pin(driver.clone().launch_on_scheduled_node(generation)).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(); + 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 = driver + .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(), + sandbox_api: scheduled_sandbox_api(driver), + 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 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_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 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] + 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), + ), + ], + ); + 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()); + } + + #[tokio::test] + async fn scheduled_launch_yields_to_a_stop_before_release() { + let now = openshell_core::time::now_ms(); + let stopping = || scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now); + 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()); + 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_eq!( + bodies[0]["metadata"]["annotations"][ANNOTATION_SUPERVISOR_MEMBER], + "node-a" + ); + } + + #[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!({"kind": "Status", "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), + ), + ], + ); + launch_scheduled(&driver, scheduled_generation(&driver)).await; + 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_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(), + ), + (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 { + unreachable!(); + }; + attach_node_supervisors(shared, &[]); + launch_scheduled(&driver, generation).await; + assert!(steps.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 reaper_deletes_a_failed_create_without_waiting_for_the_grace() { + let now = openshell_core::time::now_ms(); + 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()); + 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 preparing = || scheduled_sandbox(SandboxRuntimeBootstrapPhase::Preparing, 0); + assert!(sandbox_runtime_awaits_launch( + &preparing(), + "cr-uid", + "pod-uid" + )); + // Stopped, already launched, or a stop is releasing it. + for phase in [ + SandboxRuntimeBootstrapPhase::Suspending, + SandboxRuntimeBootstrapPhase::Released, + SandboxRuntimeBootstrapPhase::Releasing, + ] { + let object = scheduled_sandbox(phase, 0); + assert!(!sandbox_runtime_awaits_launch(&object, "cr-uid", "pod-uid")); + } + // 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; + 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 { + NetworkSupervisorTrustBundle::new( + b"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n".to_vec(), + 1, + digest, + PathBuf::from(format!("/gateway-state/{gateway_id}.crt")), + ) + } + + #[test] + fn destination_trust_config_map_is_immutable_content_addressed_and_retained() { + let digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + let bundle = network_trust_bundle("gateway-a", digest); + let expected = network_additional_ca_config_map("workspace-a", "gateway-a", &bundle) + .expect("normalized PEM must be valid UTF-8"); + let name = expected.metadata.name.as_deref().expect("ConfigMap name"); + assert_eq!(name.len(), 63); assert!(name.starts_with(ADDITIONAL_CA_CONFIG_MAP_PREFIX)); assert!( name.bytes() @@ -10664,12 +11817,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] @@ -14439,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)); @@ -14446,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] @@ -15167,6 +16350,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-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..eec77c0c4e 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: Some("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/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index 7ee198e775..64734ae732 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, })) } } @@ -812,6 +820,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, }, )))); let auth = PeerServiceAccountAuthenticator::new(resolver); @@ -836,6 +845,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()); @@ -867,6 +877,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 b8c77ec233..f324df9d8f 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,99 @@ use super::sandbox_jwt::SandboxSessionJwtAuthority; /// verification ends the chain. pub struct SupervisorTokenAuthenticator { authority: Arc, + supervisor_identity: Option>, + identity_required: bool, } 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 } + 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. + #[must_use] + pub fn with_identity_resolver( + mut self, + resolver: Arc, + required: bool, + ) -> Self { + self.supervisor_identity = Some(resolver); + self.identity_required = required; + self + } + + /// 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> { + let refuse = |reason, message: &str| { + AuthRejection::new( + AuthMechanism::SupervisorToken, + reason, + tonic::Status::unauthenticated(message), + ) + }; + let token = headers + .get(HOST_IDENTITY_TOKEN_HEADER) + .and_then(|value| value.to_str().ok()) + .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, + "supervisor identity token is required", + )); + } + return Ok(None); + }; + let identity = 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()), + ), + ) + })? + .ok_or_else(|| { + refuse( + AuthFailureReason::InvalidCredential, + "supervisor identity token is invalid", + ) + })?; + 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)))) } } @@ -61,12 +155,22 @@ impl Authenticator for SupervisorTokenAuthenticator { return Ok(Authentication::NotApplicable); } let authenticated = self.authority.verify_supervisor_token(token)?; + 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, + expires_at, + node: identity.map(|(node, _)| node), }, }, ))) @@ -79,6 +183,7 @@ mod tests { use super::*; use crate::auth::authenticator::{AuthFailureReason, AuthMechanism}; + use crate::auth::peer::test_support::FakeGatewayPeerResolver; use openshell_bootstrap::jwt::generate_jwt_key; fn authority(gateway_id: &str) -> Arc { @@ -104,6 +209,24 @@ 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()); + headers + } + + 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), + }, + )))) + } + #[tokio::test] async fn supervisor_tokens_authenticate_only_as_the_supervisor() { let attach = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; @@ -125,9 +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, 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. @@ -184,4 +314,118 @@ mod tests { .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(Some("node-a")); + let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolver.clone(), true); + + 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 + .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 + // with no node, but one it sends is still verified. + let optional = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(resolver.clone(), false); + 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()) + .with_identity_resolver( + Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), + false + ) + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) + .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") + .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_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 = 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)) => { + 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); + } } diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index dd0ef762cc..7a1d8ef332 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -430,6 +430,10 @@ pub struct ServerState { /// Optional K8s `ServiceAccount` authenticator for gateway peer RPCs. pub peer_authenticator: Option>, + /// Authenticates the shared supervisor's tokens. Without it every + /// supervisor token is refused. + pub supervisor_authenticator: Option>, + /// 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 +722,7 @@ impl ServerState { compute_driver_authenticator: None, dedicated_warm_pool: None, peer_authenticator: None, + supervisor_authenticator: None, logons: auth::audit::Logons::default(), grpc_rate_limiter, provider_token_rate_limiter, @@ -1065,6 +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()); + 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_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 557c070996..40db89b4b6 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1157,9 +1157,11 @@ 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()), - )); + 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, @@ -3896,6 +3898,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-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index b6259fda95..3d56f3b21e 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)] @@ -296,6 +302,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 +659,9 @@ 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, and only when its +/// identity token proved it runs on that node. +#[allow(clippy::too_many_arguments)] fn candidates<'a>( ring: &GatewayRing, members: &'a [LiveMember], @@ -659,12 +670,15 @@ 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.node.as_deref() == Some(pinned) + }) && !member.leaving && routes_of(member) .is_none_or(|routes| routes.contains(route) || routes.len() < max_instances) }; @@ -1157,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()))?; @@ -1313,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)); @@ -1717,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, @@ -1726,32 +1743,25 @@ impl SupervisorPool { .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, - ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Admitting) - .await - } - /// [`Self::record_assignment`], publishing the record as `phase` /// ([`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, phase: RecordPhase, ) -> Result { - self.record_assignment_scoped(assignment, phase, None).await + self.record_assignment_scoped(assignment, phase, None, 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 +1853,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| { @@ -2221,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 @@ -2247,6 +2264,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,24 +2278,28 @@ impl SupervisorPool { &charges, None, max_instances, + pinned, ); let no_room = || { + 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).await? - }; + .await?; if assignment.prepared && self.load_material(&recording.record.payload).await? != assignment.launch_material { @@ -2525,8 +2547,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 +2975,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 +2990,7 @@ impl SupervisorPool { charges, None, self.max_instances_per_member(), + assignment.member_id.as_deref(), ); if targets.is_empty() { return Ok(Reconciled::Unchanged); @@ -3024,12 +3061,21 @@ 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())) } + /// 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 +3083,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 +3102,7 @@ impl SupervisorPool { charges, Some(&record.payload.member_id), self.max_instances_per_member(), + pinned, ); for target in targets { let intent = OwnerPayload { @@ -3544,10 +3599,21 @@ 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_scoped( + &assignment, + RecordPhase::Published, + member.as_deref(), + None, + ) + .await + .map(drop) })) } } @@ -3747,6 +3813,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(); @@ -3802,6 +3869,7 @@ mod tests { claim_handle: Vec::new(), pool_id: None, claim_operation_id: None, + member_id: None, }; self.store .put_if( @@ -3928,6 +3996,7 @@ mod tests { PlacementRequest { assignment: assignment(route, sandbox_id, generation), auth_epoch: 1, + member: None, } } @@ -3989,6 +4058,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; @@ -5188,7 +5349,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(); @@ -5602,6 +5763,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving: false, connected_at_ms, + node: Some(member_id.to_string()), } } @@ -6122,6 +6284,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!( @@ -6146,6 +6309,7 @@ mod tests { runtime_address: "10.0.0.1:5500".to_string(), leaving, gateway_replica: String::new(), + node: Some(id.to_string()), } } @@ -6167,10 +6331,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 +6357,47 @@ 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()); + // 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] @@ -6210,6 +6417,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..5e4678e284 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 @@ -191,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; @@ -1025,6 +1044,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-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/README.md b/crates/openshell-supervisor-control/README.md index fb6ca4c683..c74bf773e3 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -17,8 +17,10 @@ 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 + `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. `require_host_identity` names + 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 token that opened diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index e9e35005e8..edbc8fd6b5 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}; @@ -80,11 +80,21 @@ 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, } +/// 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 @@ -225,6 +235,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 { @@ -359,6 +371,20 @@ 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>, + /// Set by [`SupervisorHostController::bind_members_to_nodes`]. + members_bound_to_nodes: AtomicBool, +} + +/// 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 +438,8 @@ impl SupervisorHostController { peer_endpoint: Mutex::new(String::new()), limits: Mutex::new(PoolLimits::default()), gateway_replicas: AtomicUsize::new(1), + supervisor_account: Mutex::new(None), + members_bound_to_nodes: AtomicBool::new(false), }), } } @@ -443,6 +471,33 @@ 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() + } + + /// Accept only supervisors whose pool member ID is the node their + /// 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 + .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) { @@ -798,6 +853,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() } @@ -935,6 +991,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); @@ -1387,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; } } @@ -1410,6 +1469,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| { @@ -1622,6 +1693,7 @@ mod tests { subject: "openshell-supervisor:test".to_string(), token_id: "token".to_string(), expires_at: i64::MAX, + node: None, } } 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-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..19086f0d99 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. 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 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/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index a0ba6dc0f9..6f49853b9b 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -117,6 +117,22 @@ 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")] + 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", + requires = "identity_token_file" + )] + node_supervisor: bool, + /// Listener for routed runtime-initiated Sandbox Protocol connections. #[arg(long, required_if_eq("mode", "shared"))] runtime_listen: Option, @@ -554,6 +570,8 @@ 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.node_supervisor || (args.runtime_listen.is_some() && args.warm_prepared_file.is_none()) || args.session_root.is_some() { @@ -1187,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 a1403bb5bb..9e860fe7cc 100644 --- a/crates/openshell-supervisor/src/shared.rs +++ b/crates/openshell-supervisor/src/shared.rs @@ -33,6 +33,8 @@ 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; + let node_supervisor = args.node_supervisor; let runtime_listen = args .runtime_listen .ok_or_else(|| miette::miette!("--runtime-listen is required for --mode=shared"))?; @@ -124,6 +126,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 { @@ -166,8 +169,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; diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 566de3ebd9..757a14bf14 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -1177,9 +1177,32 @@ 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: Option, } impl GatewayLink { + fn read_identity_token(&self) -> Result> { + use miette::{IntoDiagnostic as _, WrapErr as _}; + + 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()))?; + let token = contents.trim(); + if token.is_empty() { + return Err(miette::miette!("the identity token file is empty")); + } + token + .parse() + .map(Some) + .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 +1302,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 +1313,15 @@ 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)); + 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 .map_err(|_| { @@ -1693,7 +1727,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); } }; @@ -1722,7 +1756,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 c441cb63e4..e8dfae7359 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,18 +847,23 @@ 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, 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. 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. 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 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/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 d174315813..5e3d9e230f 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,14 @@ 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 the sandboxes the kubelet admits on its node, so the +node topology defaults to more than the kubelet's default maxPods. +*/}} {{- define "openshell.supervisorMaxInstancesPerMember" -}} -{{- include "openshell.supervisorPoolLimit" (dict "root" . "key" "maxInstancesPerMember" "max" 1024 "default" 128) -}} +{{- $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). */}} @@ -563,7 +577,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 -}} @@ -832,7 +848,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 }} @@ -845,8 +861,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 +872,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/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-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 new file mode 100644 index 0000000000..14c2bf5cd4 --- /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, 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: + 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..5f66ea4916 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -23,14 +23,15 @@ {{- $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 # 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 +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: {{ .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 # 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,6 +72,7 @@ spec: labels: {{- include "openshell.supervisorSelectorLabels" . | nindent 8 }} spec: + serviceAccountName: {{ $name }} automountServiceAccountToken: false enableServiceLinks: false # A stopping member announces that it is leaving, and the gateway moves @@ -80,6 +92,17 @@ spec: affinity: {{- toYaml . | nindent 8 }} {{- end }} + {{- with .Values.supervisor.nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.supervisor.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} + {{- with .Values.supervisor.priorityClassName }} + priorityClassName: {{ . }} + {{- end }} containers: - name: supervisor image: {{ get $kubernetes "supervisor_image" | quote }} @@ -92,6 +115,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 @@ -104,6 +129,9 @@ spec: - --nat64-prefix - {{ . | quote }} {{- end }} + {{- if $node }} + - --node-supervisor + {{- end }} env: {{- if get $app "enabled" }} - name: OPENSHELL_APP_LISTENER_ENABLED @@ -129,13 +157,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: @@ -186,6 +214,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 +235,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..962e5e5d30 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: @@ -89,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 @@ -98,6 +102,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 +113,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 +157,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 +381,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 +648,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 +684,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 +724,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: @@ -771,6 +802,43 @@ tests: value: 512Mi template: templates/supervisor.yaml documentIndex: 0 + - 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: 1000 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - matchRegex: + path: data["gateway.toml"] + 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: "1000" + template: templates/supervisor.yaml + documentIndex: 0 - it: accepts a per-member cap of one sandbox template: templates/supervisor.yaml set: @@ -994,7 +1062,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: @@ -1006,3 +1074,159 @@ 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: + # The node topology ignores replicas, which exceed the member limit. + replicas: 3 + pool: + maxMembersPerGateway: 2 + 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 + - notExists: + path: spec.template.spec.priorityClassName + - 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: 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: + 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: 'supervisor_topology = "node"' + template: templates/gateway-config.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 e5ae3b736b..646696a045 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -73,6 +73,9 @@ 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. 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 # supervisor as a high-availability pool: when a member fails or leaves, @@ -80,15 +83,18 @@ 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 + # -- (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. - 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 @@ -131,16 +137,25 @@ 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 # 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 @@ -154,9 +169,16 @@ 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 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. additionalCaConfigMapName: "" diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index c42bfd01e5..bdde817c62 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] @@ -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,23 @@ 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 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] +# service_name = "openshell-supervisor" +# service_namespace = "openshell" +# runtime_port = 5500 +# token_secret_name = "openshell-supervisor-token" +# 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 without the pod-bound token (supervisor.requireIdentityToken). +# require_identity_token = false + [openshell.drivers.kubernetes.managed_ssh_ingress] enabled = true gateway_namespace = "openshell" @@ -1881,6 +1898,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 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..1c92c334b1 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: @@ -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` @@ -685,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. | @@ -728,6 +739,65 @@ 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. +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, 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: + tolerations: + - key: nvidia.com/gpu + operator: Exists + 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`. 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 +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/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. diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 663494e929..20e53ab7d7 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. Until the workload Pod is scheduled, the runtime logs +`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 +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,9 +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 | +| 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`, `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 | 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" }