From 13fde4c0d1a49d4b3c8b612c2b9063327a9a2aa1 Mon Sep 17 00:00:00 2001 From: Shiju Date: Fri, 4 Dec 2026 17:00:22 +0530 Subject: [PATCH] feat(gateway): resolve the live workload for a sandbox generation Re-read the sandbox after the driver replies so a stop or generation change invalidates an in-flight lookup. Hold a pidfd while the caller obtains a grant. Signed-off-by: Shiju --- .../openshell-core/src/extension_protocol.rs | 3 + crates/openshell-server/src/compute/mod.rs | 11 +- .../src/compute/provider_workload.rs | 125 ++++++++++++++++++ 3 files changed, 137 insertions(+), 2 deletions(-) create mode 100644 crates/openshell-server/src/compute/provider_workload.rs diff --git a/crates/openshell-core/src/extension_protocol.rs b/crates/openshell-core/src/extension_protocol.rs index 66192142cb..f7f9df979c 100644 --- a/crates/openshell-core/src/extension_protocol.rs +++ b/crates/openshell-core/src/extension_protocol.rs @@ -162,6 +162,9 @@ pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata { ExtensionFamily::Compute => { supported_capabilities.push(COMPUTE_LAUNCH_AUTHENTICATION.to_string()); supported_capabilities.push(COMPUTE_ISOLATION_BACKEND.to_string()); + if cfg!(target_os = "linux") { + supported_capabilities.push(COMPUTE_WORKLOAD_REFERENCE.to_string()); + } supported_capabilities.push(COMPUTE_UPDATE_SANDBOX_CONFIGURATION.to_string()); } ExtensionFamily::SupervisorMiddleware => { diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 4853c4975d..a80c005723 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -7,6 +7,7 @@ pub mod driver_config; mod image_update; pub mod lease; mod mutation_guard; +mod provider_workload; pub mod provisioning_deadline; mod provisioning_operation; pub mod rootfs_tar; @@ -1355,6 +1356,7 @@ pub struct ComputeRuntime { admission: openshell_core::resource_admission::DriverAdmissionConfig, admission_acknowledgement: String, driver: TracedDriver, + workload_references: Option, image_update_driver: Option, app_endpoint_resolver: Option, driver_info: ComputeDriverInfoSnapshot, @@ -1479,6 +1481,7 @@ impl ComputeRuntime { Ok(Self { isolation_backend: None, driver: TracedDriver::new(driver, driver_name), + workload_references: None, image_update_driver: None, app_endpoint_resolver: None, admission: openshell_core::resource_admission::DriverAdmissionConfig::default(), @@ -1653,7 +1656,8 @@ impl ComputeRuntime { tracing_log_bus: TracingLogBus, supervisor_sessions: Arc, ) -> Result { - let driver = Arc::new(RemoteComputeDriver::new(endpoint.channel)); + let channel = endpoint.channel; + let driver = Arc::new(RemoteComputeDriver::new(channel.clone())); Self::from_driver( endpoint.name, driver.clone(), @@ -1665,7 +1669,8 @@ impl ComputeRuntime { supervisor_sessions, ) .await - .map(|runtime| { + .map(|mut runtime| { + runtime.configure_workload_references(channel); runtime .with_image_update_driver(Some(driver.clone())) .with_app_endpoint_resolver(Some(driver)) @@ -9421,6 +9426,7 @@ pub fn new_test_runtime_with_driver( ComputeRuntime { isolation_backend: None, driver: TracedDriver::new(driver, "test".to_string()), + workload_references: None, image_update_driver: None, app_endpoint_resolver: None, admission: openshell_core::resource_admission::DriverAdmissionConfig { @@ -10967,6 +10973,7 @@ mod tests { ComputeRuntime { isolation_backend: None, driver: TracedDriver::new(driver, "test-driver".to_string()), + workload_references: None, image_update_driver: None, app_endpoint_resolver: None, admission: openshell_core::resource_admission::DriverAdmissionConfig { diff --git a/crates/openshell-server/src/compute/provider_workload.rs b/crates/openshell-server/src/compute/provider_workload.rs new file mode 100644 index 0000000000..16b39e434f --- /dev/null +++ b/crates/openshell-server/src/compute/provider_workload.rs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Resolve the workload of a persisted sandbox generation on its trusted driver channel. + +use super::{ComputeRuntime, sandbox_compute_runtime_identity, sandbox_runtime_generation}; +use crate::otel_tracing::TraceContextInterceptor; +use openshell_core::extension_protocol::{COMPUTE_WORKLOAD_REFERENCE, has_capability}; +use openshell_core::proto::compute::v1::{ + ResolveWorkloadReferenceRequest, + compute_driver_workload_references_client::ComputeDriverWorkloadReferencesClient, +}; +use openshell_core::proto::{Sandbox, SandboxPhase}; +use openshell_core::workload_reference::LocalProcessHandle; +use openshell_core::{ObjectId, ObjectName}; +use tonic::{Status, service::interceptor::InterceptedService, transport::Channel}; + +pub(super) type WorkloadReferenceClient = + ComputeDriverWorkloadReferencesClient>; + +fn stale_reference() -> Status { + Status::failed_precondition("workload reference does not match the active sandbox generation") +} + +fn active_generation(sandbox: &Sandbox, generation: &str) -> bool { + matches!( + SandboxPhase::try_from(sandbox.phase()), + Ok(SandboxPhase::Provisioning | SandboxPhase::Starting | SandboxPhase::Ready) + ) && sandbox_runtime_generation(sandbox).is_ok_and(|value| value.as_str() == generation) +} + +impl ComputeRuntime { + pub(super) fn configure_workload_references(&mut self, channel: Channel) { + if cfg!(target_os = "linux") + && has_capability( + &self.driver_info.negotiated_extension.supported_capabilities, + COMPUTE_WORKLOAD_REFERENCE, + ) + { + self.workload_references = + Some(ComputeDriverWorkloadReferencesClient::with_interceptor( + channel, + TraceContextInterceptor, + )); + } + } + + /// Whether the connected driver can resolve a generation on this gateway's host. + #[must_use] + pub fn supports_provider_workload_process(&self) -> bool { + self.workload_references.is_some() + } + + /// Resolve a running workload for an already authorized sandbox session. + /// + /// The caller must keep the returned handle live through issuance and reauthorize + /// the session before releasing a token. Fetch a fresh reference after recovery: + /// a stored PID cannot identify a new process unambiguously. + pub async fn resolve_provider_workload_process( + &self, + sandbox: &Sandbox, + ) -> Result { + let mut driver = self.workload_references.clone().ok_or_else(|| { + Status::failed_precondition("compute driver has no local workload reference service") + })?; + let generation = sandbox_runtime_generation(sandbox).map_err(|_| stale_reference())?; + let response = driver + .resolve_workload_reference(ResolveWorkloadReferenceRequest { + sandbox_id: sandbox.object_id().to_owned(), + name: sandbox.object_name().to_owned(), + generation_id: generation.as_str().to_owned(), + }) + .await? + .into_inner(); + + // Reject a delayed reply for the previous launch or another engine object. + // Drivers with asynchronous provisioning bind the generation on the driver + // before they can resolve it, even if create returned no runtime identity. + let process = response.process.ok_or_else(stale_reference)?; + let current = self + .store + .get_message::(sandbox.object_id()) + .await + .map_err(|_| Status::unavailable("sandbox identity store unavailable"))? + .ok_or_else(stale_reference)?; + let expected_runtime = sandbox_compute_runtime_identity(¤t); + if response.sandbox_id != sandbox.object_id() + || response.generation_id != generation.as_str() + || !active_generation(¤t, generation.as_str()) + || (!expected_runtime.is_empty() && process.runtime_identity != expected_runtime) + { + return Err(stale_reference()); + } + tokio::task::spawn_blocking(move || { + let handle = LocalProcessHandle::capture(process.runtime_identity.clone(), process.pid) + .map_err(|_| stale_reference())?; + if handle.reference() != &process { + return Err(stale_reference()); + } + Ok(handle) + }) + .await + .map_err(|_| Status::unavailable("local workload lookup interrupted"))? + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::auth::sandbox_session::RUNTIME_GENERATION_ANNOTATION; + + #[test] + fn late_reference_requires_a_live_matching_generation() { + let mut sandbox = Sandbox::default(); + sandbox.metadata.get_or_insert_default().annotations.insert( + RUNTIME_GENERATION_ANNOTATION.to_owned(), + "generation-two".to_owned(), + ); + sandbox.set_phase(SandboxPhase::Ready as i32); + assert!(active_generation(&sandbox, "generation-two")); + assert!(!active_generation(&sandbox, "generation-one")); + sandbox.set_phase(SandboxPhase::Stopping as i32); + assert!(!active_generation(&sandbox, "generation-two")); + } +}