From 28bc9bd15827ffebeefcaccc456047fe50e54327 Mon Sep 17 00:00:00 2001 From: Balaji Ganesan Date: Sat, 28 Nov 2026 09:11:31 -0800 Subject: [PATCH 1/5] perf(vm): write a launch's overlay files in one debugfs run A sandbox launch writes its per-sandbox files into the overlay ext4 (the init drop-ins and their manifest, the mount manifest, then the boundary configuration, certificate and key) with one `debugfs -w -R` process per command: a mkdir per parent directory, rm and write per file, set_inode_field per mode. That is about thirty debugfs processes per launch. Measured with the same debugfs, overlay template and commands on an x86-64 workstation: 152 to 183 ms as separate processes, 7 to 9 ms as one `debugfs -f` run. RootfsImageBatch stages the same commands in the same order and runs them as one `debugfs -w -f` process (the existing run_debugfs_batch): one run for the guest overlay files, one for the boundary bundle (the boundary provisioning sits between the two), and one for the three removals of a runtime generation's material. debugfs reports a failing command (an existing directory, a missing file) on stderr and exits 0 in both modes, so a batch leaves the same disk contents and the same success or failure as the separate runs. A path debugfs would read as two lines is refused when it is staged, before anything is written, and staged contents are removed when the batch has run or is dropped. The vm.prepare_guest span moves to prepare_guest_overlay, which stages the drop-ins and the mount manifest and writes them, so it now covers the mount manifest and the write itself. Test: rootfs_image_batch_writes_what_one_debugfs_per_command_wrote applies the launch's shape of writes, modes and removals (including the harmless failures) both ways to copies of one image and compares every entry's mode, owner, size and contents; rootfs_image_batch_refuses_a_path_debugfs_reads_as_two_lines covers the refusal and the cleanup of a dropped batch. Closes #6054 Signed-off-by: Balaji Ganesan --- crates/openshell-driver-vm/src/driver.rs | 120 +++++---- crates/openshell-driver-vm/src/rootfs.rs | 308 +++++++++++++++++++---- 2 files changed, 337 insertions(+), 91 deletions(-) diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..1e0faf12c4 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -19,12 +19,11 @@ use crate::lifecycle::{ RestoreContext, 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::runtime::VmBackend; use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64_STANDARD}; @@ -2053,12 +2052,11 @@ impl VmDriver { // The mount manifest is always written, even when empty, so an // image-supplied manifest in the lowerdir can never drive guest mounts. - if let Err(err) = inject_guest_init_dropins(&overlay_disk, &plan.guest_init_dropins) - .and_then(|()| { - inject_guest_mount_manifest(&overlay_disk, &driver_config.mounts) - .map_err(|error| Status::internal(format!("inject VM mount manifest: {error}"))) - }) - { + if let Err(err) = prepare_guest_overlay( + &overlay_disk, + &plan.guest_init_dropins, + &driver_config.mounts, + ) { self.lifecycle_extensions .after_launch_failed(&sandbox, &state_dir, LaunchAbortReason::GuestPrepareFailed) .await; @@ -7414,17 +7412,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}"))??; @@ -7628,8 +7624,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, @@ -7638,23 +7635,58 @@ 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() } fn inject_guest_mount_manifest( - overlay_disk: &Path, + batch: &mut RootfsImageBatch, mounts: &[VmMountConfig], ) -> Result<(), String> { let manifest = render_mount_manifest(mounts); let guest_path = overlay_upper_path("/.openshell/mounts.manifest"); - write_rootfs_image_file(overlay_disk, &guest_path, manifest.as_bytes())?; - set_rootfs_image_file_mode(overlay_disk, &guest_path, 0o644)?; + batch.write_file(&guest_path, manifest.as_bytes())?; + batch.set_file_mode(&guest_path, 0o644)?; Ok(()) } +/// Write the launch's guest overlay files: the init drop-ins, their +/// manifest and the mount manifest. Every file is staged first and the +/// overlay is written by one debugfs run ([`RootfsImageBatch`]), so a +/// staging failure writes nothing. +#[allow(clippy::result_large_err)] +#[tracing::instrument( + name = "vm.prepare_guest", + skip(dropins, mounts), + 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], + mounts: &[VmMountConfig], +) -> 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(|()| { + inject_guest_mount_manifest(&mut batch, mounts) + .map_err(|error| Status::internal(format!("inject VM mount manifest: {error}"))) + }) + .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 { format!("{GUEST_BOUNDARY_CONFIG_DIR}/bootstrap-{generation}.json") } @@ -7671,21 +7703,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 @@ -7694,13 +7715,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 @@ -7713,8 +7736,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. @@ -7780,17 +7802,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}" )) @@ -9480,7 +9502,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" ); } diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index a292e81994..09eb10bfa2 100644 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ b/crates/openshell-driver-vm/src/rootfs.rs @@ -321,50 +321,90 @@ pub fn write_rootfs_image_file( guest_path: &str, contents: &[u8], ) -> Result<(), String> { - ensure_rootfs_image_parent_dirs(image_path, guest_path); + let mut batch = RootfsImageBatch::new(image_path); + batch.write_file(guest_path, contents)?; + batch.commit() +} - 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() - )); - }; - 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 +/// 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, } -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}")) +impl RootfsImageBatch { + pub fn new(image_path: &Path) -> Self { + Self { + image_path: image_path.to_path_buf(), + commands: Vec::new(), + staged_files: Vec::new(), + } + } + + /// 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}" + )); + Ok(()) + } + + /// 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); + } + } } /// Replay the ext4 journal and repair automatically correctable filesystem @@ -700,9 +740,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() { @@ -710,10 +755,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> { @@ -1002,6 +1051,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") @@ -1636,6 +1688,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() { From ea6c298dbe3102733fa7d74dc2ecc888caa3c3dd Mon Sep 17 00:00:00 2001 From: Balaji Ganesan Date: Sat, 28 Nov 2026 09:12:14 -0800 Subject: [PATCH 2/5] perf(vm): hash the guest runtime identity at build time Every bootstrap root disk's image cache key includes sandbox_guest_runtime_identity(), a SHA-256 over the embedded sandbox, vm-init and umoci blobs and the guest init script. It was computed on every call, and every launch resolves its root disk in a fresh image preparation worker process, so every launch hashed the embedded blobs again, even on a cache hit. On an x86-64 host without SHA instructions most of the 90 ms between the worker's "ensuring cached root disk image" and its cache hit is this hash (inferred from the driver log gap, not profiled). build.rs now hashes exactly the files the crate embeds (from OUT_DIR, plus the init script, which build.rs now watches) and the function returns that constant. The value is unchanged, so cached root disks stay valid. Test: guest_runtime_identity_built_once_matches_the_embedded_bytes holds the build-time value equal to the hash of the embedded bytes computed at run time, as before. Closes #6054 Signed-off-by: Balaji Ganesan --- crates/openshell-driver-vm/Cargo.toml | 4 +++ crates/openshell-driver-vm/build.rs | 43 ++++++++++++++++++++++-- crates/openshell-driver-vm/src/rootfs.rs | 21 ++++++++++++ 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index 7ef0c7e351..4d89f597f8 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -66,6 +66,10 @@ sha2 = { version = "0.10", optional = true } toml = { workspace = true, optional = true } zstd = { version = "0.14", optional = true } +[build-dependencies] +# The guest runtime identity is hashed once, at build time (build.rs). +sha2 = { workspace = true } + [features] default = ["compute-driver", "telemetry"] ## Build the standalone compute driver and its host runtime implementation. diff --git a/crates/openshell-driver-vm/build.rs b/crates/openshell-driver-vm/build.rs index 92525927d8..d0618782af 100644 --- a/crates/openshell-driver-vm/build.rs +++ b/crates/openshell-driver-vm/build.rs @@ -6,6 +6,7 @@ //! This crate embeds the sandbox, host supervisor, and minimal libkrun runtime //! artifacts it needs to boot VMs without a separate VM runtime binary. +use sha2::{Digest, Sha256}; use std::path::{Path, PathBuf}; use std::{env, fs}; @@ -14,6 +15,43 @@ fn main() { return; } + let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); + 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"); if let Ok(dir) = env::var("OPENSHELL_VM_RUNTIME_COMPRESSED_DIR") { @@ -32,7 +70,6 @@ fn main() { } } - let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set")); let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default(); @@ -42,7 +79,7 @@ fn main() { _ => { println!("cargo:warning=VM runtime not available for {target_os}-{target_arch}"); generate_stub_resources( - &out_dir, + out_dir, &[ "libkrun", "libkrunfw", @@ -62,7 +99,7 @@ fn main() { println!("cargo:warning=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR not set"); println!("cargo:warning=Run: mise run vm:setup && mise run vm:supervisor"); generate_stub_resources( - &out_dir, + out_dir, &[ &format!("{libkrun_name}.zst"), &format!("{libkrunfw_name}.zst"), diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index 09eb10bfa2..6459dc3b93 100644 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ b/crates/openshell-driver-vm/src/rootfs.rs @@ -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); @@ -1302,6 +1315,14 @@ 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_cache_rejects_wrong_content_and_installs_atomically() { From 246766ca424a17bd2cf2f18106f0f484ea013c8a Mon Sep 17 00:00:00 2001 From: Balaji Ganesan Date: Sat, 28 Nov 2026 09:12:55 -0800 Subject: [PATCH 3/5] perf(vm): hash the cached host supervisor once per file version Every launch validates the cached host supervisor in host_supervisor_binary by hashing all of it (about 50 MB) on an async runtime thread. On an x86-64 host without SHA instructions the driver log shows about 280 ms between "launcher spawned" and the host supervisor's start, consistent with a software SHA-256 of that file (inferred, not profiled). It runs while the guest boots, so it is mostly hidden today, but it becomes the floor of a launch once the guest boots faster, and it holds a runtime thread meanwhile. A file this driver process hashed and found good is not hashed again while its device, inode, size, mode, mtime and ctime are unchanged. Any write, chmod, chown, rename or replacement changes the ctime (set by the kernel; no caller can set it back) or the inode, and the file is hashed again. The kernel stamps ctime from a coarse clock, so a rewrite in the same tick as the file's last change can keep its ctime: only a file whose ctime is at least 1 s old is remembered (git's "racily clean" rule), so any later change gets a later ctime. Only a file unchanged across its own hash is remembered, a refused file never is, the memory is per embedded supervisor digest, and a new driver process hashes again on its first launch. Test: host_supervisor_validated_once_per_file_version counts the hashes across a just-written file (not remembered), a settled file (hashed once), a same-size rewrite in place, a replacement by rename, a chmod that drops the execute bit, another embedded digest and a fresh process. Closes #6054 Signed-off-by: Balaji Ganesan --- crates/openshell-driver-vm/src/rootfs.rs | 196 ++++++++++++++++++++++- 1 file changed, 194 insertions(+), 2 deletions(-) diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index 6459dc3b93..8f190256ac 100644 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ b/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}; @@ -75,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> { @@ -1323,6 +1437,84 @@ mod tests { 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() { From 74add27318b50636743935cba4beaa11373786c2 Mon Sep 17 00:00:00 2001 From: Balaji Ganesan Date: Mon, 30 Nov 2026 11:22:03 -0800 Subject: [PATCH 4/5] fix(vm): hash the cached host supervisor on every launch again This reverts commit 246766ca424a17bd2cf2f18106f0f484ea013c8a. The cache skipped the SHA-256 of the cached host supervisor when the file's path, device, inode, size, mode, mtime, ctime and the expected digest matched the last file found good. That metadata cannot vouch for the contents: a write through an already-open writable shared mapping changes the bytes without changing those fields (review on #6056 reproduced this on macOS; on Linux mtime and ctime move only on the first write fault after writeback, not on every write), so modified contents could keep passing validation. validate_host_supervisor therefore hashes the file on every launch again, as before. The per-launch check stays until the executable that is validated is also the one launched and cannot change afterwards, for example a sealed copy (a memfd with F_SEAL_WRITE). Refs #6054 Signed-off-by: Balaji Ganesan --- crates/openshell-driver-vm/src/rootfs.rs | 196 +---------------------- 1 file changed, 2 insertions(+), 194 deletions(-) diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index 8f190256ac..6459dc3b93 100644 --- a/crates/openshell-driver-vm/src/rootfs.rs +++ b/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}; @@ -75,122 +75,8 @@ 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> { - 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 + validate_host_supervisor_digest(path, embedded_host_supervisor_digest()?) } fn validate_host_supervisor_digest(path: &Path, expected: [u8; 32]) -> Result<(), String> { @@ -1437,84 +1323,6 @@ mod tests { 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() { From 286504a67a0a982014404c1da74612e5aa5d3498 Mon Sep 17 00:00:00 2001 From: Balaji Ganesan Date: Sat, 28 Nov 2026 09:17:23 -0800 Subject: [PATCH 5/5] perf(vm): resolve a cached digest-pinned bootstrap image without a worker Every launch starts an image preparation worker (an exec of the driver binary, which then probes for a local container engine, plus the parent's 10 ms exit poll) to resolve its root disk. When the workload image is the bootstrap image, pinned by digest, its root disk is cached and no local container engine answers, the worker writes nothing: it finds no engine and answers from the cache without a registry call (since #4582). The driver now answers that case in its own process, with the same logs and the same Pulling, CacheHit and Pulled events under the same vm.resolve_bootstrap_image span. Everything else keeps the worker: a rootfs tar, another workload image, a tag, a locally built image, a reachable container engine, a cache miss, a registry credential error, a missing bootstrap image, a sandbox that is gone or already preparing. Those checks run before any log or event, so the worker then prepares, reports and fails exactly as before. The overlay preparation keeps its worker. The engine probe is passed in (LocalEngineProbe) so the tests can run on a host where Docker answers. Test: cached_digest_pinned_image_plan_skips_the_worker_only_on_a_digest_cache_hit runs eight cases through a recording worker and checks which ones the worker answered, the plan and the events; it fails when the fast path is disabled. cached_digest_pinned_image_plan_keeps_the_worker_path_errors checks a missing and a deleting sandbox still fail as Cancelled with a cached root disk present. Closes #6055 Signed-off-by: Balaji Ganesan --- crates/openshell-driver-vm/src/driver.rs | 364 +++++++++++++++++++++++ 1 file changed, 364 insertions(+) diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 1e0faf12c4..29f01dca75 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -3299,6 +3299,36 @@ impl VmDriver { rootfs_tar: Option<&Path>, bootstrap_only: bool, ) -> Result { + self.prepare_images( + sandbox_id, + image_ref, + rootfs_tar, + bootstrap_only, + local_container_engine_reachable, + ) + .await + } + + async fn prepare_images( + &self, + sandbox_id: &str, + image_ref: &str, + rootfs_tar: Option<&Path>, + bootstrap_only: bool, + engine_reachable: LocalEngineProbe, + ) -> Result { + if let Some(plan) = self + .cached_digest_pinned_image_plan( + sandbox_id, + image_ref, + rootfs_tar, + bootstrap_only, + engine_reachable, + ) + .await + { + return Ok(plan); + } match self .run_preparation_in_worker(sandbox_id, image_ref, rootfs_tar, bootstrap_only, None) .await? @@ -3310,6 +3340,93 @@ 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: it probes for a local + /// container engine, finds none, 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 locally built image, a + /// reachable container engine, 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, + engine_reachable: LocalEngineProbe, + ) -> 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; + } + } + if is_openshell_local_build_image_ref(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() + || engine_reachable().await + { + 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 { + warn!( + image_ref = %resolved_ref, + "vm driver: no local container engine available, falling back to registry" + ); + 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), @@ -5880,6 +5997,14 @@ async fn connect_local_container_engine() -> Option { None } +/// Whether a local container engine answers; the image worker then takes +/// its local-image path instead of the registry cache. +type LocalEngineProbe = fn() -> futures::future::BoxFuture<'static, bool>; + +fn local_container_engine_reachable() -> futures::future::BoxFuture<'static, bool> { + Box::pin(async { connect_local_container_engine().await.is_some() }) +} + fn detect_podman_socket() -> Option { openshell_container_runtime::podman_socket::detect_socket() } @@ -10927,6 +11052,245 @@ 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, + gpu_bdf: 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 + } + + fn no_local_engine() -> futures::future::BoxFuture<'static, bool> { + Box::pin(async { false }) + } + + fn local_engine() -> futures::future::BoxFuture<'static, bool> { + Box::pin(async { true }) + } + + #[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, + probe: LocalEngineProbe, + /// 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 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, + probe: no_local_engine, + 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: "reachable container engine", + probe: local_engine, + 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, + probe, + 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, + probe, + ) + .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, no_local_engine) + .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, no_local_engine) + .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();