From a0e4710ed2bf09c91ce363f5072a245ea814f91a Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:11:08 +0000 Subject: [PATCH 01/25] ci: boot Firecracker microVMs on GitHub's x86_64 runners The firecracker driver's test that boots a VM only ran by hand, on aarch64 under QEMU. GitHub's x86_64 runners have KVM: a CI job builds a static fctl-agent and runs the driver's ignored tests there, with Ubuntu's passt and its AppArmor profile, and the kernel hosts pull, which the test now takes unless FCTL_TEST_FIRECRACKER_KERNEL names one. Refs #345 --- .github/workflows/ci.yml | 31 +++++++++++++++++-- .../fctl-host/src/driver/firecracker/mod.rs | 15 ++++----- ...s-run-sandboxes-in-firecracker-microvms.md | 9 ++++-- 3 files changed, 43 insertions(+), 12 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2c997886..918236bc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,5 +1,6 @@ -# Checks every pull request and push, and runs a session through the local -# stack; on main (also when started by hand), deploys app.fctl.sh and pins +# Checks every pull request and push, runs a session through the local +# stack, and boots the firecracker driver's microVMs on a runner with KVM; +# on main (also when started by hand), deploys app.fctl.sh and pins # fctl.sh (hyperstructure/fctl-site) to main's docs when they differ from the # ones it shows. Pull request titles are checked in commits.yml; the # standalone control plane's image in standalone-image.yml, on pull requests @@ -112,6 +113,32 @@ jobs: # No npm ci: like a fresh clone, cargo xtask dev installs what it needs. - run: xtask dev --smoke + # The firecracker driver's tests that boot microVMs (`--ignored` ones in + # crates/fctl-host/src/driver/firecracker), which need KVM: GitHub's x86_64 + # runners have it, for root only. They pull an image from Docker Hub, the + # kernel hosts pull and Firecracker's release, and run passt under the + # AppArmor profile Ubuntu gives it. + firecracker: + name: Firecracker sandboxes + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ./.github/actions/rust + - name: KVM for the runner's user, passt and a static fctl-agent + run: | + sudo chmod 666 /dev/kvm + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends passt e2fsprogs + # What confines passt, which runs as the host's user. + sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" + rustup target add x86_64-unknown-linux-musl + cargo build --release --locked -p fctl-agent --target x86_64-unknown-linux-musl + - name: Boot sandboxes + env: + FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + run: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that # leaves its crates, the manifests, the toolchain and this workflow as they diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 071f39a9..b97d7365 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1160,20 +1160,21 @@ mod tests { /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's - /// needs and a static fctl-agent: + /// needs and a static fctl-agent, with the kernel hosts pull (or the + /// file `FCTL_TEST_FIRECRACKER_KERNEL`). CI runs it on GitHub's x86_64 + /// runners, which have KVM (the `firecracker` job of ci.yml): /// /// ```sh /// cargo build --release -p fctl-agent --target "$(uname -m)-unknown-linux-musl" /// FCTL_TEST_FIRECRACKER_AGENT=$PWD/target/$(uname -m)-unknown-linux-musl/release/fctl-agent \ - /// FCTL_TEST_FIRECRACKER_KERNEL=/path/to/vmlinux \ /// cargo test -p fctl-host boots_a_sandbox -- --ignored --nocapture /// ``` /// - /// `FCTL_TEST_FIRECRACKER_DATA` keeps the host's files (the image, and - /// Firecracker) between runs, and `FCTL_TEST_FIRECRACKER_RUN` is a - /// command whose output it shows (`claude --version`, say). + /// `FCTL_TEST_FIRECRACKER_DATA` keeps the host's files (the image, the + /// kernel and Firecracker) between runs, and `FCTL_TEST_FIRECRACKER_RUN` + /// is a command whose output it shows (`claude --version`, say). #[tokio::test] - #[ignore = "needs KVM, passt, a kernel and a static fctl-agent"] + #[ignore = "needs KVM, passt and a static fctl-agent"] async fn boots_a_sandbox() -> Result<()> { use super::super::Driver; use tokio::io::{AsyncReadExt, AsyncWriteExt}; @@ -1187,7 +1188,7 @@ mod tests { agent_bin: Some(var("FCTL_TEST_FIRECRACKER_AGENT")?.into()), ..HostConfig::default() }; - cfg.firecracker.kernel = Some(var("FCTL_TEST_FIRECRACKER_KERNEL")?); + cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; 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 ecc6565c..b2a3cede 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 @@ -87,6 +87,9 @@ microVM of its own. reports free. - The VM's clock follows the host's at boot and at each request of the host, not between them, after the host sleeps. -- CI has no KVM: the driver's test that boots a VM runs only by hand, with - `--ignored`. Session #536 ran it, and sessions end to end, on Firecracker - in a VM under QEMU's emulation of a CPU with virtualization. +- The driver's tests that boot VMs need KVM, so they are `--ignored` in + `cargo test`. Session #536 ran them, and sessions end to end, on + Firecracker in a VM under QEMU's emulation of a CPU with virtualization + (aarch64); CI runs them on GitHub's x86_64 runners, which have KVM, with + Ubuntu's passt and its AppArmor profile (the `firecracker` job of + `ci.yml`). From 976785e3720fff0d69defbea289d23412fa4bdbd Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:14:37 +0000 Subject: [PATCH 02/25] ci: quote the firecracker job's test filter, which YAML read as a mapping --- .github/workflows/ci.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 918236bc..e181f00e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,7 +137,8 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent - run: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + run: | + cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that From 616cd0fb331f43c7a92f40d4f3d7555fb897e59f Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:18:19 +0000 Subject: [PATCH 03/25] fix(host): start passt without --hostname, which Ubuntu 24.04's passt lacks Ubuntu 24.04's passt (0.0~git20240220) refuses --hostname, which came later, so no Firecracker VM got a network there. The VM names itself, so passt's DHCP needs no hostname. --- crates/fctl-host/src/driver/firecracker/vm.rs | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 80271f48..4d476368 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -173,7 +173,7 @@ impl Vm { std::fs::create_dir_all(&self.run)?; if spec.network { let passt = passt.context("the VM needs passt for its network")?; - self.start_passt(passt, &spec.boot.name).await?; + self.start_passt(passt).await?; } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; @@ -196,10 +196,10 @@ impl Vm { /// connections of the host's: the VM gets [`ADDRESS`], the gateway and /// a DNS forwarder, and reaches neither the host's loopback nor other /// VMs. Nothing reaches the VM from outside. - async fn start_passt(&self, passt: &Path, name: &str) -> Result<()> { + async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net(), name)) + cmd.args(passt_args(&self.net())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,9 +430,11 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM named `name` whose frames come to -/// `socket`. -fn passt_args(socket: &Path, name: &str) -> Vec { +/// The arguments of `passt` for a VM whose frames come to `socket`: the +/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 +/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which +/// came later. +fn passt_args(socket: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ "--foreground".into(), @@ -449,8 +451,6 @@ fn passt_args(socket: &Path, name: &str) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - "--hostname".into(), - name.into(), ] } @@ -563,10 +563,10 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), "fctl-ses-1").join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); assert_eq!( args, - "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw --hostname fctl-ses-1" + "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } From fbf92f5ba2f774bf7b0d8851c3d8869a8a0ad0ad Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:22:54 +0000 Subject: [PATCH 04/25] test(host): say what passt and the VM's network say when a sandbox has no DNS --- .github/workflows/ci.yml | 3 ++ .../fctl-host/src/driver/firecracker/mod.rs | 30 +++++++++++++++++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e181f00e..550168e1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,6 +139,9 @@ jobs: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + - name: What AppArmor and the kernel said + if: failure() + run: sudo dmesg | grep -iE 'apparmor|passt|firecracker|kvm' | tail -50 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index b97d7365..e80b097c 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -966,7 +966,11 @@ impl FirecrackerDriver { after: super::COMMAND_TIMEOUT, })??; if out.code != 0 { - bail!("{}", String::from_utf8_lossy(&out.stderr).trim()); + let said = String::from_utf8_lossy(&out.stderr); + match said.trim() { + "" => bail!("the command exited with {} in {}", out.code, sb.name), + said => bail!("{said}"), + } } Ok(String::from_utf8_lossy(&out.stdout).into_owned()) } @@ -1222,8 +1226,28 @@ mod tests { if let Ok(command) = std::env::var("FCTL_TEST_FIRECRACKER_RUN") { eprintln!("{command}: {}", d.exec(&sb, &command).await?.trim()); } - let resolved = d.exec(&sb, "getent hosts example.com").await?; - assert!(!resolved.trim().is_empty()); + // The network, through passt: what it and the VM say when it + // doesn't work. + let resolved = d.exec(&sb, "getent hosts example.com").await; + if resolved.as_ref().is_ok_and(|r| !r.trim().is_empty()) { + eprintln!("example.com is {}", resolved.unwrap_or_default().trim()); + } else { + let passt = std::fs::read_to_string( + cfg.data_dir() + .join("firecracker/sandboxes") + .join(&name) + .join("passt.log"), + ); + let net = d + .exec( + &sb, + "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; ls -l /etc/resolv.conf", + ) + .await; + bail!( + "no address for example.com in the sandbox ({resolved:?}); passt said {passt:?}; the VM's network: {net:?}" + ); + } let fetched = d .exec( &sb, From 8f88b35e07fc2236c2ba7792e4c377e69bef31a9 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:28:29 +0000 Subject: [PATCH 05/25] fix(host): give Firecracker VMs DNS past systemd-resolved's stub, as Docker does Ubuntu's /etc/resolv.conf names only systemd-resolved's 127.0.0.53, and the passt Ubuntu 24.04 has forwards no DNS to a resolver on the host's loopback with --no-map-gw, so VMs resolved nothing there. Where the host's resolv.conf names only loopback resolvers, the host passes passt the servers systemd-resolved asks, as Docker does for its containers. --- crates/fctl-host/src/driver/firecracker/vm.rs | 89 +++++++++++++++++-- 1 file changed, 82 insertions(+), 7 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 4d476368..862b60b5 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, anyhow, bail}; use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::net::Ipv4Addr; +use std::net::{IpAddr, Ipv4Addr}; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::{Duration, Instant}; @@ -199,7 +199,7 @@ impl Vm { async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net())) + cmd.args(passt_args(&self.net(), &host_dns())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,13 +430,14 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`: the +/// The arguments of `passt` for a VM whose frames come to `socket`, whose +/// DNS queries go to `dns` (when empty, to the host's resolver): the /// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 /// have. The VM names itself, so passt's DHCP needs no `--hostname`, which /// came later. -fn passt_args(socket: &Path) -> Vec { +fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { let mask = PREFIX.to_string(); - vec![ + let mut args: Vec = vec![ "--foreground".into(), "--quiet".into(), "--socket".into(), @@ -451,7 +452,51 @@ fn passt_args(socket: &Path) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - ] + ]; + for addr in dns { + args.extend(["--dns".into(), addr.to_string()]); + } + args +} + +/// Where the VMs' DNS queries go, when passt can't find it alone: as Docker +/// does, the servers systemd-resolved asks, where the host's +/// `/etc/resolv.conf` names only a resolver on its loopback (systemd-resolved's +/// 127.0.0.53). passt before 2024's summer forwards no queries to a resolver +/// on the loopback with `--no-map-gw` (Ubuntu 24.04's says "Couldn't get any +/// nameserver address"). Empty when the host names another resolver, or +/// nothing else is known: passt finds it then, or newer passt forwards to the +/// loopback's. +fn host_dns() -> Vec { + let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); + dns_for_vms( + &read("/etc/resolv.conf"), + &read("/run/systemd/resolve/resolv.conf"), + ) +} + +/// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 +/// ones only without any, at most three. +fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { + let servers = |text: &str| -> Vec { + text.lines() + .filter_map(|l| l.trim().strip_prefix("nameserver")) + .filter_map(|rest| rest.split_whitespace().next()) + // A link-local IPv6 server carries its interface: `fe80::1%eth0`. + .filter_map(|a| a.split('%').next().and_then(|a| a.parse().ok())) + .collect() + }; + let host = servers(resolv_conf); + if host.is_empty() || host.iter().any(|a| !a.is_loopback()) { + return Vec::new(); + } + let upstream: Vec = servers(resolved_upstream) + .into_iter() + .filter(|a| !a.is_loopback()) + .collect(); + let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); + let pick = if v4.is_empty() { upstream } else { v4 }; + pick.into_iter().take(3).collect() } /// Starts `cmd` in a process group of its own, writes its id to @@ -563,11 +608,41 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), &[]).join(" "); assert_eq!( args, "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); + let dns = [IpAddr::from([168, 63, 129, 16])]; + let args = passt_args(Path::new("/s"), &dns).join(" "); + assert!(args.ends_with("--no-map-gw --dns 168.63.129.16"), "{args}"); + } + + /// systemd-resolved's stub on the loopback, as Ubuntu has it, and its + /// upstream servers, which passt gets; any other resolver passt finds + /// itself. + #[test] + fn dns_goes_past_a_resolver_on_the_hosts_loopback() { + let stub = "# This is /run/systemd/resolve/stub-resolv.conf\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch .\n"; + let upstream = "nameserver 168.63.129.16\nnameserver fe80::1%eth0\nnameserver 10.0.0.2\nnameserver 1.1.1.1\nnameserver 8.8.8.8\nsearch example.internal\n"; + let v4 = |a: [u8; 4]| IpAddr::from(a); + assert_eq!( + dns_for_vms(stub, upstream), + [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] + ); + // IPv6 servers only where there is no IPv4 one. + let only_v6 = "nameserver 2001:4860:4860::8888\nnameserver ::1\n"; + assert_eq!( + dns_for_vms(stub, only_v6), + [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] + ); + // A resolver passt can reach, or nothing to go past to. + assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); + assert!( + dns_for_vms("nameserver 127.0.0.53\nnameserver 192.168.1.1\n", upstream).is_empty() + ); + assert!(dns_for_vms(stub, "").is_empty()); + assert!(dns_for_vms("", upstream).is_empty()); } #[test] From e88ee76a5077ed825f78188866e997fae6e535ef Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:32:53 +0000 Subject: [PATCH 06/25] fix(host): leave link-local DNS servers out of passt's, which it can't reach systemd-resolved lists a link-local IPv6 server with its interface (fe80::1%eth0), which --dns can't carry: without it, passt finds a server itself rather than get one it can't reach. --- crates/fctl-host/src/driver/firecracker/vm.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 862b60b5..383851a3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -476,7 +476,8 @@ fn host_dns() -> Vec { } /// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 -/// ones only without any, at most three. +/// ones only without any, at most three. Link-local IPv6 servers are left +/// out: `--dns` can't say which interface reaches them (`fe80::1%eth0`). fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { let servers = |text: &str| -> Vec { text.lines() @@ -492,7 +493,10 @@ fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { } let upstream: Vec = servers(resolved_upstream) .into_iter() - .filter(|a| !a.is_loopback()) + .filter(|a| match a { + IpAddr::V4(a) => !a.is_loopback(), + IpAddr::V6(a) => !a.is_loopback() && !a.is_unicast_link_local(), + }) .collect(); let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); let pick = if v4.is_empty() { upstream } else { v4 }; @@ -630,12 +634,14 @@ mod tests { dns_for_vms(stub, upstream), [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] ); - // IPv6 servers only where there is no IPv4 one. - let only_v6 = "nameserver 2001:4860:4860::8888\nnameserver ::1\n"; + // IPv6 servers only where there is no IPv4 one, and no link-local + // one, which passt can't reach without its interface. + let only_v6 = "nameserver fe80::1%eth0\nnameserver 2001:4860:4860::8888\nnameserver ::1\n"; assert_eq!( dns_for_vms(stub, only_v6), [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] ); + assert!(dns_for_vms(stub, "nameserver fe80::1%eth0\nnameserver fe80::2\n").is_empty()); // A resolver passt can reach, or nothing to go past to. assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); assert!( From 681768baeed2d5a99785a3438e0eb759538c64fb Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:38:49 +0000 Subject: [PATCH 07/25] fix(host): give Firecracker VMs the host's nameservers, past systemd-resolved's stub The --dns passt took doesn't set where its forwarder sends queries in Ubuntu 24.04's passt, so VMs still resolved nothing there. As Docker gives its containers, the VM now asks the host's nameservers itself (fctl.dns= on its kernel's command line), but for those on the host's loopback, and where only those are left, the servers systemd-resolved asks. With none, it asks passt's forwarder, as before. --- crates/fctl-agent/src/vm/boot.rs | 16 ++- .../fctl-host/src/driver/firecracker/mod.rs | 3 +- crates/fctl-host/src/driver/firecracker/vm.rs | 119 ++++++++---------- crates/fctl-proto/src/vm.rs | 20 ++- 4 files changed, 82 insertions(+), 76 deletions(-) diff --git a/crates/fctl-agent/src/vm/boot.rs b/crates/fctl-agent/src/vm/boot.rs index dfa69358..316bc71c 100644 --- a/crates/fctl-agent/src/vm/boot.rs +++ b/crates/fctl-agent/src/vm/boot.rs @@ -264,11 +264,17 @@ fn system(boot: &Boot) { "127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n127.0.1.1\t{}\n", boot.name ); - let dns = std::net::Ipv4Addr::from(fctl_proto::vm::DNS); - for (file, text) in [ - ("/etc/hosts", hosts), - ("/etc/resolv.conf", format!("nameserver {dns}\n")), - ] { + // The host's nameservers, which passt reaches as the host does, or the + // address where passt forwards queries to the host's resolver. + let servers = match boot.dns.as_slice() { + [] => vec![std::net::Ipv4Addr::from(fctl_proto::vm::DNS)], + some => some.to_vec(), + }; + let resolv: String = servers + .iter() + .map(|s| format!("nameserver {s}\n")) + .collect(); + for (file, text) in [("/etc/hosts", hosts), ("/etc/resolv.conf", resolv)] { if let Err(e) = replace(file, &text) { say(&format!("writing {file}: {e}")); } diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index e80b097c..08172802 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -752,6 +752,7 @@ impl FirecrackerDriver { mode: Mode::Sandbox, name: spec.name.clone(), time_ms: Some(vsock::now_ms()), + dns: vm::vm_dns(), }, drives: vec![ Drive { @@ -1241,7 +1242,7 @@ mod tests { let net = d .exec( &sb, - "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; ls -l /etc/resolv.conf", + "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", ) .await; bail!( diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 383851a3..196c96f0 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -7,7 +7,7 @@ use anyhow::{Context, Result, anyhow, bail}; use fctl_proto::vm::{ADDRESS, Boot, DNS, GATEWAY, Mode, NET_PORT, PREFIX}; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; -use std::net::{IpAddr, Ipv4Addr}; +use std::net::Ipv4Addr; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::{Duration, Instant}; @@ -199,7 +199,7 @@ impl Vm { async fn start_passt(&self, passt: &Path) -> Result<()> { let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net(), &host_dns())) + cmd.args(passt_args(&self.net())) .stdin(Stdio::null()) .stdout(log.try_clone()?) .stderr(log); @@ -430,14 +430,13 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`, whose -/// DNS queries go to `dns` (when empty, to the host's resolver): the +/// The arguments of `passt` for a VM whose frames come to `socket`: the /// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 /// have. The VM names itself, so passt's DHCP needs no `--hostname`, which /// came later. -fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { +fn passt_args(socket: &Path) -> Vec { let mask = PREFIX.to_string(); - let mut args: Vec = vec![ + vec![ "--foreground".into(), "--quiet".into(), "--socket".into(), @@ -452,55 +451,46 @@ fn passt_args(socket: &Path, dns: &[IpAddr]) -> Vec { Ipv4Addr::from(DNS).to_string(), // The gateway's address doesn't lead to the host's loopback. "--no-map-gw".into(), - ]; - for addr in dns { - args.extend(["--dns".into(), addr.to_string()]); - } - args + ] } -/// Where the VMs' DNS queries go, when passt can't find it alone: as Docker -/// does, the servers systemd-resolved asks, where the host's -/// `/etc/resolv.conf` names only a resolver on its loopback (systemd-resolved's -/// 127.0.0.53). passt before 2024's summer forwards no queries to a resolver -/// on the loopback with `--no-map-gw` (Ubuntu 24.04's says "Couldn't get any -/// nameserver address"). Empty when the host names another resolver, or -/// nothing else is known: passt finds it then, or newer passt forwards to the -/// loopback's. -fn host_dns() -> Vec { +/// The nameservers a VM asks, which passt reaches as the host does: as +/// Docker gives its containers, the host's own, but for those on its +/// loopback, which the VM can't reach, and where only those are left +/// (systemd-resolved's 127.0.0.53, as Ubuntu has it) the servers +/// systemd-resolved asks. Empty when there are none: the VM asks passt's +/// forwarder then, which passes its queries to the host's resolver, but in +/// passt's releases before the summer of 2024 (Ubuntu 24.04's) not to one on +/// the loopback. +pub fn vm_dns() -> Vec { let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); - dns_for_vms( + dns_for_vm( &read("/etc/resolv.conf"), &read("/run/systemd/resolve/resolv.conf"), ) } -/// [`host_dns`], from the files' text: the IPv4 servers first, and IPv6 -/// ones only without any, at most three. Link-local IPv6 servers are left -/// out: `--dns` can't say which interface reaches them (`fe80::1%eth0`). -fn dns_for_vms(resolv_conf: &str, resolved_upstream: &str) -> Vec { - let servers = |text: &str| -> Vec { +/// [`vm_dns`], from the files' text: at most three IPv4 servers (the VM +/// has no IPv6), and none of the addresses that mean something else in the +/// VM's network, where the gateway and passt's forwarder are. +fn dns_for_vm(resolv_conf: &str, resolved_upstream: &str) -> Vec { + let usable = |text: &str| -> Vec { text.lines() .filter_map(|l| l.trim().strip_prefix("nameserver")) .filter_map(|rest| rest.split_whitespace().next()) - // A link-local IPv6 server carries its interface: `fe80::1%eth0`. - .filter_map(|a| a.split('%').next().and_then(|a| a.parse().ok())) + .filter_map(|a| a.parse::().ok()) + .filter(|a| { + !a.is_loopback() + && !a.is_unspecified() + && ![ADDRESS, GATEWAY, DNS].contains(&a.octets()) + }) + .take(3) .collect() }; - let host = servers(resolv_conf); - if host.is_empty() || host.iter().any(|a| !a.is_loopback()) { - return Vec::new(); - } - let upstream: Vec = servers(resolved_upstream) - .into_iter() - .filter(|a| match a { - IpAddr::V4(a) => !a.is_loopback(), - IpAddr::V6(a) => !a.is_loopback() && !a.is_unicast_link_local(), - }) - .collect(); - let v4: Vec = upstream.iter().copied().filter(IpAddr::is_ipv4).collect(); - let pick = if v4.is_empty() { upstream } else { v4 }; - pick.into_iter().take(3).collect() + match usable(resolv_conf) { + none if none.is_empty() => usable(resolved_upstream), + some => some, + } } /// Starts `cmd` in a process group of its own, writes its id to @@ -547,6 +537,7 @@ pub fn unpack_spec(kernel: PathBuf, initrd: PathBuf, name: &str, rootfs: &Path) mode: Mode::Unpack, name: name.into(), time_ms: Some(vsock::now_ms()), + dns: Vec::new(), }, drives: vec![Drive { path: rootfs.to_owned(), @@ -575,6 +566,7 @@ mod tests { mode: Mode::Sandbox, name: "fctl-ses-1".into(), time_ms: Some(5), + dns: vec![[168, 63, 129, 16].into()], }, drives: vec![ Drive { @@ -594,7 +586,7 @@ mod tests { assert_eq!( c["boot-source"]["boot_args"], format!( - "{} fctl.mode=sandbox fctl.name=fctl-ses-1 fctl.time=5", + "{} fctl.mode=sandbox fctl.name=fctl-ses-1 fctl.time=5 fctl.dns=168.63.129.16", kernel_args() ) ); @@ -612,43 +604,34 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025"), &[]).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); assert_eq!( args, "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); - let dns = [IpAddr::from([168, 63, 129, 16])]; - let args = passt_args(Path::new("/s"), &dns).join(" "); - assert!(args.ends_with("--no-map-gw --dns 168.63.129.16"), "{args}"); } - /// systemd-resolved's stub on the loopback, as Ubuntu has it, and its - /// upstream servers, which passt gets; any other resolver passt finds - /// itself. + /// The host's nameservers, past systemd-resolved's stub on its loopback + /// as Ubuntu has it, to the servers it asks. #[test] - fn dns_goes_past_a_resolver_on_the_hosts_loopback() { + fn vms_ask_the_hosts_nameservers_and_none_on_its_loopback() { let stub = "# This is /run/systemd/resolve/stub-resolv.conf\nnameserver 127.0.0.53\noptions edns0 trust-ad\nsearch .\n"; let upstream = "nameserver 168.63.129.16\nnameserver fe80::1%eth0\nnameserver 10.0.0.2\nnameserver 1.1.1.1\nnameserver 8.8.8.8\nsearch example.internal\n"; - let v4 = |a: [u8; 4]| IpAddr::from(a); + let v4 = |a: [u8; 4]| Ipv4Addr::from(a); assert_eq!( - dns_for_vms(stub, upstream), + dns_for_vm(stub, upstream), [v4([168, 63, 129, 16]), v4([10, 0, 0, 2]), v4([1, 1, 1, 1])] ); - // IPv6 servers only where there is no IPv4 one, and no link-local - // one, which passt can't reach without its interface. - let only_v6 = "nameserver fe80::1%eth0\nnameserver 2001:4860:4860::8888\nnameserver ::1\n"; - assert_eq!( - dns_for_vms(stub, only_v6), - [IpAddr::from([0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888])] - ); - assert!(dns_for_vms(stub, "nameserver fe80::1%eth0\nnameserver fe80::2\n").is_empty()); - // A resolver passt can reach, or nothing to go past to. - assert!(dns_for_vms("nameserver 10.0.2.3\n", upstream).is_empty()); - assert!( - dns_for_vms("nameserver 127.0.0.53\nnameserver 192.168.1.1\n", upstream).is_empty() - ); - assert!(dns_for_vms(stub, "").is_empty()); - assert!(dns_for_vms("", upstream).is_empty()); + // The host's own, but for those on its loopback. + let router = "nameserver 127.0.0.1\nnameserver 192.168.1.1\n"; + assert_eq!(dns_for_vm(router, upstream), [v4([192, 168, 1, 1])]); + assert_eq!(dns_for_vm("", upstream)[0], v4([168, 63, 129, 16])); + // Nothing the VM could ask: passt's forwarder. QEMU's user network + // has its resolver where the VM's forwarder is, 10.0.2.3, and IPv6 + // doesn't reach the VM. + assert!(dns_for_vm(stub, "").is_empty()); + assert!(dns_for_vm(stub, "nameserver 2001:4860:4860::8888\n").is_empty()); + assert!(dns_for_vm("nameserver 10.0.2.3\n", "").is_empty()); } #[test] diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 504352ea..7a254cf4 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -50,13 +50,18 @@ pub enum Mode { } /// What the init reads from the kernel's command line: `fctl.mode=`, -/// `fctl.name=` (the VM's hostname) and `fctl.time=` (the host's clock at -/// boot, in milliseconds since the Unix epoch). +/// `fctl.name=` (the VM's hostname), `fctl.time=` (the host's clock at +/// boot, in milliseconds since the Unix epoch) and `fctl.dns=` (the +/// nameservers the VM asks, separated by commas). #[derive(Clone, Debug, PartialEq, Eq)] pub struct Boot { pub mode: Mode, pub name: String, pub time_ms: Option, + /// The nameservers the VM asks: the host's own, which `passt` reaches as + /// the host does. Empty: [`DNS`], which `passt` forwards to the host's + /// resolver. + pub dns: Vec, } impl Boot { @@ -70,6 +75,10 @@ impl Boot { if let Some(t) = self.time_ms { p.push_str(&format!(" fctl.time={t}")); } + if !self.dns.is_empty() { + let dns: Vec = self.dns.iter().map(ToString::to_string).collect(); + p.push_str(&format!(" fctl.dns={}", dns.join(","))); + } p } @@ -78,12 +87,16 @@ impl Boot { let mut mode = None; let mut name = String::from("fctl"); let mut time_ms = None; + let mut dns = Vec::new(); for word in cmdline.split_whitespace() { match word.split_once('=') { Some(("fctl.mode", "sandbox")) => mode = Some(Mode::Sandbox), Some(("fctl.mode", "unpack")) => mode = Some(Mode::Unpack), Some(("fctl.name", n)) if !n.is_empty() => n.clone_into(&mut name), Some(("fctl.time", t)) => time_ms = t.parse().ok(), + Some(("fctl.dns", list)) => { + dns = list.split(',').filter_map(|a| a.parse().ok()).collect(); + } _ => {} } } @@ -91,6 +104,7 @@ impl Boot { mode: mode?, name, time_ms, + dns, }) } } @@ -223,11 +237,13 @@ mod tests { mode: Mode::Sandbox, name: "fctl-ses-01abc".into(), time_ms: Some(1_761_700_000_000), + dns: vec![[168, 63, 129, 16].into(), [10, 1, 0, 2].into()], }; let cmdline = format!( "console=ttyS0 reboot=k panic=1 {} rdinit=/init", boot.params() ); + assert!(cmdline.contains(" fctl.dns=168.63.129.16,10.1.0.2 ")); assert_eq!(Boot::parse(&cmdline), Some(boot)); let unpack = Boot::parse("fctl.mode=unpack quiet"); assert_eq!( From 5d45e3a0d952e73ab1ea3fa36e91f9f0144fe585 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:44:06 +0000 Subject: [PATCH 08/25] test(host): say what passt, the VM's console and AppArmor say when a sandbox has no network --- .github/workflows/ci.yml | 3 +- .../fctl-host/src/driver/firecracker/mod.rs | 41 ++++++++++++------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 550168e1..a85ca1ed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -141,7 +141,8 @@ jobs: cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - name: What AppArmor and the kernel said if: failure() - run: sudo dmesg | grep -iE 'apparmor|passt|firecracker|kvm' | tail -50 + # journald takes the kernel's audit records, AppArmor's among them. + run: sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | tail -60 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 08172802..8ba27b90 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1163,6 +1163,30 @@ mod tests { } } + /// What passt, the VM's console and the VM's network say, for a test + /// whose sandbox can't reach the network. + async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { + let dir = data.join("firecracker/sandboxes").join(&sb.name); + let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); + let passt_runs = read("passt.pid") + .trim() + .parse::() + .ok() + .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) + .map(|cmdline| cmdline.replace('\0', " ")); + let vm = d + .exec( + sb, + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", + ) + .await; + format!( + "passt runs: {passt_runs:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network: {vm:?}", + read("passt.log").trim(), + read("console.log").trim() + ) + } + /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1233,21 +1257,8 @@ mod tests { if resolved.as_ref().is_ok_and(|r| !r.trim().is_empty()) { eprintln!("example.com is {}", resolved.unwrap_or_default().trim()); } else { - let passt = std::fs::read_to_string( - cfg.data_dir() - .join("firecracker/sandboxes") - .join(&name) - .join("passt.log"), - ); - let net = d - .exec( - &sb, - "cat /etc/resolv.conf /proc/net/route /sys/class/net/eth0/operstate; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", - ) - .await; - bail!( - "no address for example.com in the sandbox ({resolved:?}); passt said {passt:?}; the VM's network: {net:?}" - ); + let report = network_report(&d, &sb, &cfg.data_dir()).await; + bail!("no address for example.com in the sandbox ({resolved:?})\n{report}"); } let fetched = d .exec( From c0f2383e1982aa3c100c42118c26bf19de2fdb93 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:49:06 +0000 Subject: [PATCH 09/25] test(host): capture passt's frames and debug log in CI, where VMs get no network --- .github/workflows/ci.yml | 1 + .../fctl-host/src/driver/firecracker/mod.rs | 73 ++++++++++++++++--- 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a85ca1ed..e6224737 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -137,6 +137,7 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + FCTL_TEST_FIRECRACKER_PASST_DEBUG: /tmp/passt.pcap run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - name: What AppArmor and the kernel said diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 8ba27b90..12d837e2 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1168,25 +1168,77 @@ mod tests { async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { let dir = data.join("firecracker/sandboxes").join(&sb.name); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); - let passt_runs = read("passt.pid") - .trim() - .parse::() - .ok() - .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) - .map(|cmdline| cmdline.replace('\0', " ")); + let passt = read("passt.pid").trim().parse::().ok().map(|pid| { + let proc = + |f: &str| std::fs::read_to_string(format!("/proc/{pid}/{f}")).unwrap_or_default(); + let fds = std::fs::read_dir(format!("/proc/{pid}/fd")) + .map(|d| { + d.flatten() + .filter_map(|e| std::fs::read_link(e.path()).ok()) + .map(|l| l.display().to_string()) + .collect::>() + }) + .unwrap_or_default(); + format!( + "{}\n{}\nfds: {fds:?}", + proc("cmdline").replace('\0', " "), + proc("status") + .lines() + .filter(|l| l.starts_with("State")) + .collect::() + ) + }); + // Its capture, where the test asked for one (debug_passt). + let frames = std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG") + .and_then(|pcap| std::fs::read(pcap).ok()) + .map(|pcap| pcap_summary(&pcap)); let vm = d .exec( sb, - "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' && echo 'TCP to 1.1.1.1:80 works'", + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; format!( - "passt runs: {passt_runs:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network: {vm:?}", + "passt: {passt:?}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), - read("console.log").trim() + read("console.log").trim(), + vm.unwrap_or_else(|e| format!("{e:#}")) ) } + /// The frames in a pcap file, each as its length and first bytes. + fn pcap_summary(pcap: &[u8]) -> Vec { + let mut frames = Vec::new(); + let mut at = 24; + while let Some(header) = pcap.get(at..at + 16) { + let len = u32::from_le_bytes([header[8], header[9], header[10], header[11]]) as usize; + let frame = pcap.get(at + 16..at + 16 + len).unwrap_or_default(); + frames.push(format!( + "{len}: {}", + hex::encode(&frame[..frame.len().min(42)]) + )); + at += 16 + len; + } + frames + } + + /// passt with its debug log and a capture of its frames, in place of the + /// host's: a script that runs it so, which + /// `FCTL_TEST_FIRECRACKER_PASST_DEBUG` asks for, naming the capture's + /// file (in /tmp, where Ubuntu's AppArmor profile lets passt write). + fn debug_passt(dir: &Path) -> Result { + let passt = find_program("passt").context("passt is not installed")?; + let script = dir.join("passt-debug"); + crate::driver::fake::write_script( + &script, + &format!( + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --debug --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + passt.display() + ), + )?; + Ok(script) + } + /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1219,6 +1271,9 @@ mod tests { }; cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; + if std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG").is_some() { + cfg.firecracker.passt = Some(debug_passt(temp.path())?); + } let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; assert!(probed.available, "{probed:?}"); From b78389c39fec4cda21a811b0d87d243aed8af0e5 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 18:56:42 +0000 Subject: [PATCH 10/25] test(host): say where passt waits, as root, when a sandbox has no network --- .../fctl-host/src/driver/firecracker/mod.rs | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 12d837e2..7cb8906f 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1179,13 +1179,34 @@ mod tests { .collect::>() }) .unwrap_or_default(); + // passt makes itself undumpable: root sees the rest, where sudo + // asks for no password (as on CI's runners). + let sudo = |args: &[&str]| { + std::process::Command::new("sudo") + .arg("-n") + .args(args) + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) + .unwrap_or_default() + }; + let p = pid.to_string(); format!( - "{}\n{}\nfds: {fds:?}", + "{}\n{}\nfds: {fds:?}\nas root: fds {}\nsyscall {}\nstack {}\nsockets: {}", proc("cmdline").replace('\0', " "), proc("status") .lines() .filter(|l| l.starts_with("State")) - .collect::() + .collect::(), + sudo(&["ls", "-l", &format!("/proc/{p}/fd")]), + sudo(&["cat", &format!("/proc/{p}/syscall")]), + sudo(&["cat", &format!("/proc/{p}/stack")]), + sudo(&["ss", "-xanp"]) + .lines() + .filter(|l| l.contains("v.sock") + || l.contains("passt") + || l.contains("firecracker")) + .collect::>() + .join("\n") ) }); // Its capture, where the test asked for one (debug_passt). From e384059193df06b26a6ca0db8faf8d73302fd6a5 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:02:09 +0000 Subject: [PATCH 11/25] test(host): passt's trace in CI, which logs each event --- crates/fctl-host/src/driver/firecracker/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 7cb8906f..8a7385c6 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1253,7 +1253,7 @@ mod tests { crate::driver::fake::write_script( &script, &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --debug --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", passt.display() ), )?; From 554c8ff37d14d68613835891e78630137c8382dd Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:06:46 +0000 Subject: [PATCH 12/25] test(host): trace passt's accept in CI --- .github/workflows/ci.yml | 6 ++++-- crates/fctl-host/src/driver/firecracker/mod.rs | 5 +++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e6224737..c3fe69c6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,7 +129,7 @@ jobs: run: | sudo chmod 666 /dev/kvm sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends passt e2fsprogs + sudo apt-get install -y --no-install-recommends passt e2fsprogs strace # What confines passt, which runs as the host's user. sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" rustup target add x86_64-unknown-linux-musl @@ -143,7 +143,9 @@ jobs: - name: What AppArmor and the kernel said if: failure() # journald takes the kernel's audit records, AppArmor's among them. - run: sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | tail -60 + run: | + sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | grep -v STATUS | tail -60 + sudo dmesg | tail -30 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 8a7385c6..915a00a7 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1219,8 +1219,9 @@ mod tests { "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; + let strace = std::fs::read_to_string("/tmp/passt.strace").unwrap_or_default(); format!( - "passt: {passt:?}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", + "passt: {passt:?}\npasst's syscalls:\n{strace}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), read("console.log").trim(), vm.unwrap_or_else(|e| format!("{e:#}")) @@ -1253,7 +1254,7 @@ mod tests { crate::driver::fake::write_script( &script, &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", + "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec strace -f -tt -e trace=accept4,accept,getsockopt,setsockopt,epoll_ctl -o /tmp/passt.strace {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", passt.display() ), )?; From c93b5a8368b2ece23ad7891ea0cf1a8ca8984d02 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:20:04 +0000 Subject: [PATCH 13/25] fix(host): link a Firecracker VM's network from the host, which Ubuntu's passt takes On Ubuntu 24.04 no Firecracker VM got a network: passt's AppArmor profile there refuses to accept the connection Firecracker makes for the VM (accept4 fails with EACCES, and nothing is logged), so the VM's frames waited in passt's backlog. CI's x86_64 runners showed it. Now the VM's init listens on its vsock port 1025, and the host, once the VM is up, connects to it and hands passt the connection with --fd, which passt reads without accepting anything. passt exits when the VM closes the connection, as it stops, rather than linger until the next start, and the host links a running VM again when its passt is gone. The test's diagnostics that found it (passt under strace, its trace and capture) are gone; on a failure it still says what passt, the VM's console and its network say. --- .github/workflows/ci.yml | 9 +- crates/fctl-agent/src/vm/net.rs | 55 +++- .../fctl-host/src/driver/firecracker/mod.rs | 114 ++----- crates/fctl-host/src/driver/firecracker/vm.rs | 290 +++++++++++++----- crates/fctl-proto/src/vm.rs | 10 +- docs/architecture.md | 16 +- 6 files changed, 305 insertions(+), 189 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3fe69c6..e181f00e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -129,7 +129,7 @@ jobs: run: | sudo chmod 666 /dev/kvm sudo apt-get update -qq - sudo apt-get install -y --no-install-recommends passt e2fsprogs strace + sudo apt-get install -y --no-install-recommends passt e2fsprogs # What confines passt, which runs as the host's user. sudo aa-status 2>/dev/null | grep -i passt || echo "No AppArmor profile confines passt" rustup target add x86_64-unknown-linux-musl @@ -137,15 +137,8 @@ jobs: - name: Boot sandboxes env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent - FCTL_TEST_FIRECRACKER_PASST_DEBUG: /tmp/passt.pcap run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 - - name: What AppArmor and the kernel said - if: failure() - # journald takes the kernel's audit records, AppArmor's among them. - run: | - sudo journalctl --no-pager -b _TRANSPORT=audit _TRANSPORT=kernel | grep -iE 'apparmor|passt|firecracker|kvm|vsock' | grep -v STATUS | tail -60 - sudo dmesg | tail -30 # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-agent/src/vm/net.rs b/crates/fctl-agent/src/vm/net.rs index 254e8c8a..74173f35 100644 --- a/crates/fctl-agent/src/vm/net.rs +++ b/crates/fctl-agent/src/vm/net.rs @@ -1,7 +1,8 @@ //! The VM's network: a TAP device, `eth0`, whose frames travel over the //! vsock to the host's `passt`, which carries them to the network as the //! host's own connections. The host needs no bridge, TAP or root for it, -//! and each VM's network is its own. +//! and each VM's network is its own. The host makes the link: it connects +//! to the VM's port, and passt takes over its connection. use super::netlink; use fctl_proto::vm::{ADDRESS, GATEWAY, MTU, NET_PORT, PREFIX}; @@ -10,13 +11,20 @@ use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio_tun::Tun; -use tokio_vsock::{OwnedReadHalf, OwnedWriteHalf, VMADDR_CID_HOST, VsockAddr, VsockStream}; +use tokio_vsock::{ + OwnedReadHalf, OwnedWriteHalf, VMADDR_CID_ANY, VMADDR_CID_HOST, VsockAddr, VsockListener, + VsockStream, +}; /// The longest frame: the MTU, an Ethernet header and a VLAN tag. const MAX_FRAME: usize = MTU as usize + 18; -/// Brings the network up and keeps it linked to the host, connecting again -/// when the link closes (the host restarts `passt`, say). +/// Brings the network up and takes the host's link to it: the host connects +/// to the VM's [`NET_PORT`] once the VM is up and hands the connection to +/// `passt`, which a connection of passt's own would need to accept (and +/// Ubuntu's AppArmor profile for passt refuses that, from Firecracker). A +/// newer link takes the place of the one before (the host started passt +/// again, after a snapshot's restore, say). pub async fn run() { if let Err(e) = netlink::ask(&netlink::link_up_message(1)) { tracing::warn!("bringing the loopback up: {e}"); @@ -28,19 +36,38 @@ pub async fn run() { return; } }; - let mut wait = Duration::from_secs(1); + let listener = match VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, NET_PORT)) { + Ok(listener) => listener, + Err(e) => { + tracing::error!("the VM has no network: listening on the vsock: {e}"); + return; + } + }; + let mut link: Option> = None; loop { - match VsockStream::connect(VsockAddr::new(VMADDR_CID_HOST, NET_PORT)).await { - Ok(stream) => { - tracing::info!("the network is linked to the host"); - wait = Duration::from_secs(1); - let e = forward(&tap, stream).await; - tracing::warn!("the network's link to the host closed: {e}"); + let (stream, peer) = match listener.accept().await { + Ok(accepted) => accepted, + Err(e) => { + tracing::warn!("taking the host's link to the network: {e}"); + tokio::time::sleep(Duration::from_secs(1)).await; + continue; } - Err(e) => tracing::debug!("linking the network to the host: {e}"), + }; + // Only the host, not a program in the VM through the vsock's + // loopback, which would see the VM's frames. + if peer.cid() != VMADDR_CID_HOST { + tracing::warn!("refused a network link from vsock CID {}", peer.cid()); + continue; + } + if let Some(old) = link.take() { + old.abort(); } - tokio::time::sleep(wait).await; - wait = (wait * 2).min(Duration::from_secs(10)); + tracing::info!("the network is linked to the host"); + let tap = tap.clone(); + link = Some(tokio::spawn(async move { + let e = forward(&tap, stream).await; + tracing::warn!("the network's link to the host closed: {e}"); + })); } } diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 915a00a7..03278d05 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -13,9 +13,9 @@ //! and starting it again boots from it. //! - **The VM** boots the kernel with fctl-agent as its init //! ([`assets::initrd`]); Firecracker and `passt`, which gives the VM its -//! network over the vsock without a TAP device or root on the host, run -//! in process groups of their own, so that restarting the host leaves -//! them running ([`vm`]). +//! network over a vsock connection the host makes once the VM is up, +//! without a TAP device or root on the host, run in process groups of +//! their own, so that restarting the host leaves them running ([`vm`]). //! - **The host runs programs** in the VM through its vsock, as `docker //! exec` would ([`vsock`]). @@ -631,7 +631,7 @@ impl FirecrackerDriver { remove_stale(&self.root.join("unpacking")); let vm = Vm::new(self.root.join("unpacking").join(&name))?; let spec = vm::unpack_spec(kernel, initrd, &name, rootfs); - vm.start(&spec, &firecracker, None).await?; + vm.start(&spec, &firecracker).await?; let result = async { vm.wait_ready().await?; let within = @@ -708,6 +708,14 @@ impl FirecrackerDriver { let socket = vm.vsock(); let answers = tokio::time::timeout(Duration::from_secs(10), vsock::hello(&socket)); if matches!(answers.await, Ok(Ok(_))) { + // Its passt exited, or was stopped: the VM gets another. + if !vm.linked() { + log(format!("Linking the network of {} again", spec.name)); + let passt = self + .passt() + .context("passt is not installed: it gives the VMs their network")?; + vm.link_network(&passt).await?; + } return Ok(sb); } log(format!( @@ -768,8 +776,12 @@ impl FirecrackerDriver { memory_mb: spec.memory_mb, network: true, }; - vm.start(&boot, &firecracker, Some(&passt)).await?; + vm.start(&boot, &firecracker).await?; vm.wait_ready().await?; + if let Err(e) = vm.link_network(&passt).await { + vm.kill().await; + return Err(e); + } record.agent = Some(agent); self.save_record(&spec.name, &record)?; Ok(sb) @@ -1168,99 +1180,26 @@ mod tests { async fn network_report(d: &super::super::Driver, sb: &Sandbox, data: &Path) -> String { let dir = data.join("firecracker/sandboxes").join(&sb.name); let read = |file: &str| std::fs::read_to_string(dir.join(file)).unwrap_or_default(); - let passt = read("passt.pid").trim().parse::().ok().map(|pid| { - let proc = - |f: &str| std::fs::read_to_string(format!("/proc/{pid}/{f}")).unwrap_or_default(); - let fds = std::fs::read_dir(format!("/proc/{pid}/fd")) - .map(|d| { - d.flatten() - .filter_map(|e| std::fs::read_link(e.path()).ok()) - .map(|l| l.display().to_string()) - .collect::>() - }) - .unwrap_or_default(); - // passt makes itself undumpable: root sees the rest, where sudo - // asks for no password (as on CI's runners). - let sudo = |args: &[&str]| { - std::process::Command::new("sudo") - .arg("-n") - .args(args) - .output() - .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) - .unwrap_or_default() - }; - let p = pid.to_string(); - format!( - "{}\n{}\nfds: {fds:?}\nas root: fds {}\nsyscall {}\nstack {}\nsockets: {}", - proc("cmdline").replace('\0', " "), - proc("status") - .lines() - .filter(|l| l.starts_with("State")) - .collect::(), - sudo(&["ls", "-l", &format!("/proc/{p}/fd")]), - sudo(&["cat", &format!("/proc/{p}/syscall")]), - sudo(&["cat", &format!("/proc/{p}/stack")]), - sudo(&["ss", "-xanp"]) - .lines() - .filter(|l| l.contains("v.sock") - || l.contains("passt") - || l.contains("firecracker")) - .collect::>() - .join("\n") - ) - }); - // Its capture, where the test asked for one (debug_passt). - let frames = std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG") - .and_then(|pcap| std::fs::read(pcap).ok()) - .map(|pcap| pcap_summary(&pcap)); + let passt = read("passt.pid") + .trim() + .parse::() + .ok() + .and_then(|pid| std::fs::read_to_string(format!("/proc/{pid}/cmdline")).ok()) + .map(|cmdline| cmdline.replace('\0', " ")); let vm = d .exec( sb, - "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev /sys/class/net/eth0/address 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", + "cat /etc/resolv.conf /proc/net/route /proc/net/arp /proc/net/dev 2>&1; timeout 5 bash -c 'exec 3<>/dev/tcp/1.1.1.1/80' 2>&1 && echo 'TCP to 1.1.1.1:80 works'; true", ) .await; - let strace = std::fs::read_to_string("/tmp/passt.strace").unwrap_or_default(); format!( - "passt: {passt:?}\npasst's syscalls:\n{strace}\npasst said:\n{}\npasst's capture: {frames:?}\nthe VM's console:\n{}\nthe VM's network:\n{}", + "passt runs: {passt:?}\npasst said:\n{}\nthe VM's console:\n{}\nthe VM's network:\n{}", read("passt.log").trim(), read("console.log").trim(), vm.unwrap_or_else(|e| format!("{e:#}")) ) } - /// The frames in a pcap file, each as its length and first bytes. - fn pcap_summary(pcap: &[u8]) -> Vec { - let mut frames = Vec::new(); - let mut at = 24; - while let Some(header) = pcap.get(at..at + 16) { - let len = u32::from_le_bytes([header[8], header[9], header[10], header[11]]) as usize; - let frame = pcap.get(at + 16..at + 16 + len).unwrap_or_default(); - frames.push(format!( - "{len}: {}", - hex::encode(&frame[..frame.len().min(42)]) - )); - at += 16 + len; - } - frames - } - - /// passt with its debug log and a capture of its frames, in place of the - /// host's: a script that runs it so, which - /// `FCTL_TEST_FIRECRACKER_PASST_DEBUG` asks for, naming the capture's - /// file (in /tmp, where Ubuntu's AppArmor profile lets passt write). - fn debug_passt(dir: &Path) -> Result { - let passt = find_program("passt").context("passt is not installed")?; - let script = dir.join("passt-debug"); - crate::driver::fake::write_script( - &script, - &format!( - "#!/bin/sh\n# As the host runs it, with its debug log and a capture of its frames.\nfor a; do shift; [ \"$a\" = --quiet ] || set -- \"$@\" \"$a\"; done\nexec strace -f -tt -e trace=accept4,accept,getsockopt,setsockopt,epoll_ctl -o /tmp/passt.strace {} --trace --pcap \"$FCTL_TEST_FIRECRACKER_PASST_DEBUG\" \"$@\"\n", - passt.display() - ), - )?; - Ok(script) - } - /// Boots a sandbox from an image of Docker Hub (or /// `FCTL_TEST_FIRECRACKER_IMAGE`), on a host with KVM, Firecracker's /// needs and a static fctl-agent, with the kernel hosts pull (or the @@ -1293,9 +1232,6 @@ mod tests { }; cfg.firecracker.kernel = std::env::var("FCTL_TEST_FIRECRACKER_KERNEL").ok(); cfg.firecracker.disk_gb = 4; - if std::env::var_os("FCTL_TEST_FIRECRACKER_PASST_DEBUG").is_some() { - cfg.firecracker.passt = Some(debug_passt(temp.path())?); - } let d = Driver::select("firecracker", &cfg).await?; let probed = d.probe().await; assert!(probed.available, "{probed:?}"); diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 196c96f0..d6e73ce2 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -106,12 +106,6 @@ impl Vm { self.run.join("v.sock") } - /// Where `passt` takes the VM's network: what Firecracker connects to - /// when the VM connects to the host's [`NET_PORT`]. - pub fn net(&self) -> PathBuf { - self.run.join(format!("v.sock_{NET_PORT}")) - } - pub fn console(&self) -> PathBuf { self.dir.join("console.log") } @@ -151,30 +145,27 @@ impl Vm { self.pid("firecracker").is_some() } - /// Starts `passt`, if the VM gets a network, and Firecracker, after - /// stopping what an earlier boot left: the `passt` of a VM that powered - /// off, say. What it started goes again when it fails. - pub async fn start(&self, spec: &Spec, firecracker: &Path, passt: Option<&Path>) -> Result<()> { + /// Whether the VM's `passt` runs, which takes its network. + pub fn linked(&self) -> bool { + self.pid("passt").is_some() + } + + /// Starts Firecracker, after stopping what an earlier boot left: the + /// `passt` of a VM that powered off, say. What it started goes again + /// when it fails. A VM that gets a network gets it once it is up + /// ([`link_network`](Self::link_network)). + pub async fn start(&self, spec: &Spec, firecracker: &Path) -> Result<()> { self.kill().await; - let started = self.start_processes(spec, firecracker, passt).await; + let started = self.start_processes(spec, firecracker).await; if started.is_err() { self.kill().await; } started } - async fn start_processes( - &self, - spec: &Spec, - firecracker: &Path, - passt: Option<&Path>, - ) -> Result<()> { + async fn start_processes(&self, spec: &Spec, firecracker: &Path) -> Result<()> { std::fs::create_dir_all(&self.dir)?; std::fs::create_dir_all(&self.run)?; - if spec.network { - let passt = passt.context("the VM needs passt for its network")?; - self.start_passt(passt).await?; - } let config = self.dir.join("firecracker.json"); std::fs::write(&config, serde_json::to_vec_pretty(&self.config(spec))?)?; let console = std::fs::File::create(self.console())?; @@ -192,23 +183,36 @@ impl Vm { Ok(()) } - /// `passt`, which takes the VM's frames at [`Vm::net`] and makes them - /// connections of the host's: the VM gets [`ADDRESS`], the gateway and - /// a DNS forwarder, and reaches neither the host's loopback nor other - /// VMs. Nothing reaches the VM from outside. - async fn start_passt(&self, passt: &Path) -> Result<()> { + /// Links the VM's network to a `passt` of its own, once the VM is up: + /// connects to the VM's [`NET_PORT`] and hands passt the connection + /// (`--fd`), which makes the VM's frames connections of the host's. The + /// VM gets [`ADDRESS`] and the gateway, and reaches neither the host's + /// loopback nor other VMs; nothing reaches it from outside. passt exits + /// when the VM closes the connection, as it stops. passt could take the + /// VM's connection on a socket of its own, but Ubuntu's AppArmor profile + /// for it refuses one from Firecracker (`accept` fails, EACCES). A link + /// made before goes: its passt took a connection that a restored + /// snapshot, say, has lost. + pub async fn link_network(&self, passt: &Path) -> Result<()> { + self.kill_one("passt").await; + let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; + let ready = self.run.join("passt.pid"); + let _ = std::fs::remove_file(&ready); let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); - cmd.args(passt_args(&self.net())) - .stdin(Stdio::null()) + cmd.args(passt_args(&ready)) + .stdin(Stdio::from(std::os::fd::OwnedFd::from(conn))) .stdout(log.try_clone()?) .stderr(log); spawn_detached(&mut cmd, &self.pid_file("passt")) .with_context(|| format!("starting {}", passt.display()))?; + // passt writes its pid as it is about to take frames, and exits + // when it can't. let until = Instant::now() + Duration::from_secs(10); - while !self.net().exists() { + while !ready.exists() { if Instant::now() > until || self.pid("passt").is_none() { let said = std::fs::read_to_string(self.dir.join("passt.log")).unwrap_or_default(); + self.kill_one("passt").await; bail!("passt did not start: {}", said.trim()); } tokio::time::sleep(Duration::from_millis(20)).await; @@ -216,6 +220,27 @@ impl Vm { Ok(()) } + /// A connection to `port` in the VM, through Firecracker's vsock + /// socket, once something there takes it, within `within`. + async fn connect_port( + &self, + port: u32, + within: Duration, + ) -> Result { + let until = Instant::now() + within; + loop { + let socket = self.vsock(); + let tried = tokio::task::spawn_blocking(move || connect_raw(&socket, port)).await?; + match tried { + Ok(conn) => return Ok(conn), + Err(e) if Instant::now() > until || !self.running() => { + return Err(e.context(format!("linking the VM's network (vsock port {port})"))); + } + Err(_) => tokio::time::sleep(Duration::from_millis(100)).await, + } + } + } + /// Firecracker's configuration for `spec`. pub fn config(&self, spec: &Spec) -> Value { let drives: Vec = spec @@ -345,18 +370,23 @@ impl Vm { /// Kills the VM's processes. pub async fn kill(&self) { for what in ["firecracker", "passt"] { - if let Some(pid) = self.pid(what) { - let _ = crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await; - let until = Instant::now() + Duration::from_secs(5); - while self.pid(what).is_some() && Instant::now() < until { - tokio::time::sleep(Duration::from_millis(50)).await; - } - } - let _ = std::fs::remove_file(self.pid_file(what)); + self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); } + /// Kills the VM's process `what`, if it runs. + async fn kill_one(&self, what: &str) { + if let Some(pid) = self.pid(what) { + let _ = crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await; + let until = Instant::now() + Duration::from_secs(5); + while self.pid(what).is_some() && Instant::now() < until { + tokio::time::sleep(Duration::from_millis(50)).await; + } + } + let _ = std::fs::remove_file(self.pid_file(what)); + } + /// Stops the VM and removes its files. pub async fn remove(&self) -> Result<()> { self.stop().await; @@ -430,17 +460,20 @@ fn response(buf: &[u8]) -> Result> { Ok((body.len() >= len).then(|| (status, &body[..len]))) } -/// The arguments of `passt` for a VM whose frames come to `socket`: the -/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 -/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which -/// came later. -fn passt_args(socket: &Path) -> Vec { +/// The arguments of `passt` for a VM whose link is its input, and which +/// writes its pid to `pid` (in the VM's directory of sockets, whose path +/// tells it from other processes): the options of passt's releases since +/// 2022, which Ubuntu 24.04 and Debian 12 have. The VM names itself, so +/// passt's DHCP needs no `--hostname`, which came later. +fn passt_args(pid: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ "--foreground".into(), "--quiet".into(), - "--socket".into(), - socket.display().to_string(), + "--fd".into(), + "0".into(), + "--pid".into(), + pid.display().to_string(), "--address".into(), Ipv4Addr::from(ADDRESS).to_string(), "--netmask".into(), @@ -454,6 +487,48 @@ fn passt_args(socket: &Path) -> Vec { ] } +/// How long a VM that is up may take to take its network's link: its +/// init listens as it starts. +const LINK_TIMEOUT: Duration = Duration::from_secs(10); + +/// Connects to `port` in the VM whose vsock socket is `socket` (`CONNECT`, +/// then Firecracker's `OK`), reading no byte past Firecracker's answer: +/// what follows is the VM's, for whoever takes the connection. +fn connect_raw(socket: &Path, port: u32) -> Result { + use std::io::{Read, Write}; + let mut conn = std::os::unix::net::UnixStream::connect(socket) + .with_context(|| format!("connecting to {}", socket.display()))?; + conn.set_read_timeout(Some(Duration::from_secs(5)))?; + // Firecracker closes the connection when nothing in the VM takes it, + // which may come as a reset. + let refused = || anyhow::anyhow!("nothing in the VM takes connections on port {port} yet"); + let gone = |e: std::io::Error| match e.kind() { + std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::BrokenPipe => refused(), + _ => e.into(), + }; + conn.write_all(format!("CONNECT {port}\n").as_bytes()) + .map_err(gone)?; + let mut line = Vec::new(); + let mut byte = [0u8; 1]; + while line.len() < 64 { + if conn.read(&mut byte).map_err(gone)? == 0 { + return Err(refused()); + } + if byte[0] == b'\n' { + break; + } + line.push(byte[0]); + } + if !line.starts_with(b"OK ") { + bail!( + "Firecracker answered {:?} to a connection to port {port}", + String::from_utf8_lossy(&line) + ); + } + conn.set_read_timeout(None)?; + Ok(conn) +} + /// The nameservers a VM asks, which passt reaches as the host does: as /// Docker gives its containers, the host's own, but for those on its /// loopback, which the VM can't reach, and where only those are left @@ -598,16 +673,15 @@ mod tests { assert_eq!(c["machine-config"]["vcpu_count"], 32); assert_eq!(c["machine-config"]["mem_size_mib"], 4096); assert_eq!(c["vsock"]["uds_path"], "/tmp/fctl-ada/vm-0123/v.sock"); - assert_eq!(vm.net(), PathBuf::from("/tmp/fctl-ada/vm-0123/v.sock_1025")); Ok(()) } #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/v.sock_1025")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/passt.pid")).join(" "); assert_eq!( args, - "--foreground --quiet --socket /tmp/fctl-ada/vm-0/v.sock_1025 --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" + "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0/passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } @@ -834,38 +908,87 @@ mod tests { Ok(()) } - /// Stand-ins: a `passt` that makes its socket's path and waits, and a - /// Firecracker that waits. + /// Says a stand-in's connections are to close. + type Closer = std::sync::Arc; + /// What a stand-in's connections read. + type Seen = std::sync::Arc>>; + + /// A stand-in for Firecracker's vsock socket at `socket`: each + /// connection asking for `CONNECT 1025` gets `OK` and stays open until + /// `close` says otherwise; the VM's side keeps what it reads in `got`. + /// Anything else is closed at once, as when nothing in the VM listens. + fn vsock_stand_in(socket: &Path) -> Result<(Closer, Seen)> { + use std::io::{BufRead, Write}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Mutex}; + std::fs::create_dir_all(socket.parent().context("no parent")?)?; + let listener = std::os::unix::net::UnixListener::bind(socket)?; + let close = Arc::new(AtomicBool::new(false)); + let got = Arc::new(Mutex::new(Vec::new())); + let (closing, seen) = (close.clone(), got.clone()); + std::thread::spawn(move || { + for conn in listener.incoming().flatten() { + let mut reader = std::io::BufReader::new(&conn); + let mut line = String::new(); + if reader.read_line(&mut line).is_err() || line != format!("CONNECT {NET_PORT}\n") { + continue; + } + let mut w = &conn; + // The VM's first frame comes with Firecracker's answer. + let _ = w.write_all(b"OK 1073741824\n\0\0\0\x02hi"); + let (closing, seen) = (closing.clone(), seen.clone()); + std::thread::spawn(move || { + let _ = conn.set_read_timeout(Some(Duration::from_millis(50))); + let mut buf = [0u8; 64]; + while !closing.load(Ordering::Relaxed) { + if let Ok(n) = std::io::Read::read(&mut &conn, &mut buf) + && let Ok(mut g) = seen.lock() + { + g.extend_from_slice(&buf[..n]); + } + } + }); + } + }); + Ok((close, got)) + } + + /// The host links a VM's network once it is up: passt gets the + /// connection, with nothing of it read, a link made again takes the + /// first one's place, passt exits as the VM goes, and a start that + /// fails leaves nothing running. Stand-ins: a Firecracker that waits, + /// and a passt that writes its pid where it's asked and echoes its + /// input. #[tokio::test] - async fn starting_again_stops_what_the_last_boot_left() -> Result<()> { + async fn links_the_vms_network_once_it_is_up() -> Result<()> { use crate::driver::fake::write_script; + use std::sync::atomic::Ordering; let dir = tempfile::tempdir()?; let passt = dir.path().join("passt"); - // Without `exec`, so that their command lines keep the sockets. + // Without `exec`, so that its command line keeps the VM's path. write_script( &passt, - "#!/bin/sh\nfor a; do [ \"$prev\" = --socket ] && touch \"$a\"; prev=$a; done\nsleep 60\n", + "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && echo $$ > \"$a\"; prev=$a; done\ncat >&0\n", )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; let vm = Vm::new(dir.path().join("fctl-ses-x"))?; let spec = unpack_spec("/k".into(), "/i".into(), "fctl-ses-x", Path::new("/r")); - let spec = Spec { - network: true, - ..spec - }; - vm.start(&spec, &firecracker, Some(&passt)).await?; - let first_passt = vm.pid("passt"); - assert!(first_passt.is_some() && vm.running()); - // Firecracker ends by itself (its VM powered off), and passt stays. - if let Some(pid) = vm.pid("firecracker") { - crate::driver::run_cmd("kill", &["-KILL", &pid.to_string()]).await?; - } - while vm.running() { + vm.start(&spec, &firecracker).await?; + assert!(vm.running() && !vm.linked()); + let (close, got) = vsock_stand_in(&vm.vsock())?; + vm.link_network(&passt).await?; + let first = vm.pid("passt"); + assert!(vm.linked()); + // passt got the VM's first frame, which came with Firecracker's + // answer, and sent it back. + let until = Instant::now() + Duration::from_secs(5); + while got.lock().map(|g| g.clone()).unwrap_or_default() != b"\0\0\0\x02hi" { + assert!(Instant::now() < until, "passt didn't get the VM's frame"); tokio::time::sleep(Duration::from_millis(20)).await; } - assert_eq!(vm.pid("passt"), first_passt); - vm.start(&spec, &firecracker, Some(&passt)).await?; + // Linked again: the first passt goes. + vm.link_network(&passt).await?; let alive = |pid: u32| { std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| { !s.rsplit_once(')') @@ -873,14 +996,41 @@ mod tests { }) }; assert!( - first_passt.is_some_and(|p| !alive(p)), + first.is_some_and(|p| !alive(p)), "the first passt still runs" ); - assert!(vm.pid("passt").is_some() && vm.running()); + assert!(vm.linked() && vm.pid("passt") != first); + // The VM goes, and its passt with it. + close.store(true, Ordering::Relaxed); + let until = Instant::now() + Duration::from_secs(5); + while vm.linked() { + assert!(Instant::now() < until, "passt outlived its link"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + // Nothing in the VM takes the link: it fails, and says why. + let other = Vm::new(dir.path().join("fctl-ses-y"))?; + std::fs::create_dir_all(&other.run)?; + let refusing = std::os::unix::net::UnixListener::bind(other.vsock())?; + std::thread::spawn(move || { + for conn in refusing.incoming().flatten() { + drop(conn); + } + }); + let e = other + .connect_port(NET_PORT, Duration::from_millis(300)) + .await + .err() + .map(|e| format!("{e:#}")); + assert!( + e.as_deref() + .is_some_and(|e| e.contains("nothing in the VM takes connections")), + "{e:?}" + ); // A start that fails leaves nothing running. let missing = dir.path().join("no-firecracker"); - assert!(vm.start(&spec, &missing, Some(&passt)).await.is_err()); - assert!(vm.pid("passt").is_none() && !vm.running()); + assert!(vm.start(&spec, &missing).await.is_err()); + assert!(!vm.linked() && !vm.running()); + let _ = std::fs::remove_dir_all(&other.run); Ok(()) } } diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs index 7a254cf4..2eaf39f4 100644 --- a/crates/fctl-proto/src/vm.rs +++ b/crates/fctl-proto/src/vm.rs @@ -9,9 +9,10 @@ //! exits; after an [`Request::Unpack`], the layers' bytes one after the //! other, then a second [`Reply`]. //! -//! The VM itself reaches the host's [`NET_PORT`], where the host's `passt` -//! takes its network: Ethernet frames, each after its length (4 bytes, big -//! endian), as passt reads them from QEMU. +//! The host connects to the VM's [`NET_PORT`] too, once the VM is up, and +//! hands the connection to a `passt` of the VM's own, which takes its +//! network: Ethernet frames, each after its length (4 bytes, big endian), +//! as passt reads them from QEMU. //! //! A host may be one version ahead of the init of a VM that was running //! when it updated, so requests only gain optional fields, and an init @@ -23,7 +24,8 @@ use serde_with::skip_serializing_none; /// The vsock port the init serves requests on. pub const PORT: u32 = 1024; -/// The vsock port of the host's network for the VM (`passt`). +/// The vsock port where the VM takes the host's link to its network +/// (`passt`). pub const NET_PORT: u32 = 1025; /// The VM's network, as the host's `passt` gives it: the VM's address and diff --git a/docs/architecture.md b/docs/architecture.md index 63e378a2..f3a06d23 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3468,10 +3468,18 @@ in `firecracker/` in the host's data directory. - **Network.** The VM's `eth0` is a TAP device inside the VM, with `10.0.2.15/24`, whose frames `vm-serve` carries over the vsock to a `passt` of the VM's own on the host, which turns them into the host's - own connections. The host has no bridge, TAP device or firewall rule for - it. A VM reaches the internet and the host's network as a Docker - container does, but neither other VMs nor the host's loopback, and - nothing reaches it from outside; DNS goes to the host's resolver. + own connections. The host makes the link once the VM is up: it connects + to the VM's vsock port 1025 and hands passt the connection (`--fd`), so + that passt exits as the VM does; passt can't take Firecracker's + connection on a socket of its own where Ubuntu's AppArmor profile for it + applies (`accept` fails). The host has no bridge, TAP device or firewall + rule for it. A VM reaches the internet and the host's network as a + Docker container does, but neither other VMs nor the host's loopback, + and nothing reaches it from outside. It asks the host's nameservers, as + a Docker container does: those in `/etc/resolv.conf` but for any on the + loopback, and where only those are left (systemd-resolved's + `127.0.0.53`), the servers systemd-resolved asks; with none, passt's + forwarder to the host's resolver. - **Processes.** Firecracker and `passt` run in process groups of their own, as the process driver's agents do, so restarting or updating the host leaves them running; the host finds a VM's processes by the ids it From 6076b121d37a86178d23e29ac9295726f7b46364 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:24:47 +0000 Subject: [PATCH 14/25] fix(host): count passt as linked once it writes its pid, not once it makes the file passt makes its pid's file as it reads its options and writes the pid only once it has set itself up, so a passt that failed in between left the VM without a network while the host took it as linked. The host now waits for the pid; the test's stand-in passt makes the file first, as passt does, and one that fails then gets no link. --- crates/fctl-host/src/driver/firecracker/vm.rs | 32 +++++++++++++++---- 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index d6e73ce2..e364cd5d 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -206,10 +206,13 @@ impl Vm { .stderr(log); spawn_detached(&mut cmd, &self.pid_file("passt")) .with_context(|| format!("starting {}", passt.display()))?; - // passt writes its pid as it is about to take frames, and exits - // when it can't. + // passt makes its pid's file as it reads its options, writes its + // pid there once it has set itself up and is about to take frames, + // and exits when it can't. + let has_pid = + || std::fs::read_to_string(&ready).is_ok_and(|p| p.trim().parse::().is_ok()); let until = Instant::now() + Duration::from_secs(10); - while !ready.exists() { + while !has_pid() { if Instant::now() > until || self.pid("passt").is_none() { let said = std::fs::read_to_string(self.dir.join("passt.log")).unwrap_or_default(); self.kill_one("passt").await; @@ -965,10 +968,20 @@ mod tests { use std::sync::atomic::Ordering; let dir = tempfile::tempdir()?; let passt = dir.path().join("passt"); - // Without `exec`, so that its command line keeps the VM's path. + // As passt: its pid's file is made at once and written once it is + // set up. Without `exec`, so that its command line keeps the VM's + // path. + let stand_in = |then: &str| { + format!( + "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && pid=$a; prev=$a; done\n: > \"$pid\"\nsleep 0.3\n{then}\n" + ) + }; + write_script(&passt, &stand_in("echo $$ > \"$pid\"\ncat >&0"))?; + // One that fails as it sets itself up. + let failing = dir.path().join("failing-passt"); write_script( - &passt, - "#!/bin/sh\nfor a; do [ \"$prev\" = --pid ] && echo $$ > \"$a\"; prev=$a; done\ncat >&0\n", + &failing, + &stand_in("echo 'No routable interface' >&2; exit 1"), )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; @@ -977,6 +990,13 @@ mod tests { vm.start(&spec, &firecracker).await?; assert!(vm.running() && !vm.linked()); let (close, got) = vsock_stand_in(&vm.vsock())?; + // A passt that fails once it has made its pid's file: no link. + let e = vm.link_network(&failing).await.err().map(|e| e.to_string()); + assert_eq!( + e.as_deref(), + Some("passt did not start: No routable interface") + ); + assert!(!vm.linked()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 79f0688239d1d54e6954a92778859a6410522156 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:36:55 +0000 Subject: [PATCH 15/25] feat(host): resume stopped Firecracker sandboxes where they were Stopping a sandbox shut its VM down, so a resume started Claude again. Now, where the disk has room for its memory, the host pauses the VM, saves its state (Firecracker's and the VM's memory, its zero pages given back to the disk) beside its disk, and a start loads it into a new Firecracker, the VM's programs running on, then links its network again. A state another Firecracker release saved, or one that doesn't load, is let go and the VM boots from its disk, which the host wrote out before saving. While the disk is low, the saved states of stopped sandboxes go first. firecracker.snapshots = false turns it off. --- crates/fctl-host/src/config.rs | 7 + crates/fctl-host/src/daemon.rs | 17 + .../fctl-host/src/driver/firecracker/mod.rs | 377 +++++++++++++++++- crates/fctl-host/src/driver/firecracker/vm.rs | 154 ++++++- crates/fctl-host/src/driver/mod.rs | 10 + 5 files changed, 562 insertions(+), 3 deletions(-) diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index 172e88d1..200517ba 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -29,6 +29,7 @@ //! firecracker = "/usr/local/bin/firecracker" # unset: the release fctl pins, downloaded //! 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 +//! 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 @@ -157,6 +158,11 @@ pub struct FirecrackerConfig { /// The disk each sandbox gets, in GiB: a sparse file, which takes only /// what the session writes. pub disk_gb: u32, + /// 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 { @@ -166,6 +172,7 @@ impl Default for FirecrackerConfig { kernel: None, passt: None, disk_gb: 64, + snapshots: true, } } } diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 359070b2..e399a777 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -351,7 +351,24 @@ 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. + let low = self.low_on_disk(); + let in_use: HashSet = self + .sessions + .keys() + .chain(self.pending_starts.keys()) + .map(|id| sandbox_name(id.as_str())) + .collect(); tokio::spawn(async move { + if low { + let freed = ctx.driver.drop_saved_states(&in_use).await; + if freed > 0 { + tracing::info!( + "let go of the saved states of stopped sandboxes for room on the disk: {freed} MiB" + ); + } + } let listed = ctx.driver.list().await; let caches = match &listed { Ok(_) => ctx diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 03278d05..6c3ba8ad 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -59,8 +59,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 { @@ -158,6 +174,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"); @@ -708,6 +788,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)); @@ -724,6 +806,17 @@ impl FirecrackerDriver { )); vm.kill().await; } + if let Some(saved) = self.record(&spec.name).and_then(|r| r.saved) { + 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)); @@ -815,6 +908,7 @@ impl FirecrackerDriver { reference: image.reference.clone(), created_ms: vsock::now_ms(), agent: None, + saved: None, }; self.save_record(&spec.name, &record)?; Ok(record) @@ -1016,13 +1110,166 @@ 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. 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.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 { + 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); + if let Err(e) = vm.snapshot(&new).await { + let _ = std::fs::remove_dir_all(&new); + return Err(e); + } + // 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)?; + Ok(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(()) } + /// Lets the state `name` saved go, files and record. + fn drop_saved(&self, vm: &Vm, name: &str) -> Result<()> { + let dir = vm.dir.join("saved"); + 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"); + if keep.contains(&name) || !saved.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); + 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; @@ -1096,6 +1343,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") @@ -1146,6 +1394,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)); @@ -1161,6 +1410,132 @@ 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(()) + } + + /// 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(()) + } + #[tokio::test] async fn probes_what_the_host_lacks() { let dir = tempfile::tempdir().ok(); diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index e364cd5d..3ba6cf8a 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -22,6 +22,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 @@ -285,6 +289,13 @@ impl Vm { }) } + /// The memory the VM booted with, in MiB, from its configuration. + pub fn memory_mb(&self) -> Option { + let config = std::fs::read(self.dir.join("firecracker.json")).ok()?; + let config: Value = serde_json::from_slice(&config).ok()?; + config["machine-config"]["mem_size_mib"].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(); @@ -316,6 +327,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 { @@ -404,9 +496,25 @@ impl Vm { /// 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> { @@ -852,6 +960,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!( @@ -896,6 +1006,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 35369d89..97c94671 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -736,6 +736,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<()> { From 9165e1421cbb4d9bff5c9d5500cf23a9c8aae814 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:47:47 +0000 Subject: [PATCH 16/25] test(host): a stopped Firecracker sandbox resumes with its programs running --- .../fctl-host/src/driver/firecracker/mod.rs | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index 6c3ba8ad..be722fb4 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1690,4 +1690,88 @@ mod tests { assert!(!d.list().await?.iter().any(|s| s.name == name)); 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; + 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 + } } From 63e078f459346da84e507bd61d81f75cca947b26 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:51:48 +0000 Subject: [PATCH 17/25] fix(host): remove a sandbox that goes without stopping it first Every driver's remove stops its sandbox, and stopping a Firecracker VM first would save its state only for the removal to delete it. Docs say what saved states are and cost. --- crates/fctl-host/src/daemon.rs | 11 ++++++---- crates/fctl-host/src/session.rs | 22 ++++++++++++------- ...s-run-sandboxes-in-firecracker-microvms.md | 4 +++- docs/architecture.md | 14 ++++++++++++ docs/cli.md | 7 +++++- 5 files changed, 44 insertions(+), 14 deletions(-) diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index e399a777..21317a8c 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -1527,12 +1527,15 @@ 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 { + // One that goes stops as it goes: stopping it first would save + // what nothing resumes (Firecracker's VMs). + if destroy { + if let Err(e) = ctx.driver.remove(&sb).await { + tracing::warn!("removing {name}: {e:#}"); + } + } else if let Err(e) = ctx.driver.stop(&sb).await { tracing::warn!("stopping {name}: {e:#}"); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {name}: {e:#}"); - } let ended = HostToFleet::SessionEnded { session_id, status: SessionStatus::Stopped, diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index 9bea8557..593f8668 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -1063,12 +1063,15 @@ 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 { + // One that goes stops as it goes: stopping it first would save + // what nothing resumes (Firecracker's VMs). + if destroy { + if let Err(e) = ctx.driver.remove(&sb).await { + tracing::warn!("removing {}: {e:#}", sb.name); + } + } else if let Err(e) = ctx.driver.stop(&sb).await { tracing::warn!("stopping {}: {e:#}", sb.name); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {}: {e:#}", sb.name); - } let msg = "Stopped before it started".to_owned(); uplink.state(state(SessionStatus::Stopped, &msg)); tokio::time::sleep(Duration::from_millis(500)).await; @@ -1579,12 +1582,15 @@ 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 { + // One that goes stops as it goes: stopping it first would save + // what nothing resumes (Firecracker's VMs). + if destroy { + if let Err(e) = ctx.driver.remove(&sb).await { + tracing::warn!("removing {}: {e:#}", sb.name); + } + } else if let Err(e) = ctx.driver.stop(&sb).await { tracing::warn!("stopping {}: {e:#}", sb.name); } - if destroy && let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {}: {e:#}", sb.name); - } let (status, reason) = outcome; // Drain a late Superseded so the next run's status is not overwritten. while let Ok(c) = cmds.try_recv() { 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 b2a3cede..bb3724b3 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 @@ -45,7 +45,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 f3a06d23..96fc1bcf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3451,6 +3451,20 @@ 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): 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; the state goes once + loaded, the disk being past it. 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. - **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 a835b666..008c1944 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 ``` With Docker on Linux, the daemon's socket lets in only root and the @@ -931,7 +932,11 @@ Agents are told their sandbox's size in their instructions and in `container`, `nproc` counts one CPU more than the sandbox may use. 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. With Apple's +stopped for `keep_stopped_hours`, or until the disk runs low. With +Firecracker it 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. 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 From 3babf1e2daa29a1afba8da883c46a10c80dae307 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:30:51 +0000 Subject: [PATCH 18/25] fix(host): write passt's pid where it can as root, and boot a sandbox as root in CI passt opens its pid file as it starts, as root but for its capabilities on a host that runs as root, then becomes nobody: it can write only in a directory root owns, and, under Ubuntu's AppArmor profile, only under /tmp or home. Its pid now goes beside the VM's socket directory, in the host's user's directory in /tmp, which both allow, and CI boots a sandbox as root too. --- .github/workflows/ci.yml | 7 ++++ crates/fctl-host/src/driver/firecracker/vm.rs | 38 +++++++++++++------ 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e181f00e..ffe980f5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,6 +139,13 @@ jobs: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | cargo test --locked -p fctl-host --lib driver::firecracker:: -- --ignored --nocapture --test-threads 1 + - name: Boot a sandbox on a host that runs as root + env: + FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent + run: | + bin=$(cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + sudo env "FCTL_TEST_FIRECRACKER_AGENT=$FCTL_TEST_FIRECRACKER_AGENT" "FCTL_TEST_FIRECRACKER_DATA=$RUNNER_TEMP/root" \ + "$bin" driver::firecracker::tests::boots_a_sandbox --ignored --nocapture # The Worker the deploy ships, built beside the checks. Its release build # takes two minutes, so it is cached by what it is built from: a push that diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index e364cd5d..f372ae97 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -63,6 +63,9 @@ pub struct Spec { pub struct Vm { pub dir: PathBuf, pub run: PathBuf, + /// What tells the VM's processes from others': the start of the + /// SHA-256 of `dir`, which names `run` too. + pub key: String, } /// Where VMs' sockets go: a directory of this user's in /tmp, private. @@ -95,7 +98,7 @@ impl Vm { pub fn new(dir: PathBuf) -> Result { let key = hex::encode(&Sha256::digest(dir.display().to_string().as_bytes())[..8]); let run = socket_base()?.join(format!("vm-{key}")); - Ok(Self { dir, run }) + Ok(Self { dir, run, key }) } pub fn api(&self) -> PathBuf { @@ -133,10 +136,12 @@ impl Vm { let ours = self.run.display().to_string(); // A kernel thread, which may take the id too, has no executable. let starting = cmdline.is_empty() && std::fs::read_link(format!("/proc/{pid}/exe")).is_ok(); + // passt has its pid's file beside `run`, named by this VM's key. let mine = starting - || cmdline - .split(|b| *b == 0) - .any(|arg| String::from_utf8_lossy(arg).starts_with(&ours)); + || cmdline.split(|b| *b == 0).any(|arg| { + let arg = String::from_utf8_lossy(arg); + arg.starts_with(&ours) || arg.contains(&self.key) + }); (mine && !zombie).then_some(pid) } @@ -196,7 +201,7 @@ impl Vm { pub async fn link_network(&self, passt: &Path) -> Result<()> { self.kill_one("passt").await; let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; - let ready = self.run.join("passt.pid"); + let ready = self.passt_pid(); let _ = std::fs::remove_file(&ready); let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); @@ -376,6 +381,16 @@ impl Vm { self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); + let _ = std::fs::remove_file(self.passt_pid()); + } + + /// Where passt writes its pid: beside `run`, in the host's user's + /// directory in /tmp, where passt's AppArmor profile lets it write, and + /// where it can as it starts on a host that runs as root, as root but + /// for its capabilities, which it drops first. + fn passt_pid(&self) -> PathBuf { + self.run + .with_file_name(format!("vm-{}.passt.pid", self.key)) } /// Kills the VM's process `what`, if it runs. @@ -464,10 +479,10 @@ fn response(buf: &[u8]) -> Result> { } /// The arguments of `passt` for a VM whose link is its input, and which -/// writes its pid to `pid` (in the VM's directory of sockets, whose path -/// tells it from other processes): the options of passt's releases since -/// 2022, which Ubuntu 24.04 and Debian 12 have. The VM names itself, so -/// passt's DHCP needs no `--hostname`, which came later. +/// writes its pid to `pid` (whose path tells it from other processes): the +/// options of passt's releases since 2022, which Ubuntu 24.04 and Debian 12 +/// have. The VM names itself, so passt's DHCP needs no `--hostname`, which +/// came later. On a host that runs as root, passt runs as nobody. fn passt_args(pid: &Path) -> Vec { let mask = PREFIX.to_string(); vec![ @@ -636,6 +651,7 @@ mod tests { let vm = Vm { dir: PathBuf::from("/data/firecracker/sandboxes/fctl-ses-1"), run: PathBuf::from("/tmp/fctl-ada/vm-0123"), + key: "0123".into(), }; let spec = Spec { kernel: "/k/vmlinux".into(), @@ -681,10 +697,10 @@ mod tests { #[test] fn passt_gives_the_vm_its_network_and_nothing_of_the_hosts() { - let args = passt_args(Path::new("/tmp/fctl-ada/vm-0/passt.pid")).join(" "); + let args = passt_args(Path::new("/tmp/fctl-ada/vm-0.passt.pid")).join(" "); assert_eq!( args, - "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0/passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" + "--foreground --quiet --fd 0 --pid /tmp/fctl-ada/vm-0.passt.pid --address 10.0.2.15 --netmask 24 --gateway 10.0.2.2 --dns-forward 10.0.2.3 --no-map-gw" ); } From e64ae963936391958385319eec25637f1d6b972a Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:33:47 +0000 Subject: [PATCH 19/25] fix(host): resume only VMs of the size asked, save one at a time, and free what saves leave - A sandbox asked for another size than its VM had boots from its disk, rather than resume at the old size. - Saves run one at a time, so that sandboxes stopping together don't each find room for their memory and write it all at once. - What a save that failed or stopped halfway left (saved.new) goes, with the saved states, and the sweep counts it. - After letting saved states go for room, the sweep measures the disk again before it removes any sandbox. - A sandbox that goes is stopped first again with every driver but Firecracker (Driver::finish): Apple's container sometimes needs its stop's second try. --- crates/fctl-host/src/daemon.rs | 31 +++-- .../fctl-host/src/driver/firecracker/mod.rs | 114 ++++++++++++++---- crates/fctl-host/src/driver/firecracker/vm.rs | 21 +++- crates/fctl-host/src/driver/mod.rs | 17 +++ crates/fctl-host/src/session.rs | 24 ++-- docs/architecture.md | 6 +- 6 files changed, 159 insertions(+), 54 deletions(-) diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 21317a8c..d8018b62 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 { @@ -361,12 +362,15 @@ impl Daemon { .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 { let freed = ctx.driver.drop_saved_states(&in_use).await; if freed > 0 { tracing::info!( "let go of the saved states of stopped sandboxes for room on the disk: {freed} MiB" ); + measured = ctx.disk_free_mb().await; } } let listed = ctx.driver.list().await; @@ -381,7 +385,7 @@ impl Daemon { }), Err(_) => Vec::new(), }; - let _ = chores.send(Chore::Listed(listed, caches)); + let _ = chores.send(Chore::Listed(listed, caches, measured)); }); } @@ -656,8 +660,13 @@ 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), _, _) => { tracing::warn!("listing sandboxes: {e:#}"); self.sweeping = false; } @@ -1527,15 +1536,13 @@ impl Daemon { let (ctx, chores) = (self.ctx.clone(), self.chores_tx.clone()); tokio::spawn(async move { let sb = ctx.driver.handle(&name); - // One that goes stops as it goes: stopping it first would save - // what nothing resumes (Firecracker's VMs). - if destroy { - if let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {name}: {e:#}"); - } - } else 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 let Err(e) = removed { + tracing::warn!("removing {name}: {e:#}"); + } let ended = HostToFleet::SessionEnded { session_id, status: SessionStatus::Stopped, diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index be722fb4..51a6869e 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -806,7 +806,9 @@ impl FirecrackerDriver { )); vm.kill().await; } - if let Some(saved) = self.record(&spec.name).and_then(|r| r.saved) { + if let Some(saved) = self.record(&spec.name).and_then(|r| r.saved) + && !self.resized(&vm, spec, log) + { match self.resume_saved(&vm, &spec.name, &saved, log).await { Ok(()) => return Ok(sb), Err(e) => log(format!( @@ -1140,6 +1142,10 @@ impl FirecrackerDriver { /// 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 @@ -1169,25 +1175,30 @@ impl FirecrackerDriver { 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); - if let Err(e) = vm.snapshot(&new).await { - let _ = std::fs::remove_dir_all(&new); - return Err(e); + 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) } - // 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:#}"); + .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); } - 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)?; - Ok(true) + saved.map(|()| true) } /// Starts the VM of the sandbox `name` from the state it saved as it @@ -1227,11 +1238,29 @@ impl FirecrackerDriver { 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<()> { - let dir = vm.dir.join("saved"); - if dir.exists() { - std::fs::remove_dir_all(&dir).with_context(|| format!("removing {}", dir.display()))?; + // 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() @@ -1252,7 +1281,8 @@ impl FirecrackerDriver { for entry in entries.flatten() { let name = entry.file_name().to_string_lossy().into_owned(); let saved = entry.path().join("saved"); - if keep.contains(&name) || !saved.is_dir() { + 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}")); @@ -1261,7 +1291,8 @@ impl FirecrackerDriver { if vm.running() { continue; } - let size = crate::caches::dir_size_mb(&saved).unwrap_or(0); + 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:#}"), @@ -1515,6 +1546,43 @@ mod tests { 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] diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 3ba6cf8a..5319bd37 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -278,8 +278,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() }, @@ -291,9 +291,18 @@ 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"]["mem_size_mib"].as_u64() + config["machine-config"][field].as_u64() } /// What the VM's console said last, for an error. @@ -494,6 +503,12 @@ 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> { api_within(socket, method, path, body, API_TIMEOUT).await diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 97c94671..2003dd5d 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -757,6 +757,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 593f8668..aeeacae6 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -1063,15 +1063,13 @@ async fn run( } Err(destroy) => { let sb = ctx.driver.handle(&sandbox_name(session_id.as_str())); - // One that goes stops as it goes: stopping it first would save - // what nothing resumes (Firecracker's VMs). - if destroy { - if let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {}: {e:#}", sb.name); - } - } else 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 let Err(e) = removed { + tracing::warn!("removing {}: {e:#}", sb.name); + } let msg = "Stopped before it started".to_owned(); uplink.state(state(SessionStatus::Stopped, &msg)); tokio::time::sleep(Duration::from_millis(500)).await; @@ -1582,15 +1580,13 @@ 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); - // One that goes stops as it goes: stopping it first would save - // what nothing resumes (Firecracker's VMs). - if destroy { - if let Err(e) = ctx.driver.remove(&sb).await { - tracing::warn!("removing {}: {e:#}", sb.name); - } - } else 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 let Err(e) = removed { + tracing::warn!("removing {}: {e:#}", sb.name); + } let (status, reason) = outcome; // Drain a late Superseded so the next run's status is not overwritten. while let Ok(c) = cmds.try_recv() { diff --git a/docs/architecture.md b/docs/architecture.md index 96fc1bcf..026813d0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3458,8 +3458,10 @@ in `firecracker/` in the host's data directory. (`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; the state goes once - loaded, the disk being past it. A state takes the disk the VM's memory + 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 From 53e91cd98d3347e2910d32d2755245bd28ff7100 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:35:02 +0000 Subject: [PATCH 20/25] ci: find the test binary to run as root without cargo's colours, and clear passt's pid when a link fails --- .github/workflows/ci.yml | 3 ++- crates/fctl-host/src/driver/firecracker/vm.rs | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ffe980f5..9b3d9fda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -143,7 +143,8 @@ jobs: env: FCTL_TEST_FIRECRACKER_AGENT: ${{ github.workspace }}/target/x86_64-unknown-linux-musl/release/fctl-agent run: | - bin=$(cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + bin=$(CARGO_TERM_COLOR=never cargo test --locked -p fctl-host --lib --no-run 2>&1 | sed -n 's/.*Executable unittests src\/lib.rs (\(.*\))/\1/p') + test -x "$bin" sudo env "FCTL_TEST_FIRECRACKER_AGENT=$FCTL_TEST_FIRECRACKER_AGENT" "FCTL_TEST_FIRECRACKER_DATA=$RUNNER_TEMP/root" \ "$bin" driver::firecracker::tests::boots_a_sandbox --ignored --nocapture diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index f372ae97..0c9fd4a3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -403,6 +403,9 @@ impl Vm { } } let _ = std::fs::remove_file(self.pid_file(what)); + if what == "passt" { + let _ = std::fs::remove_file(self.passt_pid()); + } } /// Stops the VM and removes its files. @@ -1012,7 +1015,7 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked()); + assert!(!vm.linked() && !vm.passt_pid().exists()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 6e8496cb7ef7d901bdb3fe65e0c42b8b65156220 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:38:33 +0000 Subject: [PATCH 21/25] fix(host): count the disk measured after letting saved states go when listing fails --- crates/fctl-host/src/daemon.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index d8018b62..4a63aef4 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -666,7 +666,11 @@ impl Daemon { } self.sweep_listed(list, caches); } - Chore::Listed(Err(e), _, _) => { + 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; } From 9080e50ad42f4334d42cb035f998dc093abfbebc Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:44:17 +0000 Subject: [PATCH 22/25] fix(host): write passt's pid in /tmp as root, under a name no one can make first Ubuntu's passt of 2024 drops to nobody before it opens its pid's file, and later ones open it as root without capabilities: on a host that runs as root, only /tmp lets both write. The name has a random part, recorded in the VM's directory. --- crates/fctl-host/src/driver/firecracker/vm.rs | 56 ++++++++++++++----- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 0c9fd4a3..5367c16f 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -201,8 +201,7 @@ impl Vm { pub async fn link_network(&self, passt: &Path) -> Result<()> { self.kill_one("passt").await; let conn = self.connect_port(NET_PORT, LINK_TIMEOUT).await?; - let ready = self.passt_pid(); - let _ = std::fs::remove_file(&ready); + let ready = self.new_passt_pid()?; let log = std::fs::File::create(self.dir.join("passt.log"))?; let mut cmd = std::process::Command::new(passt); cmd.args(passt_args(&ready)) @@ -381,16 +380,44 @@ impl Vm { self.kill_one(what).await; } let _ = std::fs::remove_dir_all(&self.run); - let _ = std::fs::remove_file(self.passt_pid()); } - /// Where passt writes its pid: beside `run`, in the host's user's - /// directory in /tmp, where passt's AppArmor profile lets it write, and - /// where it can as it starts on a host that runs as root, as root but - /// for its capabilities, which it drops first. - fn passt_pid(&self) -> PathBuf { - self.run - .with_file_name(format!("vm-{}.passt.pid", self.key)) + /// Where passt writes its pid, the path naming this VM's key, which + /// tells passt from other processes; recorded in the VM's directory. + /// Beside `run`, in the host's user's directory in /tmp, where passt's + /// AppArmor profile lets it write. On a host that runs as root, passt + /// opens it as nobody (passt of 2024) or as root without its + /// capabilities (later ones), which only /tmp itself lets write: there + /// its name has a random part no one else could make first. + fn new_passt_pid(&self) -> Result { + if let Some(old) = self.passt_pid() { + let _ = std::fs::remove_file(old); + } + let pid = if nix::unistd::geteuid().is_root() { + PathBuf::from(format!( + "/tmp/fctl-passt-{}-{}.pid", + self.key, + hex::encode(fctl_domain::random_bytes::<8>()) + )) + } else { + self.run + .with_file_name(format!("vm-{}.passt.pid", self.key)) + }; + std::fs::create_dir_all(&self.dir)?; + std::fs::write( + self.dir.join("passt.pid-file"), + pid.as_os_str().as_encoded_bytes(), + )?; + Ok(pid) + } + + /// Where passt writes its pid ([`new_passt_pid`](Self::new_passt_pid)). + fn passt_pid(&self) -> Option { + let path = std::fs::read_to_string(self.dir.join("passt.pid-file")).ok()?; + let path = PathBuf::from(path.trim()); + let name = path.file_name()?.to_string_lossy().into_owned(); + // Only what this VM named so: nothing else of the host's goes. + (name.contains(&self.key) && name.ends_with(".pid")).then_some(path) } /// Kills the VM's process `what`, if it runs. @@ -403,8 +430,11 @@ impl Vm { } } let _ = std::fs::remove_file(self.pid_file(what)); - if what == "passt" { - let _ = std::fs::remove_file(self.passt_pid()); + if what == "passt" + && let Some(pid) = self.passt_pid() + { + let _ = std::fs::remove_file(pid); + let _ = std::fs::remove_file(self.dir.join("passt.pid-file")); } } @@ -1015,7 +1045,7 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked() && !vm.passt_pid().exists()); + assert!(!vm.linked() && vm.passt_pid().is_none_or(|p| !p.exists())); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From 0ad0dd0fed3c27907005362ca4118ef53c89889d Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" <343971779+fctl-sh[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:54:05 +0000 Subject: [PATCH 23/25] test(host): check that a failed link removes the pid's file passt was told A failed link now forgets where passt's pid went, so the test reads the path from the stand-in, which says where it was told to write. --- crates/fctl-host/src/driver/firecracker/vm.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs index 5367c16f..e43e70d3 100644 --- a/crates/fctl-host/src/driver/firecracker/vm.rs +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -1026,11 +1026,16 @@ mod tests { ) }; write_script(&passt, &stand_in("echo $$ > \"$pid\"\ncat >&0"))?; - // One that fails as it sets itself up. + // One that fails as it sets itself up, and tells where its pid's + // file was. let failing = dir.path().join("failing-passt"); + let told = dir.path().join("failing-passt.told"); write_script( &failing, - &stand_in("echo 'No routable interface' >&2; exit 1"), + &stand_in(&format!( + "echo \"$pid\" > '{}'\necho 'No routable interface' >&2; exit 1", + told.display() + )), )?; let firecracker = dir.path().join("firecracker"); write_script(&firecracker, "#!/bin/sh\nsleep 60\n")?; @@ -1045,7 +1050,9 @@ mod tests { e.as_deref(), Some("passt did not start: No routable interface") ); - assert!(!vm.linked() && vm.passt_pid().is_none_or(|p| !p.exists())); + let made = PathBuf::from(std::fs::read_to_string(&told)?.trim()); + assert!(made.is_absolute(), "{made:?}"); + assert!(!vm.linked() && !made.exists() && vm.passt_pid().is_none()); vm.link_network(&passt).await?; let first = vm.pid("passt"); assert!(vm.linked()); From a177c5bf139c45933770f81c4a80b796a0de8a1e Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Fri, 6 Nov 2026 23:55:30 +0000 Subject: [PATCH 24/25] fix(host): resume no saved state, and keep none, on a host that turns snapshots off Only stop looked at snapshots: a host that turned them off resumed the states of sandboxes stopped before, and kept their memory on disk until then. A start now lets such a state go without trying it, and the sweep lets the states of stopped sandboxes go whenever snapshots are off. --- crates/fctl-host/src/daemon.rs | 18 ++++-- .../fctl-host/src/driver/firecracker/mod.rs | 55 ++++++++++++++++++- docs/architecture.md | 3 +- 3 files changed, 68 insertions(+), 8 deletions(-) diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index 31edc5f5..d15beaf7 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -367,8 +367,10 @@ 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. + // 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() @@ -378,12 +380,18 @@ impl Daemon { tokio::spawn(async move { // What that freed counts before any sandbox goes for room. let mut measured = None; - if low { + if low || !keeps_states { let freed = ctx.driver.drop_saved_states(&in_use).await; if freed > 0 { - tracing::info!( - "let go of the saved states of stopped sandboxes for room on the disk: {freed} MiB" - ); + 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; } } diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs index c4f99509..bf2bd697 100644 --- a/crates/fctl-host/src/driver/firecracker/mod.rs +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -1039,9 +1039,11 @@ impl FirecrackerDriver { )); vm.kill().await; } - // A jailed VM saves no state ([`stop`](Self::stop)): one saved before - // the host ran as root goes. + // 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) { @@ -2042,6 +2044,55 @@ mod tests { 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(); diff --git a/docs/architecture.md b/docs/architecture.md index 8e6940f4..fb672466 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3480,7 +3480,8 @@ in `firecracker/` in the host's data directory. 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): the host writes out + (`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 From 6fac9b246138c767c8bfe0a01bf85f39af584b66 Mon Sep 17 00:00:00 2001 From: "fctl-sh[bot]" Date: Fri, 6 Nov 2026 23:59:23 +0000 Subject: [PATCH 25/25] docs(host): say in host.toml's docs that turning snapshots off lets kept states go --- docs/cli.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 2dcad5b9..0b31ad18 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -944,8 +944,9 @@ 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 (nor does a host that runs its VMs through -the jailer, yet). With Apple's +`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