From ce38bf7a1be4677e64fae274b0704c6c6ce460fa Mon Sep 17 00:00:00 2001 From: mr-miles Date: Tue, 1 Dec 2026 23:18:26 +0000 Subject: [PATCH 1/3] feat(driver): add an optional shared host supervisor OPENSHELL_VM_SHARED_SUPERVISOR=true runs one openshell-supervisor --mode=shared process for every sandbox instead of one per sandbox. Off (the default), nothing changes. The gateway serves the shared supervisor's assignment stream only for its in-process Kubernetes driver, so the driver serves it itself, with openshell-supervisor-control's controller as a one-member pool: - the stream is on /@host.sock and accepts only the driver's own uid and a token the driver mints and renews in a file; - each launch assigns the generation's gateway-issued launch credentials, and the supervisor listens on that generation's runtime-initiated Unix control socket while it hosts it, so the guest side is unchanged and the gateway sees the same per-sandbox sessions; - stopping a sandbox asks the supervisor to let go of it and treats the control socket's removal as done. It needs a supervisor that dials a unix: assignment endpoint and serves a sandbox on its own socket (fork branch feat/shared-host-unix/mr-miles, not upstream); with the current pin every shared launch fails, so leave it off until the pin carries that change. There is no failover without a gateway-signed takeover grant: if the shared supervisor exits, its VMs fail and the next launch starts a new one. Supervisor identity, the additional destination CA and an upstream proxy are refused with it. Co-Authored-By: Claude Opus 5.5 --- README.md | 49 +- vendor/openshell/Cargo.lock | 31 +- vendor/openshell/Cargo.toml | 1 + .../crates/openshell-driver-vm/Cargo.toml | 5 + .../crates/openshell-driver-vm/README.md | 9 + .../crates/openshell-driver-vm/src/driver.rs | 480 +++++++-- .../openshell-driver-vm/src/isolation/mod.rs | 55 +- .../crates/openshell-driver-vm/src/lib.rs | 2 + .../crates/openshell-driver-vm/src/main.rs | 6 + .../src/registry_cache_tests.rs | 1 + .../src/shared_supervisor.rs | 949 ++++++++++++++++++ 11 files changed, 1515 insertions(+), 73 deletions(-) create mode 100644 vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs diff --git a/README.md b/README.md index 62baaf6..082205b 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,8 @@ The driver's `OPENSHELL_VM_DEFAULT_WORKDIR` (default `/sandbox`) sets the workin sandboxes whose image has none ([Image ENV and WORKDIR](#image-env-and-workdir)). The driver's `OPENSHELL_VM_SUPERVISOR_IDENTITY*` options (optional, off by default) are in [Supervisor identity](#supervisor-identity). +The driver's `OPENSHELL_VM_SHARED_SUPERVISOR` (default `false`) runs one host supervisor for +every sandbox; see [Shared supervisor](#shared-supervisor). The driver's `OPENSHELL_VM_MAX_VCPUS` and `OPENSHELL_VM_MAX_MEM_MIB` limit what a sandbox can request with `--cpu` and `--memory`, and `OPENSHELL_VM_MAX_OVERLAY_DISK_MIB`, `OPENSHELL_VM_FILES_ROOT` and `OPENSHELL_VM_FILES_MAX_BYTES` what it can request in its `driver_config`; see @@ -733,13 +735,56 @@ Limits: - This is not SPIRE. There is one trust domain, no federation, no X.509 SVIDs, and the attestation knows only the supervisor processes this driver started. +## Shared supervisor + +By default every sandbox gets its own host supervisor process, as upstream. Set +`OPENSHELL_VM_SHARED_SUPERVISOR=true` in the driver's environment to run one supervisor for +every sandbox on the host instead. This saves one supervisor's memory per sandbox. It is +experimental and off by default. + +The gateway needs no change: it sees the same per-sandbox supervisor sessions as with dedicated +supervisors. OpenShell's own shared supervisor topology is Kubernetes-only, because the gateway +hands out sandboxes only to an in-process driver. So here the driver does that part itself: + +- On the first launch, the driver starts `openshell-supervisor --mode=shared` and serves the + supervisor's private assignment stream on a Unix socket in its private socket directory. It + accepts only its own uid and a token it mints and renews in a file. The supervisor dials the + gateway itself for every sandbox session, with the gateway's CA (`guest_tls_ca`) when the + gateway uses TLS. +- Each launch hands the supervisor that generation's launch credentials (the ones a dedicated + supervisor receives). The supervisor listens on the VM's control socket while it hosts the + sandbox, as a dedicated supervisor does, so the guest side is unchanged. +- Stopping a sandbox asks the supervisor to stop it and waits until the supervisor lets go of + it, which removes the control socket, or until the usual shutdown grace runs out. Then it + stops the VM. + +This needs a supervisor that can dial a `unix:` assignment endpoint and serve a sandbox on its +own socket. Those changes are not upstream yet (fork branch +`feat/shared-host-unix/mr-miles`). Without them every launch with the shared supervisor +fails, so leave it off unless the pinned OpenShell revision includes them. + +Limits: + +- **No failover.** Moving a running sandbox to another supervisor needs a takeover grant signed + by the gateway. If the shared supervisor exits, every VM it supervised fails with + `ProcessExited`, as one would whose dedicated supervisor exited. The driver starts a new + supervisor for later launches. +- At most 256 sandboxes per driver. +- It cannot be combined with supervisor identity (`OPENSHELL_VM_SUPERVISOR_IDENTITY`), the + network supervisor additional CA, or an upstream proxy. The driver refuses to start with + any of them. +- Agent traces are not relayed: the upstream shared supervisor has no per-sandbox collector yet. +- Its logs and token are under `/shared-supervisor/`: `supervisor.log`, + `supervisor.err.log` and `token`. + ## What does not work - No virtiofs bind mounts and no GPU passthrough on Firecracker. A sandbox that asks for either is rejected at validation, not ignored. To get host files into a guest, use [`driver_config.files`](#per-sandbox-cpu-memory-disk-size-and-files), which copies them in. -- `[openshell.supervisor.network].additional_ca_bundle` and the shared supervisor pool - are rejected by the gateway for any external driver. +- `[openshell.supervisor.network].additional_ca_bundle` and the gateway's shared supervisor + pool are rejected by the gateway for any external driver. The driver has its own + [shared supervisor](#shared-supervisor). - Rootfs tar uploads need the driver and gateway on the same filesystem and UID. - `openshell-gateway config preflight` skips host-tool checks for an external driver; `openshell-firecracker-launcher check` covers the Firecracker ones. diff --git a/vendor/openshell/Cargo.lock b/vendor/openshell/Cargo.lock index bceac5f..93c0088 100644 --- a/vendor/openshell/Cargo.lock +++ b/vendor/openshell/Cargo.lock @@ -1002,7 +1002,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2546,6 +2546,7 @@ dependencies = [ "openshell-otel-test-support", "openshell-sandbox-backend", "openshell-spiffe", + "openshell-supervisor-control", "opentelemetry", "opentelemetry_sdk", "polling", @@ -2725,6 +2726,24 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-supervisor-control" +version = "0.0.0" +source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +dependencies = [ + "openshell-core", + "openshell-otel", + "openshell-sandbox-backend", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tokio-stream", + "tonic", + "tracing", +] + [[package]] name = "openssh" version = "0.11.6" @@ -3572,7 +3591,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3630,7 +3649,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3651,7 +3670,7 @@ dependencies = [ "security-framework", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4374,7 +4393,7 @@ dependencies = [ "getrandom 0.4.2", "once_cell", "rustix", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5160,7 +5179,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/vendor/openshell/Cargo.toml b/vendor/openshell/Cargo.toml index 74e9217..70ca3c9 100644 --- a/vendor/openshell/Cargo.toml +++ b/vendor/openshell/Cargo.toml @@ -20,6 +20,7 @@ repository = "https://github.com/NVIDIA/OpenShell" openshell-core = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false } openshell-isolation-interface = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-sandbox-backend = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } +openshell-supervisor-control = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-otel = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-otel-test-support = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } openshell-spiffe = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } diff --git a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml index 37c2dc6..07069b8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml +++ b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml @@ -28,6 +28,7 @@ openshell-core = { workspace = true, features = ["clap"] } openshell-isolation-interface = { workspace = true } openshell-sandbox-backend = { workspace = true } openshell-otel = { workspace = true, optional = true } +openshell-supervisor-control = { workspace = true, optional = true } base64 = { workspace = true, optional = true } bollard = { version = "0.20", features = ["ssh"], optional = true } @@ -62,6 +63,8 @@ zstd = { version = "0.14", optional = true } aws-lc-rs = { workspace = true, optional = true } axum = { version = "0.8", default-features = false, features = ["http1", "tokio"], optional = true } tonic-prost = { workspace = true, optional = true } +# Shared host supervisor (not in upstream): per-sandbox proxy CA material. +rcgen = { workspace = true, optional = true } [features] # Portable test instrumentation, independent of the compute runtime. @@ -100,6 +103,8 @@ compute-driver = [ "dep:axum", "dep:tonic-prost", "dep:tonic-build", + "dep:openshell-supervisor-control", + "dep:rcgen", ] ## Compile in telemetry support (forwards to openshell-core/telemetry). On by ## default; build with `--no-default-features` for a telemetry-free VM driver diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index 7e11538..a89fbe4 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -26,6 +26,15 @@ Changes from upstream: that attested process. It serves OIDC discovery and JWKS endpoints over HTTP. The server stub is generated in `build.rs` without `protoc`. See `src/supervisor_identity/` and "Supervisor identity" in the repository README. +- **Shared supervisor** (off by default, `OPENSHELL_VM_SHARED_SUPERVISOR`). One + `openshell-supervisor --mode=shared` process for every sandbox instead of one each. The + driver serves the supervisor's private `openshell.supervisor.host.v1` assignment stream + itself, on a private Unix socket with a driver-minted token, using + `openshell-supervisor-control`'s controller as a one-member pool. Each generation keeps the + dedicated runtime-initiated Unix control socket, which the shared supervisor listens on + while it hosts the sandbox, so the guest side is unchanged. Needs the fork's supervisor + changes (`feat/shared-host-unix/mr-miles`). See `src/shared_supervisor.rs` and "Shared + supervisor" in the repository README. - **CPU and memory limits.** Upstream ignores a template's `cpu_limit` and `memory_limit` (`sandbox create --cpu / --memory`) and reports both limits unsupported. Here they set the VM's vCPUs (whole CPUs only, up to `OPENSHELL_VM_MAX_VCPUS`, at most 32) and memory (256 MiB diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 86432b4..48762bc 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -27,6 +27,7 @@ use crate::rootfs::{ sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, validate_host_supervisor, write_rootfs_image_file, }; +use crate::shared_supervisor::{RouteState, SharedSupervisorHost, SharedSupervisorSettings}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; use bollard::Docker; use bollard::errors::Error as BollardError; @@ -264,6 +265,14 @@ const HOST_ADDITIONAL_CA_TEMP_SUFFIX: &str = ".tmp"; const DRIVER_ADMITTED_BACKEND: &str = openshell_sandbox_backend::BACKEND_NAME; const HOST_SUPERVISOR_BINARY: &str = "host-runtime/openshell-supervisor"; const VM_CONTROL_SOCKET: &str = "control.sock"; +/// Shared supervisor state under the driver's state directory (not in upstream). +const SHARED_SUPERVISOR_DIR: &str = "shared-supervisor"; +/// Shared supervisor per-sandbox files under the socket root, kept short for +/// Unix socket paths. `@` never appears in a sandbox ID, so it cannot collide +/// with a sandbox's socket directory. +const SHARED_SUPERVISOR_SOCKET_DIR: &str = "@s"; +/// The shared supervisor's assignment stream socket under the socket root. +const SHARED_SUPERVISOR_HOST_SOCKET: &str = "@host.sock"; const VM_CONTROL_PORT: u32 = 5500; /// Guest path of the driver-authored manifest enumerating which /// `init.d` drop-ins the guest init script is allowed to execute. @@ -497,6 +506,11 @@ pub struct VmDriverConfig { /// See [`crate::local_images`]. #[serde(default)] pub local_image_source: crate::local_images::LocalImageSourceConfig, + + /// Run one host supervisor for every sandbox instead of one per sandbox + /// (not in upstream). Off: one supervisor per sandbox, as upstream. + #[serde(default)] + pub shared_supervisor: bool, } /// Redacting `Debug` so a proxy URL or credential path never reaches a log. @@ -575,6 +589,7 @@ impl std::fmt::Debug for VmDriverConfig { &self.image_cache_max_idle_hours, ) .field("local_image_source", &self.local_image_source) + .field("shared_supervisor", &self.shared_supervisor) .finish() } } @@ -628,6 +643,7 @@ impl Default for VmDriverConfig { sandbox_storage: crate::sandbox_storage::SandboxStorageConfig::default(), image_cache_max_idle_hours: 0, local_image_source: crate::local_images::LocalImageSourceConfig::default(), + shared_supervisor: false, } } } @@ -665,6 +681,35 @@ impl VmDriverConfig { Ok(()) } + /// The shared supervisor runs every sandbox with the same settings and + /// without per-sandbox supervisor processes, so options that need either + /// are refused rather than silently dropped. + pub fn validate_shared_supervisor_config(&self) -> Result<(), String> { + if !self.shared_supervisor { + return Ok(()); + } + let refused = [ + ( + self.supervisor_identity.enabled, + "supervisor identity (OPENSHELL_VM_SUPERVISOR_IDENTITY) attests one supervisor process per sandbox", + ), + ( + self.additional_ca_bundle.is_some() || self.additional_ca_snapshot.is_some(), + "the shared supervisor does not support the network supervisor additional destination CA", + ), + ( + self.upstream_proxy.https_proxy.is_some(), + "the shared supervisor does not support an upstream proxy", + ), + ]; + match refused.iter().find(|(set, _)| *set) { + Some((_, reason)) => Err(format!( + "OPENSHELL_VM_SHARED_SUPERVISOR cannot be combined with this configuration: {reason}" + )), + None => Ok(()), + } + } + /// Most memory a sandbox may request: `max_mem_mib`, or `mem_mib` when /// unset. pub fn effective_max_mem_mib(&self) -> u32 { @@ -1261,10 +1306,29 @@ struct HostSupervisor { supervisor_identity: Option, } +/// A sandbox's place on the shared host supervisor (not in upstream). +#[derive(Debug)] +struct SharedAttachment { + host: Arc, + route: String, + /// The VM's control socket, which the supervisor listens on while it + /// hosts the sandbox and unlinks when it lets go of it. + control_socket: PathBuf, +} + +impl Drop for SharedAttachment { + fn drop(&mut self) { + self.host.forget(&self.route); + } +} + #[derive(Debug)] struct VmProcess { child: Child, - supervisor: Child, + /// The sandbox's dedicated host supervisor; `None` on the shared one. + supervisor: Option, + /// The sandbox's route on the shared supervisor (not in upstream). + shared: Option, supervisor_liveness: Option, /// This sandbox's Workload API, while supervisor identity is enabled. supervisor_identity: Option, @@ -1373,6 +1437,9 @@ pub struct VmDriver { supervisor_identity: Option>, /// Where the driver is in its shutdown ([`VmDriver::shutdown`]). shutdown: Arc>, + /// The host supervisor every sandbox shares, started by the first launch + /// while `shared_supervisor` is on (not in upstream). + shared_supervisor: Arc>>, } /// The driver's progress through [`VmDriver::shutdown`]. @@ -1431,6 +1498,7 @@ impl VmDriver { .map_err(|err| err.message().to_string())?; config.validate_sandbox_identity()?; config.validate_runtime_security_config()?; + config.validate_shared_supervisor_config()?; config.local_image_source.validate()?; info!( mode = config.local_image_source.mode.as_str(), @@ -1529,6 +1597,7 @@ impl VmDriver { lifecycle_extensions: Arc::new(lifecycle_extensions), shutdown: new_shutdown_state(), supervisor_identity, + shared_supervisor: Arc::default(), }; preparation::reconcile(&image_cache_root_dir(&driver.config.state_dir)) .map_err(|error| format!("reconcile image preparation staging: {error}"))?; @@ -1662,6 +1731,96 @@ impl VmDriver { .map_err(|error| Status::internal(format!("stage host additional CA: {error}"))) } + /// The shared host supervisor, started on first use (not in upstream). + async fn shared_supervisor_host( + &self, + tls_paths: Option<&VmDriverTlsPaths>, + ) -> Result, Status> { + if let Some(host) = self.shared_supervisor.get() { + return Ok(host.clone()); + } + let supervisor_binary = self.host_supervisor_binary().await?; + let (gateway_endpoint, gateway_tls_server_name) = + host_control_openshell_endpoint(&self.config.grpc_endpoint) + .map_err(Status::failed_precondition)?; + let mut environment = vec![ + ( + openshell_core::sandbox_env::LOG_LEVEL.to_string(), + self.config.log_level.clone(), + ), + ( + openshell_core::sandbox_env::TELEMETRY_ENABLED.to_string(), + openshell_core::telemetry::enabled_env_value().to_string(), + ), + ]; + if let Some(name) = &self.config.supervisor_gateway_name { + environment.push(( + openshell_core::sandbox_env::GATEWAY_NAME.to_string(), + name.clone(), + )); + } + let settings = SharedSupervisorSettings { + supervisor_binary, + dir: self.config.state_dir.join(SHARED_SUPERVISOR_DIR), + session_root: self.socket_root.join(SHARED_SUPERVISOR_SOCKET_DIR), + host_socket: self.socket_root.join(SHARED_SUPERVISOR_HOST_SOCKET), + gateway_endpoint, + gateway_tls_server_name, + gateway_ca: tls_paths.map(|paths| paths.ca.clone()), + environment, + args: self.config.ipv6_egress.supervisor_args(), + }; + self.shared_supervisor + .get_or_try_init(|| async { SharedSupervisorHost::start(settings) }) + .await + .cloned() + .map_err(|error| Status::unavailable(format!("start the shared supervisor: {error}"))) + } + + /// Hand one generation to the shared supervisor, which listens on its + /// control socket while it hosts it (not in upstream). + #[allow(clippy::too_many_arguments)] + async fn attach_shared_supervisor( + &self, + sandbox: &Sandbox, + route: &str, + runtime_descriptor: &SandboxRuntimeDescriptor, + auth_bundle: &openshell_core::jwt::SupervisorAuthBundle, + image_ref: &str, + workdir: Option<&str>, + tls_paths: Option<&VmDriverTlsPaths>, + control_socket: &Path, + ) -> Result { + let host = self.shared_supervisor_host(tls_paths).await?; + let main_process_spec = openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec( + sandbox.spec.as_ref(), + ) + .map_err(|error| Status::internal(format!("encode main process spec: {error}")))?; + let (assignment, auth_epoch) = crate::shared_supervisor::InstanceLaunch { + route: route.to_string(), + sandbox_id: sandbox.id.clone(), + sandbox_name: sandbox.name.clone(), + runtime_descriptor: runtime_descriptor.clone(), + auth: auth_bundle.clone(), + main_process_spec, + workdir: workdir.map(str::to_string), + container_image: image_ref.to_string(), + } + .into_assignment() + .map_err(Status::internal)?; + // From here the attachment forgets the route if the launch fails. + let attachment = SharedAttachment { + host: host.clone(), + route: route.to_string(), + control_socket: control_socket.to_path_buf(), + }; + host.launch(assignment, auth_epoch) + .await + .map_err(Status::unavailable)?; + info!(sandbox_id = %sandbox.id, %route, "vm driver: sandbox assigned to the shared supervisor"); + Ok(attachment) + } + #[allow(clippy::too_many_arguments)] async fn spawn_host_supervisor( &self, @@ -2408,6 +2567,13 @@ impl VmDriver { server_name: channel_tls.server_name.clone(), trust_anchor_pem: channel_tls.trust_anchor_pem.clone(), }; + // The shared supervisor listens on the same control socket a dedicated + // one does, while it hosts the sandbox; a route keys the generation + // on it and never goes on the wire. + let shared_route = self + .config + .shared_supervisor + .then(openshell_sandbox_backend::runtime_routed::new_route_handle); let transport = SandboxTransport::RuntimeInitiatedUnix { socket_path: control_socket.clone(), }; @@ -2482,6 +2648,24 @@ impl VmDriver { command.arg("--vm-vcpus").arg(plan.vcpus.to_string()); command.arg("--vm-mem-mib").arg(plan.mem_mib.to_string()); let _ = tokio::fs::remove_file(&control_socket).await; + // The shared supervisor takes the generation before the VM boots and + // listens on its control socket, as a dedicated supervisor would. + let mut shared_attachment = match &shared_route { + Some(route) => Some( + self.attach_shared_supervisor( + &sandbox, + route, + &runtime_descriptor, + &launch_authentication.supervisor, + &image_ref, + workdir.as_deref(), + tls_paths.as_ref(), + &control_socket, + ) + .await?, + ), + None => None, + }; command .arg("--vm-vsock-runtime-initiated") .arg("--vm-vsock-control-port") @@ -2549,38 +2733,51 @@ impl VmDriver { launcher_pid = child.id().unwrap_or(0), "vm driver: launcher spawned" ); - let host_supervisor = match self - .spawn_host_supervisor( - &sandbox, - &state_dir, - tls_paths.as_ref(), - &runtime_descriptor, - &launch_authentication.supervisor, - sandbox_owner_state, - workdir.as_deref(), - ) - .await - { - Ok(supervisor) => supervisor, - Err(error) => { - let _ = terminate_vm_process(&mut child).await; - self.lifecycle_extensions - .after_launch_failed( - &sandbox, - &state_dir, - LaunchAbortReason::LauncherSpawnFailed, - ) - .await; - return Err(error); + let process = if let Some(shared) = shared_attachment.take() { + VmProcess { + child, + supervisor: None, + shared: Some(shared), + supervisor_liveness: None, + deleting: false, + supervisor_identity: None, + } + } else { + let host_supervisor = match self + .spawn_host_supervisor( + &sandbox, + &state_dir, + tls_paths.as_ref(), + &runtime_descriptor, + &launch_authentication.supervisor, + sandbox_owner_state, + workdir.as_deref(), + ) + .await + { + Ok(supervisor) => supervisor, + Err(error) => { + let _ = terminate_vm_process(&mut child).await; + self.lifecycle_extensions + .after_launch_failed( + &sandbox, + &state_dir, + LaunchAbortReason::LauncherSpawnFailed, + ) + .await; + return Err(error); + } + }; + VmProcess { + child, + supervisor: Some(host_supervisor.child), + shared: None, + supervisor_liveness: host_supervisor.liveness, + deleting: false, + supervisor_identity: host_supervisor.supervisor_identity, } }; - let process = Arc::new(Mutex::new(VmProcess { - child, - supervisor: host_supervisor.child, - supervisor_liveness: host_supervisor.liveness, - deleting: false, - supervisor_identity: host_supervisor.supervisor_identity, - })); + let process = Arc::new(Mutex::new(process)); let mut process_to_stop = None; let mut snapshot_to_publish = None; @@ -5389,12 +5586,25 @@ impl VmDriver { if process.deleting { return; } + let process = &mut *process; + let exited = |component: &'static str, status: ExitStatus| { + let message = status.code().map_or_else( + || format!("{component} process exited"), + |code| format!("{component} process exited with status {code}"), + ); + (component, message) + }; match process.child.try_wait() { - Ok(Some(status)) => Ok(Some(("VM", status))), - Ok(None) => process - .supervisor - .try_wait() - .map(|status| status.map(|status| ("host supervisor", status))), + Ok(Some(status)) => Ok(Some(exited("VM", status))), + Ok(None) => match (process.supervisor.as_mut(), process.shared.as_ref()) { + (Some(supervisor), _) => supervisor + .try_wait() + .map(|status| status.map(|status| exited("host supervisor", status))), + (None, Some(shared)) => { + Ok(shared_route_exit(&shared.host.route_state(&shared.route))) + } + (None, None) => Ok(None), + }, Err(error) => Err(error), } }; @@ -5425,7 +5635,7 @@ impl VmDriver { } }; - if let Some((component, status)) = exit_status { + if let Some((component, mut message)) = exit_status { let state_dir = { let registry = self.registry.lock().await; registry @@ -5447,16 +5657,17 @@ impl VmDriver { } { let mut process = process.lock().await; + // The shared supervisor's route goes with the VM either + // way; dropping the attachment withdraws it. + process.shared.take(); if component == "VM" { - let _ = terminate_vm_process(&mut process.supervisor).await; + if let Some(supervisor) = process.supervisor.as_mut() { + let _ = terminate_vm_process(supervisor).await; + } } else { let _ = terminate_vm_process(&mut process.child).await; } } - let mut message = status.code().map_or_else( - || format!("{component} process exited"), - |code| format!("{component} process exited with status {code}"), - ); if component == "host supervisor" && let Some(state_dir) = state_dir.as_deref() && let Some(stderr) = read_vm_console_tail( @@ -5598,6 +5809,7 @@ pub async fn run_image_preparation_worker(request_path: &Path) -> Result<(), Str lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let prepare = async { if let Some(overlay) = request.overlay { @@ -8207,21 +8419,31 @@ async fn terminate_sandbox_processes_within( process: &mut VmProcess, supervisor_grace: Duration, ) -> Result<(), std::io::Error> { - let supervisor_pid = process.supervisor.id(); - let supervisor_error = terminate_vm_process_within(&mut process.supervisor, supervisor_grace) - .await - .inspect(|status| { - // An orderly shutdown returns the workload's exit code, which can - // be nonzero even after the guest acknowledges termination. - if status.signal().is_some() { - warn!( - ?supervisor_pid, - %status, - "VM host supervisor was terminated by a signal; guest filesystem flush was not confirmed and recent writes may be lost" - ); - } - }) - .err(); + if let Some(shared) = process.shared.take() { + // The shared supervisor stops the workload as a dedicated one does on + // SIGTERM; the VM is killed once it has, or once the grace runs out. + stop_shared_route(&shared, &mut process.child, supervisor_grace).await; + } + let supervisor_error = match process.supervisor.as_mut() { + Some(supervisor) => { + let supervisor_pid = supervisor.id(); + terminate_vm_process_within(supervisor, supervisor_grace) + .await + .inspect(|status| { + // An orderly shutdown returns the workload's exit code, which can + // be nonzero even after the guest acknowledges termination. + if status.signal().is_some() { + warn!( + ?supervisor_pid, + %status, + "VM host supervisor was terminated by a signal; guest filesystem flush was not confirmed and recent writes may be lost" + ); + } + }) + .err() + } + None => None, + }; process.supervisor_liveness.take(); // The supervisor is gone: stop its Workload API and remove the socket // and the binary link. @@ -8238,6 +8460,54 @@ async fn terminate_sandbox_processes_within( } } +/// What a shared supervisor route's state means for its VM: the component +/// that ended and why, or `None` while it runs (not in upstream). +fn shared_route_exit(state: &RouteState) -> Option<(&'static str, String)> { + match state { + RouteState::Pending | RouteState::Running => None, + RouteState::Exited(code) => Some(( + "workload", + format!("workload process exited with status {code}"), + )), + RouteState::Failed(error) => Some(( + "shared supervisor", + format!("shared supervisor could not run the sandbox: {error}"), + )), + RouteState::Lost => Some(( + "shared supervisor", + "the shared supervisor process that ran this sandbox exited".to_string(), + )), + } +} + +/// Withdraw a sandbox from the shared supervisor and wait, up to `grace`, +/// for the supervisor to let go of it: once it has stopped the workload it +/// drops the sandbox, which unlinks the control socket, as a dedicated +/// supervisor exits. Its status is no longer reported once withdrawn, so the +/// socket is the signal. Dropping the attachment then forgets the route (not +/// in upstream). +async fn stop_shared_route(shared: &SharedAttachment, vm: &mut Child, grace: Duration) { + const POLL: Duration = Duration::from_millis(100); + shared.host.withdraw(&shared.route); + let deadline = tokio::time::Instant::now() + grace; + while tokio::time::Instant::now() < deadline { + if matches!(vm.try_wait(), Ok(Some(_)) | Err(_)) + || !shared.control_socket.exists() + || matches!( + shared.host.route_state(&shared.route), + RouteState::Exited(_) | RouteState::Failed(_) | RouteState::Lost + ) + { + return; + } + tokio::time::sleep(POLL).await; + } + warn!( + route = %shared.route, + "the shared supervisor did not confirm the sandbox stopped in time; guest filesystem flush was not confirmed and recent writes may be lost" + ); +} + fn absolute_state_dir(state_dir: &Path) -> Result { if state_dir.is_absolute() { return Ok(state_dir.to_path_buf()); @@ -11757,6 +12027,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!(driver.capabilities().default_image, "openshell/sandbox:dev"); @@ -12020,6 +12291,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12057,6 +12329,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12088,6 +12361,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let sandbox = Sandbox { spec: Some(SandboxSpec { @@ -12120,6 +12394,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!( @@ -12147,6 +12422,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; assert_eq!( @@ -12171,6 +12447,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let error = driver @@ -12205,6 +12482,57 @@ mod tests { } } + #[test] + fn shared_supervisor_refuses_settings_it_cannot_apply_per_sandbox() { + let shared = VmDriverConfig { + shared_supervisor: true, + ..VmDriverConfig::default() + }; + assert!(shared.validate_shared_supervisor_config().is_ok()); + + let mut with_identity = shared.clone(); + with_identity.supervisor_identity.enabled = true; + let error = with_identity + .validate_shared_supervisor_config() + .unwrap_err(); + assert!(error.contains("OPENSHELL_VM_SHARED_SUPERVISOR"), "{error}"); + + let mut with_proxy = shared.clone(); + with_proxy.upstream_proxy.https_proxy = Some("http://proxy.example:3128".to_string()); + assert!(with_proxy.validate_shared_supervisor_config().is_err()); + + let mut with_ca = shared; + with_ca.additional_ca_bundle = Some(PathBuf::from("/etc/openshell/extra-ca.pem")); + assert!(with_ca.validate_shared_supervisor_config().is_err()); + + // Off, the same settings are accepted, as before. + let mut dedicated = with_identity; + dedicated.shared_supervisor = false; + assert!(dedicated.validate_shared_supervisor_config().is_ok()); + } + + #[test] + fn shared_route_exit_ends_the_vm_only_when_supervision_ends() { + assert_eq!(shared_route_exit(&RouteState::Pending), None); + assert_eq!(shared_route_exit(&RouteState::Running), None); + assert_eq!( + shared_route_exit(&RouteState::Exited(3)), + Some(( + "workload", + "workload process exited with status 3".to_string() + )) + ); + assert_eq!( + shared_route_exit(&RouteState::Lost).map(|(component, _)| component), + Some("shared supervisor") + ); + assert_eq!( + shared_route_exit(&RouteState::Failed("boom".to_string())) + .map(|(component, _)| component), + Some("shared supervisor") + ); + } + #[tokio::test] async fn supervisor_identity_disabled_creates_no_issuer_or_key() { let temp = tempfile::tempdir().unwrap(); @@ -13079,6 +13407,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_file = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13109,7 +13438,8 @@ mod tests { record.state_dir = retry_state_dir; record.process = Some(Arc::new(Mutex::new(VmProcess { child: spawn_exited_child(), - supervisor: spawn_exited_child(), + supervisor: Some(spawn_exited_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13148,6 +13478,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13205,6 +13536,7 @@ mod tests { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), }; let state_dir = sandbox_state_dir(&driver_state, "sandbox-123").unwrap(); @@ -13709,7 +14041,8 @@ while :; do sleep 0.05; done"#, let mut process = VmProcess { child: spawn_exited_child(), - supervisor, + supervisor: Some(supervisor), + shared: None, supervisor_liveness: Some(fs::File::from(write_end)), supervisor_identity: None, deleting: false, @@ -13791,7 +14124,8 @@ while :; do sleep 0.05; done"#, let mut process = VmProcess { child: spawn_exited_child(), - supervisor, + supervisor: Some(supervisor), + shared: None, supervisor_liveness: Some(fs::File::from(write_end)), supervisor_identity: None, deleting: false, @@ -13808,7 +14142,13 @@ while :; do sleep 0.05; done"#, "the supervisor must get its full grace before the kill: {elapsed:?}" ); assert!( - process.supervisor.try_wait().unwrap().is_some(), + process + .supervisor + .as_mut() + .unwrap() + .try_wait() + .unwrap() + .is_some(), "the supervisor is gone once the grace has expired" ); assert!(process.supervisor_liveness.is_none()); @@ -13843,7 +14183,8 @@ while :; do sleep 0.05; done"#, }; let process = Arc::new(Mutex::new(VmProcess { child, - supervisor: spawn_exited_child(), + supervisor: Some(spawn_exited_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13882,7 +14223,8 @@ while :; do sleep 0.05; done"#, ) -> Arc> { let process = Arc::new(Mutex::new(VmProcess { child: spawn_running_child(), - supervisor: spawn_running_child(), + supervisor: Some(spawn_running_child()), + shared: None, supervisor_liveness: None, supervisor_identity: None, deleting: false, @@ -13969,7 +14311,15 @@ while :; do sleep 0.05; done"#, { let mut process = process.lock().await; assert!(process.deleting); - assert!(process.supervisor.try_wait().unwrap().is_some()); + assert!( + process + .supervisor + .as_mut() + .unwrap() + .try_wait() + .unwrap() + .is_some() + ); assert!(process.child.try_wait().unwrap().is_some()); } for marker in [SANDBOX_STOPPED_FILE, MAIN_PROCESS_EXITED_FILE] { @@ -14110,6 +14460,7 @@ while :; do sleep 0.05; done"#, lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } @@ -14458,6 +14809,7 @@ while :; do sleep 0.05; done"#, lifecycle_extensions: Arc::new(extensions), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } diff --git a/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs b/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs index e054a1b..133a346 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/isolation/mod.rs @@ -102,7 +102,11 @@ impl VmBoundarySpec { tls: self.sandbox_tls, } } - SandboxTransport::RuntimeInitiatedUnix { .. } => { + // A shared supervisor's route (not in upstream): the + // guest dials the same vsock port, and the driver relays + // it to the routed listener with the route prefixed. + SandboxTransport::RuntimeInitiatedUnix { .. } + | SandboxTransport::RuntimeInitiatedRouted { .. } => { BoundaryListener::RuntimeInitiatedVsock { host_port: self.control_port, tls: self.sandbox_tls, @@ -166,6 +170,55 @@ mod tests { ); } + #[test] + fn routed_transport_keeps_the_guest_on_runtime_initiated_vsock() { + let session_id = openshell_core::SandboxSessionId::new(); + let material = generate_sandbox_tls_material(session_id).unwrap(); + let route = openshell_sandbox_backend::runtime_routed::new_route_handle(); + let provisioned = VmBoundarySpec { + boundary_id: "sandbox-1".to_string(), + generation: "generation-1".to_string(), + session_id, + session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), + auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + gateway_id: "gateway-1".to_string(), + verification_keys: Vec::new(), + image_identity: "sha256:image".to_string(), + transport: SandboxTransport::RuntimeInitiatedRouted { + authority: material.server_name.clone(), + route: route.clone(), + }, + supervisor_tls: SandboxTlsClientConfig { + server_name: material.server_name, + trust_anchor_pem: material.trust_anchor_pem, + }, + sandbox_tls: SandboxTlsServerConfig { + certificate_chain_path: "/.openshell/state/sandbox.crt".into(), + private_key_path: "/.openshell/state/sandbox.key".into(), + }, + control_port: 5500, + agent_uid: 1000, + agent_gid: 1000, + child_env: HashMap::new(), + } + .provision() + .unwrap(); + assert!(matches!( + provisioned.boundary_config.listener, + BoundaryListener::RuntimeInitiatedVsock { + host_port: 5500, + .. + } + )); + assert_eq!( + provisioned.runtime_descriptor.transport, + SandboxTransport::RuntimeInitiatedRouted { + authority: provisioned.runtime_descriptor.tls.server_name.clone(), + route, + } + ); + } + #[test] fn provisioning_binds_identical_resource_claims() { assert_provisioning_claims(); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs index 620c927..262c6e5 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs @@ -37,6 +37,8 @@ mod rootfs; #[cfg(feature = "compute-driver")] pub mod sandbox_storage; #[cfg(feature = "compute-driver")] +mod shared_supervisor; +#[cfg(feature = "compute-driver")] pub mod supervisor_identity; mod version; diff --git a/vendor/openshell/crates/openshell-driver-vm/src/main.rs b/vendor/openshell/crates/openshell-driver-vm/src/main.rs index d1a273f..0086b2f 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/main.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/main.rs @@ -236,6 +236,11 @@ struct Args { #[arg(long, env = "OPENSHELL_VM_DEFAULT_WORKDIR", default_value = "/sandbox")] default_workdir: String, + /// Run one host supervisor shared by every sandbox instead of one per + /// sandbox. Off: a dedicated supervisor per sandbox, as upstream. + #[arg(long, env = "OPENSHELL_VM_SHARED_SUPERVISOR", default_value_t = false)] + shared_supervisor: bool, + /// Issue SPIFFE JWT-SVIDs to host supervisors over a per-sandbox Workload /// API socket, and serve the JWKS that verifies them. Off: no socket, no /// JWKS listener, nothing in the supervisor's environment. @@ -422,6 +427,7 @@ async fn main() -> Result<()> { args.local_image_source_socket.as_deref(), ) .map_err(|err| miette::miette!("{err}"))?, + shared_supervisor: args.shared_supervisor, }) .await .map_err(|err| miette::miette!("{err}"))?; diff --git a/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs b/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs index 1c90c15..9df6024 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/registry_cache_tests.rs @@ -188,6 +188,7 @@ fn driver(root: &Path) -> VmDriver { lifecycle_extensions: Arc::new(LifecycleExtensionRegistry::new()), shutdown: new_shutdown_state(), supervisor_identity: None, + shared_supervisor: Arc::default(), } } diff --git a/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs b/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs new file mode 100644 index 0000000..c53554d --- /dev/null +++ b/vendor/openshell/crates/openshell-driver-vm/src/shared_supervisor.rs @@ -0,0 +1,949 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! One host supervisor shared by every sandbox of this driver (not in +//! upstream). +//! +//! With `shared_supervisor` on, the driver runs one `openshell-supervisor +//! --mode=shared` process instead of one supervisor per VM. Upstream, a +//! shared supervisor takes its sandbox instances from the gateway over the +//! private `openshell.supervisor.host.v1` stream, which the gateway serves +//! only for its in-process Kubernetes driver. Here the driver serves that +//! stream itself on a private Unix socket, so the gateway is unchanged and +//! sees the same per-sandbox supervisor sessions as with dedicated +//! supervisors: +//! +//! - The driver's [`SupervisorHostController`] is a pool of one member: this +//! host. The driver hands it the complete pool view every time a sandbox +//! starts or stops; nothing is durable, since the driver stops every VM +//! when it stops. +//! - Each sandbox's launch material is built from the same gateway-issued +//! launch credentials a dedicated supervisor receives, with the same +//! runtime-initiated Unix control socket. The supervisor listens on it for +//! as long as it hosts the sandbox, so the guest side is exactly that of a +//! dedicated supervisor. The host dials the real gateway for every sandbox +//! session (`HostAccepted.peer_endpoint`). +//! - A route keys each sandbox on the supervisor. It never goes on the wire. +//! +//! This needs a supervisor that dials a `unix:` assignment endpoint and +//! serves a sandbox on its own socket (the fork's `patched` branch, from +//! `feat/shared-host-unix/mr-miles`). +//! +//! What it does not do: move a sandbox to another supervisor. Takeover needs +//! a gateway-signed grant, so a crashed shared supervisor loses every VM it +//! supervised; the driver stops them and starts a new supervisor for the +//! next launches. + +use std::collections::BTreeMap; +use std::net::{IpAddr, Ipv4Addr, SocketAddr}; +use std::path::{Path, PathBuf}; +use std::pin::Pin; +use std::sync::{Arc, Mutex as StdMutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use openshell_core::proto::supervisor_host::v1::supervisor_host_server::{ + SupervisorHost, SupervisorHostServer, +}; +use openshell_core::proto::supervisor_host::v1::{ + HostGatewayMessage, HostMessage, SandboxInstanceAssignment, SandboxInstancePhase, +}; +use openshell_supervisor_control::{ + DEFAULT_MAX_MEMBERS_PER_GATEWAY, HostIdentity, InstanceOwner, MemberView, ObservedInstance, + PoolLimits, PoolView, SupervisorHostController, +}; +use tokio::process::Command; +use tokio::sync::watch; +use tokio::task::JoinHandle; +use tonic::{Request, Response, Status, Streaming}; +use tracing::{debug, info, warn}; + +/// Pool member ID the shared supervisor announces; the only member. +pub const MEMBER_ID: &str = "openshell-vm-driver"; +/// Most sandboxes the shared supervisor runs. Sizes its message bounds too. +pub const MAX_INSTANCES: usize = 256; +/// Subject of the supervisor tokens the driver mints. +const TOKEN_SUBJECT: &str = "openshell-supervisor:openshell-vm-driver"; +/// Lifetime of one supervisor token. The controller ends the stream when the +/// token in use expires; the host reconnects with the renewed file. +const TOKEN_TTL: Duration = Duration::from_hours(12); +/// How often a new token is written; the previous one stays valid until it +/// expires, so a host that has not re-read the file yet keeps working. +const TOKEN_RENEWAL: Duration = Duration::from_hours(1); +/// How long a launch waits for the shared supervisor to be connected. +const CONNECT_WAIT: Duration = Duration::from_mins(1); +const RESPAWN_BACKOFF_MIN: Duration = Duration::from_secs(1); +const RESPAWN_BACKOFF_MAX: Duration = Duration::from_secs(30); +/// A supervisor that ran this long before exiting restarts with the shortest +/// backoff again. +const RESPAWN_STABLE_AFTER: Duration = Duration::from_mins(1); + +/// What the driver supplies to start the shared supervisor. +pub struct SharedSupervisorSettings { + /// The host supervisor binary, the same one dedicated supervisors run. + pub supervisor_binary: PathBuf, + /// Private directory for the token and the logs. + pub dir: PathBuf, + /// Private directory, short enough for Unix socket paths, for the + /// supervisor's per-sandbox files. + pub session_root: PathBuf, + /// The assignment stream's socket, also short enough for a socket path. + pub host_socket: PathBuf, + /// Gateway endpoint as a host supervisor dials it. + pub gateway_endpoint: String, + /// TLS server name the supervisor verifies the gateway with, when it + /// differs from the endpoint's host. + pub gateway_tls_server_name: Option, + /// The gateway's CA, when the gateway uses TLS. + pub gateway_ca: Option, + /// Extra supervisor environment (log level, telemetry). + pub environment: Vec<(String, String)>, + /// Extra supervisor arguments (policy DNS IPv6 egress, NAT64 prefixes). + pub args: Vec, +} +/// What the shared supervisor reports for one sandbox's route. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RouteState { + /// Assigned; the supervisor has not reported it running yet. + Pending, + /// The supervisor runs the sandbox. + Running, + /// The sandbox's canonical process exited. + Exited(i32), + /// The supervisor could not run the sandbox. + Failed(String), + /// The supervisor process that ran the sandbox is gone, or the route was + /// never assigned. Its workload cannot be supervised again. + Lost, +} + +/// One sandbox's route as the driver assigned it. +struct RouteEntry { + assignment: SandboxInstanceAssignment, + auth_epoch: u64, + /// Supervisor process the route was assigned to. + process_id: String, + /// Withdrawn: no longer desired, so its owner stops it, but still owned + /// so the driver can watch it stop. + withdrawn: bool, +} + +#[derive(Default)] +struct HostState { + /// The connected shared supervisor process. + process_id: Option, + routes: BTreeMap, +} + +/// The driver's shared supervisor: the process, its assignment stream, and +/// the routes of the sandboxes it supervises. +pub struct SharedSupervisorHost { + controller: SupervisorHostController, + runtime_address: SocketAddr, + state: StdMutex, + /// The connected supervisor process, `None` while there is none. + process: watch::Sender>, + tasks: StdMutex>>, +} + +impl std::fmt::Debug for SharedSupervisorHost { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("SharedSupervisorHost") + .field("runtime_address", &self.runtime_address) + .finish_non_exhaustive() + } +} + +impl Drop for SharedSupervisorHost { + fn drop(&mut self) { + for task in lock(&self.tasks).drain(..) { + task.abort(); + } + } +} + +impl SharedSupervisorHost { + /// Start the assignment listener and the shared supervisor process. + /// Returns once both are running; the supervisor connects in the + /// background, and [`Self::launch`] waits for it. + pub(crate) fn start(settings: SharedSupervisorSettings) -> Result, String> { + create_private_dir(&settings.dir)?; + create_private_dir(&settings.session_root)?; + + let token_path = settings.dir.join("token"); + let tokens = Arc::new(StdMutex::new(Tokens::new()?)); + write_private_file(&token_path, lock(&tokens).current.token.as_bytes())?; + + let _ = std::fs::remove_file(&settings.host_socket); + let listener = tokio::net::UnixListener::bind(&settings.host_socket).map_err(|error| { + format!( + "listen for the shared supervisor on {}: {error}", + settings.host_socket.display() + ) + })?; + set_private_mode(&settings.host_socket)?; + // The supervisor still opens its shared runtime listener and + // advertises it, though every sandbox here has its own socket. + let runtime_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), free_port()?); + let health_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), free_port()?); + + let controller = SupervisorHostController::new(); + controller.set_pool_limits( + PoolLimits::new(MAX_INSTANCES, DEFAULT_MAX_MEMBERS_PER_GATEWAY) + .map_err(|error| format!("shared supervisor pool limits: {error}"))?, + ); + controller.set_gateway_replicas(1); + // Sandbox sessions go to the real gateway, not to this socket. + controller.set_peer_endpoint(settings.gateway_endpoint.clone()); + + let host = Arc::new(Self { + controller: controller.clone(), + runtime_address, + state: StdMutex::new(HostState::default()), + process: watch::channel(None).0, + tasks: StdMutex::new(Vec::new()), + }); + // An empty view lets the first stream receive its (empty) snapshot. + host.publish(); + + let service = HostService { + controller, + tokens: tokens.clone(), + uid: rustix::process::geteuid().as_raw(), + }; + let serve = tokio::spawn(serve_assignments(listener, service)); + let renew = tokio::spawn(renew_tokens(tokens, token_path.clone())); + let watch_members = tokio::spawn(watch_membership(Arc::downgrade(&host))); + let command = SupervisorCommand { + binary: settings.supervisor_binary, + dir: settings.dir, + session_root: settings.session_root, + assignment_endpoint: format!("unix:{}", settings.host_socket.display()), + token_path, + gateway_ca: settings.gateway_ca, + gateway_tls_server_name: settings.gateway_tls_server_name, + runtime_address, + health_address, + environment: settings.environment, + args: settings.args, + }; + let keep = tokio::spawn(keep_supervisor(command, Arc::downgrade(&host))); + lock(&host.tasks).extend([serve, renew, watch_members, keep]); + info!( + assignments = %settings.host_socket.display(), + "vm driver: shared supervisor started" + ); + Ok(host) + } + + /// Assign a sandbox generation to the shared supervisor, which starts + /// supervising it once the guest dials in. Waits for a connected + /// supervisor process. + pub(crate) async fn launch( + &self, + assignment: SandboxInstanceAssignment, + auth_epoch: u64, + ) -> Result<(), String> { + let mut process = self.process.subscribe(); + let process_id = tokio::time::timeout(CONNECT_WAIT, process.wait_for(Option::is_some)) + .await + .map_err(|_| "the shared supervisor did not connect in time".to_string())? + .map_err(|_| "the shared supervisor stopped".to_string())? + .clone() + .ok_or_else(|| "the shared supervisor is not connected".to_string())?; + { + let mut state = lock(&self.state); + let route = assignment.route.clone(); + if !state.routes.contains_key(&route) && state.routes.len() >= MAX_INSTANCES { + return Err(format!( + "the shared supervisor already runs {MAX_INSTANCES} sandboxes" + )); + } + if state.process_id.as_deref() != Some(process_id.as_str()) { + return Err("the shared supervisor restarted; retry the launch".to_string()); + } + state.routes.insert( + route, + RouteEntry { + assignment, + auth_epoch, + process_id, + withdrawn: false, + }, + ); + } + self.publish(); + Ok(()) + } + + /// Ask the shared supervisor to stop a sandbox. The route stays owned so + /// [`Self::route_state`] can watch it stop; [`Self::forget`] drops it. + pub(crate) fn withdraw(&self, route: &str) { + let changed = lock(&self.state) + .routes + .get_mut(route) + .is_some_and(|entry| !std::mem::replace(&mut entry.withdrawn, true)); + if changed { + self.publish(); + } + } + + /// Drop a stopped sandbox's route. + pub(crate) fn forget(&self, route: &str) { + if lock(&self.state).routes.remove(route).is_some() { + self.publish(); + } + } + + /// What the shared supervisor reports for `route`. + pub(crate) fn route_state(&self, route: &str) -> RouteState { + { + let state = lock(&self.state); + let Some(entry) = state.routes.get(route) else { + return RouteState::Lost; + }; + if state.process_id.as_deref() != Some(entry.process_id.as_str()) { + return RouteState::Lost; + } + } + match self.controller.observed(route) { + ObservedInstance::Reported(status) => { + match SandboxInstancePhase::try_from(status.phase) + .unwrap_or(SandboxInstancePhase::Unspecified) + { + SandboxInstancePhase::Exited => RouteState::Exited(status.exit_code), + SandboxInstancePhase::Failed => RouteState::Failed(status.error), + SandboxInstancePhase::Supervising if status.ready => RouteState::Running, + _ => RouteState::Pending, + } + } + ObservedInstance::NoHost | ObservedInstance::Pending | ObservedInstance::Absent => { + RouteState::Pending + } + } + } + + /// Replace the controller's pool view with the driver's routes. The + /// controller sends the supervisor a snapshot of the routes it owns and + /// lists withdrawn ones for it to stop. + fn publish(&self) { + let view = { + let state = lock(&self.state); + pool_view(&state, self.runtime_address) + }; + self.controller + .update_pool(view, tokio::time::Instant::now()); + } + + /// A supervisor stream connected or ended. A new supervisor process loses + /// the routes of the one before it. + fn membership_changed(&self) { + let connected = self + .controller + .connected_members() + .into_iter() + .filter(|member| member.member_id == MEMBER_ID && !member.leaving) + .max_by_key(|member| member.connected_at_ms) + .map(|member| member.process_id); + let Some(process_id) = connected else { + return; + }; + let changed = { + let mut state = lock(&self.state); + if state.process_id.as_deref() == Some(process_id.as_str()) { + false + } else { + state.process_id = Some(process_id.clone()); + state + .routes + .retain(|_, entry| entry.process_id == process_id); + true + } + }; + if changed { + info!(process = %process_id, "vm driver: shared supervisor connected"); + self.publish(); + self.process.send_replace(Some(process_id)); + } + } + + /// The supervisor process exited: every route it ran is lost. + fn process_exited(&self) { + { + let mut state = lock(&self.state); + state.process_id = None; + state.routes.clear(); + } + self.publish(); + self.process.send_replace(None); + } +} + +/// One generation's launch material for the shared supervisor: what a +/// dedicated supervisor receives as files and environment. +pub struct InstanceLaunch { + pub route: String, + pub sandbox_id: String, + pub sandbox_name: String, + /// Supervisor-side descriptor using the routed transport for `route`. + pub runtime_descriptor: openshell_sandbox_backend::boundary_protocol::SandboxRuntimeDescriptor, + pub auth: openshell_core::jwt::SupervisorAuthBundle, + pub main_process_spec: String, + pub workdir: Option, + pub container_image: String, +} + +impl InstanceLaunch { + /// Validate the registration and encode it as an assignment, with the + /// credential epoch of its launch term. + pub(crate) fn into_assignment(self) -> Result<(SandboxInstanceAssignment, u64), String> { + let auth_epoch = self.auth.auth_epoch.get(); + let registration = openshell_supervisor_control::SandboxInstanceRegistration { + route: self.route, + sandbox_id: self.sandbox_id, + sandbox_name: self.sandbox_name, + runtime_descriptor: self.runtime_descriptor, + auth: self.auth, + main_process_spec: self.main_process_spec, + workdir: self.workdir, + container_image: self.container_image, + proxy_ca: generate_proxy_ca()?, + trace_context: openshell_supervisor_control::RegistrationTraceContext::current(), + }; + registration + .validate() + .map_err(|error| format!("shared supervisor launch material: {error}"))?; + let assignment = registration + .to_assignment() + .map_err(|error| format!("shared supervisor launch material: {error}"))?; + Ok((assignment, auth_epoch)) + } +} + +/// A proxy interception CA for one generation. A dedicated supervisor makes +/// its own; a shared one receives it with the launch material. +fn generate_proxy_ca() -> Result { + use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyUsagePurpose}; + let key = openshell_crypto::pki::generate_keypair() + .map_err(|error| format!("generate proxy CA key: {error}"))?; + let mut params = CertificateParams::default(); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params + .distinguished_name + .push(DnType::CommonName, "OpenShell Sandbox CA"); + params + .distinguished_name + .push(DnType::OrganizationName, "OpenShell"); + params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign]; + let certificate = openshell_crypto::pki::self_signed(params, &key) + .map_err(|error| format!("generate proxy CA certificate: {error}"))?; + Ok(openshell_supervisor_control::ProxyCaMaterial { + certificate_pem: certificate.pem(), + private_key_pem: openshell_supervisor_control::SecretPem::new( + key.serialize_pem() + .map_err(|error| format!("export proxy CA key: {error}"))?, + ), + }) +} + +/// The single-member pool view of `state`. +fn pool_view(state: &HostState, runtime_address: SocketAddr) -> PoolView { + let mut view = PoolView::default(); + if let Some(process_id) = &state.process_id { + view.members.push(MemberView { + member_id: MEMBER_ID.to_string(), + process_id: process_id.clone(), + runtime_address: runtime_address.to_string(), + leaving: false, + }); + } + for (route, entry) in &state.routes { + view.owners.insert( + route.clone(), + InstanceOwner { + member_id: MEMBER_ID.to_string(), + process_id: entry.process_id.clone(), + auth_epoch: entry.auth_epoch, + supervisor_instance_id: None, + takeover: None, + }, + ); + if !entry.withdrawn { + view.desired.insert(route.clone()); + view.assignments + .insert(route.clone(), entry.assignment.clone()); + } + } + view +} + +// --- the supervisor process --------------------------------------------- + +struct SupervisorCommand { + binary: PathBuf, + dir: PathBuf, + session_root: PathBuf, + assignment_endpoint: String, + token_path: PathBuf, + /// The gateway's CA, for the sandbox sessions when the gateway uses TLS. + gateway_ca: Option, + gateway_tls_server_name: Option, + runtime_address: SocketAddr, + health_address: SocketAddr, + environment: Vec<(String, String)>, + args: Vec, +} + +impl SupervisorCommand { + fn command(&self) -> Result { + let log = |name: &str| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(self.dir.join(name)) + .map_err(|error| format!("open shared supervisor log {name}: {error}")) + }; + let mut command = Command::new(&self.binary); + command + .env_clear() + .kill_on_drop(true) + .stdin(std::process::Stdio::null()) + .stdout(log("supervisor.log")?) + .stderr(log("supervisor.err.log")?) + .arg("--mode") + .arg("shared") + .arg("--gateway-endpoint") + .arg(&self.assignment_endpoint) + .arg("--address") + .arg(self.health_address.to_string()) + .arg("--token-file") + .arg(&self.token_path) + .arg("--runtime-listen") + .arg(self.runtime_address.to_string()) + .arg("--session-root") + .arg(&self.session_root) + .arg("--pool-member-id") + .arg(MEMBER_ID) + .arg("--pool-advertise-ip") + .arg(self.runtime_address.ip().to_string()) + .arg("--pool-max-instances") + .arg(MAX_INSTANCES.to_string()) + .args(&self.args) + .envs(self.environment.iter().map(|(key, value)| (key, value))); + if let Some(ca) = &self.gateway_ca { + command.env(openshell_core::sandbox_env::TLS_CA, ca); + } + if let Some(name) = &self.gateway_tls_server_name { + command.env(openshell_core::sandbox_env::GATEWAY_TLS_SERVER_NAME, name); + } + // SAFETY: the closure only calls the async-signal-safe prctl(2). + #[cfg(target_os = "linux")] + #[allow(unsafe_code)] + unsafe { + command.pre_exec(|| { + nix::sys::prctl::set_pdeathsig(nix::sys::signal::Signal::SIGKILL) + .map_err(std::io::Error::other) + }); + } + Ok(command) + } +} + +/// Run the shared supervisor, restarting it when it exits, until the host is +/// dropped. +async fn keep_supervisor(command: SupervisorCommand, host: std::sync::Weak) { + let mut backoff = RESPAWN_BACKOFF_MIN; + loop { + if host.strong_count() == 0 { + return; + } + let started = tokio::time::Instant::now(); + let result = match command.command() { + Ok(mut command) => match command.spawn() { + Ok(mut child) => { + info!( + pid = child.id().unwrap_or(0), + "vm driver: shared supervisor process started" + ); + child + .wait() + .await + .map(|status| status.to_string()) + .map_err(|error| error.to_string()) + } + Err(error) => Err(format!( + "start shared supervisor '{}': {error}", + command.as_std().get_program().to_string_lossy() + )), + }, + Err(error) => Err(error), + }; + let Some(live) = host.upgrade() else { + return; + }; + let stderr = log_tail(&command.dir.join("supervisor.err.log")); + match result { + Ok(status) => { + warn!(%status, stderr = stderr.unwrap_or_default(), "vm driver: shared supervisor exited; its sandboxes are lost"); + } + Err(error) => warn!(%error, "vm driver: shared supervisor could not run"), + } + live.process_exited(); + drop(live); + if started.elapsed() >= RESPAWN_STABLE_AFTER { + backoff = RESPAWN_BACKOFF_MIN; + } + tokio::time::sleep(backoff).await; + backoff = (backoff * 2).min(RESPAWN_BACKOFF_MAX); + } +} + +async fn watch_membership(host: std::sync::Weak) { + let Some(mut changes) = host + .upgrade() + .map(|host| host.controller.membership_changes()) + else { + return; + }; + while changes.changed().await.is_ok() { + let Some(host) = host.upgrade() else { + return; + }; + host.membership_changed(); + } +} + +// --- the assignment stream ---------------------------------------------- + +#[derive(Clone)] +struct HostService { + controller: SupervisorHostController, + tokens: Arc>, + /// The driver's own uid; only its processes may attach. + uid: u32, +} + +#[tonic::async_trait] +impl SupervisorHost for HostService { + type AttachStream = Pin< + Box> + Send + 'static>, + >; + + async fn attach( + &self, + request: Request>, + ) -> Result, Status> { + // The socket sits in a private directory; the peer check and the + // token are defense in depth. + let peer_uid = request + .extensions() + .get::() + .and_then(|info| info.peer_cred) + .map(|credentials| credentials.uid()); + if peer_uid != Some(self.uid) { + return Err(Status::permission_denied( + "the shared supervisor must run as the driver's user", + )); + } + let bearer = request + .metadata() + .get("authorization") + .and_then(|value| value.to_str().ok()) + .map(|value| { + value + .strip_prefix("Bearer ") + .unwrap_or(value) + .trim() + .to_string() + }) + .ok_or_else(|| Status::unauthenticated("supervisor token required"))?; + let identity = lock(&self.tokens) + .verify(&bearer, unix_seconds()) + .ok_or_else(|| Status::unauthenticated("unknown or expired supervisor token"))?; + let (member_id, outbound) = self + .controller + .attach(identity, request.into_inner(), |_, _| None) + .await?; + if member_id != MEMBER_ID { + warn!(%member_id, "vm driver: an unexpected pool member attached to the shared supervisor socket"); + } + Ok(Response::new(Box::pin(outbound))) + } +} + +/// Serve the assignment stream on the driver's private Unix socket. +async fn serve_assignments(listener: tokio::net::UnixListener, service: HostService) { + let (connections, incoming) = + tokio::sync::mpsc::channel::>(16); + let accept = tokio::spawn(async move { + loop { + match listener.accept().await { + Ok((stream, _)) => { + if connections.send(Ok(stream)).await.is_err() { + return; + } + } + Err(error) => { + warn!(%error, "vm driver: shared supervisor socket accept failed"); + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + } + }); + let result = tonic::transport::Server::builder() + .add_service(SupervisorHostServer::new(service)) + .serve_with_incoming(tokio_stream::wrappers::ReceiverStream::new(incoming)) + .await; + accept.abort(); + if let Err(error) = result { + warn!(%error, "vm driver: shared supervisor assignment server stopped"); + } +} + +// --- supervisor tokens ------------------------------------------------------ + +/// One minted supervisor token. Only this driver verifies it, by comparing it +/// with what it minted, so it is JWT-shaped (the supervisor reads its `exp`) +/// but its signature is random. +struct Issued { + token: String, + id: String, + expires_at: i64, +} + +impl Issued { + fn mint(now: i64) -> Result { + let encode = |bytes: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes); + let random = |what: &str| { + openshell_crypto::random_bytes::<32>() + .map_err(|error| format!("generate supervisor token {what}: {error}")) + }; + let id = encode(&random("id")?[..16]); + let expires_at = now.saturating_add(i64::try_from(TOKEN_TTL.as_secs()).unwrap_or(i64::MAX)); + let header = encode(br#"{"alg":"HS256","typ":"JWT"}"#); + let payload = encode( + serde_json::json!({ + "sub": TOKEN_SUBJECT, + "jti": id, + "iat": now, + "exp": expires_at, + }) + .to_string() + .as_bytes(), + ); + let signature = encode(&random("signature")?); + Ok(Self { + token: format!("{header}.{payload}.{signature}"), + id, + expires_at, + }) + } +} + +struct Tokens { + current: Issued, + previous: Option, +} + +impl Tokens { + fn new() -> Result { + Ok(Self { + current: Issued::mint(unix_seconds())?, + previous: None, + }) + } + + fn renew(&mut self) -> Result<(), String> { + let next = Issued::mint(unix_seconds())?; + self.previous = Some(std::mem::replace(&mut self.current, next)); + Ok(()) + } + + /// The identity of an unexpired token this driver minted. + fn verify(&self, bearer: &str, now: i64) -> Option { + std::iter::once(&self.current) + .chain(self.previous.as_ref()) + .find(|issued| issued.expires_at > now && constant_time_eq(&issued.token, bearer)) + .map(|issued| HostIdentity { + subject: TOKEN_SUBJECT.to_string(), + token_id: issued.id.clone(), + expires_at: issued.expires_at, + }) + } +} + +async fn renew_tokens(tokens: Arc>, path: PathBuf) { + loop { + tokio::time::sleep(TOKEN_RENEWAL).await; + let renewed = { + let mut tokens = lock(&tokens); + tokens.renew().map(|()| tokens.current.token.clone()) + }; + match renewed.and_then(|token| write_private_file(&path, token.as_bytes())) { + Ok(()) => debug!("vm driver: renewed the shared supervisor token"), + Err(error) => warn!(%error, "vm driver: renewing the shared supervisor token failed"), + } + } +} + +/// The last few KiB of a log, for a diagnostic. +fn log_tail(path: &Path) -> Option { + const LIMIT: usize = 4096; + let bytes = std::fs::read(path).ok()?; + let tail = String::from_utf8_lossy(&bytes[bytes.len().saturating_sub(LIMIT)..]) + .trim() + .to_string(); + (!tail.is_empty()).then_some(tail) +} + +fn constant_time_eq(left: &str, right: &str) -> bool { + left.len() == right.len() + && left + .bytes() + .zip(right.bytes()) + .fold(0_u8, |difference, (a, b)| difference | (a ^ b)) + == 0 +} + +// --- helpers ------------------------------------------------------------------ + +fn lock(mutex: &StdMutex) -> std::sync::MutexGuard<'_, T> { + mutex + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn unix_seconds() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| { + i64::try_from(elapsed.as_secs()).unwrap_or(i64::MAX) + }) +} + +/// A loopback TCP port free at the moment of the call. The supervisor binds +/// it right after; it needs a concrete port because it advertises it. +fn free_port() -> Result { + std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .and_then(|listener| listener.local_addr()) + .map(|address| address.port()) + .map_err(|error| format!("find a free loopback port: {error}")) +} + +fn create_private_dir(path: &Path) -> Result<(), String> { + use std::os::unix::fs::{DirBuilderExt as _, PermissionsExt as _}; + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path) + .and_then(|()| std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))) + .map_err(|error| format!("create {}: {error}", path.display())) +} + +/// Restrict a socket the driver created to its own user. +fn set_private_mode(path: &Path) -> Result<(), String> { + use std::os::unix::fs::PermissionsExt as _; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) + .map_err(|error| format!("restrict {}: {error}", path.display())) +} + +/// Write `contents` to `path` with mode 0600, replacing it atomically. +fn write_private_file(path: &Path, contents: &[u8]) -> Result<(), String> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt as _; + let temporary = path.with_extension("tmp"); + let _ = std::fs::remove_file(&temporary); + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .and_then(|mut file| file.write_all(contents).and_then(|()| file.sync_all())) + .and_then(|()| std::fs::rename(&temporary, path)) + .map_err(|error| format!("write {}: {error}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(route: &str, process_id: &str, withdrawn: bool) -> (String, RouteEntry) { + ( + route.to_string(), + RouteEntry { + assignment: SandboxInstanceAssignment { + route: route.to_string(), + sandbox_id: format!("sandbox-{route}"), + generation: "generation-1".to_string(), + launch_material: b"{}".to_vec(), + takeover: None, + }, + auth_epoch: 1, + process_id: process_id.to_string(), + withdrawn, + }, + ) + } + + #[test] + fn pool_view_owns_every_route_and_desires_only_live_ones() { + let state = HostState { + process_id: Some("process-1".to_string()), + routes: BTreeMap::from([ + entry("route-a", "process-1", false), + entry("route-b", "process-1", true), + ]), + }; + let address: SocketAddr = "127.0.0.1:5600".parse().unwrap(); + let view = pool_view(&state, address); + assert_eq!(view.members.len(), 1); + assert_eq!(view.members[0].member_id, MEMBER_ID); + assert_eq!(view.members[0].process_id, "process-1"); + assert_eq!(view.members[0].runtime_address, "127.0.0.1:5600"); + assert_eq!(view.owners.len(), 2); + assert!( + view.owners + .values() + .all(|owner| owner.process_id == "process-1" + && owner.takeover.is_none() + && owner.supervisor_instance_id.is_none()) + ); + assert_eq!(view.desired.iter().collect::>(), ["route-a"]); + assert_eq!(view.assignments.keys().collect::>(), ["route-a"]); + } + + #[test] + fn pool_view_without_a_process_has_no_member() { + let view = pool_view(&HostState::default(), "127.0.0.1:1".parse().unwrap()); + assert!(view.members.is_empty()); + assert!(view.owners.is_empty()); + } + + #[test] + fn tokens_verify_only_what_was_minted_and_unexpired() { + let mut tokens = Tokens::new().unwrap(); + let now = unix_seconds(); + let first = tokens.current.token.clone(); + assert!(openshell_core::jwt::parse_exp_secs(&first).is_some_and(|exp| exp > now)); + assert_eq!(tokens.verify(&first, now).unwrap().subject, TOKEN_SUBJECT); + assert!(tokens.verify("not-a-token", now).is_none()); + assert!(tokens.verify(&first, tokens.current.expires_at).is_none()); + + tokens.renew().unwrap(); + let second = tokens.current.token.clone(); + assert_ne!(first, second); + // The previous token keeps working until it expires. + assert!(tokens.verify(&first, now).is_some()); + assert!(tokens.verify(&second, now).is_some()); + tokens.renew().unwrap(); + assert!(tokens.verify(&first, now).is_none()); + } + + #[test] + fn constant_time_eq_compares_whole_strings() { + assert!(constant_time_eq("abc", "abc")); + assert!(!constant_time_eq("abc", "abd")); + assert!(!constant_time_eq("abc", "abcd")); + } +} From 29896b2f48d68d70e213d53bcb133699a7c845fe Mon Sep 17 00:00:00 2001 From: mr-miles Date: Tue, 1 Dec 2026 23:23:09 +0000 Subject: [PATCH 2/3] chore(driver): pin the fork's patched branch at 4a1528b (v0.1.11, trial) Pin the vendored driver's OpenShell git dependencies and the embedded runtime to the `patched` branch of mr-miles/OpenShell at 4a1528b1, so the Release workflow builds them from one commit. That branch is the v0.1.11 release plus stacks not yet upstream: - the L7 fix: percent-encoded path bytes are forwarded as sent, and S3 paths are signed single-encoded; - the shared supervisor host over Unix sockets, which the driver's OPENSHELL_VM_SHARED_SUPERVISOR needs; - ai-openshell/openshell#6056 and #6057 (driver-only; the vendored driver carries its own merge of them). Three-way merge the upstream driver changes since f16795b: - #5117: driver_config is decoded with proto_struct::from_struct, which keeps protobuf integers as integers. - #6023: the counting test allocator moved to openshell-supervisor-network, so allocation_tracking and its feature are gone. Not taken: #5914's launched mode (`serve` and `preflight`, the table on stdin and the gateway's Configure call). This driver runs as an external service the gateway reaches by socket_path, which v0.1.11 still supports. Re-lock: v0.1.11 requires libc 0.2.191, smallvec and kube 5.2.0. Not for merging. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 +- driver/UPSTREAM.env | 4 +- vendor/openshell/Cargo.lock | 160 +++++++++++++----- vendor/openshell/Cargo.toml | 16 +- .../crates/openshell-driver-vm/Cargo.toml | 2 - .../crates/openshell-driver-vm/README.md | 6 +- .../src/allocation_tracking.rs | 59 ------- .../crates/openshell-driver-vm/src/driver.rs | 8 +- .../crates/openshell-driver-vm/src/lib.rs | 3 - 9 files changed, 148 insertions(+), 126 deletions(-) delete mode 100644 vendor/openshell/crates/openshell-driver-vm/src/allocation_tracking.rs diff --git a/README.md b/README.md index 082205b..314e615 100644 --- a/README.md +++ b/README.md @@ -48,8 +48,13 @@ The guest has no network device. ## The vendored driver `vendor/openshell` holds one crate: OpenShell's VM driver (`openshell-driver-vm`), taken from -NVIDIA/OpenShell `main` at commit `f16795b` (after `v0.1.9`; not a release; pinned in [`driver/UPSTREAM.env`](driver/UPSTREAM.env)) and -trimmed. It is its own cargo workspace. The other OpenShell crates it uses (`openshell-core` +the `patched` branch of the fork [mr-miles/OpenShell](https://github.com/mr-miles/OpenShell) at commit +`4a1528b` (pinned in [`driver/UPSTREAM.env`](driver/UPSTREAM.env)) and trimmed. That branch is OpenShell +release `v0.1.11` plus fixes not yet merged upstream: the L7 +proxy keeps percent-encoded path bytes and signs S3 paths as AWS does, and the VM driver +perf changes of ai-openshell/openshell#6056 and #6057 (fewer `debugfs` runs, hashes and worker +processes per launch), and the shared supervisor host over Unix sockets that the driver's +[shared supervisor](#shared-supervisor) needs. It is its own cargo workspace. The other OpenShell crates it uses (`openshell-core` and friends) are **git dependencies on the same commit**, not copies, so building needs network access to GitHub. The changes from upstream are listed in [its README](vendor/openshell/crates/openshell-driver-vm/README.md): image `ENV` and @@ -61,9 +66,10 @@ pinned commit when a release is made. `mise run driver:check-pin` fails if the r ### Compatibility The supervisor protocol is not stable across OpenShell revisions, so the gateway must come -from a revision compatible with the one in `driver/UPSTREAM.env`, currently `main` -at `f16795b`, which is not a release: build the gateway from that commit. Released gateways, -`v0.1.9` included, have not been checked against it. `install.sh` prints +from a revision compatible with the one in `driver/UPSTREAM.env`, currently the fork's `patched` +branch at `4a1528b`, which is not a release: build the gateway from that commit (or use the +`v0.1.11` release, its base; the stack changes no gateway protocol). Older released gateways, +`v0.1.10` included, have not been checked against it. `install.sh` prints the commit the installed driver was built from and the gateway's reported version, and leaves the comparison to you. diff --git a/driver/UPSTREAM.env b/driver/UPSTREAM.env index fd131d0..aed109d 100644 --- a/driver/UPSTREAM.env +++ b/driver/UPSTREAM.env @@ -7,8 +7,8 @@ # protocol is not stable across revisions. To move to another revision, re-vendor the # driver crate from it (see crates/openshell-driver-vm/README.md), then change the commit here # and the `rev` in vendor/openshell/Cargo.toml. -OPENSHELL_REPO=https://github.com/NVIDIA/OpenShell -OPENSHELL_COMMIT=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9 +OPENSHELL_REPO=https://github.com/mr-miles/OpenShell +OPENSHELL_COMMIT=4a1528b14904f9c41bbde149ff3a2c87d467eae9 OPENSHELL_TAG= # Optional: build the embedded runtime (host supervisor, guest sandbox, guest init) from diff --git a/vendor/openshell/Cargo.lock b/vendor/openshell/Cargo.lock index 93c0088..637e207 100644 --- a/vendor/openshell/Cargo.lock +++ b/vendor/openshell/Cargo.lock @@ -1168,8 +1168,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" dependencies = [ "futures-core", - "lock_api", - "parking_lot", + "lock_api 0.4.14", + "parking_lot 0.12.5", ] [[package]] @@ -1784,8 +1784,22 @@ version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175dc66334db3b9ab9985bf8b61cfed50dc16d20964bb47f9e479adcae984a7f" dependencies = [ - "jiff-core", - "jiff-static", + "jiff-core 0.1.8", + "jiff-static 0.2.46", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core 1.0.2", + "jiff-static 1.0.3", "log", "portable-atomic", "portable-atomic-util", @@ -1801,18 +1815,39 @@ dependencies = [ "log", ] +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7b1af7547d47354bc438d797e3854601bde8f8d185780c5ba4ab27afa54f1ba" dependencies = [ - "jiff-core", + "jiff-core 0.1.8", "proc-macro2", "quote", "syn 2.0.117", ] +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core 1.0.2", + "proc-macro2", + "quote", + "syn 3.0.5", +] + [[package]] name = "jni" version = "0.21.1" @@ -1967,7 +2002,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab0d13801242174b1f3966907c3f32039f2d6b36c7ce82c61225d66ed5d1eb70" dependencies = [ "base64 0.22.1", - "jiff", + "jiff 0.2.46", "serde", "serde_json", ] @@ -1989,9 +2024,9 @@ checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" [[package]] name = "kube" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c73b082f549411623a4f8949bd24dcaedacb1511379c461c76d579fde301d021" +checksum = "f95e1a9107878bef32cfbe2e5e084584db832c9616df9981adc4673f9fb1c853" dependencies = [ "k8s-openapi", "kube-client", @@ -2002,9 +2037,9 @@ dependencies = [ [[package]] name = "kube-client" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae56b223bca490db1f1b115bfc606d411177511d7748d8cc019a7e3b2935430b" +checksum = "703ee17477c86501627e83492895c06ab6fc2c55a319bb2fbc582ccae739ba67" dependencies = [ "base64 0.23.1", "bytes", @@ -2017,7 +2052,7 @@ dependencies = [ "hyper-rustls", "hyper-timeout", "hyper-util", - "jiff", + "jiff 0.2.46", "jsonpath-rust", "k8s-openapi", "kube-core", @@ -2039,14 +2074,14 @@ dependencies = [ [[package]] name = "kube-core" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6de84b47fc1aa35ba0ef9059ef54b47c8b47f0979afd15487e525282f2d73fb9" +checksum = "b5e9a9aa533b2f4106ac1ac45e168bb452325eb9e918d57335444f60bef34ffc" dependencies = [ "derive_more", "form_urlencoded", "http", - "jiff", + "jiff 0.2.46", "json-patch", "k8s-openapi", "schemars", @@ -2058,9 +2093,9 @@ dependencies = [ [[package]] name = "kube-derive" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de1fb46ac34371491ac0277c13e0e1bb9288000e64c86ca3d91343754818e64e" +checksum = "cedc991dbe7757a646098dead35e070e13ce66e2996b02162ac7f97eb97f4d6e" dependencies = [ "darling 0.24.1", "proc-macro2", @@ -2072,9 +2107,9 @@ dependencies = [ [[package]] name = "kube-runtime" -version = "5.0.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dea60005024b6ec1819c426209aa29b9eaca64f6b3988ab73c55f43fa484392" +checksum = "ca78d9eeb4674eb75e381e6a956e8a5005942928dec87de4db9ef9701af8a637" dependencies = [ "ahash", "async-broadcast", @@ -2087,7 +2122,7 @@ dependencies = [ "json-patch", "k8s-openapi", "kube-client", - "parking_lot", + "parking_lot 0.13.0", "pin-project", "serde", "serde_json", @@ -2111,9 +2146,9 @@ checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" -version = "0.2.189" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libm" @@ -2165,6 +2200,15 @@ dependencies = [ "scopeguard", ] +[[package]] +name = "lock_api" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65d91b22da179613dcf4d6ec8349563f52a363f6849e03b00dd0a185ec4a59af" +dependencies = [ + "scopeguard", +] + [[package]] name = "log" version = "0.4.34" @@ -2466,14 +2510,14 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "openshell-core" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "async-trait", "base64 0.22.1", - "chrono", "clap", "glob", "ipnet", + "jiff 1.0.3", "jsonwebtoken", "libc", "miette", @@ -2495,6 +2539,7 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "tokio-util", "tonic", "tonic-prost", "tonic-prost-build", @@ -2502,13 +2547,14 @@ dependencies = [ "tracing", "url", "uuid", + "windows-sys 0.61.2", "zeroize", ] [[package]] name = "openshell-crypto" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "aws-lc-rs", "jsonwebtoken", @@ -2577,7 +2623,7 @@ dependencies = [ [[package]] name = "openshell-extension-core" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "hyper-util", "serde", @@ -2590,7 +2636,7 @@ dependencies = [ [[package]] name = "openshell-isolation-interface" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "openshell-core", "serde", @@ -2602,9 +2648,9 @@ dependencies = [ [[package]] name = "openshell-ocsf" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ - "chrono", + "jiff 1.0.3", "serde", "serde_json", "serde_repr", @@ -2616,7 +2662,7 @@ dependencies = [ [[package]] name = "openshell-otel" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "async-trait", "bytes", @@ -2648,7 +2694,7 @@ dependencies = [ [[package]] name = "openshell-otel-test-support" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "bytes", "http", @@ -2672,7 +2718,7 @@ dependencies = [ [[package]] name = "openshell-policy-schema" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "miette", "noyalib", @@ -2685,7 +2731,7 @@ dependencies = [ [[package]] name = "openshell-sandbox-backend" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "async-trait", "bytes", @@ -2717,7 +2763,7 @@ dependencies = [ [[package]] name = "openshell-spiffe" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "async-trait", "base64 0.22.1", @@ -2729,7 +2775,7 @@ dependencies = [ [[package]] name = "openshell-supervisor-control" version = "0.0.0" -source = "git+https://github.com/NVIDIA/OpenShell?rev=f16795bc76b13fcc35d8b0d2b49cfc788c701ef9#f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" +source = "git+https://github.com/mr-miles/OpenShell?rev=4a1528b14904f9c41bbde149ff3a2c87d467eae9#4a1528b14904f9c41bbde149ff3a2c87d467eae9" dependencies = [ "openshell-core", "openshell-otel", @@ -2868,8 +2914,18 @@ version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" dependencies = [ - "lock_api", - "parking_lot_core", + "lock_api 0.4.14", + "parking_lot_core 0.9.12", +] + +[[package]] +name = "parking_lot" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9cf937ca4e1d0b7578784559063422fc39ae7c5a00f02471f2614d5486fd226" +dependencies = [ + "lock_api 0.5.0", + "parking_lot_core 0.10.0", ] [[package]] @@ -2885,6 +2941,18 @@ dependencies = [ "windows-link", ] +[[package]] +name = "parking_lot_core" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cfff060068cc18aa7815010fcaf80c68c7fb9e85fc7f5c0f9bf142c21d19826" +dependencies = [ + "libc", + "redox_syscall 0.9.5", + "smallvec", + "windows-link", +] + [[package]] name = "pem" version = "3.0.6" @@ -3408,6 +3476,15 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + [[package]] name = "ref-cast" version = "1.0.27" @@ -4026,9 +4103,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.15.1" +version = "1.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" dependencies = [ "serde", ] @@ -4078,7 +4155,7 @@ version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ - "lock_api", + "lock_api 0.4.14", ] [[package]] @@ -4380,7 +4457,7 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96374855068f47402c3121c6eed88d29cb1de8f3ab27090e273e420bdabcf050" dependencies = [ - "parking_lot", + "parking_lot 0.12.5", ] [[package]] @@ -4530,7 +4607,7 @@ dependencies = [ "bytes", "libc", "mio", - "parking_lot", + "parking_lot 0.12.5", "pin-project-lite", "signal-hook-registry", "socket2", @@ -4579,6 +4656,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "libc", "pin-project-lite", "slab", diff --git a/vendor/openshell/Cargo.toml b/vendor/openshell/Cargo.toml index 70ca3c9..dce0bfb 100644 --- a/vendor/openshell/Cargo.toml +++ b/vendor/openshell/Cargo.toml @@ -17,14 +17,14 @@ repository = "https://github.com/NVIDIA/OpenShell" # The rest of OpenShell, from the revision driver/UPSTREAM.env names (keep the two in sync: # `mise run driver:check-pin` checks). The host supervisor and guest binaries the driver # embeds are built from that revision too. -openshell-core = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false } -openshell-isolation-interface = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-sandbox-backend = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-supervisor-control = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-otel = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-otel-test-support = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-spiffe = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9" } -openshell-crypto = { git = "https://github.com/NVIDIA/OpenShell", rev = "f16795bc76b13fcc35d8b0d2b49cfc788c701ef9", default-features = false, features = ["aws-lc"] } +openshell-core = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9", default-features = false } +openshell-isolation-interface = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-sandbox-backend = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-supervisor-control = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-otel = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-otel-test-support = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-spiffe = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9" } +openshell-crypto = { git = "https://github.com/mr-miles/OpenShell", rev = "4a1528b14904f9c41bbde149ff3a2c87d467eae9", default-features = false, features = ["aws-lc"] } # Async runtime tokio = { version = "1.53.3", features = ["full"] } diff --git a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml index 07069b8..e4baa45 100644 --- a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml +++ b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml @@ -67,8 +67,6 @@ tonic-prost = { workspace = true, optional = true } rcgen = { workspace = true, optional = true } [features] -# Portable test instrumentation, independent of the compute runtime. -allocation-tracking = [] default = ["compute-driver", "telemetry"] ## Build the standalone compute driver and its host runtime implementation. compute-driver = [ diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index a89fbe4..8af8b69 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -69,6 +69,10 @@ Changes from upstream: `src/local_images.rs`. - **Removed.** libkrun and its embedded runtime, QEMU, GPU passthrough and `openshell-vfio`, virtiofs bind mounts, and the backend negotiation in the lifecycle extension API. A - sandbox that asks for a GPU or bind mounts is rejected. + sandbox that asks for a GPU or bind mounts is rejected. Also the launched mode upstream + added in v0.1.11 (`serve` and `preflight`, with the table on stdin and the gateway's + `Configure` call, in `src/serve.rs`, `src/settings.rs` and `src/listener.rs`): this driver + runs as an external service the gateway reaches by `socket_path`, so it keeps the flag and + environment mode, which upstream still supports. Kept: Docker/Podman and registry image sources, rootfs tar uploads, telemetry. diff --git a/vendor/openshell/crates/openshell-driver-vm/src/allocation_tracking.rs b/vendor/openshell/crates/openshell-driver-vm/src/allocation_tracking.rs deleted file mode 100644 index b08ca7e..0000000 --- a/vendor/openshell/crates/openshell-driver-vm/src/allocation_tracking.rs +++ /dev/null @@ -1,59 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Allocation instrumentation used by network performance tests. - -use std::alloc::{GlobalAlloc, Layout, System}; -use std::sync::atomic::{AtomicU64, Ordering}; - -/// System allocator with counters for explicit performance tests. -pub struct CountingAllocator; - -static ALLOCATIONS: AtomicU64 = AtomicU64::new(0); -static ALLOCATED_BYTES: AtomicU64 = AtomicU64::new(0); - -#[allow(unsafe_code)] -unsafe impl GlobalAlloc for CountingAllocator { - unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - let pointer = unsafe { System.alloc(layout) }; - if !pointer.is_null() { - ALLOCATIONS.fetch_add(1, Ordering::Relaxed); - ALLOCATED_BYTES.fetch_add(layout.size() as u64, Ordering::Relaxed); - } - pointer - } - - unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - let pointer = unsafe { System.alloc_zeroed(layout) }; - if !pointer.is_null() { - ALLOCATIONS.fetch_add(1, Ordering::Relaxed); - ALLOCATED_BYTES.fetch_add(layout.size() as u64, Ordering::Relaxed); - } - pointer - } - - unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) { - unsafe { System.dealloc(pointer, layout) }; - } - - unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - let pointer = unsafe { System.realloc(pointer, layout, new_size) }; - if !pointer.is_null() { - ALLOCATIONS.fetch_add(1, Ordering::Relaxed); - ALLOCATED_BYTES.fetch_add(new_size as u64, Ordering::Relaxed); - } - pointer - } -} - -pub fn reset() { - ALLOCATIONS.store(0, Ordering::SeqCst); - ALLOCATED_BYTES.store(0, Ordering::SeqCst); -} - -pub fn snapshot() -> (u64, u64) { - ( - ALLOCATIONS.load(Ordering::SeqCst), - ALLOCATED_BYTES.load(Ordering::SeqCst), - ) -} diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 48762bc..176a56a 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -67,9 +67,7 @@ use openshell_core::proto::compute::v1::{ WatchSandboxesSandboxEvent, WorkloadIdentityRequest, compute_driver_server::ComputeDriver, watch_sandboxes_event, }; -use openshell_core::proto_struct::{ - deserialize_optional_non_empty_string_list, struct_to_json_value, -}; +use openshell_core::proto_struct::{deserialize_optional_non_empty_string_list, from_struct}; use openshell_core::{ NetworkSupervisorTrustBundle, network_trust::MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES, }; @@ -175,8 +173,8 @@ impl VmSandboxDriverConfig { return Ok(Self::default()); }; - let config: Self = serde_json::from_value(struct_to_json_value(config)) - .map_err(|err| format!("invalid vm driver_config: {err}"))?; + let config: Self = + from_struct(config).map_err(|err| format!("invalid vm driver_config: {err}"))?; if config.mem_mib.is_some() { return Err("driver_config.mem_mib is no longer supported: \ set the memory with sandbox create --memory" diff --git a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs index 262c6e5..acb822b 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/lib.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/lib.rs @@ -11,9 +11,6 @@ compile_error!( build a telemetry-free VM driver with `--no-default-features --features defaults-without-telemetry`" ); -#[cfg(feature = "allocation-tracking")] -pub mod allocation_tracking; - #[cfg(feature = "compute-driver")] pub mod driver; #[cfg(feature = "compute-driver")] From 2bd3f95c5d5fe70bcb4eaf8c6a5a8e4ee87ee147 Mon Sep 17 00:00:00 2001 From: mr-miles Date: Tue, 1 Dec 2026 23:24:06 +0000 Subject: [PATCH 3/3] perf(driver): merge ai-openshell/openshell#6056 and #6057 (trial) Three-way merge the driver half of #6056/#6057, which cut per-launch VM bookkeeping and are not yet upstream, into the vendored crate: - write a launch's overlay files in one debugfs run (RootfsImageBatch); - hash the guest runtime identity at build time (build.rs); - re-hash the cached host supervisor only when the file changes; - resolve a cached digest-pinned bootstrap image without a preparation worker, which here also spares the launcher's exec of the driver. Adapted to the fork: no mount manifest is written (bind mounts are refused and the guest init reads none), and the worker is skipped only for a name with a registry host. Those never consult a local engine here, so the fast path probes none. write_rootfs_image_file is dropped: its only upstream caller is the libkrun runtime, which is not vendored. Kept off main: it arrives with a pin once the PRs land upstream. Co-Authored-By: Claude Opus 5.5 --- .../crates/openshell-driver-vm/Cargo.toml | 2 + .../crates/openshell-driver-vm/README.md | 7 + .../crates/openshell-driver-vm/build.rs | 42 +- .../crates/openshell-driver-vm/src/driver.rs | 426 ++++++++++++-- .../crates/openshell-driver-vm/src/rootfs.rs | 525 ++++++++++++++++-- 5 files changed, 909 insertions(+), 93 deletions(-) diff --git a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml index e4baa45..973a0a9 100644 --- a/vendor/openshell/crates/openshell-driver-vm/Cargo.toml +++ b/vendor/openshell/crates/openshell-driver-vm/Cargo.toml @@ -121,6 +121,8 @@ defaults-without-telemetry = ["compute-driver"] [build-dependencies] # Generates the SPIFFE Workload API server stub without protoc. tonic-build = { version = "0.14", optional = true } +# The guest runtime identity is hashed once, at build time (build.rs). +sha2 = { workspace = true } [dev-dependencies] spiffe = { workspace = true } diff --git a/vendor/openshell/crates/openshell-driver-vm/README.md b/vendor/openshell/crates/openshell-driver-vm/README.md index 8af8b69..199d9b4 100644 --- a/vendor/openshell/crates/openshell-driver-vm/README.md +++ b/vendor/openshell/crates/openshell-driver-vm/README.md @@ -67,6 +67,13 @@ Changes from upstream: `off`) and `OPENSHELL_VM_LOCAL_IMAGE_SOURCE_SOCKET` choose the engine. `DOCKER_HOST`, `OPENSHELL_PODMAN_SOCKET` and `podman info` are no longer consulted. See `src/local_images.rs`. +- **Launch bookkeeping (from the fork's `patched` branch, ai-openshell/openshell#6056 and + #6057, not yet upstream).** A launch writes its overlay files in one `debugfs` run, the guest + runtime identity is hashed at build time, a cached host supervisor is re-hashed only when the + file changes, and a cached digest-pinned bootstrap image is resolved without a preparation + worker. Adapted here: no mount manifest is written (bind mounts are refused), and the + worker is skipped only for a name with a registry host, since those never consult a local + engine (see Image sources), so no engine is probed. - **Removed.** libkrun and its embedded runtime, QEMU, GPU passthrough and `openshell-vfio`, virtiofs bind mounts, and the backend negotiation in the lifecycle extension API. A sandbox that asks for a GPU or bind mounts is rejected. Also the launched mode upstream diff --git a/vendor/openshell/crates/openshell-driver-vm/build.rs b/vendor/openshell/crates/openshell-driver-vm/build.rs index d4bbfbc..d3ed3b8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/build.rs +++ b/vendor/openshell/crates/openshell-driver-vm/build.rs @@ -7,6 +7,7 @@ //! artifacts it needs to prepare images and run sandboxes without a separate //! runtime download. The VMM is an external launcher, so no VMM is embedded. +use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use std::{env, fs}; @@ -22,10 +23,45 @@ fn main() { return; } - println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR"); - let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); generate_workload_api_server(&out_dir); + embed_runtime_artifacts(&out_dir); + write_guest_runtime_identity(&out_dir); +} + +/// The guest runtime identity (`rootfs::sandbox_guest_runtime_identity`): +/// SHA-256 over the embedded sandbox, vm-init and umoci blobs and the guest +/// init script, exactly the bytes the crate embeds. It keys the image +/// cache, so a changed guest runtime invalidates cached root disks. Hashed +/// here once instead of in every image preparation worker, a fresh process +/// per sandbox launch. +fn write_guest_runtime_identity(out_dir: &Path) { + const GUEST_INIT_SCRIPT: &str = "scripts/openshell-vm-sandbox-init.sh"; + println!("cargo:rerun-if-changed={GUEST_INIT_SCRIPT}"); + let manifest_dir = + PathBuf::from(env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set")); + let mut hasher = Sha256::new(); + for path in [ + out_dir.join("openshell-sandbox.zst"), + out_dir.join("openshell-vm-init.zst"), + out_dir.join("umoci.zst"), + manifest_dir.join(GUEST_INIT_SCRIPT), + ] { + let bytes = fs::read(&path).unwrap_or_else(|e| { + panic!( + "read {} for the guest runtime identity: {e}", + path.display() + ) + }); + hasher.update(&bytes); + } + let identity = format!("{:x}", hasher.finalize()); + let path = out_dir.join("guest-runtime-identity"); + fs::write(&path, identity).unwrap_or_else(|e| panic!("write {}: {e}", path.display())); +} + +fn embed_runtime_artifacts(out_dir: &Path) { + println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR"); let Ok(dir) = env::var("OPENSHELL_VM_RUNTIME_COMPRESSED_DIR") else { // Lint, check and test builds (the debug profile) never run the embedded @@ -35,7 +71,7 @@ fn main() { println!("cargo:warning=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR not set"); println!("cargo:warning=Stage the compressed runtime artifacts and point it at them"); } - generate_stub_resources(&out_dir); + generate_stub_resources(out_dir); return; }; let compressed_dir = PathBuf::from(dir); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs index 176a56a..9206bb5 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/driver.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/driver.rs @@ -20,12 +20,11 @@ use crate::lifecycle::{ extension_state_dir, }; use crate::rootfs::{ - clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, create_rootfs_image_from_dir, - ext4_image_has_directory, extract_host_supervisor, extract_rootfs_archive_to, - prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, remove_rootfs_image_file, + RootfsImageBatch, clone_or_copy_sparse_file, create_ext4_image_from_dir_with_size, + create_rootfs_image_from_dir, ext4_image_has_directory, extract_host_supervisor, + extract_rootfs_archive_to, prepare_sandbox_rootfs_from_image_root, recover_rootfs_image, sandbox_guest_init_path, sandbox_guest_runtime_identity, sandbox_guest_user_ids_from_image, - sandbox_guest_user_ids_from_overlay_image, set_rootfs_image_file_mode, - validate_host_supervisor, write_rootfs_image_file, + sandbox_guest_user_ids_from_overlay_image, validate_host_supervisor, }; use crate::shared_supervisor::{RouteState, SharedSupervisorHost, SharedSupervisorSettings}; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; @@ -2546,7 +2545,7 @@ impl VmDriver { } } - if let Err(err) = inject_guest_init_dropins(&overlay_disk, &plan.guest_init_dropins) { + if let Err(err) = prepare_guest_overlay(&overlay_disk, &plan.guest_init_dropins) { self.lifecycle_extensions .after_launch_failed(&sandbox, &state_dir, LaunchAbortReason::GuestPrepareFailed) .await; @@ -3776,6 +3775,23 @@ impl VmDriver { rootfs_tar: Option<&Path>, bootstrap_only: bool, ) -> Result { + self.prepare_images(sandbox_id, image_ref, rootfs_tar, bootstrap_only) + .await + } + + async fn prepare_images( + &self, + sandbox_id: &str, + image_ref: &str, + rootfs_tar: Option<&Path>, + bootstrap_only: bool, + ) -> Result { + if let Some(plan) = self + .cached_digest_pinned_image_plan(sandbox_id, image_ref, rootfs_tar, bootstrap_only) + .await + { + return Ok(plan); + } match self .run_preparation_in_worker(sandbox_id, image_ref, rootfs_tar, bootstrap_only, None) .await? @@ -3787,6 +3803,90 @@ impl VmDriver { } } + /// The image plan of a launch whose root disk is the bootstrap image, + /// pinned by digest and already cached, resolved in this process. + /// + /// The worker writes nothing for such a launch: the name has a registry + /// host, so it skips the local engine, and answers from the cache without + /// a registry call (`ensure_cached_registry_rootfs_image`). Answering here + /// spares the worker process (an exec of the driver binary and its exit + /// poll) on every such launch, with the same logs and events. Anything + /// else returns `None` before any log or event, and the worker prepares, + /// reports and fails exactly as before: a rootfs tar, a workload image + /// other than the bootstrap image, a tag, a name without a registry host + /// (local engine images), a cache miss, a registry credential + /// error, a missing bootstrap image, or a sandbox that is gone or + /// already preparing. + async fn cached_digest_pinned_image_plan( + &self, + sandbox_id: &str, + image_ref: &str, + rootfs_tar: Option<&Path>, + bootstrap_only: bool, + ) -> Option { + if rootfs_tar.is_some() { + return None; + } + let bootstrap_image_ref = self.bootstrap_image_ref().ok()?; + let resolved_ref = if bootstrap_only { + image_ref + } else if image_ref.trim() == bootstrap_image_ref.trim() { + bootstrap_image_ref.as_str() + } else { + return None; + }; + { + let registry = self.registry.lock().await; + let record = registry.get(sandbox_id)?; + if record.deleting || record.preparation.is_some() { + return None; + } + } + // A name without a registry host comes only from the local engine. + if !crate::local_images::image_ref_has_registry_host(resolved_ref) { + return None; + } + let digest = parse_registry_reference(resolved_ref) + .ok()? + .digest()? + .to_owned(); + let image_identity = bootstrap_image_cache_identity(&digest); + let image_path = image_cache_rootfs_image(&self.config.state_dir, &image_identity); + if tokio::fs::metadata(&image_path).await.is_err() || registry_auth(resolved_ref).is_err() { + return None; + } + + let span = tracing::info_span!( + "vm.resolve_bootstrap_image", + otel.name = "vm.resolve_bootstrap_image", + otel.status_code = tracing::field::Empty, + sandbox.id = %sandbox_id, + image.ref = %bootstrap_image_ref, + ); + async { + debug!( + image_ref = %resolved_ref, + "vm driver: image names a registry host, skipping the local engine" + ); + info!(image_ref = %resolved_ref, "vm driver: ensuring cached root disk image (registry)"); + info!( + image_identity = %image_identity, + image_path = %image_path.display(), + "vm driver: root disk image cache hit (digest-pinned, no registry call)" + ); + self.publish_registry_cache_hit(sandbox_id, resolved_ref, &image_identity, &image_path) + .await; + } + .instrument(span) + .await; + Some(RuntimeImagePlan { + root_disk: image_path, + image_disk: None, + image_identity: image_identity.clone(), + bootstrap_image_identity: image_identity, + }) + } + #[tracing::instrument( name = "vm.prepare_overlay", skip(self), @@ -7799,17 +7899,15 @@ async fn remove_runtime_generation_material(state_dir: &Path) -> Result<(), Stri let generation_for_cleanup = generation.clone(); tokio::task::spawn_blocking(move || { let tls = guest_boundary_tls_paths(&generation_for_cleanup); + let mut batch = RootfsImageBatch::new(&overlay); for guest_path in [ PathBuf::from(guest_boundary_config_path(&generation_for_cleanup)), tls.certificate_chain_path, tls.private_key_path, ] { - remove_rootfs_image_file( - &overlay, - &overlay_upper_path(&guest_path.to_string_lossy()), - )?; + batch.remove_file(&overlay_upper_path(&guest_path.to_string_lossy()))?; } - Ok::<(), String>(()) + batch.commit() }) .await .map_err(|error| format!("guest authentication cleanup task failed: {error}"))??; @@ -8013,8 +8111,9 @@ fn inject_guest_boundary_bundle( .encode() .map_err(|error| format!("encode VM boundary configuration: {error}"))?; let config_path = overlay_upper_path(guest_path); - write_rootfs_image_file(overlay_disk, &config_path, &encoded_config)?; - set_rootfs_image_file_mode(overlay_disk, &config_path, 0o600)?; + let mut batch = RootfsImageBatch::new(overlay_disk); + batch.write_file(&config_path, &encoded_config)?; + batch.set_file_mode(&config_path, 0o600)?; for (guest_path, contents) in [ ( tls.certificate_chain_path, @@ -8023,10 +8122,37 @@ fn inject_guest_boundary_bundle( (tls.private_key_path, material.private_key_pem.as_bytes()), ] { let path = overlay_upper_path(guest_path.to_string_lossy().as_ref()); - write_rootfs_image_file(overlay_disk, &path, contents)?; - set_rootfs_image_file_mode(overlay_disk, &path, 0o600)?; + batch.write_file(&path, contents)?; + batch.set_file_mode(&path, 0o600)?; } - Ok(()) + batch.commit() +} + +/// Write the launch's guest overlay files: the init drop-ins and their +/// manifest. Every file is staged first and the overlay is written by one +/// debugfs run ([`RootfsImageBatch`]), so a staging failure writes nothing. +/// (Upstream also writes a mount manifest here; this driver refuses bind +/// mounts and its guest init reads no manifest.) +#[allow(clippy::result_large_err)] +#[tracing::instrument( + name = "vm.prepare_guest", + skip(dropins), + fields( + otel.name = "vm.prepare_guest", + otel.status_code = tracing::field::Empty, + overlay.path = %overlay_disk.display(), + dropin.count = dropins.len(), + ) +)] +fn prepare_guest_overlay(overlay_disk: &Path, dropins: &[GuestInitDropin]) -> Result<(), Status> { + let span_status = openshell_otel::ErrorStatusGuard::current(); + let mut batch = RootfsImageBatch::new(overlay_disk); + let result = inject_guest_init_dropins(&mut batch, dropins).and_then(|()| { + batch + .commit() + .map_err(|error| Status::internal(format!("write VM guest overlay files: {error}"))) + }); + span_status.finish(result) } fn guest_boundary_config_path(generation: &str) -> String { @@ -8045,21 +8171,10 @@ fn guest_boundary_tls_paths(generation: &str) -> SandboxTlsServerConfig { } #[allow(clippy::result_large_err)] -#[tracing::instrument( - name = "vm.prepare_guest", - skip(dropins), - fields( - otel.name = "vm.prepare_guest", - otel.status_code = tracing::field::Empty, - overlay.path = %overlay_disk.display(), - dropin.count = dropins.len(), - ) -)] fn inject_guest_init_dropins( - overlay_disk: &Path, + batch: &mut RootfsImageBatch, dropins: &[GuestInitDropin], ) -> Result<(), Status> { - let span_status = openshell_otel::ErrorStatusGuard::current(); validate_guest_init_dropins(dropins).map_err(Status::failed_precondition)?; // Drop-ins are *executed* in a child shell by run_openshell_init_dropins @@ -8068,13 +8183,15 @@ fn inject_guest_init_dropins( // contract drop-in authors should rely on. for dropin in dropins { let guest_path = overlay_upper_path(&format!("{GUEST_INIT_DROPIN_DIR}/{}", dropin.name)); - write_rootfs_image_file(overlay_disk, &guest_path, &dropin.contents).map_err(|err| { - Status::internal(format!( - "write VM guest init drop-in '{}' failed: {err}", - dropin.name - )) - })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o755).map_err(|err| { + batch + .write_file(&guest_path, &dropin.contents) + .map_err(|err| { + Status::internal(format!( + "write VM guest init drop-in '{}' failed: {err}", + dropin.name + )) + })?; + batch.set_file_mode(&guest_path, 0o755).map_err(|err| { Status::internal(format!( "set VM guest init drop-in '{}' executable failed: {err}", dropin.name @@ -8087,8 +8204,7 @@ fn inject_guest_init_dropins( // injected — so the guest always fails closed: only names the driver // explicitly injected this launch are eligible to run, and a guest // image cannot smuggle in extra `init.d` entries. - write_guest_init_dropin_manifest(overlay_disk, dropins)?; - span_status.finish(Ok(())) + write_guest_init_dropin_manifest(batch, dropins) } /// Build the corporate upstream-proxy arguments passed to host control. @@ -8154,17 +8270,17 @@ fn render_guest_init_dropin_manifest(dropins: &[GuestInitDropin]) -> Vec { #[allow(clippy::result_large_err)] fn write_guest_init_dropin_manifest( - overlay_disk: &Path, + batch: &mut RootfsImageBatch, dropins: &[GuestInitDropin], ) -> Result<(), Status> { let guest_path = overlay_upper_path(GUEST_INIT_DROPIN_MANIFEST); let contents = render_guest_init_dropin_manifest(dropins); - write_rootfs_image_file(overlay_disk, &guest_path, &contents).map_err(|err| { + batch.write_file(&guest_path, &contents).map_err(|err| { Status::internal(format!( "write VM guest init drop-in manifest failed: {err}" )) })?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o644).map_err(|err| { + batch.set_file_mode(&guest_path, 0o644).map_err(|err| { Status::internal(format!( "set VM guest init drop-in manifest mode failed: {err}" )) @@ -9914,7 +10030,7 @@ mod tests { ); let invalid_dropin = GuestInitDropin::new("../invalid", Vec::new()); assert!( - inject_guest_init_dropins(Path::new("/unused"), &[invalid_dropin]).is_err(), + prepare_guest_overlay(Path::new("/unused"), &[invalid_dropin]).is_err(), "an invalid drop-in should fail after creating its span" ); } @@ -11551,6 +11667,234 @@ mod tests { task.abort(); } + /// A driver whose image preparation worker records each run in + /// `worker-runs` and answers with `plan`, and a registered sandbox `id`. + async fn cached_image_test_driver( + root: &Path, + bootstrap_image: &str, + id: &str, + plan: &RuntimeImagePlan, + ) -> VmDriver { + use std::os::unix::fs::PermissionsExt as _; + + let mut driver = test_driver_with_extensions(LifecycleExtensionRegistry::new()); + driver.config.state_dir = root.to_path_buf(); + driver.config.bootstrap_image = bootstrap_image.to_string(); + driver.launcher_bin = root.join("worker"); + let complete = + preparation::Message::Complete(Ok(preparation::Output::Images(plan.clone()))); + fs::write( + root.join("images.json"), + serde_json::to_vec(&complete).unwrap(), + ) + .unwrap(); + fs::write( + &driver.launcher_bin, + "#!/bin/sh\ncontrol=$(dirname \"$0\")\necho run >> \"$control/worker-runs\"\ncat \"$control/images.json\"\nprintf '\\n'\n", + ) + .unwrap(); + fs::set_permissions(&driver.launcher_bin, fs::Permissions::from_mode(0o700)).unwrap(); + let state_dir = sandboxes_root_dir(root).join(id); + create_private_dir_all(&state_dir).await.unwrap(); + driver.registry.lock().await.insert( + id.to_string(), + SandboxRecord { + snapshot: Sandbox { + id: id.to_string(), + ..Default::default() + }, + state_dir, + process: None, + provisioning_task: None, + preparation: None, + deleting: false, + }, + ); + driver + } + + fn platform_event_reasons( + events: &mut broadcast::Receiver, + ) -> Vec { + let mut reasons = Vec::new(); + while let Ok(event) = events.try_recv() { + if let Some(watch_sandboxes_event::Payload::PlatformEvent(value)) = event.payload + && let Some(event) = value.event + { + reasons.push(event.reason); + } + } + reasons + } + + #[tokio::test] + async fn cached_digest_pinned_image_plan_skips_the_worker_only_on_a_digest_cache_hit() { + #[allow(clippy::struct_excessive_bools)] + struct Case<'a> { + name: &'static str, + bootstrap_ref: &'a str, + image_ref: &'a str, + rootfs_tar: bool, + cached: bool, + bootstrap_only: bool, + /// Answered without the worker. + fast: bool, + } + const DIGEST: &str = + "sha256:6c70a5370000000000000000000000000000000000000000000000000000beef"; + let pinned = format!("registry.example.com/sandbox:1@{DIGEST}"); + let tag = "registry.example.com/sandbox:1"; + let other = "registry.example.com/other@sha256:00"; + let local_pinned = format!("localhost/sandbox@{DIGEST}"); + let identity = bootstrap_image_cache_identity(DIGEST); + + let hit = Case { + name: "bootstrap-only hit", + bootstrap_ref: &pinned, + image_ref: &pinned, + rootfs_tar: false, + cached: true, + bootstrap_only: true, + fast: true, + }; + let cases = [ + Case { + name: "workload is the bootstrap image", + bootstrap_only: false, + ..hit + }, + Case { + name: "cache miss", + cached: false, + fast: false, + ..hit + }, + Case { + name: "tag", + bootstrap_ref: tag, + image_ref: tag, + fast: false, + ..hit + }, + Case { + name: "other workload image", + image_ref: other, + bootstrap_only: false, + fast: false, + ..hit + }, + Case { + name: "rootfs tar", + rootfs_tar: true, + bootstrap_only: false, + fast: false, + ..hit + }, + Case { + name: "no registry host (local engine image)", + bootstrap_ref: &local_pinned, + image_ref: &local_pinned, + fast: false, + ..hit + }, + Case { + name: "locally built image", + bootstrap_ref: "openshell/sandbox-from:1", + image_ref: "openshell/sandbox-from:1", + fast: false, + ..hit + }, + hit, + ]; + for Case { + name: case, + bootstrap_ref, + image_ref, + rootfs_tar: tar, + cached, + bootstrap_only, + fast, + } in cases + { + let root = tempfile::tempdir().unwrap(); + let cached_root = image_cache_rootfs_image(root.path(), &identity); + let worker_plan = RuntimeImagePlan { + root_disk: root.path().join("from-worker.ext4"), + image_disk: None, + image_identity: "worker".to_string(), + bootstrap_image_identity: "worker".to_string(), + }; + let driver = + cached_image_test_driver(root.path(), bootstrap_ref, "sb", &worker_plan).await; + if cached { + fs::create_dir_all(cached_root.parent().unwrap()).unwrap(); + fs::write(&cached_root, b"cached bootstrap").unwrap(); + } + let tar_path = root.path().join("rootfs.tar"); + let mut events = driver.events.subscribe(); + + let plan = driver + .prepare_images( + "sb", + image_ref, + tar.then_some(tar_path.as_path()), + bootstrap_only, + ) + .await + .unwrap_or_else(|error| panic!("{case}: {error}")); + + let worker_ran = root.path().join("worker-runs").exists(); + assert_eq!(worker_ran, !fast, "{case}: worker ran"); + if fast { + assert_eq!(plan.root_disk, cached_root, "{case}"); + assert_eq!(plan.image_disk, None, "{case}"); + assert_eq!(plan.image_identity, identity, "{case}"); + assert_eq!(plan.bootstrap_image_identity, identity, "{case}"); + assert_eq!( + platform_event_reasons(&mut events), + ["Pulling", "CacheHit", "Pulled"], + "{case}: the worker's events" + ); + } else { + assert_eq!(plan.root_disk, worker_plan.root_disk, "{case}"); + } + assert!( + driver.registry.lock().await["sb"].preparation.is_none(), + "{case}" + ); + } + } + + #[tokio::test] + async fn cached_digest_pinned_image_plan_keeps_the_worker_path_errors() { + const PINNED: &str = "registry.example.com/sandbox@sha256:00"; + let root = tempfile::tempdir().unwrap(); + let plan = RuntimeImagePlan { + root_disk: root.path().join("unused"), + image_disk: None, + image_identity: String::new(), + bootstrap_image_identity: String::new(), + }; + let driver = cached_image_test_driver(root.path(), PINNED, "sb", &plan).await; + let cached_root = + image_cache_rootfs_image(root.path(), &bootstrap_image_cache_identity("sha256:00")); + fs::create_dir_all(cached_root.parent().unwrap()).unwrap(); + fs::write(&cached_root, b"cached bootstrap").unwrap(); + + let error = driver + .prepare_images("missing", PINNED, None, true) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Cancelled); + driver.registry.lock().await.get_mut("sb").unwrap().deleting = true; + let error = driver + .prepare_images("sb", PINNED, None, true) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Cancelled); + assert!(!root.path().join("worker-runs").exists()); + } + #[tokio::test] async fn blocked_worker_does_not_delay_independent_image_and_overlay_requests() { let root = tempfile::tempdir().unwrap(); diff --git a/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs b/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs index 8308849..18a32a8 100644 --- a/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs +++ b/vendor/openshell/crates/openshell-driver-vm/src/rootfs.rs @@ -10,8 +10,8 @@ use std::io::BufWriter; use std::io::{BufRead, BufReader, Cursor, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::OnceLock; use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock, PoisonError}; use crate::driver::{DEFAULT_SANDBOX_UID, PREPARED_IMAGE_ROOTFS_DIR}; @@ -40,7 +40,20 @@ pub const fn sandbox_guest_init_path() -> &'static str { /// /// Including this in the image-cache key makes local, uncommitted guest-sandbox /// changes invalidate the cache even when the `OpenShell` version is unchanged. +/// build.rs hashes the same bytes the crate embeds, once per build: every +/// sandbox launch resolves its root disk in a fresh preparation worker +/// process, which hashed the embedded blobs again each time. pub fn sandbox_guest_runtime_identity() -> String { + GUEST_RUNTIME_IDENTITY.to_string() +} + +const GUEST_RUNTIME_IDENTITY: &str = + include_str!(concat!(env!("OUT_DIR"), "/guest-runtime-identity")); + +/// The identity hashed from the embedded bytes at run time, as it was +/// before build.rs computed it; the tests hold the two equal. +#[cfg(test)] +fn sandbox_guest_runtime_identity_of_embedded_bytes() -> String { let mut hasher = Sha256::new(); hasher.update(SANDBOX); hasher.update(VM_INIT); @@ -62,8 +75,122 @@ pub fn extract_host_supervisor(path: &Path) -> Result<(), String> { validate_host_supervisor(path) } +/// Check the cached host supervisor against the embedded one. +/// +/// Every sandbox launch asks, and hashing the ~50 MB file each time cost a +/// launch hundreds of milliseconds of CPU on a host without SHA +/// instructions. A file this driver process has hashed and found good is +/// not hashed again while its identity is unchanged: device, inode, size, +/// mode, mtime and ctime. Any write, chmod, chown, rename or replacement of +/// the file changes its ctime or inode (the kernel sets ctime; no caller can +/// set it back), so it is hashed again. The kernel stamps ctime from a +/// coarse clock, so a rewrite within the same tick as the last change can +/// keep the same ctime: only a file whose ctime is at least +/// [`SETTLED_CTIME`] in the past is remembered (git's "racily clean" rule), +/// and any later change then gets a later ctime. A new driver process +/// remembers nothing: it hashes once more on its first launch. pub fn validate_host_supervisor(path: &Path) -> Result<(), String> { - validate_host_supervisor_digest(path, embedded_host_supervisor_digest()?) + static VALIDATED: Mutex> = Mutex::new(None); + validate_host_supervisor_once( + path, + embedded_host_supervisor_digest()?, + &VALIDATED, + validate_host_supervisor_digest, + ) +} + +/// How old a file's ctime must be before its stamp is trusted to change +/// with its next modification: well above any kernel timestamp tick. +const SETTLED_CTIME: std::time::Duration = std::time::Duration::from_secs(1); + +/// A cached host supervisor that matched `digest` when it had `stamp`. +#[derive(Clone, PartialEq, Eq)] +struct ValidatedHostSupervisor { + path: PathBuf, + stamp: FileStamp, + digest: [u8; 32], +} + +/// What identifies one version of a file without reading it. +#[derive(Clone, Copy, PartialEq, Eq)] +struct FileStamp { + dev: u64, + ino: u64, + size: u64, + mode: u32, + mtime: (i64, i64), + ctime: (i64, i64), +} + +impl FileStamp { + #[cfg(unix)] + #[allow(clippy::unnecessary_wraps)] + fn of(metadata: &fs::Metadata) -> Option { + use std::os::unix::fs::MetadataExt as _; + Some(Self { + dev: metadata.dev(), + ino: metadata.ino(), + size: metadata.size(), + mode: metadata.mode(), + mtime: (metadata.mtime(), metadata.mtime_nsec()), + ctime: (metadata.ctime(), metadata.ctime_nsec()), + }) + } + + #[cfg(not(unix))] + fn of(_metadata: &fs::Metadata) -> Option { + None + } + + fn read(path: &Path) -> Option { + fs::symlink_metadata(path).ok().as_ref().and_then(Self::of) + } + + /// Whether the last change is [`SETTLED_CTIME`] or more in the past. + fn settled(&self) -> bool { + let (secs, nanos) = self.ctime; + let (Ok(secs), Ok(nanos)) = (u64::try_from(secs), u32::try_from(nanos)) else { + return false; + }; + let ctime = std::time::UNIX_EPOCH + std::time::Duration::new(secs, nanos); + std::time::SystemTime::now() + .duration_since(ctime) + .is_ok_and(|age| age >= SETTLED_CTIME) + } +} + +fn validate_host_supervisor_once( + path: &Path, + expected: [u8; 32], + validated: &Mutex>, + validate: impl Fn(&Path, [u8; 32]) -> Result<(), String>, +) -> Result<(), String> { + let before = FileStamp::read(path); + let remembered = |stamp: FileStamp| ValidatedHostSupervisor { + path: path.to_path_buf(), + stamp, + digest: expected, + }; + if let Some(stamp) = before + && validated + .lock() + .unwrap_or_else(PoisonError::into_inner) + .as_ref() + .is_some_and(|known| *known == remembered(stamp)) + { + return Ok(()); + } + let result = validate(path, expected); + // Remember only a file that did not change while it was hashed and + // whose next change cannot share its ctime. + let after = FileStamp::read(path); + *validated.lock().unwrap_or_else(PoisonError::into_inner) = match (&result, before, after) { + (Ok(()), Some(before), Some(after)) if before == after && before.settled() => { + Some(remembered(before)) + } + _ => None, + }; + result } fn validate_host_supervisor_digest(path: &Path, expected: [u8; 32]) -> Result<(), String> { @@ -316,55 +443,85 @@ pub fn clone_or_copy_sparse_file(source: &Path, dest: &Path) -> Result<(), Strin }) } -pub fn write_rootfs_image_file( - image_path: &Path, - guest_path: &str, - contents: &[u8], -) -> Result<(), String> { - ensure_rootfs_image_parent_dirs(image_path, guest_path); +/// Writes into one ext4 image, run as ONE `debugfs -w -f` process. +/// +/// Each staged item is exactly the command sequence the single-file helpers +/// used to run as one `debugfs -w -R` process per command: a `mkdir` per +/// parent component, `rm` and `write` for a file, `set_inode_field ... mode` +/// for a mode, `rm` for a removal, in the order they were staged. debugfs +/// reports a failing command (an existing directory, a missing file) on +/// stderr and exits 0 in both modes: only an unknown command or a failure to +/// run debugfs fails the run, so one batch leaves the same disk contents and +/// the same success or failure as the separate runs did, in one process +/// instead of about thirty per sandbox launch. A path debugfs cannot take +/// on one line (a newline, carriage return or NUL in it) is refused when it +/// is staged, before anything is written. Staged file contents live in +/// temporary files beside the image until the batch has run or is dropped. +pub struct RootfsImageBatch { + image_path: PathBuf, + commands: Vec, + staged_files: Vec, +} + +impl RootfsImageBatch { + pub fn new(image_path: &Path) -> Self { + Self { + image_path: image_path.to_path_buf(), + commands: Vec::new(), + staged_files: Vec::new(), + } + } - let tmp_path = temporary_injection_path(image_path); - fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - let Some(quoted_tmp_path) = debugfs_quote_argument(&tmp_path.to_string_lossy()) else { - let _ = fs::remove_file(&tmp_path); - return Err(format!( - "invalid debugfs injection path '{}'", - tmp_path.display() + /// Replace `guest_path` with `contents`, creating missing parents. + pub fn write_file(&mut self, guest_path: &str, contents: &[u8]) -> Result<(), String> { + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + let mut commands = rootfs_image_parent_dir_commands(guest_path)?; + let tmp_path = temporary_injection_path(&self.image_path); + let quoted_tmp_path = debugfs_quote_argument(&tmp_path.to_string_lossy()) + .ok_or_else(|| format!("invalid debugfs injection path '{}'", tmp_path.display()))?; + fs::write(&tmp_path, contents).map_err(|e| format!("write {}: {e}", tmp_path.display()))?; + self.staged_files.push(tmp_path); + commands.push(format!("rm {quoted_guest_path}")); + commands.push(format!("write {quoted_tmp_path} {quoted_guest_path}")); + self.commands.append(&mut commands); + Ok(()) + } + + /// Set the permission bits of the regular file at `guest_path`. + pub fn set_file_mode(&mut self, guest_path: &str, mode: u32) -> Result<(), String> { + let regular_file_mode = 0o100_000 | (mode & 0o7777); + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + self.commands.push(format!( + "set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}" )); - }; - let _ = run_debugfs(image_path, &format!("rm {quoted_guest_path}")); - let result = run_debugfs( - image_path, - &format!("write {quoted_tmp_path} {quoted_guest_path}"), - ); - let _ = fs::remove_file(&tmp_path); - result -} + Ok(()) + } -pub fn remove_rootfs_image_file(image_path: &Path, guest_path: &str) -> Result<(), String> { - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs(image_path, &format!("rm {quoted_guest_path}")) + /// Remove the file at `guest_path` (nothing happens when it is absent). + pub fn remove_file(&mut self, guest_path: &str) -> Result<(), String> { + let quoted_guest_path = debugfs_quote_absolute_path(guest_path) + .ok_or_else(|| format!("invalid debugfs guest path '{guest_path}'"))?; + self.commands.push(format!("rm {quoted_guest_path}")); + Ok(()) + } + + /// Run every staged command in one debugfs process. + pub fn commit(self) -> Result<(), String> { + if self.commands.is_empty() { + return Ok(()); + } + run_debugfs_batch(&self.image_path, &self.commands) + } } -pub fn set_rootfs_image_file_mode( - image_path: &Path, - guest_path: &str, - mode: u32, -) -> Result<(), String> { - let regular_file_mode = 0o100_000 | (mode & 0o7777); - let Some(quoted_guest_path) = debugfs_quote_absolute_path(guest_path) else { - return Err(format!("invalid debugfs guest path '{guest_path}'")); - }; - run_debugfs( - image_path, - &format!("set_inode_field {quoted_guest_path} mode 0{regular_file_mode:o}"), - ) +impl Drop for RootfsImageBatch { + fn drop(&mut self) { + for path in self.staged_files.drain(..) { + let _ = fs::remove_file(path); + } + } } /// Write a tree of files into an ext4 image in one `debugfs` session. @@ -782,9 +939,14 @@ fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), St )) } -fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { +/// The `mkdir` commands for every parent component of `guest_path`, as +/// the single-file writer always issued them (unquoted, existing ones fail +/// harmlessly). A component debugfs would read as more than one line is +/// refused. +fn rootfs_image_parent_dir_commands(guest_path: &str) -> Result, String> { + let mut commands = Vec::new(); let Some(parent) = Path::new(guest_path).parent() else { - return; + return Ok(commands); }; let mut current = String::new(); for component in parent.components() { @@ -792,10 +954,14 @@ fn ensure_rootfs_image_parent_dirs(image_path: &Path, guest_path: &str) { if part == "/" || part.is_empty() { continue; } + if part.contains(['\0', '\n', '\r']) { + return Err(format!("invalid debugfs guest path '{guest_path}'")); + } current.push('/'); current.push_str(&part); - let _ = run_debugfs(image_path, &format!("mkdir {current}")); + commands.push(format!("mkdir {current}")); } + Ok(commands) } fn normalize_sandbox_owner_in_rootfs_image(source: &Path, image_path: &Path) -> Result<(), String> { @@ -1084,6 +1250,9 @@ fn run_debugfs_batch_file(image_path: &Path, command_path: &Path) -> Result<(), } } +/// One debugfs process per command: what the overlay writes did before +/// [`RootfsImageBatch`]; the batch tests compare against it. +#[cfg(test)] fn run_debugfs(image_path: &Path, command: &str) -> Result<(), String> { let output = e2fs_command("debugfs")? .arg("-w") @@ -1332,6 +1501,92 @@ mod tests { use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{SystemTime, UNIX_EPOCH}; + #[test] + fn guest_runtime_identity_built_once_matches_the_embedded_bytes() { + let identity = sandbox_guest_runtime_identity(); + assert_eq!(identity.len(), 64, "{identity}"); + assert!(identity.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert_eq!(identity, sandbox_guest_runtime_identity_of_embedded_bytes()); + } + + #[cfg(target_os = "linux")] + #[test] + fn host_supervisor_validated_once_per_file_version() { + use std::sync::atomic::AtomicUsize; + + // Past the settle time: the file's last change is then remembered. + let settle = || std::thread::sleep(SETTLED_CTIME + std::time::Duration::from_millis(100)); + let directory = tempfile::tempdir().expect("cache directory"); + let path = directory.path().join("openshell-sandbox"); + let good = b"trusted supervisor".as_slice(); + let bad = b"tampered supervisor".as_slice(); + fs::write(&path, good).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + let expected = sha256_bytes(good); + let validated = Mutex::new(None); + let hashes = AtomicUsize::new(0); + let count = |path: &Path, expected| { + hashes.fetch_add(1, Ordering::Relaxed); + validate_host_supervisor_digest(path, expected) + }; + let check = |path: &Path| validate_host_supervisor_once(path, expected, &validated, count); + let hash_count = || hashes.load(Ordering::Relaxed); + + // Just written: a rewrite in the same timestamp tick could keep the + // stamp, so it is not remembered yet. + check(&path).expect("first launch hashes the cache"); + check(&path).expect("hashed again"); + assert_eq!(hash_count(), 2, "a just-changed file is not remembered"); + settle(); + check(&path).expect("settled"); + check(&path).expect("later launch"); + check(&path).expect("later launch"); + assert_eq!(hash_count(), 3, "hashed once while unchanged"); + + // Rewritten in place (same inode, same size as the good file). + let mut same_size = bad[..good.len()].to_vec(); + same_size[0] = b'X'; + fs::write(&path, &same_size).unwrap(); + assert!( + check(&path).is_err(), + "a rewrite is hashed again and refused" + ); + assert!(check(&path).is_err(), "a refused file is never remembered"); + assert_eq!(hash_count(), 5); + + // Good again, then replaced by rename (a new inode). + fs::write(&path, good).unwrap(); + settle(); + check(&path).expect("good content again"); + let replacement = directory.path().join("replacement"); + fs::write(&replacement, bad).unwrap(); + fs::set_permissions(&replacement, fs::Permissions::from_mode(0o755)).unwrap(); + fs::rename(&replacement, &path).unwrap(); + assert!(check(&path).is_err(), "a replaced file is hashed again"); + assert_eq!(hash_count(), 7); + + // Good again, then made non-executable: the mode is part of the stamp. + fs::write(&path, good).unwrap(); + settle(); + check(&path).expect("good content again"); + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + assert!(check(&path).is_err(), "a non-executable cache is refused"); + + // A different embedded supervisor (a new driver build) never reuses + // the memory of another digest, nor does a new driver process. + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + settle(); + check(&path).expect("good and executable"); + let before = hash_count(); + assert!( + validate_host_supervisor_once(&path, sha256_bytes(bad), &validated, count).is_err() + ); + let fresh_process = Mutex::new(None); + validate_host_supervisor_once(&path, expected, &fresh_process, count) + .expect("a new process hashes again"); + assert_eq!(hash_count(), before + 2); + } + #[cfg(target_os = "linux")] #[test] fn host_supervisor_cache_rejects_wrong_content_and_installs_atomically() { @@ -1717,6 +1972,178 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + /// What the overlay writes did before the batch: one debugfs process + /// per command, in the same order. + enum LegacyOp<'a> { + Write(&'a str, &'a [u8]), + Mode(&'a str, u32), + Remove(&'a str), + } + + fn legacy_apply(image: &Path, op: &LegacyOp<'_>) { + match op { + LegacyOp::Write(guest_path, contents) => { + let parent = Path::new(guest_path).parent().unwrap(); + let mut current = String::new(); + for component in parent.components() { + let part = component.as_os_str().to_string_lossy(); + if part == "/" || part.is_empty() { + continue; + } + current.push('/'); + current.push_str(&part); + let _ = run_debugfs(image, &format!("mkdir {current}")); + } + let tmp = temporary_injection_path(image); + fs::write(&tmp, contents).unwrap(); + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + let source = debugfs_quote_argument(&tmp.to_string_lossy()).unwrap(); + let _ = run_debugfs(image, &format!("rm {guest}")); + run_debugfs(image, &format!("write {source} {guest}")).unwrap(); + fs::remove_file(&tmp).unwrap(); + } + LegacyOp::Mode(guest_path, mode) => { + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + let mode = 0o100_000 | (mode & 0o7777); + run_debugfs(image, &format!("set_inode_field {guest} mode 0{mode:o}")).unwrap(); + } + LegacyOp::Remove(guest_path) => { + let guest = debugfs_quote_absolute_path(guest_path).unwrap(); + run_debugfs(image, &format!("rm {guest}")).unwrap(); + } + } + } + + fn batch_apply(batch: &mut RootfsImageBatch, op: &LegacyOp<'_>) { + match op { + LegacyOp::Write(guest_path, contents) => batch.write_file(guest_path, contents), + LegacyOp::Mode(guest_path, mode) => batch.set_file_mode(guest_path, *mode), + LegacyOp::Remove(guest_path) => batch.remove_file(guest_path), + } + .unwrap(); + } + + fn debugfs_read(image: &Path, command: &str) -> String { + let output = e2fs_command("debugfs") + .unwrap() + .arg("-R") + .arg(command) + .arg(image) + .output() + .unwrap(); + assert!(output.status.success(), "debugfs {command}"); + String::from_utf8_lossy(&output.stdout).into_owned() + } + + /// Every entry under `dirs` as debugfs's parseable listing (inode, mode, + /// uid, gid, name, size: no timestamps) plus every regular file's bytes. + fn image_tree(image: &Path, dirs: &[&str]) -> Vec { + let mut tree = Vec::new(); + for dir in dirs { + let listing = debugfs_read(image, &format!("ls -p {dir}")); + for line in listing.lines().filter(|line| line.starts_with('/')) { + tree.push(format!("{dir} {line}")); + let fields: Vec<&str> = line.split('/').collect(); + if fields.len() > 5 && fields[2].starts_with("100") { + let path = format!("{dir}/{}", fields[5]); + let quoted = debugfs_quote_absolute_path(&path).unwrap(); + tree.push(format!( + "{path} = {:?}", + debugfs_read(image, &format!("cat {quoted}")) + )); + } + } + } + tree + } + + #[test] + fn rootfs_image_batch_writes_what_one_debugfs_per_command_wrote() { + if e2fs_command("debugfs").is_err() { + return; + } + let dir = unique_temp_dir(); + let source = dir.join("source"); + fs::create_dir_all(source.join("upper/etc/openshell/init.d")).unwrap(); + fs::write(source.join("upper/etc/openshell/init.d/stale"), "old\n").unwrap(); + let legacy = dir.join("legacy.ext4"); + let batched = dir.join("batched.ext4"); + create_ext4_image_from_dir_with_size(&source, &legacy, 64 * 1024 * 1024).unwrap(); + fs::copy(&legacy, &batched).unwrap(); + + // The launch's shape: drop-ins (an existing one replaced), a + // manifest, credentials 0600 in a new nested directory, a removal, + // and the harmless failures (mode or removal of a missing file). + let ops = [ + LegacyOp::Write("/upper/etc/openshell/init.d/stale", b"new\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d/stale", 0o755), + LegacyOp::Write("/upper/etc/openshell/init.d/two", b"#!/bin/sh\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d/two", 0o755), + LegacyOp::Write("/upper/etc/openshell/init.d.manifest", b"stale\ntwo\n"), + LegacyOp::Mode("/upper/etc/openshell/init.d.manifest", 0o644), + LegacyOp::Write("/upper/.openshell/boundary/sandbox-g1.key", b"key"), + LegacyOp::Mode("/upper/.openshell/boundary/sandbox-g1.key", 0o600), + LegacyOp::Write("/upper/.openshell/boundary/with space.json", b"{}"), + LegacyOp::Remove("/upper/.openshell/boundary/sandbox-g1.key"), + LegacyOp::Write("/upper/.openshell/boundary/sandbox-g1.key", b"key2"), + LegacyOp::Remove("/upper/missing"), + LegacyOp::Mode("/upper/missing", 0o600), + ]; + for op in &ops { + legacy_apply(&legacy, op); + } + let mut batch = RootfsImageBatch::new(&batched); + for op in &ops { + batch_apply(&mut batch, op); + } + batch.commit().expect("one debugfs run"); + + let dirs = [ + "/upper", + "/upper/etc/openshell", + "/upper/etc/openshell/init.d", + "/upper/.openshell", + "/upper/.openshell/boundary", + ]; + let expected = image_tree(&legacy, &dirs); + assert!( + expected + .iter() + .any(|entry| entry.contains("100755/0/0/stale/4/")), + "{expected:#?}" + ); + assert_eq!(image_tree(&batched, &dirs), expected); + assert!( + fs::read_dir(&dir).unwrap().all(|entry| !entry + .unwrap() + .file_name() + .to_string_lossy() + .contains("inject")), + "staged contents are removed after the run" + ); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn rootfs_image_batch_refuses_a_path_debugfs_reads_as_two_lines() { + let dir = unique_temp_dir(); + fs::create_dir_all(&dir).unwrap(); + let image = dir.join("overlay.ext4"); + let mut batch = RootfsImageBatch::new(&image); + batch.write_file("/upper/ok", b"staged").unwrap(); + assert!(batch.write_file("/upper/a\nrm /etc/x", b"x").is_err()); + assert!(batch.write_file("/upper/a\nb/file", b"x").is_err()); + assert!(batch.set_file_mode("/upper/a\rb", 0o600).is_err()); + assert!(batch.remove_file("relative").is_err()); + assert_eq!(batch.commands.len(), 3, "only the valid write is staged"); + drop(batch); + assert!( + fs::read_dir(&dir).unwrap().next().is_none(), + "a dropped batch removes its staged contents" + ); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn ext4_image_has_directory_distinguishes_directories_files_and_missing_paths() { if e2fs_command("debugfs").is_err() {