diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 69a0f766ad..f96c288697 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -259,6 +259,10 @@ const BOOTSTRAP_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-bootstrap-rootfs-ext const PREPARED_IMAGE_CACHE_LAYOUT_VERSION: &str = "sandbox-prepared-rootfs-ext4-umoci-v4"; const IMAGE_IDENTITY_FILE: &str = "image-identity"; const IMAGE_REFERENCE_FILE: &str = "image-reference"; +/// Digest-pinned form of a registry image reference, recorded when the +/// sandbox's writable overlay is first prepared. Restarts resolve this pin +/// instead of the tag so the overlay keeps the lower image it was built on. +const IMAGE_PINNED_REFERENCE_FILE: &str = "image-pinned-reference"; const IMAGE_PREP_INIT_MODE: &str = "image-prep"; const IMAGE_PREP_CONSOLE_LOG: &str = "image-prep-console.log"; /// Directory the guest image-prep init writes at the root of the prepared disk @@ -279,12 +283,17 @@ struct RuntimeImagePlan { image_disk: Option, image_identity: String, bootstrap_image_identity: String, + #[serde(default)] + pinned_image_ref: Option, } #[derive(Debug, Clone)] struct PreparedImageDisk { image_identity: String, disk_path: PathBuf, + /// Set only for registry images: the reference the disk was built from, + /// pinned to the manifest digest that was verified. + pinned_image_ref: Option, } #[derive(Debug, Clone)] @@ -1871,17 +1880,31 @@ impl VmDriver { image_disk: Some(image_disk), image_identity: persisted_identity, bootstrap_image_identity, + pinned_image_ref: None, } } else { - self.prepare_images_in_worker( - &sandbox.id, - &image_ref, - rootfs_tar_path.as_deref(), - false, - ) - .await? + let resolve_ref = if overlay_preparation == OverlayPreparation::PreserveExisting { + restart_image_ref(&state_dir, &image_ref).await? + } else { + image_ref.clone() + }; + let mut plan = self + .prepare_images_in_worker( + &sandbox.id, + &resolve_ref, + rootfs_tar_path.as_deref(), + false, + ) + .await?; + // A local engine can serve the pinned digest; keep the pin so the + // next restart does not fall back to the tag. + if plan.pinned_image_ref.is_none() && resolve_ref != image_ref { + plan.pinned_image_ref = Some(resolve_ref); + } + plan }; let image_identity = image_plan.image_identity.clone(); + let pinned_image_ref = image_plan.pinned_image_ref.clone(); self.ensure_provisioning_active(&sandbox.id).await?; info!( sandbox_id = %sandbox.id, @@ -1931,8 +1954,13 @@ impl VmDriver { .map_err(|err| Status::internal(format!("prepare guest overlay disk failed: {err}")))?; self.ensure_provisioning_active(&sandbox.id).await?; - if let Err(err) = - write_sandbox_image_metadata(&state_dir, &image_ref, &image_identity).await + if let Err(err) = write_sandbox_image_metadata( + &state_dir, + &image_ref, + &image_identity, + pinned_image_ref.as_deref(), + ) + .await { return Err(Status::internal(format!( "write sandbox image metadata failed: {err}" @@ -3547,6 +3575,7 @@ impl VmDriver { image_disk: Some(prepared.disk_path), image_identity: prepared.image_identity, bootstrap_image_identity, + pinned_image_ref: None, }); } @@ -3556,6 +3585,7 @@ impl VmDriver { image_disk: None, image_identity: bootstrap_image_identity.clone(), bootstrap_image_identity, + pinned_image_ref: None, })); } @@ -3567,6 +3597,7 @@ impl VmDriver { image_disk: Some(prepared.disk_path), image_identity: prepared.image_identity, bootstrap_image_identity, + pinned_image_ref: prepared.pinned_image_ref, })) } @@ -4149,6 +4180,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }); } @@ -4159,6 +4191,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }); } @@ -4202,6 +4235,7 @@ impl VmDriver { Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }) } @@ -4256,6 +4290,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }); } @@ -4272,6 +4307,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }); } @@ -4345,6 +4381,7 @@ impl VmDriver { Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: None, }) } @@ -4358,6 +4395,22 @@ impl VmDriver { ) -> Result { let reference = parse_registry_reference(image_ref)?; + // Same contract as the bootstrap cache: a prepared disk is published + // only after its manifest was verified against the digest in its + // identity, so a digest-pinned hit needs no registry round trip. + if let Some(digest) = reference.digest() { + let cache_identity = prepared_image_cache_identity(digest, &self.config); + let image_path = image_cache_rootfs_image(&self.config.state_dir, &cache_identity); + if tokio::fs::metadata(&image_path).await.is_ok() { + self.publish_prepared_cache_hit(sandbox_id, image_ref, "registry", &cache_identity); + return Ok(PreparedImageDisk { + image_identity: cache_identity, + disk_path: image_path, + pinned_image_ref: Some(reference.whole()), + }); + } + } + self.publish_vm_progress( sandbox_id, "AuthenticatingRegistry", @@ -4401,6 +4454,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: Some(reference.whole()), }); } @@ -4411,6 +4465,7 @@ impl VmDriver { return Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: Some(reference.whole()), }); } @@ -4494,6 +4549,7 @@ impl VmDriver { Ok(PreparedImageDisk { image_identity: cache_identity, disk_path: image_path, + pinned_image_ref: Some(reference.whole()), }) } @@ -5258,6 +5314,7 @@ pub async fn run_image_preparation_worker(request_path: &Path) -> Result<(), Str image_disk: None, image_identity: identity.clone(), bootstrap_image_identity: identity, + pinned_image_ref: None, })) } else { driver @@ -7347,7 +7404,17 @@ async fn write_sandbox_image_metadata( state_dir: &Path, image_ref: &str, image_identity: &str, + pinned_image_ref: Option<&str>, ) -> Result<(), std::io::Error> { + let pin_path = state_dir.join(IMAGE_PINNED_REFERENCE_FILE); + match pinned_image_ref { + Some(pinned) => tokio::fs::write(&pin_path, format!("{pinned}\n")).await?, + None => match tokio::fs::remove_file(&pin_path).await { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error), + }, + } tokio::fs::write( state_dir.join(IMAGE_IDENTITY_FILE), format!("{image_identity}\n"), @@ -7367,6 +7434,44 @@ async fn read_persisted_image_identity(state_dir: &Path) -> Result Result, Status> { + match tokio::fs::read_to_string(path).await { + Ok(contents) => Ok(Some(contents.trim().to_string())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(Status::internal(format!( + "read {}: {error}", + path.display() + ))), + } +} + +/// Returns the reference a restart should resolve. A tag can move while the +/// sandbox is stopped; resolving it again would mount the preserved overlay +/// over a different image than the one it was written against. Sandboxes +/// prepared before pins were recorded keep resolving the requested reference. +async fn restart_image_ref(state_dir: &Path, image_ref: &str) -> Result { + let requested = read_optional_state_file(&state_dir.join(IMAGE_REFERENCE_FILE)).await?; + if requested.as_deref() != Some(image_ref.trim()) { + return Ok(image_ref.to_string()); + } + let Some(pinned) = + read_optional_state_file(&state_dir.join(IMAGE_PINNED_REFERENCE_FILE)).await? + else { + return Ok(image_ref.to_string()); + }; + let pinned_reference = parse_registry_reference(&pinned)?; + let requested_reference = parse_registry_reference(image_ref)?; + if pinned_reference.digest().is_none() + || pinned_reference.resolve_registry() != requested_reference.resolve_registry() + || pinned_reference.repository() != requested_reference.repository() + { + return Err(Status::failed_precondition(format!( + "persisted image pin '{pinned}' does not match sandbox image '{image_ref}'" + ))); + } + Ok(pinned) +} + async fn write_sandbox_request(state_dir: &Path, sandbox: &Sandbox) -> Result<(), std::io::Error> { restrict_owner_only_dir(state_dir).await?; let destination = state_dir.join(SANDBOX_REQUEST_FILE); @@ -9159,7 +9264,7 @@ mod tests { ) .await .unwrap(); - write_sandbox_image_metadata(&state_dir, "unused-image", "sha256:original-image") + write_sandbox_image_metadata(&state_dir, "unused-image", "sha256:original-image", None) .await .unwrap(); tokio::fs::write(state_dir.join(marker), b"inactive\n") @@ -10921,6 +11026,7 @@ mod tests { image_disk: None, image_identity: "warm".to_string(), bootstrap_image_identity: "warm".to_string(), + pinned_image_ref: None, }))); let overlay = preparation::Message::Complete(Ok(preparation::Output::Overlay( SandboxOwnerIdentity { @@ -15151,4 +15257,50 @@ while :; do sleep 0.05; done"#, "osfs0\t/sandbox/a\tro\nosfs1\t/sandbox/b\trw\n" ); } + + #[tokio::test] + async fn restart_image_ref_uses_the_recorded_pin_for_the_same_image() { + let directory = tempfile::tempdir().unwrap(); + let state_dir = directory.path(); + let tag = "registry.example.com/team/agent:latest"; + let pinned = format!("{tag}@sha256:{}", "a".repeat(64)); + + assert_eq!(restart_image_ref(state_dir, tag).await.unwrap(), tag); + + write_sandbox_image_metadata(state_dir, tag, "identity", Some(&pinned)) + .await + .unwrap(); + assert_eq!(restart_image_ref(state_dir, tag).await.unwrap(), pinned); + assert_eq!( + restart_image_ref(state_dir, "registry.example.com/team/other:latest") + .await + .unwrap(), + "registry.example.com/team/other:latest" + ); + + write_sandbox_image_metadata(state_dir, tag, "identity", None) + .await + .unwrap(); + assert!(!state_dir.join(IMAGE_PINNED_REFERENCE_FILE).exists()); + assert_eq!(restart_image_ref(state_dir, tag).await.unwrap(), tag); + } + + #[tokio::test] + async fn restart_image_ref_rejects_a_pin_for_another_image_or_without_a_digest() { + let directory = tempfile::tempdir().unwrap(); + let state_dir = directory.path(); + let tag = "registry.example.com/team/agent:latest"; + let digest = format!("sha256:{}", "b".repeat(64)); + for pinned in [ + format!("registry.example.com/team/other@{digest}"), + format!("mirror.example.com/team/agent@{digest}"), + "registry.example.com/team/agent:v2".to_string(), + ] { + write_sandbox_image_metadata(state_dir, tag, "identity", Some(&pinned)) + .await + .unwrap(); + let error = restart_image_ref(state_dir, tag).await.unwrap_err(); + assert_eq!(error.code(), Code::FailedPrecondition, "{pinned}"); + } + } } diff --git a/crates/openshell-driver-vm/src/registry_cache_tests.rs b/crates/openshell-driver-vm/src/registry_cache_tests.rs index b71d0d5db0..be64e69ccc 100644 --- a/crates/openshell-driver-vm/src/registry_cache_tests.rs +++ b/crates/openshell-driver-vm/src/registry_cache_tests.rs @@ -678,3 +678,95 @@ async fn bootstrap_extraction_limit_spans_layers_and_cleans_failed_build() { ); fs::set_permissions(rootfs.join("readonly"), fs::Permissions::from_mode(0o755)).unwrap(); } + +#[tokio::test] +async fn prepared_restart_keeps_the_pinned_image_after_its_tag_moves() { + let original = manifest("original"); + let original_digest = sha256(&original); + let moved = manifest("moved"); + let moved_digest = sha256(&moved); + let registry = Registry::start( + moved_digest.clone(), + HashMap::from([ + ("latest".to_string(), moved.clone()), + (moved_digest.clone(), moved), + (original_digest.clone(), original), + ]), + None, + false, + ) + .await; + let root = tempfile::tempdir().unwrap(); + let driver = driver(root.path()); + let client = client(); + + let identity = prepared_image_cache_identity(&original_digest, &driver.config); + let path = image_cache_rootfs_image(root.path(), &identity); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"prepared disk").unwrap(); + + let state_dir = root.path().join("sandbox"); + fs::create_dir_all(&state_dir).unwrap(); + let tag = registry.reference(None); + let pinned = format!("{tag}@{original_digest}"); + write_sandbox_image_metadata(&state_dir, &tag, &identity, Some(&pinned)) + .await + .unwrap(); + + let resolve_ref = restart_image_ref(&state_dir, &tag).await.unwrap(); + assert_eq!(resolve_ref, pinned); + let prepared = driver + .ensure_prepared_registry_image_disk( + "test", + &resolve_ref, + Path::new("unused"), + &client, + &RegistryAuth::Anonymous, + ) + .await + .unwrap(); + assert_eq!(prepared.image_identity, identity); + assert_eq!(prepared.disk_path, path); + assert_eq!(prepared.pinned_image_ref.as_deref(), Some(pinned.as_str())); + assert!( + registry.requests().is_empty(), + "a restart from a cached pin reached the registry: {:?}", + registry.requests() + ); +} + +#[tokio::test] +async fn prepared_registry_disk_records_the_digest_its_tag_resolved_to() { + let body = manifest("resolved"); + let digest = sha256(&body); + let registry = Registry::start( + digest.clone(), + HashMap::from([("latest".to_string(), body.clone()), (digest.clone(), body)]), + None, + false, + ) + .await; + let root = tempfile::tempdir().unwrap(); + let driver = driver(root.path()); + let identity = prepared_image_cache_identity(&digest, &driver.config); + let path = image_cache_rootfs_image(root.path(), &identity); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, b"prepared disk").unwrap(); + + let tag = registry.reference(None); + let prepared = driver + .ensure_prepared_registry_image_disk( + "test", + &tag, + Path::new("unused"), + &client(), + &RegistryAuth::Anonymous, + ) + .await + .unwrap(); + assert_eq!(prepared.image_identity, identity); + assert_eq!( + prepared.pinned_image_ref, + Some(registry.reference(Some(&digest))) + ); +}