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/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..29f01dca75 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; @@ -3301,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? @@ -3312,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), @@ -5882,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() } @@ -7414,17 +7537,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 +7749,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 +7760,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 +7828,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 +7840,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 +7861,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 +7927,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 +9627,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" ); } @@ -10905,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(); diff --git a/crates/openshell-driver-vm/src/rootfs.rs b/crates/openshell-driver-vm/src/rootfs.rs index a292e81994..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); @@ -321,50 +334,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 +753,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 +768,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 +1064,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") @@ -1250,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() { @@ -1636,6 +1709,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() {