Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 148 additions & 10 deletions crates/openshell-driver-vm/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ 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";
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
Expand All @@ -279,12 +280,15 @@ struct RuntimeImagePlan {
image_disk: Option<PathBuf>,
image_identity: String,
bootstrap_image_identity: String,
#[serde(default)]
pinned_image_ref: Option<String>,
}

#[derive(Debug, Clone)]
struct PreparedImageDisk {
image_identity: String,
disk_path: PathBuf,
pinned_image_ref: Option<String>,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -1871,17 +1875,29 @@ 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?;
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,
Expand Down Expand Up @@ -1931,8 +1947,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}"
Expand Down Expand Up @@ -3547,6 +3568,7 @@ impl VmDriver {
image_disk: Some(prepared.disk_path),
image_identity: prepared.image_identity,
bootstrap_image_identity,
pinned_image_ref: None,
});
}

Expand All @@ -3556,6 +3578,7 @@ impl VmDriver {
image_disk: None,
image_identity: bootstrap_image_identity.clone(),
bootstrap_image_identity,
pinned_image_ref: None,
}));
}

Expand All @@ -3567,6 +3590,7 @@ impl VmDriver {
image_disk: Some(prepared.disk_path),
image_identity: prepared.image_identity,
bootstrap_image_identity,
pinned_image_ref: prepared.pinned_image_ref,
}))
}

Expand Down Expand Up @@ -4149,6 +4173,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
});
}

Expand All @@ -4159,6 +4184,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
});
}

Expand Down Expand Up @@ -4202,6 +4228,7 @@ impl VmDriver {
Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
})
}

Expand Down Expand Up @@ -4256,6 +4283,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
});
}

Expand All @@ -4272,6 +4300,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
});
}

Expand Down Expand Up @@ -4345,6 +4374,7 @@ impl VmDriver {
Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: None,
})
}

Expand All @@ -4358,6 +4388,19 @@ impl VmDriver {
) -> Result<PreparedImageDisk, Status> {
let reference = parse_registry_reference(image_ref)?;

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",
Expand Down Expand Up @@ -4401,6 +4444,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: Some(reference.whole()),
});
}

Expand All @@ -4411,6 +4455,7 @@ impl VmDriver {
return Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: Some(reference.whole()),
});
}

Expand Down Expand Up @@ -4494,6 +4539,7 @@ impl VmDriver {
Ok(PreparedImageDisk {
image_identity: cache_identity,
disk_path: image_path,
pinned_image_ref: Some(reference.whole()),
})
}

Expand Down Expand Up @@ -5258,6 +5304,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
Expand Down Expand Up @@ -7347,7 +7394,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"),
Expand All @@ -7367,6 +7424,40 @@ async fn read_persisted_image_identity(state_dir: &Path) -> Result<String, std::
Ok(raw.trim().to_string())
}

async fn read_optional_state_file(path: &Path) -> Result<Option<String>, 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()
))),
}
}

async fn restart_image_ref(state_dir: &Path, image_ref: &str) -> Result<String, Status> {
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);
Expand Down Expand Up @@ -9159,7 +9250,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")
Expand Down Expand Up @@ -10921,6 +11012,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 {
Expand Down Expand Up @@ -15151,4 +15243,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}");
}
}
}
Loading