Files
woiken-sandboxes/src/sandbox.rs
T

75 lines
2.7 KiB
Rust

//! Sandbox bookkeeping: listing, removal, image gc.
use crate::oci;
use crate::util::sanitize;
use anyhow::{Context, Result, anyhow, bail};
use serde_json::Value;
use std::fs;
use std::os::unix::fs::MetadataExt;
use std::path::Path;
/// The lock `run` holds for the VM's lifetime; Err if the sandbox is running.
pub fn lock_stopped(dir: &Path) -> Result<fs::File> {
let f = fs::File::create(dir.join("lock"))?;
f.try_lock().map_err(|_| anyhow!("locked by a running VM"))?;
Ok(f)
}
pub fn ls(h: &Path) -> Result<()> {
println!("{:<28} {:<8} {:<40} {:>8} WORKSPACE", "NAME", "STATUS", "IMAGE", "DISK");
let Ok(rd) = fs::read_dir(h.join("sandboxes")) else { return Ok(()) };
let mut rows: Vec<_> = rd.flatten().collect();
rows.sort_by_key(|e| e.file_name());
for e in rows {
let Ok(m) = fs::read(e.path().join("meta.json")) else { continue };
let m: Value = serde_json::from_slice(&m)?;
let used = fs::metadata(e.path().join("disk.img")).map(|m| m.blocks() * 512).unwrap_or(0);
let status = if lock_stopped(&e.path()).is_err() { "running" } else { "stopped" };
println!(
"{:<28} {:<8} {:<40} {:>6}MB {}",
e.file_name().to_string_lossy(),
status,
m["image"].as_str().unwrap_or("?"),
used / 1_000_000,
m["workspace"].as_str().unwrap_or("-")
);
}
Ok(())
}
pub fn rm(h: &Path, names: Vec<String>, disk: bool) -> Result<()> {
for n in names {
if n.is_empty() || sanitize(&n) != n {
bail!("invalid sandbox name {n:?}");
}
let d = h.join("sandboxes").join(&n);
if !d.join("meta.json").exists() {
bail!("no sandbox {n}");
}
// Held across the delete so the sandbox can't be started meanwhile.
let _lock = lock_stopped(&d).with_context(|| format!("sandbox {n} is running"))?;
if disk {
match fs::remove_file(d.join("disk.img")) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => println!("removed disk of {n}"),
}
} else {
fs::remove_dir_all(d)?;
println!("removed {n}");
}
}
Ok(())
}
/// Delete cached images no sandbox was created from.
pub fn gc(h: &Path) -> Result<()> {
let used: Vec<String> = fs::read_dir(h.join("sandboxes"))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| serde_json::from_slice::<Value>(&fs::read(e.path().join("meta.json")).ok()?).ok())
.filter_map(|m| m["image"].as_str().map(String::from))
.collect();
println!("freed {} MB", oci::gc(h, &used)? / 1_000_000);
Ok(())
}