diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index fe83fe2b..11c457db 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -30,6 +30,7 @@ //! kernel = "/var/lib/fctl/vmlinux" # a file, or an image with /vmlinux (unset: the published one) //! disk_gb = 64 # each sandbox's own disk, which takes only what it holds //! jailer = true # as root: each VM as a user of its own, in a chroot and a cgroup +//! snapshots = true # a stopped sandbox keeps its VM's memory, and resumes as it was //! ``` //! //! The runner token lives next to it in `host-token`, and the Claude token @@ -162,6 +163,11 @@ pub struct FirecrackerConfig { /// jailer: as a user of its own, in a chroot with only its files, and /// in a cgroup of its own. A host that doesn't run as root can't. pub jailer: bool, + /// Whether stopping a sandbox saves its VM's state, its memory with the + /// programs in it, so that it resumes where it was rather than boot + /// again: it takes as much disk as the memory the VM uses, until the + /// sandbox starts again, goes, or the disk runs low. + pub snapshots: bool, } impl Default for FirecrackerConfig { @@ -172,6 +178,7 @@ impl Default for FirecrackerConfig { passt: None, disk_gb: 64, jailer: true, + snapshots: true, } } } diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 3d546d90..d15beaf7 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -141,8 +141,9 @@ enum CacheDone { /// What background work on sandboxes that no session runs in reports. enum Chore { /// The sweep listed this host's sandboxes, and the projects whose - /// package caches are here. - Listed(Result>, Vec), + /// package caches are here; and the disk's free MiB, when it measured + /// it again after letting saved states go. + Listed(Result>, Vec, Option), /// The sweep removed a sandbox, or failed to, and measured the disk /// again. Removed { @@ -365,7 +366,35 @@ impl Daemon { } self.sweeping = true; let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); + // While the disk is low, the VMs' saved states go first: their + // sandboxes boot again from their disks, and lose no more. A host + // that keeps none (`snapshots = false`) lets go of those it kept. + let low = self.low_on_disk(); + let keeps_states = self.ctx.cfg.firecracker.snapshots; + let in_use: HashSet = self + .sessions + .keys() + .chain(self.pending_starts.keys()) + .map(|id| sandbox_name(id.as_str())) + .collect(); tokio::spawn(async move { + // What that freed counts before any sandbox goes for room. + let mut measured = None; + if low || !keeps_states { + let freed = ctx.driver.drop_saved_states(&in_use).await; + if freed > 0 { + if low { + tracing::info!( + "let go of the saved states of stopped sandboxes for room on the disk: {freed} MiB" + ); + } else { + tracing::info!( + "let go of the saved states of stopped sandboxes, which snapshots = false keeps none of: {freed} MiB" + ); + } + measured = ctx.disk_free_mb().await; + } + } let listed = ctx.driver.list().await; let caches = match &listed { Ok(_) => ctx @@ -378,7 +407,7 @@ impl Daemon { }), Err(_) => Vec::new(), }; - let _ = chores.send(Chore::Listed(listed, caches)); + let _ = chores.send(Chore::Listed(listed, caches, measured)); }); } @@ -657,8 +686,17 @@ impl Daemon { fn on_chore(&mut self, chore: Chore) { match chore { - Chore::Listed(Ok(list), caches) => self.sweep_listed(list, caches), - Chore::Listed(Err(e), _) => { + Chore::Listed(Ok(list), caches, measured) => { + if measured.is_some() { + self.note_disk(measured); + } + self.sweep_listed(list, caches); + } + Chore::Listed(Err(e), _, measured) => { + // What letting saved states go freed counts all the same. + if measured.is_some() { + self.note_disk(measured); + } tracing::warn!("listing sandboxes: {e:#}"); self.sweeping = false; } @@ -1528,10 +1566,11 @@ impl Daemon { let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); tokio::spawn(async move { let sb = ctx.driver.handle(&name); - if let Err(e) = ctx.driver.stop(&sb).await { + let (stopped, removed) = ctx.driver.finish(&sb, destroy).await; + if let Err(e) = stopped { tracing::warn!("stopping {name}: {e:#}"); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { + if let Err(e) = removed { tracing::warn!("removing {name}: {e:#}"); } let ended = HostToFleet::SessionEnded { diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 26afe36e..bf2bd697 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -61,8 +61,24 @@ struct Record { /// The fctl-agent its VM last booted with (the start of its SHA-256). #[serde(default)] agent: Option, + /// The VM's state, saved as it stopped (in `saved/`), which it resumes + /// from. + #[serde(default)] + saved: Option, +} + +/// A VM's state that the host saved as the VM stopped. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Saved { + /// The Firecracker release that saved it: only the same one loads it. + firecracker: String, + at_ms: i64, } +/// What a VM's saved state may leave free, at least: below it, the VM stops +/// without saving it. +const SAVE_MARGIN_MB: u64 = 2048; + type Log<'a> = &'a (dyn Fn(String) + Send + Sync); pub struct FirecrackerDriver { @@ -208,6 +224,70 @@ async fn make_fs(path: &Path, gb: u64, label: &str, journal: bool) -> Result<()> Ok(()) } +/// The release of the Firecracker binary `firecracker` (`1.17.0`). +async fn binary_version(firecracker: &Path) -> Result { + let out = super::run_cmd(&firecracker.display().to_string(), &["--version"]).await?; + out.lines() + .next() + .map(|l| { + l.trim() + .trim_start_matches("Firecracker ") + .trim_start_matches('v') + .to_owned() + }) + .filter(|v| !v.is_empty()) + .with_context(|| format!("{} didn't say its version", firecracker.display())) +} + +/// Gives back the disk that the pages of zeros in the file at `path` take, +/// which most of a VM's saved memory is. +fn punch_zeros(path: &Path) -> Result<()> { + use nix::fcntl::{FallocateFlags, fallocate}; + use std::os::unix::fs::FileExt; + const PAGE: usize = 4096; + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open(path)?; + let punch = |start: u64, end: u64| { + let (Ok(start), Ok(len)) = (i64::try_from(start), i64::try_from(end - start)) else { + return Ok(()); + }; + fallocate( + &file, + FallocateFlags::FALLOC_FL_PUNCH_HOLE | FallocateFlags::FALLOC_FL_KEEP_SIZE, + start, + len, + ) + }; + let mut buf = vec![0u8; 1 << 20]; + let mut offset = 0u64; + // Where the run of zero pages this is in started. + let mut zeros: Option = None; + loop { + let n = file.read_at(&mut buf, offset)?; + if n == 0 { + break; + } + for (i, page) in buf[..n].chunks(PAGE).enumerate() { + let at = offset + (i * PAGE) as u64; + match (page.iter().all(|b| *b == 0), zeros) { + (true, None) => zeros = Some(at), + (false, Some(start)) => { + punch(start, at)?; + zeros = None; + } + _ => {} + } + } + offset += n as u64; + } + if let Some(start) = zeros { + punch(start, offset)?; + } + Ok(()) +} + impl FirecrackerDriver { pub fn new(host: &HostConfig) -> Self { let root = host.data_dir().join("firecracker"); @@ -941,6 +1021,8 @@ impl FirecrackerDriver { let socket = vm.vsock(); let answers = tokio::time::timeout(Duration::from_secs(10), vsock::hello(&socket)); if matches!(answers.await, Ok(Ok(_))) { + // Running, its disk is past any state saved before. + self.drop_saved(&vm, &spec.name)?; // Its passt exited, or was stopped: the VM gets another. if !vm.linked() { log(format!("Linking the network of {} again", spec.name)); @@ -957,6 +1039,24 @@ impl FirecrackerDriver { )); vm.kill().await; } + // A host that keeps no states (`snapshots = false`) resumes none it + // kept before, nor does a jailed VM ([`stop`](Self::stop)) one saved + // before the host ran as root: they go. + if let Some(saved) = self.record(&spec.name).and_then(|r| r.saved) + && self.cfg().snapshots + && vm.jails.is_none() + && !self.resized(&vm, spec, log) + { + match self.resume_saved(&vm, &spec.name, &saved, log).await { + Ok(()) => return Ok(sb), + Err(e) => log(format!( + "{} couldn't resume where it stopped ({e:#}), so it starts again from its disk", + spec.name + )), + } + } + // A state saved as the host stopped, before it could record it. + self.drop_saved(&vm, &spec.name)?; let mut record = match self.record(&spec.name) { Some(record) => { log(format!("Starting the existing sandbox {}", spec.name)); @@ -1059,6 +1159,7 @@ impl FirecrackerDriver { reference: image.reference.clone(), created_ms: vsock::now_ms(), agent: None, + saved: None, }; self.save_record(&spec.name, &record)?; Ok(record) @@ -1260,13 +1361,202 @@ impl FirecrackerDriver { } } + /// Stops the sandbox's VM, saving its state first where the host + /// keeps them (`snapshots`) and the disk has room for its memory, so + /// that it resumes where it was. A VM paused while the disk was nearly + /// full stops without, as does one in the jailer's chroot, which + /// Firecracker would write its state into and which goes as it stops, + /// and an image builder, which boots afresh for each build. pub async fn stop(&self, sb: &Sandbox) -> Result<()> { let lock = self.lock(&format!("sandbox {}", sb.name)); let _held = lock.lock().await; - self.vm(&sb.name)?.stop().await; + let vm = self.vm(&sb.name)?; + if self.cfg().snapshots + && vm.jails.is_none() + && !crate::driver::is_builder(&sb.name) + && vm.running() + && !vm.paused().await + { + match self.save(&vm, &sb.name).await { + Ok(true) => { + vm.kill().await; + return Ok(()); + } + Ok(false) => {} + Err(e) => tracing::warn!( + "saving the state of {} failed, so it stops without it: {e:#}", + sb.name + ), + } + } + vm.stop().await; + Ok(()) + } + + /// Saves the state of `vm`, which runs, in its `saved/`, unless the disk + /// lacks room for its memory; whether it did. What the VM has yet to + /// write goes to its disk first, so that one whose state doesn't come + /// back boots from a disk as whole as a clean stop leaves it. + async fn save(&self, vm: &Vm, name: &str) -> Result { + // One at a time: sandboxes that stop together (a host that drains) + // would each find room for their memory, and all write it at once. + let lock = self.lock("saving"); + let _held = lock.lock().await; + let memory_mb = vm.memory_mb().unwrap_or(u64::MAX / 2); + let floor = self + .host + .min_free_disk_mb() + .unwrap_or(0) + .max(SAVE_MARGIN_MB); + let free = crate::sysinfo::disk_available_mb(&vm.dir).await; + if free.is_none_or(|free| free < memory_mb.saturating_add(floor)) { + tracing::info!( + "{name} stops without saving its state: the disk lacks room for its {memory_mb} MiB of memory" + ); + return Ok(false); + } + let firecracker = vm.firecracker_version().await?; + let sync = Exec { + argv: vec!["sync".into()], + user: Some("root".into()), + cwd: Some("/".into()), + ..Exec::default() + }; + let synced = + tokio::time::timeout(Duration::from_secs(60), vsock::run(&vm.vsock(), sync, None)) + .await; + if !matches!(synced, Ok(Ok(vsock::Output { code: 0, .. }))) { + tracing::warn!("{name}'s disk wasn't written out before its state was saved"); + } + let (dir, new) = (vm.dir.join("saved"), vm.dir.join("saved.new")); + let _ = std::fs::remove_dir_all(&new); + let _ = std::fs::remove_dir_all(&dir); + let saved = async { + vm.snapshot(&new).await?; + // The memory the VM never touched, or gave back, takes no disk. + let memory = new.join("memory"); + if let Err(e) = tokio::task::spawn_blocking(move || punch_zeros(&memory)).await? { + tracing::warn!("giving back the disk {name}'s memory doesn't use: {e:#}"); + } + std::fs::rename(&new, &dir)?; + let Some(mut record) = self.record(name) else { + bail!("{name} has no record to keep its saved state in"); + }; + record.saved = Some(Saved { + firecracker, + at_ms: vsock::now_ms(), + }); + self.save_record(name, &record) + } + .await; + // What a save that failed left takes as much disk as the VM's memory. + if saved.is_err() { + let _ = std::fs::remove_dir_all(&new); + let _ = std::fs::remove_dir_all(&dir); + } + saved.map(|()| true) + } + + /// Starts the VM of the sandbox `name` from the state it saved as it + /// stopped, with its programs running on, then links its network and + /// lets the state go: the VM's disk is past it once the VM runs. + /// Fails, letting it go too, when the state can't come back: another + /// Firecracker saved it, say. + async fn resume_saved(&self, vm: &Vm, name: &str, saved: &Saved, log: Log<'_>) -> Result<()> { + let dir = vm.dir.join("saved"); + let restored = async { + if !dir.join("vmstate").is_file() || !dir.join("memory").is_file() { + bail!("its saved state is incomplete"); + } + let firecracker = self.firecracker(log).await?; + let version = binary_version(&firecracker).await?; + if version != saved.firecracker { + bail!( + "Firecracker {} saved its state, and this host runs {version}", + saved.firecracker + ); + } + log(format!("Resuming the sandbox {name} where it stopped")); + vm.restore(&dir, &firecracker, name).await + } + .await; + // Firecracker maps the memory it loaded, which stays while it runs. + self.drop_saved(vm, name)?; + restored?; + vm.wait_ready().await?; + let passt = self + .passt() + .context("passt is not installed: it gives the VMs their network")?; + if let Err(e) = vm.link_network(&passt).await { + vm.kill().await; + return Err(e); + } Ok(()) } + /// Whether the session asks `vm`, stopped, for another size than it + /// had: its saved state, which has the old one, then won't do. + fn resized(&self, vm: &Vm, spec: &SandboxSpec, log: Log<'_>) -> bool { + let (cpus, memory_mb) = vm::size(spec.cpus, spec.memory_mb); + let had = (vm.cpus(), vm.memory_mb()); + if had == (Some(u64::from(cpus)), Some(u64::from(memory_mb))) { + return false; + } + log(format!( + "{} asks for {cpus} CPUs and {memory_mb} MiB now, so it starts again from its disk rather than where it stopped", + spec.name + )); + true + } + + /// Lets the state `name` saved go, files and record. + fn drop_saved(&self, vm: &Vm, name: &str) -> Result<()> { + // Saved, or half saved as a save failed or the host stopped. + for dir in [vm.dir.join("saved"), vm.dir.join("saved.new")] { + if dir.exists() { + std::fs::remove_dir_all(&dir) + .with_context(|| format!("removing {}", dir.display()))?; + } + } + if let Some(mut record) = self.record(name) + && record.saved.take().is_some() + { + self.save_record(name, &record)?; + } + Ok(()) + } + + /// Lets the states that stopped sandboxes saved go, but those of `keep`, + /// to make room on the disk: their sandboxes start again from their + /// disks. What that freed, in MiB. + pub async fn drop_saved_states(&self, keep: &std::collections::HashSet) -> u64 { + let Ok(entries) = std::fs::read_dir(self.sandboxes()) else { + return 0; + }; + let mut freed = 0; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let saved = entry.path().join("saved"); + let half = entry.path().join("saved.new"); + if keep.contains(&name) || !(saved.is_dir() || half.is_dir()) { + continue; + } + let lock = self.lock(&format!("sandbox {name}")); + let _held = lock.lock().await; + let Ok(vm) = self.vm(&name) else { continue }; + if vm.running() { + continue; + } + let size = crate::caches::dir_size_mb(&saved).unwrap_or(0) + + crate::caches::dir_size_mb(&half).unwrap_or(0); + match self.drop_saved(&vm, &name) { + Ok(()) => freed += size, + Err(e) => tracing::warn!("letting {name}'s saved state go: {e:#}"), + } + } + freed + } + pub async fn remove(&self, sb: &Sandbox) -> Result<()> { let lock = self.lock(&format!("sandbox {}", sb.name)); let _held = lock.lock().await; @@ -1454,6 +1744,7 @@ mod tests { reference: image.reference.clone(), created_ms: 1, agent: None, + saved: None, }, )?; d.remove_image("ghcr.io/hyperstructure/sandbox:0.26.0-replaced-222222222222") @@ -1542,6 +1833,7 @@ mod tests { reference: "x".into(), created_ms: 1, agent: None, + saved: None, }; d.save_record("fctl-ses-01abc", &record)?; assert_eq!(d.record("fctl-ses-01abc"), Some(record)); @@ -1589,6 +1881,218 @@ mod tests { Ok(()) } + #[test] + fn saved_memory_takes_no_disk_for_its_zero_pages() -> Result<()> { + use std::os::unix::fs::{FileExt, MetadataExt}; + let dir = tempfile::tempdir()?; + let memory = dir.path().join("memory"); + // 8 MiB of written zeros, but for two pages of something else. + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create_new(true) + .open(&memory)?; + file.write_all_at(&vec![0u8; 8 << 20], 0)?; + file.write_all_at(b"the agent's heap", 4096)?; + file.write_all_at(b"its stack", (6 << 20) + 17)?; + file.sync_all()?; + let before = std::fs::metadata(&memory)?.blocks() * 512; + punch_zeros(&memory)?; + let after = std::fs::metadata(&memory)?; + assert_eq!(after.len(), 8 << 20); + let mut page = [0u8; 16]; + file.read_exact_at(&mut page, 4096)?; + assert_eq!(&page, b"the agent's heap"); + let mut tail = [0u8; 9]; + file.read_exact_at(&mut tail, (6 << 20) + 17)?; + assert_eq!(&tail, b"its stack"); + // Where the filesystem gives back what holes don't take. + if before >= 8 << 20 { + assert!( + after.blocks() * 512 <= 64 * 1024, + "{} bytes", + after.blocks() * 512 + ); + } + Ok(()) + } + + /// A sandbox with a saved state, as a stop leaves it. + fn with_saved(d: &FirecrackerDriver, name: &str, firecracker: &str) -> Result { + let vm = d.vm(name)?; + std::fs::create_dir_all(vm.dir.join("saved"))?; + std::fs::write(vm.dir.join("saved/vmstate"), b"state")?; + std::fs::write(vm.dir.join("saved/memory"), vec![1u8; 64 * 1024])?; + d.save_record( + name, + &Record { + image: "sha256:1".into(), + reference: "x".into(), + created_ms: 1, + agent: None, + saved: Some(Saved { + firecracker: firecracker.into(), + at_ms: 2, + }), + }, + )?; + Ok(vm) + } + + /// A state that another Firecracker saved goes, and the sandbox boots + /// from its disk instead; one that never came about goes too. + #[tokio::test] + async fn lets_go_of_saved_states_it_cant_resume() -> Result<()> { + let dir = tempfile::tempdir()?; + let bin = tempfile::tempdir()?; + let firecracker = bin.path().join("firecracker"); + crate::driver::fake::write_script( + &firecracker, + "#!/bin/sh\necho 'Firecracker v1.18.0'\necho\necho 'Supported snapshot data format versions: v8.0.0'\n", + )?; + let mut host = HostConfig { + data_dir: Some(dir.path().to_owned()), + ..HostConfig::default() + }; + host.firecracker.firecracker = Some(firecracker); + let d = FirecrackerDriver::new(&host); + let vm = with_saved(&d, "fctl-ses-01old", "1.17.0")?; + let log = |_: String| {}; + let saved = d + .record("fctl-ses-01old") + .and_then(|r| r.saved) + .context("saved")?; + let e = d + .resume_saved(&vm, "fctl-ses-01old", &saved, &log) + .await + .err() + .map(|e| e.to_string()); + assert_eq!( + e.as_deref(), + Some("Firecracker 1.17.0 saved its state, and this host runs 1.18.0") + ); + assert!(!vm.dir.join("saved").exists()); + assert_eq!(d.record("fctl-ses-01old").and_then(|r| r.saved), None); + // Its memory never written out. + let vm = with_saved(&d, "fctl-ses-01half", "1.18.0")?; + std::fs::remove_file(vm.dir.join("saved/memory"))?; + let saved = d + .record("fctl-ses-01half") + .and_then(|r| r.saved) + .context("saved")?; + let e = d.resume_saved(&vm, "fctl-ses-01half", &saved, &log).await; + assert!(e.is_err_and(|e| e.to_string() == "its saved state is incomplete")); + assert!(!vm.dir.join("saved").exists()); + Ok(()) + } + + /// A VM asked for another size boots from its disk rather than resume + /// as it was; what a save that stopped halfway left goes with the rest. + #[tokio::test] + async fn saved_states_go_when_the_size_changes_or_they_were_never_done() -> Result<()> { + let dir = tempfile::tempdir()?; + let d = driver(dir.path()); + let vm = with_saved(&d, "fctl-ses-01size", "1.17.0")?; + let spec = |cpus, memory_mb| SandboxSpec { + name: "fctl-ses-01size".into(), + image: "x".into(), + fallback_image: None, + cpus, + memory_mb, + cache: None, + }; + let boot = vm::unpack_spec("/k".into(), "/i".into(), "fctl-ses-01size", Path::new("/r")); + std::fs::write( + vm.dir.join("firecracker.json"), + serde_json::to_vec(&vm.config(&vm::Spec { + cpus: 2, + memory_mb: 4096, + ..boot + }))?, + )?; + let log = |_: String| {}; + assert!(!d.resized(&vm, &spec(2, 4096), &log)); + assert!(d.resized(&vm, &spec(4, 4096), &log)); + assert!(d.resized(&vm, &spec(2, 8192), &log)); + // Half saved, as the host stopped. + std::fs::create_dir_all(vm.dir.join("saved.new"))?; + std::fs::write(vm.dir.join("saved.new/memory"), vec![1u8; 4096])?; + d.drop_saved(&vm, "fctl-ses-01size")?; + assert!(!vm.dir.join("saved").exists() && !vm.dir.join("saved.new").exists()); + assert_eq!(d.record("fctl-ses-01size").and_then(|r| r.saved), None); + Ok(()) + } + + /// For room on the disk, the states of stopped sandboxes go, but those + /// of the sessions here. + #[tokio::test] + async fn lets_saved_states_go_for_room_on_the_disk() -> Result<()> { + let dir = tempfile::tempdir()?; + let d = driver(dir.path()); + let stopped = with_saved(&d, "fctl-ses-01stopped", "1.17.0")?; + let starting = with_saved(&d, "fctl-ses-01starting", "1.17.0")?; + let keep = std::collections::HashSet::from(["fctl-ses-01starting".to_owned()]); + assert!(d.drop_saved_states(&keep).await >= 1); + assert!(!stopped.dir.join("saved").exists()); + assert_eq!(d.record("fctl-ses-01stopped").and_then(|r| r.saved), None); + assert!(starting.dir.join("saved").is_dir()); + assert!( + d.record("fctl-ses-01starting") + .and_then(|r| r.saved) + .is_some() + ); + Ok(()) + } + + /// A host that keeps no states resumes none it kept before: a start + /// lets the state go without trying it. + #[tokio::test] + async fn keeping_no_states_resumes_none() -> Result<()> { + let dir = tempfile::tempdir()?; + let bin = tempfile::tempdir()?; + // Another release than the one that saved: a resume would fail at + // once, and say so. + let firecracker = bin.path().join("firecracker"); + crate::driver::fake::write_script( + &firecracker, + "#!/bin/sh\necho 'Firecracker v1.18.0'\necho\necho 'Supported snapshot data format versions: v8.0.0'\n", + )?; + let mut host = HostConfig { + data_dir: Some(dir.path().to_owned()), + ..HostConfig::default() + }; + host.firecracker.firecracker = Some(firecracker); + host.firecracker.snapshots = false; + let d = FirecrackerDriver::new(&host); + let vm = with_saved(&d, "fctl-ses-01cold", "1.17.0")?; + // The size it saved with, which the start asks for again. + std::fs::write( + vm.dir.join("firecracker.json"), + br#"{"machine-config": {"vcpu_count": 1, "mem_size_mib": 512}}"#, + )?; + let spec = SandboxSpec { + name: "fctl-ses-01cold".into(), + image: "127.0.0.1:9/fctl-test/none:1".into(), + fallback_image: None, + cpus: 1, + memory_mb: 512, + cache: None, + }; + let said = std::sync::Mutex::new(Vec::new()); + let log = |line: String| { + said.lock() + .unwrap_or_else(PoisonError::into_inner) + .push(line) + }; + // No KVM here, nor that image: it can't boot, but its state goes first. + let _ = d.ensure(&spec, &log).await; + assert!(!vm.dir.join("saved").exists()); + assert_eq!(d.record("fctl-ses-01cold").and_then(|r| r.saved), None); + let said = said.into_inner().unwrap_or_else(PoisonError::into_inner); + assert!(!said.iter().any(|l| l.contains("resume")), "{said:?}"); + Ok(()) + } + #[tokio::test] async fn probes_what_the_host_lacks() { let dir = tempfile::tempdir().ok(); @@ -1767,6 +2271,9 @@ mod tests { let owner = std::fs::symlink_metadata(&path)?.uid(); assert!(owner < vm::JAIL_ID_BASE, "{path:?} is {owner}'s"); } + // A jailed VM saves no state yet. + let saved = firecracker.join("sandboxes").join(&name).join("saved"); + assert!(!saved.exists(), "the jailed VM saved its state"); } let listed = d.list().await?; assert!(listed.iter().any(|s| s.name == name && !s.running), "{listed:?}"); @@ -1833,10 +2340,17 @@ mod tests { d.build(&job, &log).await?; eprintln!("built in {:?}", started.elapsed()); assert!(d.has_image(&tag).await); - // The builder stopped, and the sweep counts its time from now. + // The builder stopped, and the sweep counts its time from now. It + // saved no state: it boots afresh for each build. let builder = super::builds::builder_name(&tag); let stopped = crate::expiry::load(&crate::expiry::path(&cfg.data_dir())); assert!(stopped.contains_key(&builder), "{stopped:?}"); + let saved = cfg + .data_dir() + .join("firecracker/sandboxes") + .join(&builder) + .join("saved"); + assert!(!saved.exists(), "the builder saved its state"); // It keeps only its own layers, over Debian's. let Driver::Firecracker(fd) = &d else { bail!("not the firecracker driver"); @@ -1877,4 +2391,91 @@ mod tests { d.remove_image(&tag).await?; result } + + /// A sandbox stopped with its state saved resumes with its programs + /// running and its network linked again; without it, it boots from its + /// disk. As [`boots_a_sandbox`] says. + #[tokio::test] + #[ignore = "needs KVM, passt and a static fctl-agent"] + async fn stopped_sandboxes_resume_where_they_were() -> Result<()> { + use super::super::Driver; + let temp = tempfile::tempdir()?; + let data = std::env::var("FCTL_TEST_FIRECRACKER_DATA") + .map(PathBuf::from) + .unwrap_or_else(|_| temp.path().to_owned()); + let mut cfg = HostConfig { + data_dir: Some(data.clone()), + agent_bin: Some( + std::env::var("FCTL_TEST_FIRECRACKER_AGENT") + .context("FCTL_TEST_FIRECRACKER_AGENT isn't set")? + .into(), + ), + ..HostConfig::default() + }; + cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); + cfg.firecracker.disk_gb = 4; + // Jailed VMs save no state yet: as root, this tests saving without + // the jailer. + cfg.firecracker.jailer = false; + let d = Driver::select("firecracker", &cfg).await?; + let log = |line: String| eprintln!("{line}"); + let name = format!( + "fctl-test-{}", + hex::encode(fctl_domain::random_bytes::<4>()) + ); + let spec = SandboxSpec { + name: name.clone(), + image: std::env::var("FCTL_TEST_FIRECRACKER_IMAGE") + .unwrap_or_else(|_| "docker.io/library/debian:trixie-slim".into()), + fallback_image: None, + cpus: 1, + memory_mb: 512, + cache: None, + }; + let sb = d.ensure(&spec, &log).await?; + let dir = data.join("firecracker/sandboxes").join(&name); + let result = async { + // A program of its own, and a file in memory (/run is a tmpfs). + d.exec( + &sb, + "setsid sh -c 'while :; do sleep 1; done' /dev/null 2>&1 & echo $! > /run/held", + ) + .await?; + let held = d.exec(&sb, "cat /run/held").await?; + let started = std::time::Instant::now(); + d.stop(&sb).await?; + eprintln!( + "saved in {:?}: {} MiB of memory on disk", + started.elapsed(), + crate::caches::dir_size_mb(&dir.join("saved"))? + ); + assert!(dir.join("saved/memory").is_file()); + assert!(!d.list().await?.iter().any(|s| s.name == name && s.running)); + let started = std::time::Instant::now(); + d.ensure(&spec, &log).await?; + eprintln!("resumed in {:?}", started.elapsed()); + assert!(!dir.join("saved").exists()); + assert_eq!(d.exec(&sb, "cat /run/held").await?, held); + let alive = d + .exec(&sb, "kill -0 \"$(cat /run/held)\" && echo alive") + .await?; + assert_eq!(alive.trim(), "alive"); + let resolved = d.exec(&sb, "getent hosts example.com").await?; + assert!(!resolved.trim().is_empty()); + // Without saving its state, it boots again from its disk. + d.exec(&sb, "echo kept > /root/note").await?; + let mut cold = cfg.clone(); + cold.firecracker.snapshots = false; + let d = Driver::select("firecracker", &cold).await?; + d.stop(&sb).await?; + assert!(!dir.join("saved").exists()); + d.ensure(&spec, &log).await?; + assert_eq!(d.exec(&sb, "cat /root/note").await?, "kept\n"); + assert!(d.exec(&sb, "cat /run/held").await.is_err()); + Ok::<_, anyhow::Error>(()) + } + .await; + d.remove(&sb).await?; + result + } } diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index a51ed176..9710ce1b 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -23,6 +23,10 @@ const STOP_TIMEOUT: Duration = Duration::from_secs(30); /// How long Firecracker has to answer a request on its API socket. const API_TIMEOUT: Duration = Duration::from_secs(10); +/// How long Firecracker may take to save a VM's state or load it: its +/// memory goes to or comes from a file, gigabytes of it. +const SNAPSHOT_TIMEOUT: Duration = Duration::from_secs(600); + /// The kernel's command line, before what fctl-agent reads: the console, a /// reset that ends Firecracker, and no modules to look for. On x86_64 also /// what Firecracker suggests to boot faster: no PS/2 probing, and no PCI @@ -513,8 +517,8 @@ impl Vm { }, "drives": drives, "machine-config": { - "vcpu_count": spec.cpus.clamp(1, 32), - "mem_size_mib": spec.memory_mb.max(256), + "vcpu_count": size(spec.cpus, spec.memory_mb).0, + "mem_size_mib": size(spec.cpus, spec.memory_mb).1, "smt": false, }, "vsock": { "guest_cid": 3, "uds_path": self.vsock() }, @@ -524,6 +528,22 @@ impl Vm { }) } + /// The memory the VM booted with, in MiB, from its configuration. + pub fn memory_mb(&self) -> Option { + self.machine("mem_size_mib") + } + + /// The CPUs the VM booted with, from its configuration. + pub fn cpus(&self) -> Option { + self.machine("vcpu_count") + } + + fn machine(&self, field: &str) -> Option { + let config = std::fs::read(self.dir.join("firecracker.json")).ok()?; + let config: Value = serde_json::from_slice(&config).ok()?; + config["machine-config"][field].as_u64() + } + /// What the VM's console said last, for an error. pub fn console_tail(&self) -> String { let text = std::fs::read_to_string(self.console()).unwrap_or_default(); @@ -555,6 +575,87 @@ impl Vm { .context("Firecracker didn't say what its VM does") } + /// The Firecracker release that runs the VM (`1.17.0`). + pub async fn firecracker_version(&self) -> Result { + let body = api(&self.api(), "GET", "/", None).await?; + let info: Value = serde_json::from_slice(&body).context("reading Firecracker's answer")?; + info["vmm_version"] + .as_str() + .map(str::to_owned) + .context("Firecracker didn't say its version") + } + + /// Pauses the VM and saves its state in `dir`: Firecracker's + /// (`vmstate`) and the VM's memory (`memory`), with its programs as + /// they are. The VM stays paused. + pub async fn snapshot(&self, dir: &Path) -> Result<()> { + std::fs::create_dir_all(dir)?; + if !self.paused().await { + self.pause().await?; + } + let body = json!({ + "snapshot_type": "Full", + "snapshot_path": dir.join("vmstate"), + "mem_file_path": dir.join("memory"), + }); + api_within( + &self.api(), + "PUT", + "/snapshot/create", + Some(&body), + SNAPSHOT_TIMEOUT, + ) + .await + .map(drop) + } + + /// Starts Firecracker on the state saved in `dir` ([`snapshot`](Self::snapshot)), + /// the VM running on where it was, after stopping what an earlier boot + /// left. The VM's disks must be where they were. What it started goes + /// again when it fails. + pub async fn restore(&self, dir: &Path, firecracker: &Path, name: &str) -> Result<()> { + self.kill().await; + let restored = async { + std::fs::create_dir_all(&self.run)?; + let console = std::fs::File::create(self.console())?; + let mut cmd = std::process::Command::new(firecracker); + cmd.arg("--api-sock") + .arg(self.api()) + .args(["--id", name, "--level", "Warning"]) + .stdin(Stdio::null()) + .stdout(console.try_clone()?) + .stderr(console); + spawn_detached(&mut cmd, &self.pid_file("firecracker")) + .with_context(|| format!("starting {}", firecracker.display()))?; + let until = Instant::now() + Duration::from_secs(10); + while self.state().await.is_err() { + if Instant::now() > until || !self.running() { + bail!("Firecracker did not start: {}", self.console_tail()); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + let body = json!({ + "snapshot_path": dir.join("vmstate"), + "mem_backend": { "backend_type": "File", "backend_path": dir.join("memory") }, + "resume_vm": true, + }); + api_within( + &self.api(), + "PUT", + "/snapshot/load", + Some(&body), + SNAPSHOT_TIMEOUT, + ) + .await?; + Ok::<_, anyhow::Error>(()) + } + .await; + if restored.is_err() { + self.kill().await; + } + restored + } + /// Whether the VM is paused. One that doesn't run, or whose Firecracker /// doesn't answer, isn't. pub async fn paused(&self) -> bool { @@ -704,11 +805,33 @@ impl Vm { } } +/// The CPUs and MiB of memory a VM gets when asked for `cpus` and +/// `memory_mb`: Firecracker's bounds, and enough memory to boot. +pub fn size(cpus: u32, memory_mb: u32) -> (u32, u32) { + (cpus.clamp(1, 32), memory_mb.max(256)) +} + /// A request to Firecracker's API on `socket`: its answer's body. async fn api(socket: &Path, method: &str, path: &str, body: Option<&Value>) -> Result> { - tokio::time::timeout(API_TIMEOUT, request(socket, method, path, body)) + api_within(socket, method, path, body, API_TIMEOUT).await +} + +/// [`api`], with a time limit of its own. +async fn api_within( + socket: &Path, + method: &str, + path: &str, + body: Option<&Value>, + within: Duration, +) -> Result> { + tokio::time::timeout(within, request(socket, method, path, body)) .await - .map_err(|_| anyhow!("Firecracker didn't answer {method} {path} within 10 seconds"))? + .map_err(|_| { + anyhow!( + "Firecracker didn't answer {method} {path} within {} seconds", + within.as_secs() + ) + })? } async fn request(socket: &Path, method: &str, path: &str, body: Option<&Value>) -> Result> { @@ -1527,6 +1650,8 @@ mod tests { } else if request.contains(r#""state":"Resumed""#) && state == "Paused" { state = "Running"; "HTTP/1.1 204 No Content\r\n\r\n".to_owned() + } else if request.starts_with("PUT /snapshot/create ") && state == "Paused" { + "HTTP/1.1 204 No Content\r\n\r\n".to_owned() } else { let body = r#"{"fault_message":"The requested operation is not supported in the current VM state."}"#; format!( @@ -1571,6 +1696,46 @@ mod tests { Ok(()) } + /// Saving a VM's state pauses it first, as Firecracker asks, and says + /// where its files go; a running VM's Firecracker says its version. + #[tokio::test] + async fn saves_the_vms_state_through_firecrackers_api() -> Result<()> { + let dir = tempfile::tempdir()?; + let vm = Vm::new(dir.path().join("fctl-ses-x"))?; + let (api, requests) = firecracker_api(&vm.api())?; + assert_eq!(vm.firecracker_version().await?, "1.17.0"); + let saved = dir.path().join("saved"); + vm.snapshot(&saved).await?; + assert!(vm.paused().await); + let requests = requests.lock().map(|r| r.clone()).unwrap_or_default(); + let created = format!( + r#"PUT /snapshot/create HTTP/1.1 {{"mem_file_path":"{0}/memory","snapshot_path":"{0}/vmstate","snapshot_type":"Full"}}"#, + saved.display() + ); + assert_eq!( + requests, + [ + "GET / HTTP/1.1 ", + "GET / HTTP/1.1 ", + r#"PATCH /vm HTTP/1.1 {"state":"Paused"}"#, + &created, + "GET / HTTP/1.1 ", + ] + ); + // The memory the VM booted with, from its configuration. + assert_eq!(vm.memory_mb(), None); + std::fs::create_dir_all(&vm.dir)?; + let spec = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); + std::fs::write( + vm.dir.join("firecracker.json"), + serde_json::to_vec(&vm.config(&spec))?, + )?; + assert_eq!(vm.memory_mb(), Some(1024)); + api.abort(); + let _ = std::fs::remove_dir_all(&vm.run); + Ok(()) + } + #[test] fn reads_an_answer_once_all_of_it_is_there() -> Result<()> { let whole = diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 6aea5a35..ca3075ee 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -743,6 +743,16 @@ impl Driver { } } + /// Lets the states that stopped sandboxes saved go, but those of + /// `keep`, to make room on the disk (Firecracker saves its VMs' as they + /// stop); what that freed, in MiB. + pub async fn drop_saved_states(&self, keep: &std::collections::HashSet) -> u64 { + match self { + Self::Firecracker(d) => d.drop_saved_states(keep).await, + _ => 0, + } + } + /// Stops the sandbox, which keeps its files. An Apple `container` /// sandbox first gives back the disk space of the files deleted in it. pub async fn stop(&self, sb: &Sandbox) -> Result<()> { @@ -754,6 +764,23 @@ impl Driver { } } + /// Stops the sandbox, and with `destroy` removes it; what each came to. + /// A Firecracker VM that goes isn't stopped first, which would save the + /// state of a VM nothing resumes; others are, as Apple's `container` + /// sometimes needs its stop's second try. + pub async fn finish(&self, sb: &Sandbox, destroy: bool) -> (Result<()>, Result<()>) { + if destroy && matches!(self, Self::Firecracker(_)) { + return (Ok(()), self.remove(sb).await); + } + let stopped = self.stop(sb).await; + let removed = if destroy { + self.remove(sb).await + } else { + Ok(()) + }; + (stopped, removed) + } + pub async fn remove(&self, sb: &Sandbox) -> Result<()> { match self { Self::Process(d) => d.remove(sb).await, diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index 9bea8557..aeeacae6 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -1063,10 +1063,11 @@ async fn run( } Err(destroy) => { let sb = ctx.driver.handle(&sandbox_name(session_id.as_str())); - if let Err(e) = ctx.driver.stop(&sb).await { + let (stopped, removed) = ctx.driver.finish(&sb, destroy).await; + if let Err(e) = stopped { tracing::warn!("stopping {}: {e:#}", sb.name); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { + if let Err(e) = removed { tracing::warn!("removing {}: {e:#}", sb.name); } let msg = "Stopped before it started".to_owned(); @@ -1579,10 +1580,11 @@ async fn run( // Give the uplink a moment to deliver the agent's last events. tokio::time::sleep(Duration::from_millis(1500)).await; let destroy = stop.map(|(d, _)| d).unwrap_or(false); - if let Err(e) = ctx.driver.stop(&sb).await { + let (stopped, removed) = ctx.driver.finish(&sb, destroy).await; + if let Err(e) = stopped { tracing::warn!("stopping {}: {e:#}", sb.name); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { + if let Err(e) = removed { tracing::warn!("removing {}: {e:#}", sb.name); } let (status, reason) = outcome; diff --git a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md index 13befe7e..37216679 100644 --- a/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md +++ b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md @@ -46,7 +46,9 @@ microVM of its own. otherwise) that the VM lays over it with overlayfs. It takes what the session writes, and gives back what it deletes (discard, which Firecracker has from 1.17). A stopped sandbox keeps its disk, and - resuming the session boots from it, with Claude's conversation. + resuming the session boots from it, with Claude's conversation. (Since + session #802, stopping it also saves its VM's state, which a resume + loads, its programs running on.) - **fctl-agent is the VM's init.** The host boots each VM with an initramfs whose init is its own static fctl-agent. It mounts the root, copies itself to `/opt/fctl/bin`, sets up what an image doesn't bring diff --git a/docs/architecture.md b/docs/architecture.md index 6fcd45a9..fb672466 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3479,6 +3479,26 @@ in `firecracker/` in the host's data directory. which keeps what it has yet to write in its memory, and resumes it once there is room; a VM paused when its sandbox stops or starts again is resumed first ([ADR 0076](adr/0076-sessions-hear-when-their-runner-runs-short-of-disk-and-vm-sandboxes-pause-before-it-fills.md)). +- **Saved states.** Stopping a sandbox saves its VM's state first + (`snapshots`, on unless `host.toml` turns it off, which also lets the + states kept before go, at the next sweep or start): the host writes out + what the VM has yet to write to its disk, pauses it, and has + Firecracker save its state and its memory in the sandbox's `saved/` + (`PUT /snapshot/create`), then gives back the disk the memory's zero + pages take. Starting the sandbox again loads that into a new Firecracker + (`PUT /snapshot/load`), so that its programs, Claude among them, run on + where they were, and links its network again, unless the session asks + for another size than the VM had, which boots it from its disk; the + state goes once loaded, the disk being past it. One state saves at a + time. A state takes the disk the VM's memory + uses; the host saves none where the disk lacks room for the memory over + `min_free_disk_gb`, nor for a VM paused for the disk or a sandbox that + goes, and lets the states of stopped sandboxes go first while the disk + is low. One another Firecracker release saved, or one that doesn't load, + goes too, and the sandbox boots from its disk. A VM that runs through + the jailer saves none yet: Firecracker would write it in the jail's + chroot, which goes as the VM stops, so it boots from its disk. Image + builders save none either: they boot afresh for each build. - **The VM's init** is fctl-agent, from an initramfs the host makes of its own static fctl-agent (`crates/fctl-agent/src/vm`). It mounts the root, copies itself to `/opt/fctl/bin/fctl-agent`, sets up what images don't diff --git a/docs/cli.md b/docs/cli.md index 958d108e..0b31ad18 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -829,6 +829,7 @@ agent_as_root = true # fctl-agent as root in sandboxes, out of the agent's r # firecracker = "/usr/local/bin/firecracker" # unset: the release fctl pins, which the host downloads # kernel = "/var/lib/fctl/vmlinux" # a file, or an image whose /vmlinux it is (unset: the published one) disk_gb = 64 # each sandbox's own disk, which takes only what its session writes +snapshots = true # a stopped sandbox keeps its VM's memory, and resumes as it was # jailer = true # on a host that runs as root: each VM as a user of its own, in a chroot and a cgroup ``` @@ -939,7 +940,13 @@ Agents are told their sandbox's size in their instructions and in A stopped session's sandbox takes disk on the host until it has been stopped for `keep_stopped_hours`, or until the disk runs low, and so does a Firecracker host's image builder, with its project's build cache, -counted from its last build. With Apple's +counted from its last build. With Firecracker a session's sandbox also +keeps its VM's state, the memory the VM used, so that a message resumes +the session with Claude running where it was rather than starting it +again; the host lets those states go first when the disk runs low, and +`snapshots = false` keeps none: turned off, it lets those kept before go +at its next sweep or the sandbox's next start, rather than resume them. A +host that runs its VMs through the jailer keeps none yet. With Apple's `container`, a sandbox's disk image keeps the space of the files its session deleted (a build of fctl leaves about 5.5 GB) until the host stops the sandbox: then the host gives that space back to the Mac with