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..7da062c62c 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -3301,6 +3301,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 +3342,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 +5999,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() } @@ -10905,6 +11030,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..933eba01ee 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); @@ -1250,6 +1263,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() {