Add image gc, stop VMs on kernel panic, harden first boot

- Add `wsbx gc` to delete cached images that no sandbox uses, and
  drop the superseded image automatically when a tag moves to a new
  digest (unless another ref still points at it).
- Boot the guest with panic=1. Virtualization.framework restarts a
  rebooting guest, so init now leaves a marker in the per-launch
  control share and powers off when it is already there. A kernel
  panic (or a reboot inside the VM) now ends the run with exit 1
  instead of hanging or looping forever.
- Report a VM that stops without an exit status as an error.
- Sync the first-boot image unpack before marking the sandbox
  provisioned; a crash right after first boot previously left an
  empty root filesystem.
- Validate kernel, workspace and state-dir paths before creating any
  sandbox files, so rejected runs no longer leave a sandbox behind.
- Ignore .llm-wiki/, commit .gitignore, fix the remaining Clippy
  warning, and document gc and the panic behavior.
This commit is contained in:
2026-10-02 15:33:30 +02:00
parent 9117f05db9
commit cff6dae88f
6 changed files with 104 additions and 23 deletions
+58 -15
View File
@@ -7,6 +7,7 @@ use std::collections::HashSet;
use std::fs::{self, File};
use std::io::{BufReader, Read, Write};
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
const ACCEPT: &str = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json";
@@ -177,24 +178,66 @@ const REF_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 3600);
/// Pull (or reuse cached) image, returning its flattened rootfs tar + config.
pub fn pull(home: &Path, image: &str, refresh: bool) -> Result<Image> {
validate_ref(&parse_ref(image)).with_context(|| format!("invalid image reference {image:?}"))?;
let refs = home.join("images/refs");
fs::create_dir_all(&refs)?;
let ref_file = refs.join(image.replace(['/', ':', '@'], "_"));
let cached = fs::read_to_string(&ref_file).ok().and_then(|d| load(home, d.trim()).ok());
fs::create_dir_all(home.join("images/refs"))?;
let ref_file = ref_path(home, image);
let old = fs::read_to_string(&ref_file).ok().map(|d| d.trim().to_string());
let Some(img) = old.as_deref().and_then(|d| load(home, d).ok()) else { return fetch(home, image, &ref_file) };
let age = fs::metadata(&ref_file).and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok());
if let Some(img) = cached {
if !refresh && (image.contains('@') || age.is_some_and(|a| a < REF_TTL)) {
return Ok(img);
if !refresh && (image.contains('@') || age.is_some_and(|a| a < REF_TTL)) {
return Ok(img);
}
match fetch(home, image, &ref_file) {
Ok(new) => {
drop_unreferenced(home, &img.digest)?; // tag moved: the old multi-GB tar is dead weight
Ok(new)
}
return fetch(home, image, &ref_file).or_else(|e| {
if refresh {
return Err(e);
}
Err(e) if !refresh => {
eprintln!("wsbx: could not re-resolve {image} ({e:#}); using cached copy");
Ok(img)
});
}
Err(e) => Err(e),
}
fetch(home, image, &ref_file)
}
fn ref_path(home: &Path, image: &str) -> PathBuf {
home.join("images/refs").join(image.replace(['/', ':', '@'], "_"))
}
fn image_dir(home: &Path, digest: &str) -> PathBuf {
home.join("images").join(digest.replace(':', "-"))
}
/// Remove an image unless some ref still points at it. A VM still provisioning from its tar keeps
/// its open file descriptor, so unlinking under it is safe.
fn drop_unreferenced(home: &Path, digest: &str) -> Result<()> {
let used = fs::read_dir(home.join("images/refs"))?.flatten().any(|e| fs::read_to_string(e.path()).is_ok_and(|d| d.trim() == digest));
if !used && check_digest(digest).is_ok() {
let _ = fs::remove_dir_all(image_dir(home, digest));
}
Ok(())
}
/// Delete every cached image not referenced (via its tag) by one of `keep`; returns bytes freed.
pub fn gc(home: &Path, keep: &[String]) -> Result<u64> {
let keep: HashSet<PathBuf> = keep.iter().map(|i| ref_path(home, i)).collect();
let mut live = HashSet::new();
for e in fs::read_dir(home.join("images/refs"))?.flatten() {
match fs::read_to_string(e.path()) {
Ok(d) if keep.contains(&e.path()) => drop(live.insert(image_dir(home, d.trim()))),
_ => fs::remove_file(e.path())?,
}
}
let mut freed = 0;
for e in fs::read_dir(home.join("images"))?.flatten() {
let p = e.path();
if e.file_name() == "refs" || live.contains(&p) {
continue;
}
// ponytail: also removes a .tmp dir of a pull running right now; that pull fails and can be retried
freed += fs::read_dir(&p)?.flatten().filter_map(|f| f.metadata().ok()).map(|m| m.blocks() * 512).sum::<u64>();
fs::remove_dir_all(p)?;
}
Ok(freed)
}
fn fetch(home: &Path, image: &str, ref_file: &Path) -> Result<Image> {
@@ -217,7 +260,7 @@ fn fetch(home: &Path, image: &str, ref_file: &Path) -> Result<Image> {
}
(manifest, digest) = (m2, d2);
}
let dir = home.join("images").join(digest.replace(':', "-"));
let dir = image_dir(home, &digest);
if let Ok(img) = load(home, &digest) {
fs::write(ref_file, &digest)?; // also bumps mtime -> TTL restarts
return Ok(img);
@@ -256,7 +299,7 @@ fn fetch(home: &Path, image: &str, ref_file: &Path) -> Result<Image> {
}
fn load(home: &Path, digest: &str) -> Result<Image> {
let dir = home.join("images").join(digest.replace(':', "-"));
let dir = image_dir(home, digest);
let cfg: Value = serde_json::from_slice(&fs::read(dir.join("config.json"))?)?;
let rootfs = dir.join("rootfs.tar");
if !rootfs.exists() {