Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/openshell-core/src/extension_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
11 changes: 9 additions & 2 deletions crates/openshell-server/src/compute/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1355,6 +1356,7 @@ pub struct ComputeRuntime {
admission: openshell_core::resource_admission::DriverAdmissionConfig,
admission_acknowledgement: String,
driver: TracedDriver,
workload_references: Option<provider_workload::WorkloadReferenceClient>,
image_update_driver: Option<SharedComputeDriverConfigurationUpdates>,
app_endpoint_resolver: Option<SharedComputeDriverAppEndpoints>,
driver_info: ComputeDriverInfoSnapshot,
Expand Down Expand Up @@ -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(),
Expand Down Expand Up @@ -1653,7 +1656,8 @@ impl ComputeRuntime {
tracing_log_bus: TracingLogBus,
supervisor_sessions: Arc<SupervisorSessionRegistry>,
) -> Result<Self, ComputeError> {
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(),
Expand All @@ -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))
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
125 changes: 125 additions & 0 deletions crates/openshell-server/src/compute/provider_workload.rs
Original file line number Diff line number Diff line change
@@ -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<InterceptedService<Channel, TraceContextInterceptor>>;

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<LocalProcessHandle, Status> {
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>(sandbox.object_id())
.await
.map_err(|_| Status::unavailable("sandbox identity store unavailable"))?
.ok_or_else(stale_reference)?;
let expected_runtime = sandbox_compute_runtime_identity(&current);
if response.sandbox_id != sandbox.object_id()
|| response.generation_id != generation.as_str()
|| !active_generation(&current, 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"));
}
}
Loading