diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index 1f39befca6..5a059dbd7f 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -399,14 +399,22 @@ driver instance. The gate preserves concurrency across sandboxes; it does not provide distributed exclusion between separate gateway or driver processes. In a high-availability gateway, only the lease holder reconciles, while any -replica can serve a lifecycle RPC. A restart marks the CR `Preparing` before it -creates the supervisor Pod, and reconciliation respects that claim until the -bootstrap grace period expires, then reaps it: a stale restart is suspended and -a stale create is deleted. Before it deletes the supervisor Pod of a stopped -sandbox, reconciliation reads the CR again and skips the deletion if the CR -changed after its refresh. Lifecycle writes to the CR retry on resourceVersion -conflicts without checking whether another replica started a transition, so a -request on one replica can still overwrite a suspension started by another. +replica can serve a lifecycle RPC. A restart claims the CR, marking it +`Preparing`, before it creates the supervisor Pod. The claim succeeds only if +the CR is stopped and no other transition is in progress, and reconciliation +respects it until the bootstrap grace period expires, then reaps it: a stale +restart is suspended and a stale create is deleted. Every create or restart +write to the CR is a compare-and-swap against the request's claim (CR UID, +operation, and generation), and supervisor Pods are deleted by UID. If another +replica started a transition such as a suspension, the request fails. A failed +create deletes its CR. A failed restart that lost its claim leaves the CR to the +other transition and deletes only the supervisor Pod it created. Stop and +suspend writes don't check a claim yet +([#6110](https://github.com/ai-openshell/openshell/issues/6110)), so a stop, +including a failed restart's rollback, can remove the supervisor Pod of a start +that claimed the CR while the stop was finishing. Before it +deletes the supervisor Pod of a stopped sandbox, reconciliation reads the CR +again and skips the deletion if the CR changed after its refresh. ## GPU Support diff --git a/crates/openshell-driver-kubernetes/src/bootstrap_claim.rs b/crates/openshell-driver-kubernetes/src/bootstrap_claim.rs new file mode 100644 index 0000000000..b51a2792e8 --- /dev/null +++ b/crates/openshell-driver-kubernetes/src/bootstrap_claim.rs @@ -0,0 +1,368 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Bootstrap claims on a Sandbox CR and the compare-and-swap writes that +//! respect them. +//! +//! A create or restart claims a Sandbox by recording its operation, phase, +//! and generation in annotations. Any gateway replica may serve the request, +//! so each later write compares the stored claim with the request's own and +//! refuses to overwrite a transition another replica started. + +use super::{ + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE, + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING, + ANNOTATION_SANDBOX_RUNTIME_GENERATION, ANNOTATION_SANDBOX_RUNTIME_READINESS, KUBE_API_TIMEOUT, + KubernetesDriverError, is_kube_resource_version_conflict, kubernetes_pod_termination_timeout, + sandbox_runtime_generation, sandbox_runtime_should_run, +}; +use k8s_openapi::api::core::v1::Pod; +use kube::Api; +use kube::Error as KubeError; +use kube::api::{DeleteParams, Patch, PatchParams, Preconditions}; +use kube::core::DynamicObject; +use std::collections::BTreeMap; +use std::time::Duration; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SandboxRuntimeBootstrapPhase { + Preparing, + Released, + Releasing, + Suspending, +} + +impl SandboxRuntimeBootstrapPhase { + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Preparing => "preparing", + Self::Released => "released", + Self::Releasing => "releasing", + Self::Suspending => "suspending", + } + } + + pub(super) fn parse(value: &str) -> Option { + match value { + "preparing" => Some(Self::Preparing), + "released" => Some(Self::Released), + "releasing" => Some(Self::Releasing), + "suspending" => Some(Self::Suspending), + _ => None, + } + } + + /// Whether a create or restart claim in this phase still belongs to the + /// request that made it. `Released` does, so a request whose `Released` + /// write timed out but landed can still roll back. + const fn held_by_claimant(self) -> bool { + matches!(self, Self::Preparing | Self::Released) + } +} + +/// The lifecycle request that started a bootstrap transition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum SandboxRuntimeBootstrapOperation { + Create, + Restart, + Stop, +} + +impl SandboxRuntimeBootstrapOperation { + const fn as_str(self) -> &'static str { + match self { + Self::Create => "create", + Self::Restart => "restart", + Self::Stop => "stop", + } + } + + fn parse(value: &str) -> Option { + [Self::Create, Self::Restart, Self::Stop] + .into_iter() + .find(|operation| operation.as_str() == value) + } +} + +fn annotation<'a>(object: &'a DynamicObject, key: &str) -> Option<&'a str> { + object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(key)) + .map(String::as_str) +} + +pub(super) fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING) == Some("true") +} + +pub(super) fn sandbox_runtime_bootstrap_operation( + object: &DynamicObject, +) -> Option { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION) + .and_then(SandboxRuntimeBootstrapOperation::parse) +} + +pub(super) fn sandbox_runtime_bootstrap_phase( + object: &DynamicObject, +) -> Option { + annotation(object, ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE) + .and_then(SandboxRuntimeBootstrapPhase::parse) +} + +/// Annotations that start a bootstrap transition and its grace period. +fn bootstrap_annotations( + operation: SandboxRuntimeBootstrapOperation, + phase: SandboxRuntimeBootstrapPhase, +) -> BTreeMap { + BTreeMap::from([ + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), + "true".to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), + openshell_core::time::now_ms().to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), + operation.as_str().to_string(), + ), + ( + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), + phase.as_str().to_string(), + ), + ]) +} + +/// Annotations that start a stop in `phase` and mark the runtime unavailable. +pub(super) fn stop_annotations(phase: SandboxRuntimeBootstrapPhase) -> BTreeMap { + let mut annotations = bootstrap_annotations(SandboxRuntimeBootstrapOperation::Stop, phase); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), + "unavailable".to_string(), + ); + annotations +} + +/// The resourceVersion a compare-and-swap patch pins. An object without one +/// would turn the patch into an unconditional write, so it is an error. +pub(super) fn resource_version(object: &DynamicObject) -> Result<&str, KubernetesDriverError> { + object.metadata.resource_version.as_deref().ok_or_else(|| { + KubernetesDriverError::Message(format!( + "Kubernetes resource {} has no resourceVersion", + object.metadata.name.as_deref().unwrap_or("") + )) + }) +} + +/// Read `name` and apply the merge patch `patch_for` builds from it, retrying +/// with a fresh read on a resourceVersion conflict. `patch_for` sees the +/// current object each time and may refuse the write; the patch must pin +/// [`resource_version`] for the comparison to hold. +pub(super) async fn compare_and_patch_dynamic_object( + api: &Api, + name: &str, + mut patch_for: impl FnMut(&DynamicObject) -> Result, +) -> Result { + let operation = async { + loop { + let current = api + .get(name) + .await + .map_err(KubernetesDriverError::from_kube)?; + let patch = patch_for(¤t)?; + match api + .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) + .await + { + Ok(updated) => return Ok(updated), + Err(error) if is_kube_resource_version_conflict(&error) => { + tokio::task::yield_now().await; + } + Err(error) => return Err(KubernetesDriverError::from_kube(error)), + } + } + }; + tokio::time::timeout(KUBE_API_TIMEOUT, operation) + .await + .map_err(|_| { + KubernetesDriverError::Message(format!( + "timed out after {}s updating Kubernetes resource {name}", + KUBE_API_TIMEOUT.as_secs() + )) + })? +} + +/// A create or restart request's claim on a Sandbox's bootstrap. +#[derive(Clone, Copy, Debug)] +pub(super) struct SandboxRuntimeBootstrapClaim<'a> { + cr_uid: &'a str, + operation: SandboxRuntimeBootstrapOperation, + generation: &'a str, +} + +impl<'a> SandboxRuntimeBootstrapClaim<'a> { + pub(super) const fn new( + cr_uid: &'a str, + operation: SandboxRuntimeBootstrapOperation, + generation: &'a str, + ) -> Self { + Self { + cr_uid, + operation, + generation, + } + } + + pub(super) const fn cr_uid(&self) -> &'a str { + self.cr_uid + } + + /// Annotations that record a claim for `operation` and `generation`. A + /// create writes them when it creates the CR, before its UID exists. + pub(super) fn annotations( + operation: SandboxRuntimeBootstrapOperation, + generation: &str, + ) -> BTreeMap { + let mut annotations = + bootstrap_annotations(operation, SandboxRuntimeBootstrapPhase::Preparing); + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), + generation.to_string(), + ); + annotations + } + + /// Claim a stopped Sandbox that no other transition has claimed. + pub(super) async fn begin( + &self, + api: &Api, + name: &str, + ) -> Result<(), KubernetesDriverError> { + compare_and_patch_dynamic_object(api, name, |current| { + if current.metadata.uid.as_deref() != Some(self.cr_uid) { + return Err(KubernetesDriverError::Precondition( + "the Sandbox resource was replaced".to_string(), + )); + } + if sandbox_runtime_bootstrap_in_progress(current) || sandbox_runtime_should_run(current) + { + return Err(KubernetesDriverError::Precondition( + "another lifecycle transition claimed the sandbox; retry after it completes" + .to_string(), + )); + } + Ok(serde_json::json!({ + "metadata": { + "resourceVersion": resource_version(current)?, + "annotations": Self::annotations(self.operation, self.generation), + }, + })) + }) + .await?; + Ok(()) + } + + /// Apply the patch `patch_for` builds from the current resourceVersion, + /// but only while this claim still holds. Fails with `Precondition` once + /// another transition has replaced it. + pub(super) async fn patch( + &self, + api: &Api, + name: &str, + mut patch_for: impl FnMut(&str) -> serde_json::Value, + ) -> Result { + compare_and_patch_dynamic_object(api, name, |current| { + self.ensure_held(current)?; + Ok(patch_for(resource_version(current)?)) + }) + .await + } + + /// Mark the generation installed so reconciliation may complete it. + pub(super) async fn release( + &self, + api: &Api, + name: &str, + ) -> Result<(), KubernetesDriverError> { + self.patch(api, name, |version| { + serde_json::json!({ + "metadata": { + "resourceVersion": version, + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: + SandboxRuntimeBootstrapPhase::Released.as_str(), + } + } + }) + }) + .await?; + Ok(()) + } + + fn ensure_held(&self, current: &DynamicObject) -> Result<(), KubernetesDriverError> { + let held = current.metadata.uid.as_deref() == Some(self.cr_uid) + && sandbox_runtime_bootstrap_in_progress(current) + && sandbox_runtime_bootstrap_phase(current) + .is_some_and(SandboxRuntimeBootstrapPhase::held_by_claimant) + && sandbox_runtime_bootstrap_operation(current) == Some(self.operation) + && sandbox_runtime_generation(current) == Some(self.generation); + if held { + Ok(()) + } else { + Err(KubernetesDriverError::Precondition(format!( + "sandbox {} of generation {} was superseded by another lifecycle transition", + self.operation.as_str(), + self.generation + ))) + } + } +} + +/// Delete `pod` by UID and wait until it is gone. A Pod that has since been +/// created under the same name, such as by a restart on another replica, is +/// left running and does not extend the wait. +pub(super) async fn delete_supervisor_pod_and_wait( + pods: &Api, + pod: Pod, +) -> Result<(), KubernetesDriverError> { + let name = + pod.metadata.name.clone().ok_or_else(|| { + KubernetesDriverError::Message("supervisor Pod has no name".to_string()) + })?; + let uid = pod.metadata.uid.clone(); + let deletion_timeout = kubernetes_pod_termination_timeout(&pod); + match pods + .delete( + &name, + &DeleteParams::foreground().preconditions(Preconditions { + uid: uid.clone(), + resource_version: None, + }), + ) + .await + { + Ok(_) => {} + Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), + Err(error) => return Err(KubernetesDriverError::from_kube(error)), + } + let deadline = tokio::time::Instant::now() + deletion_timeout; + loop { + let current = pods + .get_opt(&name) + .await + .map_err(KubernetesDriverError::from_kube)?; + if current.is_none_or(|current| current.metadata.uid != uid) { + return Ok(()); + } + if tokio::time::Instant::now() >= deadline { + return Err(KubernetesDriverError::Message(format!( + "timed out after {}s waiting for supervisor Pod deletion", + deletion_timeout.as_secs() + ))); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index da7786eeca..d57887ae40 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -90,9 +90,18 @@ use tokio::sync::{OnceCell, mpsc}; use tokio_stream::wrappers::ReceiverStream; use tracing::{debug, info, warn}; +#[path = "bootstrap_claim.rs"] +mod bootstrap_claim; #[path = "image_update.rs"] mod image_update; +use bootstrap_claim::{ + SandboxRuntimeBootstrapClaim, SandboxRuntimeBootstrapOperation, SandboxRuntimeBootstrapPhase, + compare_and_patch_dynamic_object, delete_supervisor_pod_and_wait, resource_version, + sandbox_runtime_bootstrap_in_progress, sandbox_runtime_bootstrap_operation, + sandbox_runtime_bootstrap_phase, stop_annotations, +}; + pub type WatchStream = Pin> + Send>>; @@ -318,35 +327,6 @@ async fn create_or_validate_network_additional_ca_config_map( } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum SandboxRuntimeBootstrapPhase { - Preparing, - Released, - Releasing, - Suspending, -} - -impl SandboxRuntimeBootstrapPhase { - const fn as_str(self) -> &'static str { - match self { - Self::Preparing => "preparing", - Self::Released => "released", - Self::Releasing => "releasing", - Self::Suspending => "suspending", - } - } - - fn parse(value: &str) -> Option { - match value { - "preparing" => Some(Self::Preparing), - "released" => Some(Self::Released), - "releasing" => Some(Self::Releasing), - "suspending" => Some(Self::Suspending), - _ => None, - } - } -} - fn boundary_service_authority( namespace: &str, names: &SandboxRuntimeNames, @@ -389,6 +369,32 @@ struct StagedBootstrapMaterial { client_tls: Option, } +/// A failed restart and the supervisor Pod it created, if it got that far. +struct RestartFailure { + source: KubernetesDriverError, + created_supervisor_pod: Option, +} + +/// Suspend the Sandbox in one write if `claim` still holds it. Returns +/// `false`, writing nothing, once another transition has replaced the claim +/// or the Sandbox is gone. +async fn suspend_if_claimed( + sandbox_api: &AgentSandboxApi, + cr_name: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, +) -> Result { + match claim + .patch(&sandbox_api.api, cr_name, |version| { + sandbox_runtime_suspension_patch(&sandbox_api.resource.version, version) + }) + .await + { + Ok(_) => Ok(true), + Err(KubernetesDriverError::Precondition(_) | KubernetesDriverError::NotFound) => Ok(false), + Err(error) => Err(error), + } +} + /// The supervisor a generation is installed with. enum GenerationSupervisor { /// A supervisor Pod paired with this generation's workload Pod. @@ -543,86 +549,6 @@ fn is_kube_resource_version_conflict(error: &KubeError) -> bool { matches!(error, KubeError::Api(api) if api.code == 409 && api.reason == "Conflict") } -async fn patch_dynamic_object_with_resource_version_retry( - api: &Api, - name: &str, - mut patch_for_resource_version: impl FnMut(&str) -> serde_json::Value, -) -> Result { - let operation = async { - loop { - let current = api.get(name).await?; - let resource_version = current - .metadata - .resource_version - .as_deref() - .unwrap_or_default(); - let patch = patch_for_resource_version(resource_version); - match api - .patch(name, &PatchParams::default(), &Patch::Merge(&patch)) - .await - { - Ok(updated) => return Ok(updated), - Err(error) if is_kube_resource_version_conflict(&error) => { - tokio::task::yield_now().await; - } - Err(error) => return Err(error), - } - } - }; - tokio::time::timeout(KUBE_API_TIMEOUT, operation) - .await - .map_err(|_| { - KubernetesDriverError::Message(format!( - "timed out after {}s updating Kubernetes resource {name}", - KUBE_API_TIMEOUT.as_secs() - )) - })? - .map_err(KubernetesDriverError::from_kube) -} - -/// Delete `pod` by UID and wait until it is gone. A Pod that has since been -/// created under the same name, such as by a restart on another replica, is -/// left running and does not extend the wait. -async fn delete_supervisor_pod_and_wait( - pods: &Api, - pod: Pod, -) -> Result<(), KubernetesDriverError> { - let name = pod.metadata.name.clone().unwrap_or_default(); - let uid = pod.metadata.uid.clone(); - let deletion_timeout = kubernetes_pod_termination_timeout(&pod); - match pods - .delete( - &name, - &DeleteParams::foreground().preconditions(Preconditions { - uid: uid.clone(), - resource_version: None, - }), - ) - .await - { - Ok(_) => {} - Err(KubeError::Api(error)) if error.code == 404 => return Ok(()), - Err(error) => return Err(KubernetesDriverError::from_kube(error)), - } - let deadline = tokio::time::Instant::now() + deletion_timeout; - loop { - let current = pods - .get_opt(&name) - .await - .map_err(KubernetesDriverError::from_kube)?; - if current.is_none_or(|current| current.metadata.uid != uid) { - return Ok(()); - } - if tokio::time::Instant::now() >= deadline { - return Err(KubernetesDriverError::Message(format!( - "timed out after {}s waiting for supervisor Pod deletion", - deletion_timeout.as_secs() - ))); - } - tokio::time::sleep(Duration::from_millis(100)).await; - } -} - impl From for openshell_core::ComputeDriverError { fn from(err: KubernetesDriverError) -> Self { match err { @@ -2731,10 +2657,9 @@ impl KubernetesComputeDriver { .to_string(), ); add_trace_context_annotation(&mut annotations); - annotations.extend(sandbox_runtime_bootstrap_claim( - "create", - SandboxRuntimeBootstrapPhase::Preparing, - Some(&generation), + annotations.extend(SandboxRuntimeBootstrapClaim::annotations( + SandboxRuntimeBootstrapOperation::Create, + &generation, )); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC.to_string(), @@ -2820,6 +2745,7 @@ impl KubernetesComputeDriver { &kube_name, &agent_sandbox_api, &created, + &generation, &proxy_names, control_connection, &placement, @@ -3340,6 +3266,7 @@ impl KubernetesComputeDriver { cr_name: &str, sandbox_api: &AgentSandboxApi, sandbox_cr: &DynamicObject, + generation: &str, names: &SandboxRuntimeNames, control_connection: KubernetesControlConnection, placement: &SupervisorPlacement, @@ -3362,6 +3289,11 @@ impl KubernetesComputeDriver { let cr_uid = sandbox_cr.metadata.uid.as_deref().ok_or_else(|| { KubernetesDriverError::Message("created Sandbox CR has no UID".to_string()) })?; + let claim = SandboxRuntimeBootstrapClaim::new( + cr_uid, + SandboxRuntimeBootstrapOperation::Create, + generation, + ); let dependent_owner = sandbox_runtime_sandbox_owner_reference( cr_name, cr_uid, @@ -3415,10 +3347,11 @@ impl KubernetesComputeDriver { // the workload Pod. The Pod remains unschedulable because its template // carries the OpenShell scheduling gate and references a Secret that // does not exist yet. - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { - sandbox_operating_state_patch(&sandbox_api.resource.version, version, true) - }) - .await?; + claim + .patch(&sandbox_api.api, cr_name, |version| { + sandbox_operating_state_patch(&sandbox_api.resource.version, version, true) + }) + .await?; let mut child_env = sandbox .spec @@ -3436,7 +3369,7 @@ impl KubernetesComputeDriver { cr_name, sandbox_api, &sandbox.id, - cr_uid, + claim, names, &supervisor, agent_uid, @@ -3794,7 +3727,7 @@ impl KubernetesComputeDriver { cr_name: &str, sandbox_api: &AgentSandboxApi, sandbox_id: &str, - cr_uid: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, names: &SandboxRuntimeNames, supervisor: &GenerationSupervisor, agent_uid: u32, @@ -3803,6 +3736,7 @@ impl KubernetesComputeDriver { launch_authentication: &openshell_core::jwt::SandboxLaunchAuthentication, staged: StagedBootstrapMaterial, ) -> Result<(), KubernetesDriverError> { + let cr_uid = claim.cr_uid(); let namespace_uid = Api::::all(self.client.clone()) .get(namespace) .await @@ -3883,12 +3817,13 @@ impl KubernetesComputeDriver { annotations[ANNOTATION_SANDBOX_RUNTIME_CONTROL_POLICY_GENERATION] = policy.generation.to_string().into(); } - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { - serde_json::json!({ - "metadata": {"resourceVersion": version, "annotations": annotations.clone()} + claim + .patch(&sandbox_api.api, cr_name, |version| { + serde_json::json!({ + "metadata": {"resourceVersion": version, "annotations": annotations.clone()} + }) }) - }) - .await?; + .await?; let session_id = launch_authentication.supervisor.session_id; let tls = generate_sandbox_tls_material(session_id) @@ -4099,10 +4034,7 @@ impl KubernetesComputeDriver { ) .await .map_err(KubernetesDriverError::from_kube)?; - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { - sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) - }) - .await?; + claim.release(&sandbox_api.api, cr_name).await?; let control = match target { GenerationLaunchTarget::Dedicated { .. } => BootstrapControl::SupervisorPod { pods, @@ -4148,13 +4080,12 @@ impl KubernetesComputeDriver { if phase != Some(SandboxRuntimeBootstrapPhase::Suspending) { self.release_generation_supervisor(sandbox_id, &namespace, &placement) .await?; - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - |version| { - sandbox_runtime_suspension_patch(&agent_sandbox_api.resource.version, version) - }, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_suspension_patch( + &agent_sandbox_api.resource.version, + resource_version(current)?, + )) + }) .await?; } let pod_api = Api::::namespaced(self.client.clone(), &namespace); @@ -4200,11 +4131,11 @@ impl KubernetesComputeDriver { sandbox_runtime_generation(&object).as_slice(), ) .await?; - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - sandbox_runtime_suspension_completion_patch, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_suspension_completion_patch( + resource_version(current)?, + )) + }) .await?; return Ok(()); } @@ -4282,7 +4213,8 @@ impl KubernetesComputeDriver { if sandbox_runtime_bootstrap_in_progress(&object) { let phase = sandbox_runtime_bootstrap_phase(&object); if phase != Some(SandboxRuntimeBootstrapPhase::Suspending) - && sandbox_runtime_bootstrap_operation(&object) != Some("restart") + && sandbox_runtime_bootstrap_operation(&object) + != Some(SandboxRuntimeBootstrapOperation::Restart) { return Err(KubernetesDriverError::Precondition( "initial sandbox bootstrap has not completed; wait for reconciliation" @@ -4498,15 +4430,24 @@ impl KubernetesComputeDriver { })?; sandbox_secret["secretName"] = serde_json::json!(names.sandbox_secret); let image_pull_secrets = self.generation_image_pull_secret_names(&names); + let claim = SandboxRuntimeBootstrapClaim::new( + cr_uid, + SandboxRuntimeBootstrapOperation::Restart, + generation.as_str(), + ); let restart = async { + let before_supervisor = |source| RestartFailure { + source, + created_supervisor_pod: None, + }; // Only the lease holder reconciles, and its lifecycle gate does - // not cover requests served by other replicas. Mark the Sandbox - // Preparing before creating the supervisor Pod so reconciliation - // that refreshed the stopped Sandbox cannot delete the new Pod. - patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { - sandbox_runtime_restart_begin_patch(version, generation.as_str()) - }) - .await?; + // not cover requests served by other replicas. Claim the Sandbox + // before creating the supervisor Pod so reconciliation that + // refreshed the stopped Sandbox cannot delete the new Pod. + claim + .begin(&sandbox_api.api, cr_name) + .await + .map_err(before_supervisor)?; let supervisor = match &placement { SupervisorPlacement::Dedicated => GenerationSupervisor::Dedicated { pod_uid: self @@ -4527,17 +4468,20 @@ impl KubernetesComputeDriver { &log_level, staged.upstream_proxy_ca_bundle.is_some(), ) - .await?, + .await + .map_err(before_supervisor)?, connection: control_connection, }, SupervisorPlacement::Shared { route } => GenerationSupervisor::Shared { route: route.clone(), }, }; - patch_dynamic_object_with_resource_version_retry( - &sandbox_api.api, - cr_name, - |version| { + let created_supervisor_pod = match &supervisor { + GenerationSupervisor::Dedicated { pod_uid, .. } => Some(pod_uid.clone()), + GenerationSupervisor::Shared { .. } => None, + }; + let finish = async { + claim.patch(&sandbox_api.api, cr_name, |version| { let mut running_patch = sandbox_operating_state_patch(&sandbox_api.resource.version, version, true); let (supervisor_uid, topology, instance_route) = match &supervisor { @@ -4565,41 +4509,59 @@ impl KubernetesComputeDriver { &image_pull_secrets, ); running_patch - }, - ) - .await?; + }) + .await?; - let child_env = child_environment_from_sandbox_object(&object); - self.install_sandbox_runtime_generation( - &namespace, - cr_name, - &sandbox_api, - sandbox_id, - cr_uid, - &names, - &supervisor, - agent_uid, - agent_gid, - child_env, - &launch_authentication, - staged, - ) - .await?; + let child_env = child_environment_from_sandbox_object(&object); + self.install_sandbox_runtime_generation( + &namespace, + cr_name, + &sandbox_api, + sandbox_id, + claim, + &names, + &supervisor, + agent_uid, + agent_gid, + child_env, + &launch_authentication, + staged, + ) + .await + } + .await; + finish.map_err(|source| RestartFailure { + source, + created_supervisor_pod, + })?; Ok(supervisor) } .await; let supervisor = match restart { Ok(supervisor) => supervisor, - Err(error) => { + Err(RestartFailure { + source, + created_supervisor_pod, + }) => { // The restart patch may not have recorded the sandbox instance yet. self.remove_shared_instance(&placement); - if let Err(rollback_error) = self.stop_sandbox_inner(sandbox_id).await { + if let Err(rollback_error) = self + .roll_back_restart( + &sandbox_api, + cr_name, + claim, + &namespace, + sandbox_id, + created_supervisor_pod.as_deref(), + ) + .await + { return Err(KubernetesDriverError::Message(format!( - "restart failed: {error}; rollback remains pending: {rollback_error}" + "restart failed: {source}; rollback remains pending: {rollback_error}" ))); } - return Err(error); + return Err(source); } }; Ok(kubernetes_runtime_identity( @@ -4677,11 +4639,9 @@ impl KubernetesComputeDriver { SandboxRuntimeBootstrapPhase::Releasing | SandboxRuntimeBootstrapPhase::Suspending ) ) { - patch_dynamic_object_with_resource_version_retry( - &agent_sandbox_api.api, - &kube_name, - sandbox_runtime_stop_begin_patch, - ) + compare_and_patch_dynamic_object(&agent_sandbox_api.api, &kube_name, |current| { + Ok(sandbox_runtime_stop_begin_patch(resource_version(current)?)) + }) .await?; } @@ -4725,6 +4685,55 @@ impl KubernetesComputeDriver { } } + /// Roll back a failed restart. While the claim holds, suspend the + /// Sandbox, delete the supervisor Pod this request created, and stop the + /// sandbox. Once another transition has replaced the claim, such as + /// another replica's restart or the lease holder's suspension, leave the + /// Sandbox to it and delete only the created Pod. + /// + /// The stop is not claim-aware yet (#6110): if another start completes the + /// same stop and claims the Sandbox before this stop's last poll, this + /// stop can still remove that start's supervisor Pod. + async fn roll_back_restart( + &self, + sandbox_api: &AgentSandboxApi, + cr_name: &str, + claim: SandboxRuntimeBootstrapClaim<'_>, + namespace: &str, + sandbox_id: &str, + created_supervisor_pod: Option<&str>, + ) -> Result<(), KubernetesDriverError> { + let suspended = suspend_if_claimed(sandbox_api, cr_name, claim).await?; + if let Some(uid) = created_supervisor_pod { + self.delete_created_supervisor_pod(namespace, sandbox_id, uid) + .await?; + } + if suspended { + self.stop_sandbox_inner(sandbox_id).await?; + } + Ok(()) + } + + /// Delete this sandbox's supervisor Pod only if it is still the Pod with + /// `uid`, leaving one another request created under the same name. + async fn delete_created_supervisor_pod( + &self, + namespace: &str, + sandbox_id: &str, + uid: &str, + ) -> Result<(), KubernetesDriverError> { + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(pod) = pods + .get_opt(&SandboxRuntimeNames::new(sandbox_id).supervisor_pod) + .await + .map_err(KubernetesDriverError::from_kube)? + && pod.metadata.uid.as_deref() == Some(uid) + { + delete_supervisor_pod_and_wait(&pods, pod).await?; + } + Ok(()) + } + async fn delete_sandbox_runtime_supervisor_pod( &self, sandbox_id: &str, @@ -5544,7 +5553,9 @@ impl KubernetesComputeDriver { ) { return; } - if sandbox_runtime_bootstrap_operation(object) != Some("create") { + if sandbox_runtime_bootstrap_operation(object) + != Some(SandboxRuntimeBootstrapOperation::Create) + { warn!( sandbox = object.metadata.name.as_deref().unwrap_or(""), "suspending stale sandbox-runtime restart bootstrap" @@ -6121,43 +6132,19 @@ fn sandbox_runtime_runtime_is_ready(object: &DynamicObject) -> bool { ready && !suspended } -fn sandbox_runtime_bootstrap_in_progress(object: &DynamicObject) -> bool { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING)) - .is_some_and(|value| value == "true") -} - -fn sandbox_runtime_bootstrap_operation(object: &DynamicObject) -> Option<&str> { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION)) - .map(String::as_str) -} - 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) && matches!( sandbox_runtime_bootstrap_operation(object), - Some("create" | "restart") + Some( + SandboxRuntimeBootstrapOperation::Create + | SandboxRuntimeBootstrapOperation::Restart + ) ) && sandbox_runtime_runtime_is_ready(object) } -fn sandbox_runtime_bootstrap_phase(object: &DynamicObject) -> Option { - object - .metadata - .annotations - .as_ref() - .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE)) - .and_then(|value| SandboxRuntimeBootstrapPhase::parse(value)) -} - fn sandbox_runtime_generation(object: &DynamicObject) -> Option<&str> { object .metadata @@ -6167,20 +6154,6 @@ fn sandbox_runtime_generation(object: &DynamicObject) -> Option<&str> { .map(String::as_str) } -fn sandbox_runtime_bootstrap_phase_patch( - resource_version: &str, - phase: SandboxRuntimeBootstrapPhase, -) -> serde_json::Value { - serde_json::json!({ - "metadata": { - "resourceVersion": resource_version, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase.as_str(), - } - } - }) -} - fn sandbox_runtime_bootstrap_is_stale( object: &DynamicObject, now: SystemTime, @@ -7226,7 +7199,8 @@ fn sandbox_from_object_with_bootstrap_state( ) -> Result<(String, Sandbox), String> { let (name, mut sandbox) = sandbox_from_object(namespace, obj.clone())?; if sandbox_runtime_bootstrap_in_progress(obj) { - if sandbox_runtime_bootstrap_operation(obj) == Some("stop") { + if sandbox_runtime_bootstrap_operation(obj) == Some(SandboxRuntimeBootstrapOperation::Stop) + { mark_sandbox_runtime_stopping(&mut sandbox); } else { mark_sandbox_runtime_bootstrapping(&mut sandbox); @@ -8863,46 +8837,8 @@ fn sandbox_operating_state_patch( } } -/// Annotations that start a bootstrap transition and its grace period. -fn sandbox_runtime_bootstrap_claim( - operation: &str, - phase: SandboxRuntimeBootstrapPhase, - generation: Option<&str>, -) -> BTreeMap { - let mut annotations = BTreeMap::from([ - ( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), - "true".to_string(), - ), - ( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT.to_string(), - openshell_core::time::now_ms().to_string(), - ), - ( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION.to_string(), - operation.to_string(), - ), - ( - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE.to_string(), - phase.as_str().to_string(), - ), - ]); - if let Some(generation) = generation { - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), - generation.to_string(), - ); - } - annotations -} - fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value { - let mut annotations = - sandbox_runtime_bootstrap_claim("stop", SandboxRuntimeBootstrapPhase::Releasing, None); - annotations.insert( - ANNOTATION_SANDBOX_RUNTIME_READINESS.to_string(), - "unavailable".to_string(), - ); + let annotations = stop_annotations(SandboxRuntimeBootstrapPhase::Releasing); serde_json::json!({ "metadata": { "resourceVersion": resource_version, @@ -8911,24 +8847,6 @@ fn sandbox_runtime_stop_begin_patch(resource_version: &str) -> serde_json::Value }) } -/// Claim a stopped Sandbox for a restart before it creates the supervisor -/// Pod. The Running patch adds the generation's bindings. -fn sandbox_runtime_restart_begin_patch( - resource_version: &str, - generation: &str, -) -> serde_json::Value { - serde_json::json!({ - "metadata": { - "resourceVersion": resource_version, - "annotations": sandbox_runtime_bootstrap_claim( - "restart", - SandboxRuntimeBootstrapPhase::Preparing, - Some(generation), - ), - }, - }) -} - fn sandbox_runtime_suspension_patch( api_version: &str, resource_version: &str, @@ -8938,16 +8856,11 @@ fn sandbox_runtime_suspension_patch( } else { serde_json::json!({"replicas": 0}) }; + let annotations = stop_annotations(SandboxRuntimeBootstrapPhase::Suspending); serde_json::json!({ "metadata": { "resourceVersion": resource_version, - "annotations": { - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING: "true", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: openshell_core::time::now_ms().to_string(), - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "stop", - ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: SandboxRuntimeBootstrapPhase::Suspending.as_str(), - ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", - }, + "annotations": annotations, }, "spec": desired_state, }) @@ -10631,7 +10544,7 @@ mod tests { assert!(sandbox_runtime_bootstrap_in_progress(&object)); assert_eq!( sandbox_runtime_bootstrap_operation(&object), - Some("restart") + Some(SandboxRuntimeBootstrapOperation::Restart) ); let started_at = SystemTime::UNIX_EPOCH + started; assert!(!sandbox_runtime_bootstrap_is_stale( diff --git a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs index dc8a601330..1db9895955 100644 --- a/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs +++ b/crates/openshell-driver-kubernetes/src/lifecycle_tests.rs @@ -476,7 +476,10 @@ mod lifecycle_reconciliation { // before it gave up. let sandbox = format!("/apis/agents.x-k8s.io/{version}/namespaces/openshell/sandboxes/sandbox-cr"); - assert_eq!(requests_to(&requests, &http::Method::GET, &sandbox), 2, "{version}"); + assert!( + requests_to(&requests, &http::Method::GET, &sandbox) >= 2, + "{version}" + ); assert_eq!(mutations(&requests), vec![], "{version}"); } } @@ -538,6 +541,177 @@ mod lifecycle_reconciliation { } } + /// A Sandbox API whose reads return the next of `reads`, repeating the + /// last, and whose first patch conflicts when `conflict_first` is set. + fn claimed_sandbox_api( + reads: Vec, + conflict_first: bool, + ) -> (Api, RecordedRequests) { + let requests = RecordedRequests::default(); + let recorded = requests.clone(); + let reads = Arc::new(std::sync::Mutex::new(VecDeque::from(reads))); + let conflict = Arc::new(std::sync::atomic::AtomicBool::new(conflict_first)); + let service = tower::service_fn(move |request: http::Request| { + let method = request.method().clone(); + recorded + .lock() + .unwrap() + .push((method.clone(), request.uri().path().to_string())); + let mut reads = reads.lock().unwrap(); + let current = if reads.len() > 1 { + reads.pop_front().unwrap() + } else { + reads.front().unwrap().clone() + }; + let (status, body) = if method == http::Method::PATCH + && conflict.swap(false, std::sync::atomic::Ordering::SeqCst) + { + ( + http::StatusCode::CONFLICT, + serde_json::json!({ + "apiVersion": "v1", "kind": "Status", "status": "Failure", + "reason": "Conflict", "code": 409, "message": "object was modified" + }), + ) + } else { + (http::StatusCode::OK, current) + }; + async move { Ok::<_, std::convert::Infallible>(kube_test_response(status, body)) } + }); + let api = KubernetesComputeDriver::agent_sandbox_api( + Client::new(service, "openshell"), + SANDBOX_VERSION_V1BETA1, + "openshell", + ) + .api; + (api, requests) + } + + fn restart_claim() -> SandboxRuntimeBootstrapClaim<'static> { + SandboxRuntimeBootstrapClaim::new( + "cr-uid", + SandboxRuntimeBootstrapOperation::Restart, + "gen2", + ) + } + + fn our_restart_claim() -> serde_json::Value { + let mut object = fresh_claim(SANDBOX_VERSION_V1BETA1, "restart"); + object["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen2"); + object + } + + fn patches(requests: &RecordedRequests) -> usize { + requests + .lock() + .unwrap() + .iter() + .filter(|(method, _)| *method == http::Method::PATCH) + .count() + } + + // The lease holder suspends a Sandbox, for example after an admission + // failure, while a restart on another replica holds its claim. The + // restart's next write conflicts, rereads the suspension, and must fail + // so the restart rolls back instead of releasing the workload again. + #[tokio::test] + async fn claimed_writes_do_not_overwrite_another_transition() { + let suspended = snapshot( + SANDBOX_VERSION_V1BETA1, + Some(SandboxRuntimeBootstrapPhase::Suspending), + ); + let (api, requests) = claimed_sandbox_api(vec![our_restart_claim(), suspended], true); + let error = restart_claim() + .patch(&api, "sandbox-cr", |version| { + sandbox_operating_state_patch(SANDBOX_VERSION_V1BETA1, version, true) + }) + .await + .unwrap_err(); + assert!( + matches!(error, KubernetesDriverError::Precondition(_)), + "{error}" + ); + assert_eq!(patches(&requests), 1, "only the conflicting write was sent"); + + let (api, requests) = claimed_sandbox_api(vec![our_restart_claim()], true); + restart_claim().release(&api, "sandbox-cr").await.unwrap(); + assert_eq!(patches(&requests), 2, "a held claim retries the conflict"); + } + + #[tokio::test] + async fn restart_claims_only_an_unclaimed_stopped_sandbox() { + let mut other_generation = our_restart_claim(); + other_generation["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen3"); + let mut running = snapshot(SANDBOX_VERSION_V1BETA1, None); + running["spec"]["operatingMode"] = serde_json::json!("Running"); + for (name, current) in [ + ("another restart", other_generation), + ("our own claim", our_restart_claim()), + ( + "a stop", + snapshot( + SANDBOX_VERSION_V1BETA1, + Some(SandboxRuntimeBootstrapPhase::Releasing), + ), + ), + ("a running sandbox", running), + ] { + let (api, requests) = claimed_sandbox_api(vec![current], false); + let error = restart_claim() + .begin(&api, "sandbox-cr") + .await + .unwrap_err(); + assert!( + matches!(error, KubernetesDriverError::Precondition(_)), + "{name}: {error}" + ); + assert_eq!(patches(&requests), 0, "{name}"); + } + + let (api, requests) = claimed_sandbox_api(vec![snapshot(SANDBOX_VERSION_V1BETA1, None)], true); + restart_claim().begin(&api, "sandbox-cr").await.unwrap(); + assert_eq!(patches(&requests), 2); + } + + // A slow restart's claim (gen2) was taken over by a restart on another + // replica (gen3), which created its own supervisor Pod under the same + // name. The superseded restart's rollback must leave both alone. + #[tokio::test] + async fn superseded_restart_rollback_spares_the_other_restart() { + let mut other_restart = our_restart_claim(); + other_restart["metadata"]["annotations"][ANNOTATION_SANDBOX_RUNTIME_GENERATION] = + serde_json::json!("gen3"); + let (driver, requests) = other_replica_driver(SANDBOX_VERSION_V1BETA1, vec![other_restart]); + let sandbox_api = KubernetesComputeDriver::agent_sandbox_api( + driver.client.clone(), + SANDBOX_VERSION_V1BETA1, + "openshell", + ); + driver + .roll_back_restart( + &sandbox_api, + "sandbox-cr", + restart_claim(), + "openshell", + "sandbox-1", + Some("our-supervisor-uid"), + ) + .await + .unwrap(); + // It looked for its own Pod, found the other restart's, and kept it. + assert_eq!( + requests_to( + &requests, + &http::Method::GET, + "/api/v1/namespaces/openshell/pods/os-supervisor-sandbox-1" + ), + 1 + ); + assert_eq!(mutations(&requests), vec![]); + } + #[tokio::test] async fn supervisor_deletion_does_not_wait_for_a_replacement_pod() { let pod = |uid: &str| {