diff --git a/Cargo.lock b/Cargo.lock index 4ed1484c..d4e1b3c4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -207,6 +207,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "chacha20" version = "0.10.2" @@ -534,12 +540,18 @@ dependencies = [ "clap", "fctl-domain", "fctl-proto", + "flate2", + "nix", "serde", "serde_json", + "tar", "tempfile", "tokio", + "tokio-tun", + "tokio-vsock", "tracing", "tracing-subscriber", + "vsock", ] [[package]] @@ -621,6 +633,7 @@ dependencies = [ "flate2", "futures", "hex", + "http", "regex", "serde", "serde_json", @@ -631,6 +644,7 @@ dependencies = [ "tokio-tungstenite", "toml", "tracing", + "url", ] [[package]] @@ -1178,6 +1192,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1199,6 +1222,19 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1905,6 +1941,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-tun" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2688a909b49d133bf55f2e29271fb3a81ff1e1a0b99c366da9ffd9af69b933a" +dependencies = [ + "libc", + "nix", + "tokio", +] + [[package]] name = "tokio-tungstenite" version = "0.30.0" @@ -1935,6 +1982,19 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-vsock" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b319ef9394889dab2e1b4f0085b45ba11d0c79dc9d1a9d1afc057d009d0f1c7" +dependencies = [ + "bytes", + "futures", + "libc", + "tokio", + "vsock", +] + [[package]] name = "toml" version = "1.1.8+spec-1.1.0" @@ -2205,6 +2265,16 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vsock" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ba782755fc073877e567c2253c0be48e4aa9a254c232d36d3985dfae0bd5205" +dependencies = [ + "libc", + "nix", +] + [[package]] name = "want" version = "0.3.2" diff --git a/ROADMAP.md b/ROADMAP.md index 4e775705..50d0c3a9 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -121,5 +121,5 @@ this file is the overview. Order within a section is priority. verified with a GitHub sign-in, without an instance admin's approval - [ ] GitHub sign-in as a way to sign in to fctl - [ ] Merging two accounts into one with both their addresses -- [ ] Linux hosts with Firecracker microVMs +- [x] Linux hosts with Firecracker microVMs: the `firecracker` driver, experimental - [ ] Windows hosts through WSL 2 diff --git a/crates/fctl-agent/Cargo.toml b/crates/fctl-agent/Cargo.toml index c3b73bf2..c465aab2 100644 --- a/crates/fctl-agent/Cargo.toml +++ b/crates/fctl-agent/Cargo.toml @@ -23,6 +23,15 @@ tokio.workspace = true tracing.workspace = true tracing-subscriber.workspace = true +# The init of Firecracker microVMs (src/vm). +[target.'cfg(target_os = "linux")'.dependencies] +flate2.workspace = true +nix = { workspace = true, features = ["hostname", "mount", "net", "reboot", "resource", "socket", "time"] } +tar.workspace = true +tokio-tun = "0.15.2" +tokio-vsock = "0.7.2" +vsock = "0.5.4" + [dev-dependencies] tempfile = "3" diff --git a/crates/fctl-agent/src/main.rs b/crates/fctl-agent/src/main.rs index 0d03336e..86d2bb40 100644 --- a/crates/fctl-agent/src/main.rs +++ b/crates/fctl-agent/src/main.rs @@ -2,6 +2,8 @@ //! //! - `fctl-agent serve` runs the supervisor (started detached by the host). //! - `fctl-agent attach` connects stdin/stdout to it (the host's channel). +//! - As PID 1 it is a Firecracker microVM's init, and `vm-serve` and +//! `vm-run` run what the host asks there (src/vm). //! //! See docs/architecture.md and crates/fctl-proto/src/agent.rs. @@ -16,6 +18,8 @@ mod prompt; mod refresh; mod supervisor; mod tasks; +#[cfg(target_os = "linux")] +mod vm; mod workspace; use clap::{Parser, Subcommand}; @@ -59,10 +63,42 @@ enum Command { )] socket: PathBuf, }, + /// Run what the host asks in a Firecracker microVM, under its init. + #[cfg(target_os = "linux")] + #[command(hide = true)] + VmServe, + /// Run a program as a user, in a session of its own (for vm-serve). + #[cfg(target_os = "linux")] + #[command(hide = true)] + VmRun { + uid: u32, + gid: u32, + /// Supplementary groups, separated by commas. + groups: String, + cwd: String, + #[arg(last = true, required = true)] + argv: Vec, + }, } fn main() -> anyhow::Result<()> { + // As a microVM's PID 1, fctl-agent is its init. + #[cfg(target_os = "linux")] + if std::process::id() == 1 { + vm::init(); + } let cli = Cli::parse(); + #[cfg(target_os = "linux")] + if let Command::VmRun { + uid, + gid, + groups, + cwd, + argv, + } = &cli.command + { + return vm::run_as(*uid, *gid, groups, cwd, argv); + } let rt = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .enable_all() @@ -77,6 +113,21 @@ fn main() -> anyhow::Result<()> { r } Command::Attach { socket } => rt.block_on(link::attach(&socket)), + #[cfg(target_os = "linux")] + Command::VmServe => { + // To the VM's console, which the host keeps in a file. + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_env("FCTL_LOG") + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")), + ) + .with_ansi(false) + .with_writer(std::io::stderr) + .init(); + rt.block_on(vm::serve()) + } + #[cfg(target_os = "linux")] + Command::VmRun { .. } => Ok(()), } } diff --git a/crates/fctl-agent/src/vm/boot.rs b/crates/fctl-agent/src/vm/boot.rs new file mode 100644 index 00000000..dbaa1ad3 --- /dev/null +++ b/crates/fctl-agent/src/vm/boot.rs @@ -0,0 +1,329 @@ +//! PID 1: from the initramfs to the sandbox's root, the system there, and +//! reaping. + +use super::{serve, unpack}; +use anyhow::{Context, Result, bail}; +use fctl_proto::vm::{Boot, Mode}; +use nix::errno::Errno; +use nix::mount::{MsFlags, mount}; +use nix::sys::reboot::{RebootMode, reboot}; +use nix::sys::wait::waitpid; +use nix::unistd::{Pid, chdir, chroot}; +use std::ffi::CString; +use std::path::Path; +use std::time::{Duration, Instant}; + +/// A file only the initramfs has, which the host puts there. +pub const MARKER: &str = "/fctl-initramfs"; + +/// Where the sandbox's root comes together before the init switches to it. +const NEW_ROOT: &str = "/newroot"; + +/// Where the image's filesystem and the sandbox's disk stay mounted, in the +/// sandbox's root. +const IMAGE_MOUNT: &str = "/run/fctl/image"; +const DISK_MOUNT: &str = "/run/fctl/disk"; + +/// Where fctl-agent lives in sandboxes (the host's `driver::AGENT_PATH`). +const AGENT_PATH: &str = "/opt/fctl/bin/fctl-agent"; + +/// fctl-agent as PID 1: in the initramfs it prepares the sandbox's root and +/// runs itself there, or unpacks an image; in the sandbox's root it sets the +/// system up and reaps. It never returns: when it can't go on, it powers the +/// VM off, which ends its Firecracker. +pub fn init() -> ! { + let result = if Path::new(MARKER).exists() { + first() + } else { + second() + }; + if let Err(e) = result { + say(&format!("{e:#}")); + } + power_off() +} + +/// The init writes to the VM's console, which the host keeps in the +/// sandbox's `console.log`. +pub fn say(line: &str) { + eprintln!("fctl-agent init: {line}"); +} + +/// Resets the VM: Firecracker exits when its guest does (`reboot=k` on +/// x86_64, PSCI on aarch64). +pub fn power_off() -> ! { + nix::unistd::sync(); + let _ = reboot(RebootMode::RB_AUTOBOOT); + loop { + std::thread::sleep(Duration::from_secs(60)); + } +} + +/// In the initramfs. +fn first() -> Result<()> { + mount_fs( + "devtmpfs", + "/dev", + "devtmpfs", + MsFlags::MS_NOSUID, + Some("mode=0755"), + )?; + let hidden = MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC; + mount_fs("proc", "/proc", "proc", hidden, None)?; + mount_fs("sysfs", "/sys", "sysfs", hidden, None)?; + let boot = boot_params()?; + match boot.mode { + Mode::Unpack => unpack_image(), + Mode::Sandbox => switch_root(), + } +} + +/// The kernel's command line says what to boot to. +fn boot_params() -> Result { + let cmdline = std::fs::read_to_string("/proc/cmdline").context("reading /proc/cmdline")?; + Boot::parse(&cmdline).context("the kernel's command line has no fctl.mode") +} + +/// Mounts `source` at `target`, making `target` first. +fn mount_fs( + source: &str, + target: &str, + fstype: &str, + flags: MsFlags, + data: Option<&str>, +) -> Result<()> { + std::fs::create_dir_all(target).with_context(|| format!("making {target}"))?; + mount(Some(source), target, Some(fstype), flags, data) + .with_context(|| format!("mounting {source} ({fstype}) at {target}")) +} + +/// Moves the mount at `from` to `to`. +fn move_mount(from: &str, to: &str) -> Result<()> { + std::fs::create_dir_all(to).with_context(|| format!("making {to}"))?; + mount(Some(from), to, None::<&str>, MsFlags::MS_MOVE, None::<&str>) + .with_context(|| format!("moving {from} to {to}")) +} + +/// Waits for the kernel to find a disk. +fn wait_for(device: &str) -> Result<()> { + let until = Instant::now() + Duration::from_secs(10); + while !Path::new(device).exists() { + if Instant::now() > until { + bail!("{device} did not appear"); + } + std::thread::sleep(Duration::from_millis(20)); + } + Ok(()) +} + +/// Puts the sandbox's root together, copies fctl-agent into it, and runs it +/// there as PID 1. Returns only when something fails. +fn switch_root() -> Result<()> { + wait_for("/dev/vda")?; + wait_for("/dev/vdb")?; + mount_fs("/dev/vda", "/image", "ext4", MsFlags::MS_RDONLY, None)?; + // `discard` gives the host back what the session deletes; + // `noinit_itable` keeps the kernel from zeroing the inode tables of a + // new disk, which would make it take room on the host. + mount_fs( + "/dev/vdb", + "/disk", + "ext4", + MsFlags::empty(), + Some("discard,noinit_itable"), + )?; + for dir in ["/disk/root", "/disk/work"] { + std::fs::create_dir_all(dir).with_context(|| format!("making {dir}"))?; + } + mount_fs( + "overlay", + NEW_ROOT, + "overlay", + MsFlags::empty(), + Some("lowerdir=/image,upperdir=/disk/root,workdir=/disk/work"), + )?; + let run = format!("{NEW_ROOT}/run"); + mount_fs( + "tmpfs", + &run, + "tmpfs", + MsFlags::MS_NOSUID | MsFlags::MS_NODEV, + Some("mode=0755"), + )?; + move_mount("/image", &format!("{NEW_ROOT}{IMAGE_MOUNT}"))?; + move_mount("/disk", &format!("{NEW_ROOT}{DISK_MOUNT}"))?; + install_self(&format!("{NEW_ROOT}{AGENT_PATH}"))?; + for dir in ["/dev", "/proc", "/sys"] { + move_mount(dir, &format!("{NEW_ROOT}{dir}"))?; + } + // The initramfs stays in memory under the new root; this is most of it. + let _ = std::fs::remove_file("/init"); + let _ = std::fs::remove_file(MARKER); + chdir(NEW_ROOT).context("changing to the new root")?; + mount(Some("."), "/", None::<&str>, MsFlags::MS_MOVE, None::<&str>) + .context("moving the new root to /")?; + chroot(".").context("changing the root")?; + chdir("/").context("changing to /")?; + let path = CString::new(AGENT_PATH)?; + let argv = [CString::new("fctl-agent")?, CString::new("vm-init")?]; + let e = nix::unistd::execv(&path, &argv).err(); + bail!("running {AGENT_PATH}: {e:?}") +} + +/// Copies the running fctl-agent (`/init`) to `to`, where the host's +/// commands find it. +fn install_self(to: &str) -> Result<()> { + let to = Path::new(to); + if let Some(dir) = to.parent() { + std::fs::create_dir_all(dir).with_context(|| format!("making {}", dir.display()))?; + } + let new = to.with_extension("new"); + std::fs::copy("/init", &new).with_context(|| format!("copying /init to {}", new.display()))?; + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&new, std::fs::Permissions::from_mode(0o755))?; + std::fs::rename(&new, to).with_context(|| format!("installing {}", to.display())) +} + +/// Unpacks an image onto `/dev/vda`, then returns for [`init`] to power +/// off. +fn unpack_image() -> Result<()> { + wait_for("/dev/vda")?; + mount_fs( + "/dev/vda", + "/target", + "ext4", + MsFlags::empty(), + Some("noinit_itable"), + )?; + let result = unpack::serve(Path::new("/target")); + nix::unistd::sync(); + let _ = nix::mount::umount("/target"); + result +} + +/// PID 1 in the sandbox's root. +fn second() -> Result<()> { + let boot = boot_params()?; + system(&boot); + supervise() +} + +/// What a system needs that the image doesn't bring: the kernel's +/// filesystems, a hostname, names for the network. What fails is said on +/// the console and left out. +fn system(boot: &Boot) { + let hidden = MsFlags::MS_NOSUID | MsFlags::MS_NOEXEC; + let mounts: [(&str, &str, &str, MsFlags, Option<&str>); 3] = [ + ( + "devpts", + "/dev/pts", + "devpts", + hidden, + Some("gid=5,mode=620,ptmxmode=666"), + ), + ( + "tmpfs", + "/dev/shm", + "tmpfs", + MsFlags::MS_NOSUID | MsFlags::MS_NODEV, + Some("mode=1777"), + ), + ( + "cgroup2", + "/sys/fs/cgroup", + "cgroup2", + hidden | MsFlags::MS_NODEV, + None, + ), + ]; + for (source, target, fstype, flags, data) in mounts { + if let Err(e) = mount_fs(source, target, fstype, flags, data) { + say(&format!("{e:#}")); + } + } + for (link, to) in [ + ("/dev/fd", "/proc/self/fd"), + ("/dev/stdin", "/proc/self/fd/0"), + ("/dev/stdout", "/proc/self/fd/1"), + ("/dev/stderr", "/proc/self/fd/2"), + ] { + let _ = std::os::unix::fs::symlink(to, link); + } + if let Err(e) = nix::unistd::sethostname(&boot.name) { + say(&format!("setting the hostname: {e}")); + } + let hosts = format!( + "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")), + ] { + if let Err(e) = replace(file, &text) { + say(&format!("writing {file}: {e}")); + } + } + if let Some(t) = boot.time_ms { + serve::follow_clock(t); + } + // What Docker gives its containers: Claude Code, Node.js and builds + // open many files. + let files = 1024 * 1024; + if let Err(e) = + nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_NOFILE, files, files) + { + say(&format!("raising the open files limit: {e}")); + } + if !Path::new("/tmp").is_dir() { + let _ = std::fs::create_dir("/tmp"); + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions("/tmp", std::fs::Permissions::from_mode(0o1777)); + } +} + +/// Writes `text` to `file`, in place of a link there (to systemd's +/// resolver, say, which doesn't run here). +fn replace(file: &str, text: &str) -> std::io::Result<()> { + if std::fs::symlink_metadata(file).is_ok_and(|m| m.file_type().is_symlink()) { + std::fs::remove_file(file)?; + } + std::fs::write(file, text) +} + +/// Keeps `fctl-agent vm-serve` running, and reaps every program whose +/// parent exited before it. +fn supervise() -> Result<()> { + loop { + let server = std::process::Command::new("/proc/self/exe") + .arg("vm-serve") + .spawn(); + match server { + Ok(child) => { + let pid = Pid::from_raw(i32::try_from(child.id()).unwrap_or(i32::MAX)); + reap_until(pid); + } + Err(e) => say(&format!("starting vm-serve: {e}")), + } + std::thread::sleep(Duration::from_secs(1)); + } +} + +/// Reaps children until `server` exits. +fn reap_until(server: Pid) { + loop { + match waitpid(Pid::from_raw(-1), None) { + Ok(status) if status.pid() == Some(server) => { + say(&format!("vm-serve stopped ({status:?}); starting it again")); + return; + } + Ok(_) | Err(Errno::EINTR) => {} + Err(Errno::ECHILD) => return, + Err(e) => { + say(&format!("waiting for programs: {e}")); + std::thread::sleep(Duration::from_secs(1)); + } + } + } +} diff --git a/crates/fctl-agent/src/vm/mod.rs b/crates/fctl-agent/src/vm/mod.rs new file mode 100644 index 00000000..a7ec660f --- /dev/null +++ b/crates/fctl-agent/src/vm/mod.rs @@ -0,0 +1,34 @@ +//! fctl-agent as the init of a Firecracker microVM, and what it runs there +//! (the `firecracker` driver: crates/fctl-host/src/driver/firecracker). +//! +//! The host boots each VM with fctl-agent as the initramfs's `/init`, and +//! the kernel's command line says what to boot to ([`fctl_proto::vm::Boot`]). +//! +//! - **A session's sandbox.** The init mounts the image's root filesystem +//! (`/dev/vda`, read only, shared by the sandboxes made from that image) +//! under the sandbox's own disk (`/dev/vdb`) as an overlay, copies itself +//! to `/opt/fctl/bin/fctl-agent` there, and runs that copy as PID 1 in the +//! new root ([`boot`]). That one sets the system up and keeps `fctl-agent +//! vm-serve` running ([`serve`]), which runs what the host asks over the +//! vsock, as `docker exec` would, and bridges the VM's network to the +//! host's `passt` ([`net`]). PID 1 itself only reaps the programs whose +//! parents exit before them. +//! - **Unpacking an image.** The init mounts `/dev/vda`, an empty +//! filesystem, and unpacks the layers the host sends onto it, as root, so +//! that their owners and modes stay theirs ([`unpack`]), then powers off. +//! An image's files never touch the host's filesystem. + +mod boot; +mod net; +mod netlink; +mod run_as; +mod serve; +mod unpack; +mod users; + +pub use boot::init; +pub use run_as::run_as; +pub use serve::serve; + +/// What the init reports to the host's `hello`. +const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/fctl-agent/src/vm/net.rs b/crates/fctl-agent/src/vm/net.rs new file mode 100644 index 00000000..254e8c8a --- /dev/null +++ b/crates/fctl-agent/src/vm/net.rs @@ -0,0 +1,105 @@ +//! 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. + +use super::netlink; +use fctl_proto::vm::{ADDRESS, GATEWAY, MTU, NET_PORT, PREFIX}; +use std::net::Ipv4Addr; +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}; + +/// 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). +pub async fn run() { + if let Err(e) = netlink::ask(&netlink::link_up_message(1)) { + tracing::warn!("bringing the loopback up: {e}"); + } + let tap = match tap() { + Ok(tap) => Arc::new(tap), + Err(e) => { + tracing::error!("the VM has no network: {e}"); + return; + } + }; + let mut wait = Duration::from_secs(1); + 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}"); + } + Err(e) => tracing::debug!("linking the network to the host: {e}"), + } + tokio::time::sleep(wait).await; + wait = (wait * 2).min(Duration::from_secs(10)); + } +} + +/// `eth0`, with its address, and the default route through it. +fn tap() -> std::io::Result { + let mask = u32::MAX + .checked_shl(32 - u32::from(PREFIX)) + .unwrap_or_default(); + let tun = Tun::builder() + .name("eth0") + .tap() + .mtu(i32::try_from(MTU).unwrap_or(1500)) + .address(Ipv4Addr::from(ADDRESS)) + .netmask(Ipv4Addr::from(mask)) + .up() + .build() + .map_err(std::io::Error::other)? + .pop() + .ok_or_else(|| std::io::Error::other("no queue for eth0"))?; + let index = nix::net::if_::if_nametoindex("eth0")?; + netlink::ask(&netlink::default_route_message(index, GATEWAY))?; + Ok(tun) +} + +/// Carries frames both ways until either side fails, and says why. +async fn forward(tap: &Arc, stream: VsockStream) -> std::io::Error { + let (mut from_host, mut to_host) = stream.into_split(); + let result = tokio::select! { + r = up(tap, &mut to_host) => r, + r = down(tap, &mut from_host) => r, + }; + match result { + Err(e) => e, + Ok(()) => std::io::Error::other("closed"), + } +} + +/// The VM's frames to the host, each after its length, in one write. +async fn up(tap: &Tun, to_host: &mut OwnedWriteHalf) -> std::io::Result<()> { + let mut buf = vec![0u8; 4 + MAX_FRAME]; + loop { + let n = tap.recv(&mut buf[4..]).await?; + let len = u32::try_from(n).unwrap_or(u32::MAX).to_be_bytes(); + buf[..4].copy_from_slice(&len); + to_host.write_all(&buf[..4 + n]).await?; + } +} + +/// The host's frames to the VM. +async fn down(tap: &Tun, from_host: &mut OwnedReadHalf) -> std::io::Result<()> { + let mut buf = vec![0u8; MAX_FRAME]; + loop { + let len = from_host.read_u32().await? as usize; + if len > buf.len() { + return Err(std::io::Error::other(format!( + "a frame of {len} bytes, more than the MTU allows" + ))); + } + from_host.read_exact(&mut buf[..len]).await?; + tap.send_all(&buf[..len]).await?; + } +} diff --git a/crates/fctl-agent/src/vm/netlink.rs b/crates/fctl-agent/src/vm/netlink.rs new file mode 100644 index 00000000..ed620f85 --- /dev/null +++ b/crates/fctl-agent/src/vm/netlink.rs @@ -0,0 +1,162 @@ +//! The two routing requests the VM's network needs, over rtnetlink: a link +//! up (the loopback) and a default route. Images have no `ip` to run. + +use nix::sys::socket::{ + AddressFamily, MsgFlags, NetlinkAddr, SockFlag, SockProtocol, SockType, bind, recv, send, + socket, +}; +use std::io; +use std::os::fd::AsRawFd; + +const RTM_NEWLINK: u16 = 16; +const RTM_NEWROUTE: u16 = 24; +const NLMSG_ERROR: u16 = 2; +const NLM_F_REQUEST: u16 = 0x1; +const NLM_F_ACK: u16 = 0x4; +const NLM_F_REPLACE: u16 = 0x100; +const NLM_F_CREATE: u16 = 0x400; +const IFF_UP: u32 = 0x1; +const AF_INET: u8 = 2; +const RT_TABLE_MAIN: u8 = 254; +const RTPROT_BOOT: u8 = 3; +const RT_SCOPE_UNIVERSE: u8 = 0; +const RTN_UNICAST: u8 = 1; +const RTA_OIF: u16 = 4; +const RTA_GATEWAY: u16 = 5; + +/// A message: its header (`nlmsghdr`), then `body`. +fn message(kind: u16, flags: u16, body: &[u8]) -> Vec { + let len = u32::try_from(16 + body.len()).unwrap_or(u32::MAX); + let mut m = Vec::with_capacity(16 + body.len()); + m.extend_from_slice(&len.to_ne_bytes()); + m.extend_from_slice(&kind.to_ne_bytes()); + m.extend_from_slice(&(flags | NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); + m.extend_from_slice(&1u32.to_ne_bytes()); + m.extend_from_slice(&0u32.to_ne_bytes()); + m.extend_from_slice(body); + m +} + +/// An attribute (`rtattr`), padded to 4 bytes. +fn attribute(kind: u16, data: &[u8]) -> Vec { + let len = u16::try_from(4 + data.len()).unwrap_or(u16::MAX); + let mut a = Vec::with_capacity(8 + data.len()); + a.extend_from_slice(&len.to_ne_bytes()); + a.extend_from_slice(&kind.to_ne_bytes()); + a.extend_from_slice(data); + while !a.len().is_multiple_of(4) { + a.push(0); + } + a +} + +/// Sets the link `index` up (`ifinfomsg` with `IFF_UP` in its flags and +/// change mask). +pub fn link_up_message(index: u32) -> Vec { + let mut body = vec![0u8, 0]; + body.extend_from_slice(&0u16.to_ne_bytes()); + body.extend_from_slice(&index.to_ne_bytes()); + body.extend_from_slice(&IFF_UP.to_ne_bytes()); + body.extend_from_slice(&IFF_UP.to_ne_bytes()); + message(RTM_NEWLINK, 0, &body) +} + +/// The default route via `gateway` on the link `index` (`rtmsg` and its +/// attributes), in place of any there. +pub fn default_route_message(index: u32, gateway: [u8; 4]) -> Vec { + let mut body = vec![ + AF_INET, + 0, + 0, + 0, + RT_TABLE_MAIN, + RTPROT_BOOT, + RT_SCOPE_UNIVERSE, + RTN_UNICAST, + ]; + body.extend_from_slice(&0u32.to_ne_bytes()); + body.extend(attribute(RTA_GATEWAY, &gateway)); + body.extend(attribute(RTA_OIF, &index.to_ne_bytes())); + message(RTM_NEWROUTE, NLM_F_CREATE | NLM_F_REPLACE, &body) +} + +/// What the kernel's acknowledgement says: `Ok`, or the error it carries. +pub fn acknowledged(reply: &[u8]) -> io::Result<()> { + let kind = reply.get(4..6).map(|b| u16::from_ne_bytes([b[0], b[1]])); + let code = reply + .get(16..20) + .map(|b| i32::from_ne_bytes([b[0], b[1], b[2], b[3]])); + match (kind, code) { + (Some(NLMSG_ERROR), Some(0)) => Ok(()), + (Some(NLMSG_ERROR), Some(e)) => Err(io::Error::from_raw_os_error(-e)), + _ => Err(io::Error::other( + "the kernel's answer isn't an acknowledgement", + )), + } +} + +/// Sends `request` to the kernel and waits for its acknowledgement. +pub fn ask(request: &[u8]) -> io::Result<()> { + let fd = socket( + AddressFamily::Netlink, + SockType::Raw, + SockFlag::SOCK_CLOEXEC, + SockProtocol::NetlinkRoute, + )?; + bind(fd.as_raw_fd(), &NetlinkAddr::new(0, 0))?; + send(fd.as_raw_fd(), request, MsgFlags::empty())?; + let mut reply = [0u8; 1024]; + let n = recv(fd.as_raw_fd(), &mut reply, MsgFlags::empty())?; + acknowledged(&reply[..n]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn u32_at(m: &[u8], at: usize) -> u32 { + u32::from_ne_bytes([m[at], m[at + 1], m[at + 2], m[at + 3]]) + } + + #[test] + fn a_link_comes_up() { + let m = link_up_message(1); + assert_eq!(m.len(), 32); + assert_eq!(u32_at(&m, 0), 32); + assert_eq!(&m[4..6], &RTM_NEWLINK.to_ne_bytes()); + assert_eq!(&m[6..8], &(NLM_F_REQUEST | NLM_F_ACK).to_ne_bytes()); + // ifinfomsg: family, padding, type, index, flags, change. + assert_eq!(u32_at(&m, 20), 1); + assert_eq!((u32_at(&m, 24), u32_at(&m, 28)), (IFF_UP, IFF_UP)); + } + + #[test] + fn the_default_route_goes_through_the_gateway() { + let m = default_route_message(2, [10, 0, 2, 2]); + // Header, rtmsg, then RTA_GATEWAY and RTA_OIF of 8 bytes each. + assert_eq!(m.len(), 16 + 12 + 8 + 8); + assert_eq!(u32_at(&m, 0) as usize, m.len()); + assert_eq!(&m[4..6], &RTM_NEWROUTE.to_ne_bytes()); + assert_eq!( + &m[6..8], + &(NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_REPLACE).to_ne_bytes() + ); + assert_eq!(&m[16..24], &[AF_INET, 0, 0, 0, 254, 3, 0, 1]); + assert_eq!(&m[28..30], &8u16.to_ne_bytes()); + assert_eq!(&m[30..32], &RTA_GATEWAY.to_ne_bytes()); + assert_eq!(&m[32..36], &[10, 0, 2, 2]); + assert_eq!(&m[38..40], &RTA_OIF.to_ne_bytes()); + assert_eq!(u32_at(&m, 40), 2); + } + + #[test] + fn reads_the_kernels_acknowledgement() { + let mut ack = message(NLMSG_ERROR, 0, &0i32.to_ne_bytes()); + assert!(acknowledged(&ack).is_ok()); + ack.truncate(16); + ack.extend_from_slice(&(-17i32).to_ne_bytes()); + let e = acknowledged(&ack).err(); + assert_eq!(e.and_then(|e| e.raw_os_error()), Some(17)); + assert!(acknowledged(&[0u8; 8]).is_err()); + } +} diff --git a/crates/fctl-agent/src/vm/run_as.rs b/crates/fctl-agent/src/vm/run_as.rs new file mode 100644 index 00000000..e201b238 --- /dev/null +++ b/crates/fctl-agent/src/vm/run_as.rs @@ -0,0 +1,43 @@ +//! `fctl-agent vm-run UID GID GROUPS CWD -- PROGRAM ARGS…`: what `vm-serve` +//! starts for each program the host runs. As root, it takes the user's +//! identity and a session of its own, so that the init can stop the program +//! with everything it started, then becomes the program. + +use anyhow::{Context, Result, bail}; +use nix::unistd::{Gid, Uid, execvp, setgid, setgroups, setsid, setuid}; +use std::ffi::CString; + +pub fn run_as(uid: u32, gid: u32, groups: &str, cwd: &str, argv: &[String]) -> Result<()> { + let Some(program) = argv.first() else { + bail!("no program to run"); + }; + setsid().context("starting a session")?; + let groups = groups + .split(',') + .filter(|g| !g.is_empty()) + .map(|g| g.parse().map(Gid::from_raw)) + .collect::, _>>() + .context("reading the groups")?; + setgroups(&groups).context("setting the groups")?; + setgid(Gid::from_raw(gid)).context("setting the group")?; + setuid(Uid::from_raw(uid)).context("setting the user")?; + std::env::set_current_dir(cwd) + .with_context(|| format!("changing to the working directory {cwd}"))?; + let program_c = CString::new(program.as_str())?; + let args = argv + .iter() + .map(|a| CString::new(a.as_str())) + .collect::, _>>()?; + let e = execvp(&program_c, &args).err(); + // As a shell says it: 127 for a program that isn't there, 126 for one + // that can't run. + eprintln!( + "{program}: {}", + e.map(|e| e.desc()).unwrap_or("can't run it") + ); + std::process::exit(if e == Some(nix::errno::Errno::ENOENT) { + 127 + } else { + 126 + }) +} diff --git a/crates/fctl-agent/src/vm/serve.rs b/crates/fctl-agent/src/vm/serve.rs new file mode 100644 index 00000000..f8399d78 --- /dev/null +++ b/crates/fctl-agent/src/vm/serve.rs @@ -0,0 +1,345 @@ +//! `fctl-agent vm-serve`: runs what the host asks over the vsock, as +//! `docker exec` would, and keeps the VM's network linked to the host. + +use super::users::{self, User}; +use super::{VERSION, net}; +use anyhow::{Context, Result}; +use fctl_proto::vm::{Exec, MAX_LINE, PORT, Reply, Request, frame}; +use nix::sys::signal::{Signal, kill, killpg}; +use nix::time::{ClockId, clock_gettime, clock_settime}; +use nix::unistd::Pid; +use std::process::Stdio; +use std::time::Duration; +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader}; +use tokio::sync::mpsc; +use tokio_vsock::{VMADDR_CID_ANY, VMADDR_CID_HOST, VsockAddr, VsockListener, VsockStream}; + +/// The PATH a program gets when the image sets none, as with Docker. +const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; + +pub async fn serve() -> Result<()> { + tokio::spawn(net::run()); + let listener = VsockListener::bind(VsockAddr::new(VMADDR_CID_ANY, PORT)) + .context("listening on the vsock")?; + loop { + let (conn, peer) = listener.accept().await.context("taking a connection")?; + // Only the host, not a program in the VM through the vsock's + // loopback, which would run what it liked as anyone. + if peer.cid() != VMADDR_CID_HOST { + tracing::warn!("refused a connection from vsock CID {}", peer.cid()); + continue; + } + tokio::spawn(async move { + if let Err(e) = handle(conn).await { + tracing::debug!("a request from the host: {e:#}"); + } + }); + } +} + +/// Sets the VM's clock to the host's, `now_ms`, when they differ by more +/// than a second: the VM's runs on while the host sleeps. +pub fn follow_clock(now_ms: i64) { + let Ok(here) = clock_gettime(ClockId::CLOCK_REALTIME) else { + return; + }; + let here_ms = here.tv_sec() * 1000 + here.tv_nsec() / 1_000_000; + if (here_ms - now_ms).abs() <= 1000 { + return; + } + let to = nix::sys::time::TimeSpec::new(now_ms / 1000, (now_ms % 1000) * 1_000_000); + if let Err(e) = clock_settime(ClockId::CLOCK_REALTIME, to) { + tracing::warn!("setting the clock: {e}"); + } +} + +async fn reply(w: &mut (impl AsyncWrite + Unpin), r: &Reply) -> Result<()> { + let mut line = serde_json::to_vec(r)?; + line.push(b'\n'); + w.write_all(&line).await?; + w.flush().await?; + Ok(()) +} + +async fn handle(conn: VsockStream) -> Result<()> { + let (r, mut w) = conn.into_split(); + let mut r = BufReader::new(r); + let mut line = Vec::new(); + (&mut r) + .take(MAX_LINE as u64) + .read_until(b'\n', &mut line) + .await?; + let request = match serde_json::from_slice::(&line) { + Ok(request) => request, + Err(e) => { + return reply(&mut w, &Reply::failed(format!("unknown request: {e}"))).await; + } + }; + match request { + Request::Hello { now_ms } => { + if let Some(t) = now_ms { + follow_clock(t); + } + let hello = Reply { + version: Some(VERSION.into()), + ..Reply::default() + }; + reply(&mut w, &hello).await + } + Request::Exec(exec) => run(exec, r, w).await, + Request::Unpack { .. } => { + reply( + &mut w, + &Reply::failed("this VM runs a sandbox; it unpacks no images"), + ) + .await + } + Request::Shutdown => { + reply(&mut w, &Reply::default()).await?; + shutdown().await + } + } +} + +/// The environment a program gets: the image's, with `HOME`, `HOSTNAME` +/// and `PATH` when it has none. +fn environment(image: &[String], user: &User, hostname: &str) -> Vec<(String, String)> { + let mut env: Vec<(String, String)> = image + .iter() + .filter_map(|kv| kv.split_once('=')) + .filter(|(k, _)| !k.is_empty()) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect(); + for (k, v) in [ + ("PATH", DEFAULT_PATH), + ("HOSTNAME", hostname), + ("HOME", user.home.as_str()), + ] { + if !env.iter().any(|(have, _)| have == k) { + env.push((k.to_owned(), v.to_owned())); + } + } + env +} + +/// Runs `exec`, and carries its input and output until it exits. +async fn run( + exec: Exec, + from_host: BufReader, + mut to_host: tokio_vsock::OwnedWriteHalf, +) -> Result<()> { + if let Some(t) = exec.now_ms { + follow_clock(t); + } + if exec.argv.is_empty() { + return reply(&mut to_host, &Reply::failed("no program to run")).await; + } + let user = match users::find(exec.user.as_deref()) { + Ok(user) => user, + Err(e) => return reply(&mut to_host, &Reply::failed(e)).await, + }; + let hostname = nix::unistd::gethostname() + .map(|h| h.to_string_lossy().into_owned()) + .unwrap_or_default(); + let cwd = exec + .cwd + .clone() + .filter(|c| !c.is_empty()) + .unwrap_or_else(|| "/".into()); + let groups: Vec = user.groups.iter().map(u32::to_string).collect(); + let mut cmd = tokio::process::Command::new("/proc/self/exe"); + cmd.arg("vm-run") + .arg(user.uid.to_string()) + .arg(user.gid.to_string()) + .arg(groups.join(",")) + .arg(&cwd) + .arg("--") + .args(&exec.argv) + .env_clear() + .envs(environment(&exec.env, &user, &hostname)); + if exec.detach { + cmd.stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + return match cmd.spawn() { + Ok(mut child) => { + // Reaped here; by PID 1 should vm-serve stop first. + tokio::spawn(async move { child.wait().await }); + reply(&mut to_host, &Reply::default()).await + } + Err(e) => reply(&mut to_host, &Reply::failed(format!("starting it: {e}"))).await, + }; + } + cmd.stdin(if exec.stdin { + Stdio::piped() + } else { + Stdio::null() + }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(e) => return reply(&mut to_host, &Reply::failed(format!("starting it: {e}"))).await, + }; + reply(&mut to_host, &Reply::default()).await?; + let pid = child.id().and_then(|p| i32::try_from(p).ok()); + let (frames, mut outgoing) = mpsc::channel::<(u8, Vec)>(16); + let writer = tokio::spawn(async move { + while let Some((kind, data)) = outgoing.recv().await { + let header = frame::header(kind, data.len()); + if to_host.write_all(&header).await.is_err() || to_host.write_all(&data).await.is_err() + { + break; + } + } + let _ = to_host.shutdown().await; + }); + let mut outputs = Vec::new(); + for (kind, out) in [ + ( + frame::STDOUT, + child + .stdout + .take() + .map(|o| Box::new(o) as Box), + ), + ( + frame::STDERR, + child + .stderr + .take() + .map(|o| Box::new(o) as Box), + ), + ] { + if let Some(out) = out { + outputs.push(tokio::spawn(pump(out, kind, frames.clone()))); + } + } + // The host's input; when the host goes away, so does the program, with + // everything it started. + let stdin = child.stdin.take(); + let input = tokio::spawn(async move { + take_input(from_host, stdin).await; + if let Some(pid) = pid { + let _ = killpg(Pid::from_raw(pid), Signal::SIGKILL); + } + }); + let status = child.wait().await; + // Output still under way, unless something it started holds the pipes. + for out in outputs { + let _ = tokio::time::timeout(Duration::from_secs(2), out).await; + } + let code = match status { + Ok(s) => { + use std::os::unix::process::ExitStatusExt; + s.code().or(s.signal().map(|n| 128 + n)).unwrap_or(1) + } + Err(_) => 1, + }; + let _ = frames + .send((frame::EXIT, code.to_be_bytes().to_vec())) + .await; + drop(frames); + let _ = writer.await; + input.abort(); + Ok(()) +} + +/// Sends what `out` gives as frames of `kind`. +async fn pump( + mut out: Box, + kind: u8, + frames: mpsc::Sender<(u8, Vec)>, +) { + let mut buf = vec![0u8; 64 * 1024]; + loop { + match out.read(&mut buf).await { + Ok(0) | Err(_) => return, + Ok(n) => { + if frames.send((kind, buf[..n].to_vec())).await.is_err() { + return; + } + } + } + } +} + +/// Writes the host's input to the program until the host ends it; returns +/// when the host goes away. +async fn take_input( + mut from_host: BufReader, + mut stdin: Option, +) { + let mut buf = vec![0u8; frame::MAX]; + loop { + let mut header = [0u8; 5]; + if from_host.read_exact(&mut header).await.is_err() { + return; + } + let Some((kind, len)) = frame::parse(header) else { + return; + }; + if from_host.read_exact(&mut buf[..len]).await.is_err() { + return; + } + match kind { + frame::STDIN => { + if let Some(s) = stdin.as_mut() + && s.write_all(&buf[..len]).await.is_err() + { + stdin = None; + } + } + frame::STDIN_END => stdin = None, + _ => {} + } + } +} + +/// Stops every program, writes what the disks hold, and resets the VM, +/// which ends its Firecracker. +async fn shutdown() -> Result<()> { + tracing::info!("shutting down"); + // Everything but PID 1 and this process. + let _ = kill(Pid::from_raw(-1), Signal::SIGTERM); + tokio::time::sleep(Duration::from_secs(2)).await; + let _ = kill(Pid::from_raw(-1), Signal::SIGKILL); + super::boot::power_off() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn programs_get_the_images_environment_and_a_home() { + let user = User { + uid: 1000, + gid: 1000, + groups: vec![1000], + home: "/home/agent".into(), + }; + let env = environment( + &[ + "PATH=/opt/fctl/bin:/usr/bin".into(), + "LANG=C.UTF-8".into(), + "junk".into(), + ], + &user, + "fctl-ses-1", + ); + assert_eq!( + env, + [ + ("PATH".into(), "/opt/fctl/bin:/usr/bin".into()), + ("LANG".into(), "C.UTF-8".into()), + ("HOSTNAME".into(), "fctl-ses-1".into()), + ("HOME".into(), "/home/agent".into()), + ] + ); + let bare = environment(&["HOME=/root".into()], &user, "h"); + assert!(bare.contains(&("PATH".into(), DEFAULT_PATH.into()))); + assert!(bare.contains(&("HOME".into(), "/root".into()))); + } +} diff --git a/crates/fctl-agent/src/vm/unpack.rs b/crates/fctl-agent/src/vm/unpack.rs new file mode 100644 index 00000000..1acf2ec7 --- /dev/null +++ b/crates/fctl-agent/src/vm/unpack.rs @@ -0,0 +1,404 @@ +//! Unpacking an image's layers onto a disk, in a VM booted for it: the host +//! sends the layers as its registry gave them, and this applies them one +//! after the other, as Docker does, with their whiteouts. + +use super::boot::say; +use anyhow::{Context, Result, bail}; +use fctl_proto::vm::{Layer, MAX_LINE, PORT, Reply, Request}; +use std::collections::HashSet; +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Component, Path, PathBuf}; +use vsock::{VMADDR_CID_ANY, VMADDR_CID_HOST, VsockAddr, VsockListener}; + +/// What unpacking wrote. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct Unpacked { + pub files: u64, + pub bytes: u64, +} + +/// Answers the host until one `unpack` request is done. +pub fn serve(root: &Path) -> Result<()> { + let listener = VsockListener::bind(&VsockAddr::new(VMADDR_CID_ANY, PORT)) + .context("listening on the vsock")?; + loop { + let (conn, peer) = listener.accept().context("taking a connection")?; + if peer.cid() != VMADDR_CID_HOST { + continue; + } + let mut reader = BufReader::new(conn.try_clone()?); + let mut writer = conn; + let mut line = Vec::new(); + (&mut reader) + .take(MAX_LINE as u64) + .read_until(b'\n', &mut line)?; + let request = serde_json::from_slice::(&line); + let reply = |w: &mut vsock::VsockStream, r: &Reply| -> Result<()> { + let mut line = serde_json::to_vec(r)?; + line.push(b'\n'); + w.write_all(&line)?; + Ok(()) + }; + match request { + Ok(Request::Hello { .. }) => reply( + &mut writer, + &Reply { + version: Some(super::VERSION.into()), + ..Reply::default() + }, + )?, + Ok(Request::Unpack { layers }) => { + reply(&mut writer, &Reply::default())?; + let result = layers_onto(root, &layers, &mut reader); + let answer = match &result { + Ok(u) => Reply { + files: Some(u.files), + bytes: Some(u.bytes), + ..Reply::default() + }, + Err(e) => Reply::failed(format!("{e:#}")), + }; + nix::unistd::sync(); + reply(&mut writer, &answer)?; + return result.map(drop); + } + Ok(_) => reply( + &mut writer, + &Reply::failed("this VM unpacks an image; it runs nothing"), + )?, + Err(e) => reply(&mut writer, &Reply::failed(format!("unknown request: {e}")))?, + } + } +} + +/// Reads each of `layers` from `from` and applies it onto `root`. +fn layers_onto(root: &Path, layers: &[Layer], from: &mut impl Read) -> Result { + let mut done = Unpacked::default(); + for (i, layer) in layers.iter().enumerate() { + let mut bytes = from.take(layer.size); + let n = i + 1; + match compression(&layer.media_type)? { + Compression::Gzip => apply( + root, + flate2::read::MultiGzDecoder::new(&mut bytes), + &mut done, + ), + Compression::None => apply(root, &mut bytes, &mut done), + } + .with_context(|| format!("unpacking layer {n} of {}", layers.len()))?; + // What the decompressor left, padding say. + std::io::copy(&mut bytes, &mut std::io::sink())?; + say(&format!( + "unpacked layer {n} of {}: {} files so far", + layers.len(), + done.files + )); + } + Ok(done) +} + +enum Compression { + Gzip, + None, +} + +/// How a layer of `media_type` is compressed. +fn compression(media_type: &str) -> Result { + match media_type { + "application/vnd.oci.image.layer.v1.tar+gzip" + | "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" + | "application/vnd.docker.image.rootfs.diff.tar.gzip" + | "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip" => Ok(Compression::Gzip), + "application/vnd.oci.image.layer.v1.tar" + | "application/vnd.oci.image.layer.nondistributable.v1.tar" + | "application/vnd.docker.image.rootfs.diff.tar" => Ok(Compression::None), + other => bail!("layers of type {other} can't be unpacked here yet (only tar and tar+gzip)"), + } +} + +/// The path of an entry, relative and without `.` or `..`; `None` for one +/// that would leave the root, or names it. +fn relative(path: &Path) -> Option { + let mut out = PathBuf::new(); + for part in path.components() { + match part { + Component::Normal(p) => out.push(p), + Component::CurDir | Component::RootDir => {} + Component::ParentDir | Component::Prefix(_) => return None, + } + } + (!out.as_os_str().is_empty()).then_some(out) +} + +/// Removes whatever is at `path`, a directory with all it holds too. +fn remove(path: &Path) -> std::io::Result<()> { + match std::fs::symlink_metadata(path) { + Ok(m) if m.is_dir() => std::fs::remove_dir_all(path), + Ok(_) => std::fs::remove_file(path), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(e) => Err(e), + } +} + +/// `path` in `root` through no link that leads out of it: its directory as +/// the filesystem resolves it, and its name. `None` when that is outside +/// `root` (`root` is canonical), or isn't there. +fn within(root: &Path, path: &Path) -> Option { + let dir = root.join(path.parent()?).canonicalize().ok()?; + let name = path.file_name()?; + dir.starts_with(root).then(|| dir.join(name)) +} + +/// Applies one layer, a tar stream, onto `root`: `.wh.` removes +/// `` from the layers below, `.wh..wh..opq` everything they have in +/// its directory, and an entry replaces what was at its path unless both +/// are directories. Owners, modes, times and extended attributes stay as +/// the layer has them (the VM's init runs as root). Nothing it does +/// reaches out of `root`, whatever links the layers make. +pub fn apply(root: &Path, layer: impl Read, done: &mut Unpacked) -> Result<()> { + let root = root.canonicalize()?; + let root = root.as_path(); + let mut archive = tar::Archive::new(layer); + archive.set_preserve_permissions(true); + archive.set_preserve_ownerships(nix::unistd::geteuid().is_root()); + archive.set_preserve_mtime(true); + archive.set_unpack_xattrs(true); + archive.set_overwrite(true); + // What this layer put in place, which its opaque whiteouts keep. + let mut ours: HashSet = HashSet::new(); + for entry in archive.entries()? { + let mut entry = entry?; + let Some(path) = relative(&entry.path()?) else { + continue; + }; + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + if name == ".wh..wh..opq" { + let Some(dir) = within(root, &path) + .as_deref() + .and_then(Path::parent) + .map(Path::to_path_buf) + else { + continue; + }; + if let Ok(children) = std::fs::read_dir(&dir) { + for child in children.flatten() { + let full = child.path(); + let rel = full.strip_prefix(root).map(Path::to_path_buf); + if rel.is_ok_and(|r| !ours.contains(&r)) { + remove(&full)?; + } + } + } + continue; + } + if let Some(hidden) = name.strip_prefix(".wh.") { + if let Some(target) = within(root, &path.with_file_name(hidden)) { + remove(&target)?; + } + continue; + } + let kind = entry.header().entry_type(); + if let Some(target) = within(root, &path) + && let Ok(meta) = std::fs::symlink_metadata(&target) + && !(meta.is_dir() && kind.is_dir()) + { + remove(&target)?; + } + if kind.is_character_special() || kind.is_block_special() || kind.is_fifo() { + special(root, &path, entry.header())?; + } else { + entry.unpack_in(root)?; + } + done.files += 1; + done.bytes += entry.header().size().unwrap_or(0); + ours.insert(path); + } + Ok(()) +} + +/// A device node or a FIFO, which the tar crate would make a plain file. +fn special(root: &Path, path: &Path, header: &tar::Header) -> Result<()> { + use nix::sys::stat::{Mode, SFlag, makedev, mknod}; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(root.join(dir))?; + } + let Some(target) = within(root, path) else { + bail!("{} would be outside the image", path.display()); + }; + let kind = header.entry_type(); + let flag = if kind.is_character_special() { + SFlag::S_IFCHR + } else if kind.is_block_special() { + SFlag::S_IFBLK + } else { + SFlag::S_IFIFO + }; + let mode = Mode::from_bits_truncate(header.mode()? & 0o7777); + let dev = makedev( + u64::from(header.device_major()?.unwrap_or(0)), + u64::from(header.device_minor()?.unwrap_or(0)), + ); + mknod(&target, flag, mode, dev).with_context(|| format!("making {}", path.display()))?; + if nix::unistd::geteuid().is_root() { + let uid = u32::try_from(header.uid()?).ok(); + let gid = u32::try_from(header.gid()?).ok(); + nix::unistd::chown( + &target, + uid.map(nix::unistd::Uid::from_raw), + gid.map(nix::unistd::Gid::from_raw), + )?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A layer of `(path, contents)`: a path ending in `/` is a directory, + /// contents starting with `->` a symlink. + fn layer(entries: &[(&str, &str)]) -> Vec { + let mut b = tar::Builder::new(Vec::new()); + for (path, contents) in entries { + let mut h = tar::Header::new_gnu(); + h.set_mtime(1_700_000_000); + if let Some(dir) = path.strip_suffix('/') { + h.set_entry_type(tar::EntryType::Directory); + h.set_mode(0o755); + h.set_size(0); + b.append_data(&mut h, dir, std::io::empty()).ok(); + } else if let Some(to) = contents.strip_prefix("->") { + h.set_entry_type(tar::EntryType::Symlink); + h.set_size(0); + b.append_link(&mut h, path, to).ok(); + } else { + h.set_mode(0o644); + h.set_size(contents.len() as u64); + b.append_data(&mut h, path, contents.as_bytes()).ok(); + } + } + b.into_inner().unwrap_or_default() + } + + fn read(root: &Path, path: &str) -> Option { + std::fs::read_to_string(root.join(path)).ok() + } + + #[test] + fn layers_apply_with_their_whiteouts() -> Result<()> { + let dir = tempfile::tempdir()?; + let root = dir.path(); + let mut done = Unpacked::default(); + apply( + root, + &layer(&[ + ("etc/", ""), + ("etc/hostname", "base"), + ("etc/motd", "hello"), + ("opt/app/", ""), + ("opt/app/old", "1"), + ("opt/app/keep", "2"), + ("bin/", ""), + ("bin/sh", "->busybox"), + ("var/thing", "a file"), + ])[..], + &mut done, + )?; + assert_eq!(done.files, 9); + apply( + root, + &layer(&[ + ("etc/.wh.motd", ""), + // Opaque: what the layers below have in opt/app goes, but + // not what this layer puts there, before or after. + ("opt/app/new", "3"), + ("opt/app/.wh..wh..opq", ""), + ("opt/app/later", "4"), + ("etc/hostname", "top"), + // A directory where a file was. + ("var/thing/", ""), + ("var/thing/inside", "x"), + ])[..], + &mut done, + )?; + assert_eq!(read(root, "etc/hostname").as_deref(), Some("top")); + assert!(!root.join("etc/motd").exists()); + assert!(!root.join("etc/.wh.motd").exists()); + assert_eq!(read(root, "opt/app/new").as_deref(), Some("3")); + assert_eq!(read(root, "opt/app/later").as_deref(), Some("4")); + assert!(!root.join("opt/app/old").exists()); + assert!(!root.join("opt/app/keep").exists()); + assert!(!root.join("opt/app/.wh..wh..opq").exists()); + assert_eq!(read(root, "var/thing/inside").as_deref(), Some("x")); + assert_eq!( + std::fs::read_link(root.join("bin/sh"))?, + PathBuf::from("busybox") + ); + Ok(()) + } + + #[test] + fn entries_stay_inside_the_root() -> Result<()> { + let dir = tempfile::tempdir()?; + let root = dir.path().join("root"); + std::fs::create_dir(&root)?; + let mut done = Unpacked::default(); + // A link out of the root, then a file through it, and a whiteout + // that climbs out. + let mut b = tar::Builder::new(Vec::new()); + let mut h = tar::Header::new_gnu(); + h.set_entry_type(tar::EntryType::Symlink); + h.set_size(0); + b.append_link(&mut h, "escape", dir.path())?; + let mut h = tar::Header::new_gnu(); + h.set_size(1); + h.set_mode(0o644); + b.append_data(&mut h, "escape/outside", &b"x"[..])?; + let bytes = b.into_inner()?; + let r = apply(&root, &bytes[..], &mut done); + assert!(r.is_err(), "{r:?}"); + assert!(!dir.path().join("outside").exists()); + // Whiteouts and replaced entries reach nothing through the link. + std::fs::write(dir.path().join("precious"), "x")?; + apply( + &root, + &layer(&[("escape/.wh.precious", ""), ("escape/.wh..wh..opq", "")])[..], + &mut done, + )?; + assert!(dir.path().join("precious").exists()); + let r = apply( + &root, + &layer(&[("escape/precious", "replaced")])[..], + &mut done, + ); + assert!(r.is_err(), "{r:?}"); + assert_eq!(read(dir.path(), "precious").as_deref(), Some("x")); + assert_eq!(relative(Path::new("../../etc/passwd")), None); + assert_eq!(relative(Path::new("./")), None); + assert_eq!( + relative(Path::new("/./usr//bin/")), + Some(PathBuf::from("usr/bin")) + ); + Ok(()) + } + + #[test] + fn layers_are_gzip_or_plain_tar() { + assert!(matches!( + compression("application/vnd.oci.image.layer.v1.tar+gzip"), + Ok(Compression::Gzip) + )); + assert!(matches!( + compression("application/vnd.docker.image.rootfs.diff.tar.gzip"), + Ok(Compression::Gzip) + )); + assert!(matches!( + compression("application/vnd.oci.image.layer.v1.tar"), + Ok(Compression::None) + )); + assert!(compression("application/vnd.oci.image.layer.v1.tar+zstd").is_err()); + } +} diff --git a/crates/fctl-agent/src/vm/users.rs b/crates/fctl-agent/src/vm/users.rs new file mode 100644 index 00000000..440dd5a6 --- /dev/null +++ b/crates/fctl-agent/src/vm/users.rs @@ -0,0 +1,146 @@ +//! Who a program runs as: the image's user, found as `docker exec` finds it +//! in the image's `/etc/passwd` and `/etc/group`. + +/// A user to run a program as. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct User { + pub uid: u32, + pub gid: u32, + /// Its supplementary groups. + pub groups: Vec, + pub home: String, +} + +/// The user `spec` names (`name`, `uid`, `name:group` or `uid:gid`; unset: +/// root), from this system's files. +pub fn find(spec: Option<&str>) -> Result { + let passwd = std::fs::read_to_string("/etc/passwd").unwrap_or_default(); + let group = std::fs::read_to_string("/etc/group").unwrap_or_default(); + find_in(spec, &passwd, &group) +} + +/// A line of `/etc/passwd`: name, uid, gid, home. +fn accounts(passwd: &str) -> impl Iterator { + passwd.lines().filter_map(|line| { + let f: Vec<&str> = line.split(':').collect(); + match f.as_slice() { + [name, _, uid, gid, _, home, ..] => { + Some((*name, uid.parse().ok()?, gid.parse().ok()?, *home)) + } + _ => None, + } + }) +} + +/// A line of `/etc/group`: name, gid, members. +fn groups(group: &str) -> impl Iterator)> { + group.lines().filter_map(|line| { + let f: Vec<&str> = line.split(':').collect(); + match f.as_slice() { + [name, _, gid, members, ..] => Some(( + *name, + gid.parse().ok()?, + members.split(',').filter(|m| !m.is_empty()).collect(), + )), + [name, _, gid] => Some((*name, gid.parse().ok()?, Vec::new())), + _ => None, + } + }) +} + +/// [`find`], from the files' text. A uid that no account has runs with +/// group 0 and `/` as its home, as with Docker. +pub fn find_in(spec: Option<&str>, passwd: &str, group: &str) -> Result { + let spec = spec + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or("root"); + let (user, group_spec) = match spec.split_once(':') { + Some((u, g)) => (u, Some(g)), + None => (spec, None), + }; + let number = user.parse::().ok(); + let account = accounts(passwd).find(|(name, uid, _, _)| match number { + Some(n) => *uid == n, + None => *name == user, + }); + let (name, uid, mut gid, home) = match (account, number) { + (Some((name, uid, gid, home)), _) => (Some(name), uid, gid, home.to_owned()), + (None, Some(n)) => (None, n, 0, "/".to_owned()), + (None, None) if user == "root" => (Some("root"), 0, 0, "/root".to_owned()), + (None, None) => { + return Err(format!( + "unable to find user {user}: no matching entries in passwd file" + )); + } + }; + if let Some(g) = group_spec { + gid = match g.parse::() { + Ok(n) => n, + Err(_) => groups(group) + .find(|(n, _, _)| *n == g) + .map(|(_, gid, _)| gid) + .ok_or_else(|| { + format!("unable to find group {g}: no matching entries in group file") + })?, + }; + } + let mut supplementary = vec![gid]; + if let Some(name) = name { + for (_, g, members) in groups(group) { + if members.contains(&name) && !supplementary.contains(&g) { + supplementary.push(g); + } + } + } + Ok(User { + uid, + gid, + groups: supplementary, + home: if home.is_empty() { "/".into() } else { home }, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const PASSWD: &str = + "root:x:0:0:root:/root:/bin/bash\nagent:x:1000:1000::/home/agent:/bin/bash\nbroken line\n"; + const GROUP: &str = "root:x:0:\nsudo:x:27:agent\nagent:x:1000:\ndocker:x:999:other,agent\n"; + + #[test] + fn finds_users_as_docker_does() { + assert_eq!( + find_in(Some("agent"), PASSWD, GROUP), + Ok(User { + uid: 1000, + gid: 1000, + groups: vec![1000, 27, 999], + home: "/home/agent".into() + }) + ); + // By uid, with another group. + let u = find_in(Some("1000:sudo"), PASSWD, GROUP); + assert_eq!( + u.map(|u| (u.uid, u.gid, u.groups)), + Ok((1000, 27, vec![27, 999])) + ); + // Root, also with no files at all. + for (passwd, group) in [(PASSWD, GROUP), ("", "")] { + let root = find_in(None, passwd, group); + assert_eq!( + root.map(|u| (u.uid, u.gid, u.home)), + Ok((0, 0, "/root".into())) + ); + } + // A uid no account has. + let u = find_in(Some("4242"), PASSWD, GROUP); + assert_eq!(u.map(|u| (u.uid, u.gid, u.home)), Ok((4242, 0, "/".into()))); + assert_eq!( + find_in(Some("ghost"), PASSWD, GROUP), + Err("unable to find user ghost: no matching entries in passwd file".into()) + ); + assert!(find_in(Some("agent:nogroup"), PASSWD, GROUP).is_err()); + } +} diff --git a/crates/fctl-host/Cargo.toml b/crates/fctl-host/Cargo.toml index 16db949d..860583e9 100644 --- a/crates/fctl-host/Cargo.toml +++ b/crates/fctl-host/Cargo.toml @@ -21,10 +21,12 @@ serde_json.workspace = true sha2.workspace = true tar.workspace = true hex.workspace = true +http.workspace = true tokio.workspace = true tokio-tungstenite.workspace = true toml.workspace = true tracing.workspace = true +url.workspace = true [dev-dependencies] tempfile.workspace = true diff --git a/crates/fctl-host/src/config.rs b/crates/fctl-host/src/config.rs index 4ebb71ff..2be69fda 100644 --- a/crates/fctl-host/src/config.rs +++ b/crates/fctl-host/src/config.rs @@ -3,7 +3,7 @@ //! ```toml //! server = "https://app.fctl.sh" //! name = "studio-mac" -//! driver = "auto" # apple | docker | lima | process | auto +//! driver = "auto" # apple | docker | firecracker | lima | process | auto //! capacity = 4 //! image = "ghcr.io/acme/agent:1" # unset: the published image of this version //! cpus = 4 # per sandbox, when its project sets none @@ -23,6 +23,11 @@ //! # Where `fctl host claude set-token` keeps your Claude token (unset: claude-token here). //! claude_token_file = "/run/secrets/claude-token" //! auto_update = true # update fctl to the version the control plane runs +//! +//! [firecracker] # the firecracker driver +//! 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 //! ``` //! //! The runner token lives next to it in `host-token`, and the Claude token @@ -120,6 +125,44 @@ pub struct HostConfig { /// the version the control plane runs, once it is newer than this /// host's ([`crate::update`]). pub auto_update: bool, + /// The `firecracker` driver's settings. + #[serde(skip_serializing_if = "FirecrackerConfig::is_default")] + pub firecracker: FirecrackerConfig, +} + +/// The `firecracker` driver's settings: `[firecracker]` in `host.toml`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct FirecrackerConfig { + /// Firecracker's binary. Unset: the release fctl pins, which the host + /// downloads. + pub firecracker: Option, + /// The kernel the VMs boot: a file, or an image whose `/vmlinux` it is. + /// Unset: the one hyperstructure/sandbox publishes. + pub kernel: Option, + /// `passt`, which gives the VMs their network. Unset: the one on the + /// PATH. + pub passt: Option, + /// The disk each sandbox gets, in GiB: a sparse file, which takes only + /// what the session writes. + pub disk_gb: u32, +} + +impl Default for FirecrackerConfig { + fn default() -> Self { + Self { + firecracker: None, + kernel: None, + passt: None, + disk_gb: 64, + } + } +} + +impl FirecrackerConfig { + fn is_default(&self) -> bool { + *self == Self::default() + } } impl Default for HostConfig { @@ -152,6 +195,7 @@ impl Default for HostConfig { max_build_mb: 20 * 1024, claude_token_file: None, auto_update: true, + firecracker: FirecrackerConfig::default(), } } } @@ -336,12 +380,12 @@ impl HostConfig { } /// The images and builds this host's sessions may start from. Builds - /// need a `driver` that makes sandboxes from images. - pub fn images(&self, driver_uses_images: bool) -> Images { + /// need a driver that builds images (`driver_builds`). + pub fn images(&self, driver_builds: bool) -> Images { Images { own: self.image(), allowed: self.allowed_images.clone(), - builds: if driver_uses_images { + builds: if driver_builds { self.allowed_builds.clone() } else { None diff --git a/crates/fctl-host/src/daemon.rs b/crates/fctl-host/src/daemon.rs index f2b04b54..d4e0b903 100644 --- a/crates/fctl-host/src/daemon.rs +++ b/crates/fctl-host/src/daemon.rs @@ -178,7 +178,7 @@ impl Daemon { std::fs::create_dir_all(&data)?; // What image builds left behind when the host last stopped. let _ = std::fs::remove_dir_all(data.join("builds")); - let driver = Driver::select(&cfg.driver, &data, cfg.agent_bin.clone()).await?; + let driver = Driver::select(&cfg.driver, &cfg).await?; let ctx = Arc::new(HostCtx::new(cfg, driver, token)); ctx.refresh_facts().await; tracing::info!( diff --git a/crates/fctl-host/src/driver/firecracker/assets.rs b/crates/fctl-host/src/driver/firecracker/assets.rs new file mode 100644 index 00000000..393efee7 --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/assets.rs @@ -0,0 +1,349 @@ +//! What the host needs besides images to run microVMs: Firecracker itself, +//! a kernel, and the initramfs with fctl-agent as its init. + +use super::registry::{Registry, file_digest}; +use anyhow::{Context, Result, bail}; +use sha2::{Digest, Sha256}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +/// The Firecracker the host downloads, and the SHA-256 of each +/// architecture's release archive. Older ones lack what the VMs use +/// (discard on their disks, from 1.17). +pub const FIRECRACKER_VERSION: &str = "1.17.0"; +const FIRECRACKER_ARCHIVES: [(&str, &str); 2] = [ + ( + "x86_64", + "06094a1108ae9e82aa4c23a775aa92758f53f1175d422270d9d6162cb9ade558", + ), + ( + "aarch64", + "e351ebe4f7a16b5873bbd51005d2e6767103cff4d5ebc829df2d3f95a93e2256", + ), +]; + +/// The kernel VMs boot unless `host.toml` names another: Firecracker's +/// guest configuration for Linux 6.18, built and published by +/// hyperstructure/sandbox, as `/vmlinux` in an image. +pub const KERNEL_IMAGE: &str = "ghcr.io/hyperstructure/sandbox-kernel:6.18.59"; + +/// Where the release archive of Firecracker `version` is. +fn firecracker_url(version: &str, arch: &str) -> String { + format!( + "https://github.com/firecracker-microvm/firecracker/releases/download/v{version}/firecracker-v{version}-{arch}.tgz" + ) +} + +/// The Firecracker binary the host downloads for this machine, in `bin`. +pub fn pinned_firecracker(bin: &Path) -> PathBuf { + bin.join(format!("firecracker-v{FIRECRACKER_VERSION}")) +} + +/// Downloads the pinned Firecracker into `bin`, checked against its +/// archive's SHA-256, unless it is there. +pub async fn download_firecracker( + bin: &Path, + log: &(dyn Fn(String) + Send + Sync), +) -> Result { + let path = pinned_firecracker(bin); + if path.is_file() { + return Ok(path); + } + let arch = std::env::consts::ARCH; + let Some((_, sum)) = FIRECRACKER_ARCHIVES.iter().find(|(a, _)| *a == arch) else { + bail!("Firecracker runs on x86_64 and aarch64, not {arch}"); + }; + std::fs::create_dir_all(bin)?; + let url = firecracker_url(FIRECRACKER_VERSION, arch); + log(format!("Downloading Firecracker {FIRECRACKER_VERSION}")); + let archive = bin.join(format!(".firecracker-v{FIRECRACKER_VERSION}.tgz")); + let http = fctl_client::HttpClient::new(std::time::Duration::from_secs(600)); + http.download_to( + &url, + None, + &[], + &archive, + 512 * 1024 * 1024, + std::time::Duration::from_secs(600), + ) + .await + .with_context(|| format!("downloading {url}"))?; + let result = (|| -> Result<()> { + let digest = file_digest(&archive)?; + if digest != format!("sha256:{sum}") { + bail!("{url} doesn't match the checksum fctl expects"); + } + let inside = format!( + "release-v{FIRECRACKER_VERSION}-{arch}/firecracker-v{FIRECRACKER_VERSION}-{arch}" + ); + let file = std::fs::File::open(&archive)?; + let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(file)); + for entry in tar.entries()? { + let mut entry = entry?; + if entry.path()?.to_string_lossy() == inside { + let tmp = path.with_extension("tmp"); + let mut out = std::fs::File::create(&tmp)?; + std::io::copy(&mut entry, &mut out)?; + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?; + std::fs::rename(&tmp, &path)?; + return Ok(()); + } + } + bail!("{url} has no {inside}") + })(); + let _ = std::fs::remove_file(&archive); + result.map(|()| path) +} + +/// The kernel at `kernel`: a file, or an image reference whose `/vmlinux` +/// it pulls into `dir` once. +pub async fn kernel( + kernel: &str, + dir: &Path, + log: &(dyn Fn(String) + Send + Sync), +) -> Result { + if kernel.starts_with('/') { + let path = PathBuf::from(kernel); + if !path.is_file() { + bail!("the kernel {kernel} (firecracker.kernel in host.toml) isn't there"); + } + return Ok(path); + } + let key = hex::encode(&Sha256::digest(kernel.as_bytes())[..8]); + let path = dir.join(key).join("vmlinux"); + if path.is_file() { + return Ok(path); + } + log(format!("Pulling the VMs' kernel, {kernel}")); + let registry = Registry::new(); + let image = registry.resolve(kernel, std::env::consts::ARCH).await?; + let Some(parent) = path.parent() else { + bail!("no directory for the kernel"); + }; + std::fs::create_dir_all(parent)?; + // The kernel is the image's only file; its last layer has it. + for layer in image.layers.iter().rev() { + let blob = parent.join("layer.tmp"); + registry.blob(kernel, layer, &blob).await?; + let found = extract( + &blob, + &layer.media_type, + "vmlinux", + &path.with_extension("tmp"), + ); + let _ = std::fs::remove_file(&blob); + if found? { + std::fs::rename(path.with_extension("tmp"), &path)?; + return Ok(path); + } + } + bail!("{kernel} has no /vmlinux") +} + +/// Copies the file `name` from the layer at `blob` to `to`; whether it was +/// there. +fn extract(blob: &Path, media_type: &str, name: &str, to: &Path) -> Result { + let file = std::fs::File::open(blob)?; + let reader: Box = if media_type.ends_with("gzip") { + Box::new(flate2::read::GzDecoder::new(file)) + } else { + Box::new(file) + }; + let mut tar = tar::Archive::new(reader); + for entry in tar.entries()? { + let mut entry = entry?; + let path = entry.path()?.into_owned(); + let path = path.strip_prefix("/").unwrap_or(&path); + let path = path.strip_prefix("./").unwrap_or(path); + if path == Path::new(name) && entry.header().entry_type().is_file() { + let mut out = std::fs::File::create(to)?; + std::io::copy(&mut entry, &mut out)?; + return Ok(true); + } + } + Ok(false) +} + +/// Whether the ELF binary `bytes` loads without shared libraries: the +/// initramfs has none. `None` when it isn't an ELF binary. +pub fn is_static(bytes: &[u8]) -> Option { + if bytes.get(..4)? != b"\x7fELF" || *bytes.get(4)? != 2 || *bytes.get(5)? != 1 { + // Only 64-bit little-endian binaries run here. + return None; + } + let u16_at = |at: usize| Some(u16::from_le_bytes(bytes.get(at..at + 2)?.try_into().ok()?)); + let u32_at = |at: usize| Some(u32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)); + let u64_at = |at: usize| Some(u64::from_le_bytes(bytes.get(at..at + 8)?.try_into().ok()?)); + let phoff = usize::try_from(u64_at(0x20)?).ok()?; + let phentsize = usize::from(u16_at(0x36)?); + let phnum = usize::from(u16_at(0x38)?); + // PT_INTERP names the dynamic loader. + let interp = (0..phnum).any(|i| u32_at(phoff + i * phentsize) == Some(3)); + Some(!interp) +} + +/// An archive in the `newc` format the kernel unpacks as its initramfs. +#[derive(Default)] +pub struct Cpio { + bytes: Vec, + ino: u32, +} + +impl Cpio { + fn entry(&mut self, name: &str, mode: u32, rdev: (u32, u32), data: &[u8]) { + self.ino += 1; + let size = u32::try_from(data.len()).unwrap_or(u32::MAX); + let namesize = u32::try_from(name.len() + 1).unwrap_or(u32::MAX); + let fields = [ + self.ino, mode, 0, 0, 1, 0, size, 0, 0, rdev.0, rdev.1, namesize, 0, + ]; + self.bytes.extend_from_slice(b"070701"); + for f in fields { + self.bytes.extend_from_slice(format!("{f:08x}").as_bytes()); + } + self.bytes.extend_from_slice(name.as_bytes()); + self.bytes.push(0); + self.pad(); + self.bytes.extend_from_slice(data); + self.pad(); + } + + fn pad(&mut self) { + while !self.bytes.len().is_multiple_of(4) { + self.bytes.push(0); + } + } + + pub fn dir(&mut self, name: &str) { + self.entry(name, 0o040755, (0, 0), &[]); + } + + pub fn file(&mut self, name: &str, mode: u32, data: &[u8]) { + self.entry(name, 0o100000 | mode, (0, 0), data); + } + + pub fn char_device(&mut self, name: &str, mode: u32, major: u32, minor: u32) { + self.entry(name, 0o020000 | mode, (major, minor), &[]); + } + + pub fn finish(mut self) -> Vec { + self.entry("TRAILER!!!", 0, (0, 0), &[]); + self.bytes + } +} + +/// The initramfs for `agent`, a static fctl-agent: it is the init, with a +/// console to write to and the file that tells it it's in the initramfs +/// (`fctl-agent`'s `vm::boot::MARKER`). Made in `dir` once for each agent. +pub fn initrd(agent: &Path, dir: &Path) -> Result { + let bytes = std::fs::read(agent).with_context(|| format!("reading {}", agent.display()))?; + match is_static(&bytes) { + Some(true) => {} + Some(false) => bail!( + "{} loads shared libraries, which a microVM's initramfs doesn't have: the firecracker driver needs the static fctl-agent of fctl's release archives (fctl-agent-{}-linux), or one built for {}-unknown-linux-musl (agent_bin in host.toml)", + agent.display(), + std::env::consts::ARCH, + std::env::consts::ARCH + ), + None => bail!("{} isn't a Linux binary for this machine", agent.display()), + } + let key = hex::encode(&Sha256::digest(&bytes)[..8]); + let path = dir.join(format!("{key}.cpio")); + if path.is_file() { + return Ok(path); + } + let mut cpio = Cpio::default(); + cpio.dir("dev"); + cpio.char_device("dev/console", 0o600, 5, 1); + cpio.dir("proc"); + cpio.dir("sys"); + cpio.file("fctl-initramfs", 0o644, b""); + cpio.file("init", 0o755, &bytes); + std::fs::create_dir_all(dir)?; + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, cpio.finish())?; + std::fs::rename(&tmp, &path)?; + Ok(path) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pinned_firecracker_is_for_both_architectures() { + assert_eq!( + firecracker_url("1.17.0", "aarch64"), + "https://github.com/firecracker-microvm/firecracker/releases/download/v1.17.0/firecracker-v1.17.0-aarch64.tgz" + ); + for arch in ["x86_64", "aarch64"] { + let sum = FIRECRACKER_ARCHIVES.iter().find(|(a, _)| *a == arch); + assert!(sum.is_some_and(|(_, s)| s.len() == 64), "{arch}"); + } + } + + #[test] + fn tells_static_binaries_from_dynamic_ones() { + // An ELF header with one program header at 64: PT_LOAD, or PT_INTERP. + let elf = |kind: u32| { + let mut b = vec![0u8; 64 + 56]; + b[..4].copy_from_slice(b"\x7fELF"); + b[4] = 2; + b[5] = 1; + b[0x20..0x28].copy_from_slice(&64u64.to_le_bytes()); + b[0x36..0x38].copy_from_slice(&56u16.to_le_bytes()); + b[0x38..0x3a].copy_from_slice(&1u16.to_le_bytes()); + b[64..68].copy_from_slice(&kind.to_le_bytes()); + b + }; + assert_eq!(is_static(&elf(1)), Some(true)); + assert_eq!(is_static(&elf(3)), Some(false)); + assert_eq!(is_static(b"#!/bin/sh\n"), None); + // This test's own binary, built against the system's libc. + if cfg!(all(target_os = "linux", target_env = "gnu")) + && let Ok(exe) = std::env::current_exe() + && let Ok(bytes) = std::fs::read(exe) + { + assert_eq!(is_static(&bytes), Some(false)); + } + } + + #[test] + fn writes_newc_archives() { + let mut cpio = Cpio::default(); + cpio.dir("dev"); + cpio.char_device("dev/console", 0o600, 5, 1); + cpio.file("init", 0o755, b"hello"); + let bytes = cpio.finish(); + assert_eq!(bytes.len() % 4, 0); + assert!(bytes.starts_with(b"070701")); + // The console: a character device (020600), 5:1. + let console = bytes + .windows(11) + .position(|w| w == b"dev/console") + .unwrap_or_default(); + let header = &bytes[console - 110..console]; + assert_eq!(&header[14..22], b"00002180"); + assert_eq!(&header[78..86], b"00000005"); + assert_eq!(&header[86..94], b"00000001"); + assert!(bytes.windows(5).any(|w| w == b"hello")); + assert!(bytes.windows(10).any(|w| w == b"TRAILER!!!")); + // What the system's cpio makes of it, where there is one. + if let Ok(mut child) = std::process::Command::new("cpio") + .args(["-t", "--quiet"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + { + use std::io::Write; + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(&bytes); + } + if let Ok(out) = child.wait_with_output() { + let listed = String::from_utf8_lossy(&out.stdout).into_owned(); + assert_eq!(listed, "dev\ndev/console\ninit\n"); + } + } + } +} diff --git a/crates/fctl-host/src/driver/firecracker/images.rs b/crates/fctl-host/src/driver/firecracker/images.rs new file mode 100644 index 00000000..e0a08e68 --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/images.rs @@ -0,0 +1,292 @@ +//! The images a Firecracker host keeps: for each, the root filesystem its +//! layers make (read only, shared by the sandboxes made from it) and what +//! its config says about running it; and the names that refer to them, as +//! Docker's tags do. + +use anyhow::{Context, Result}; +use fctl_domain::image::ImageRef; +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +/// An image here. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Image { + /// Its config's digest, as Docker's image ID. + pub id: String, + /// The name it was pulled by. + pub reference: String, + #[serde(default)] + pub user: Option, + #[serde(default)] + pub env: Vec, + #[serde(default)] + pub workdir: Option, + #[serde(default)] + pub labels: BTreeMap, + /// What its layers unpacked to. + #[serde(default)] + pub files: u64, + #[serde(default)] + pub bytes: u64, + pub pulled_ms: i64, +} + +/// A reference as the store keeps it: `ubuntu` is +/// `docker.io/library/ubuntu:latest`. +pub fn canonical(reference: &str) -> Option { + let r = ImageRef::parse(reference)?; + Some(match (&r.digest, &r.tag) { + (Some(d), Some(t)) => format!("{}:{t}@{d}", r.name), + (Some(d), None) => format!("{}@{d}", r.name), + (None, Some(t)) => format!("{}:{t}", r.name), + (None, None) => format!("{}:latest", r.name), + }) +} + +/// The images under `dir`: `refs.json`, and a directory for each image +/// named after its ID's hex digits, with `image.json` and `rootfs.ext4`. +/// What changes names or removes images holds [`Store::lock`]. +#[derive(Clone, Debug)] +pub struct Store { + pub dir: PathBuf, +} + +impl Store { + pub fn new(dir: PathBuf) -> Self { + Self { dir } + } + + /// Waits for the store's lock, which the returned file holds until it + /// goes: between the host and `fctl host image pull` too, which run in + /// processes of their own. + pub fn lock(&self) -> Result { + std::fs::create_dir_all(&self.dir)?; + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(self.dir.join(".lock"))?; + file.lock() + .with_context(|| format!("locking {}", self.dir.display()))?; + Ok(file) + } + + fn refs_path(&self) -> PathBuf { + self.dir.join("refs.json") + } + + pub fn refs(&self) -> BTreeMap { + std::fs::read(self.refs_path()) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() + } + + fn save_refs(&self, refs: &BTreeMap) -> Result<()> { + std::fs::create_dir_all(&self.dir)?; + let tmp = self + .refs_path() + .with_extension(format!("{}.tmp", std::process::id())); + std::fs::write(&tmp, serde_json::to_vec_pretty(refs)?)?; + std::fs::rename(&tmp, self.refs_path())?; + Ok(()) + } + + /// The directory of the image `id`. + pub fn image_dir(&self, id: &str) -> PathBuf { + let hex = id.split_once(':').map_or(id, |(_, h)| h); + let safe: String = hex.chars().filter(char::is_ascii_alphanumeric).collect(); + self.dir.join(safe) + } + + pub fn rootfs(&self, id: &str) -> PathBuf { + self.image_dir(id).join("rootfs.ext4") + } + + /// The image `id`, when its root filesystem is here. + pub fn image(&self, id: &str) -> Option { + let dir = self.image_dir(id); + if !dir.join("rootfs.ext4").is_file() { + return None; + } + let bytes = std::fs::read(dir.join("image.json")).ok()?; + serde_json::from_slice(&bytes).ok() + } + + /// The image `reference` names here. + pub fn lookup(&self, reference: &str) -> Option { + let key = canonical(reference)?; + let id = self.refs().get(&key)?.clone(); + self.image(&id) + } + + /// Keeps `image`, whose root filesystem is at `rootfs`, and names it + /// `reference`. + pub fn add(&self, image: &Image, rootfs: &Path) -> Result<()> { + let dir = self.image_dir(&image.id); + let tmp = dir.with_extension("new"); + let _ = std::fs::remove_dir_all(&tmp); + std::fs::create_dir_all(&tmp)?; + std::fs::rename(rootfs, tmp.join("rootfs.ext4"))?; + std::fs::write(tmp.join("image.json"), serde_json::to_vec_pretty(image)?)?; + let _ = std::fs::remove_dir_all(&dir); + std::fs::rename(&tmp, &dir)?; + self.tag(&image.reference, &image.id) + } + + /// Names the image `id` `reference`, in place of what that named (with + /// the lock held). + pub fn tag(&self, reference: &str, id: &str) -> Result<()> { + let key = canonical(reference) + .with_context(|| format!("{reference} isn't an image reference"))?; + let mut refs = self.refs(); + refs.insert(key, id.to_owned()); + self.save_refs(&refs) + } + + /// Takes the name `reference` away; returns the image it named (with + /// the lock held). + pub fn untag(&self, reference: &str) -> Result> { + let Some(key) = canonical(reference) else { + return Ok(None); + }; + let mut refs = self.refs(); + let id = refs.remove(&key); + if id.is_some() { + self.save_refs(&refs)?; + } + Ok(id) + } + + /// The names of `repository`'s images (`repository:tag`). + pub fn names(&self, repository: &str) -> Vec { + let Some(name) = ImageRef::parse(repository).map(|r| r.name) else { + return Vec::new(); + }; + self.refs() + .into_keys() + .filter(|k| { + k.strip_prefix(&name) + .and_then(|rest| rest.strip_prefix(':')) + .is_some_and(|tag| !tag.is_empty() && !tag.contains('@')) + }) + .collect() + } + + /// Whether a name refers to the image `id`. + pub fn named(&self, id: &str) -> bool { + self.refs().values().any(|v| v == id) + } + + /// Removes the image `id`'s files. + pub fn remove(&self, id: &str) -> Result<()> { + let dir = self.image_dir(id); + match std::fs::remove_dir_all(&dir) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + Err(e).with_context(|| format!("removing {}", dir.display())) + } + _ => Ok(()), + } + } + + /// The IDs of the images here. + pub fn ids(&self) -> Vec { + let Ok(entries) = std::fs::read_dir(&self.dir) else { + return Vec::new(); + }; + entries + .flatten() + .filter(|e| e.path().join("image.json").is_file()) + .filter_map(|e| { + let bytes = std::fs::read(e.path().join("image.json")).ok()?; + serde_json::from_slice::(&bytes).ok().map(|i| i.id) + }) + .collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn references_are_kept_as_docker_reads_them() { + assert_eq!( + canonical("ubuntu").as_deref(), + Some("docker.io/library/ubuntu:latest") + ); + assert_eq!( + canonical("ghcr.io/hyperstructure/sandbox:0.26.0").as_deref(), + Some("ghcr.io/hyperstructure/sandbox:0.26.0") + ); + let pinned = format!("ghcr.io/acme/agent@sha256:{}", "a".repeat(64)); + assert_eq!(canonical(&pinned), Some(pinned.clone())); + assert_eq!(canonical("-not an image"), None); + } + + #[test] + fn names_refer_to_images_as_tags_do() -> Result<()> { + let dir = tempfile::tempdir()?; + let store = Store::new(dir.path().join("images")); + let image = Image { + id: format!("sha256:{}", "1".repeat(64)), + reference: "ghcr.io/hyperstructure/sandbox:0.26.0".into(), + user: Some("agent".into()), + pulled_ms: 1, + ..Image::default() + }; + let rootfs = dir.path().join("rootfs.tmp"); + std::fs::write(&rootfs, b"ext4")?; + store.add(&image, &rootfs)?; + assert_eq!( + store.lookup("ghcr.io/hyperstructure/sandbox:0.26.0"), + Some(image.clone()) + ); + assert_eq!(store.lookup("ghcr.io/hyperstructure/sandbox:latest"), None); + store.tag("ghcr.io/hyperstructure/sandbox:latest", &image.id)?; + store.tag("ghcr.io/hyperstructure/sandbox", &image.id)?; + assert_eq!( + store.names("ghcr.io/hyperstructure/sandbox"), + [ + "ghcr.io/hyperstructure/sandbox:0.26.0", + "ghcr.io/hyperstructure/sandbox:latest" + ] + ); + assert!( + store + .names("ghcr.io/hyperstructure/sandbox-kernel") + .is_empty() + ); + assert_eq!( + store.untag("ghcr.io/hyperstructure/sandbox:0.26.0")?, + Some(image.id.clone()) + ); + assert!(store.named(&image.id)); + assert_eq!( + store.untag("ghcr.io/hyperstructure/sandbox:latest")?, + Some(image.id.clone()) + ); + assert!(!store.named(&image.id)); + assert_eq!(store.ids(), std::slice::from_ref(&image.id)); + store.remove(&image.id)?; + assert_eq!(store.image(&image.id), None); + assert!(store.ids().is_empty()); + Ok(()) + } + + #[test] + fn one_process_at_a_time_holds_the_lock() -> Result<()> { + let dir = tempfile::tempdir()?; + let store = Store::new(dir.path().join("images")); + let held = store.lock()?; + // Another open of the file, as another process's would be. + let other = std::fs::OpenOptions::new() + .write(true) + .open(store.dir.join(".lock"))?; + assert!(other.try_lock().is_err()); + drop(held); + assert!(other.try_lock().is_ok()); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/firecracker/mod.rs b/crates/fctl-host/src/driver/firecracker/mod.rs new file mode 100644 index 00000000..191faa10 --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/mod.rs @@ -0,0 +1,1191 @@ +//! The `firecracker` driver (Linux hosts with KVM): each sandbox is a +//! Firecracker microVM with a kernel of its own (ADR 0070). +//! +//! - **Images** are pulled from their registries as Docker pulls them +//! ([`registry`]), and their layers unpacked onto an ext4 filesystem in a +//! short-lived VM ([`fctl_proto::vm::Mode::Unpack`]), as root there, so +//! that their owners and modes stay theirs and none of their files touch +//! the host's filesystem. The sandboxes made from an image share its +//! filesystem, read only ([`images`]). +//! - **A sandbox** is a directory with the VM's own disk, a sparse ext4 file +//! that takes what the session writes (`disk_gb` at most), which the +//! VM's init lays over the image's filesystem. Stopping the VM keeps it, +//! 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`]). +//! - **The host runs programs** in the VM through its vsock, as `docker +//! exec` would ([`vsock`]). + +pub mod assets; +pub mod images; +pub mod registry; +pub mod vm; +pub mod vsock; + +use super::{ + AGENT_PATH, AgentIo, DiskSpot, Running, Sandbox, SandboxInfo, SandboxSpec, attach_script, + serve_script, +}; +use crate::config::{FirecrackerConfig, HostConfig}; +use crate::driver::ImageInfo; +use anyhow::{Context, Result, bail}; +use fctl_proto::runner::DriverInfo; +use fctl_proto::vm::{Boot, Exec, Mode}; +use images::{Image, Store}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; +use vm::{Drive, Spec, Vm}; + +/// The size of an image's filesystem: a sparse file, which takes only what +/// the image holds. +const IMAGE_FS_GB: u64 = 64; + +/// What a sandbox was made from, in `sandbox.json`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Record { + /// The image's ID. + image: String, + /// The name it was made from. + reference: String, + created_ms: i64, + /// The fctl-agent its VM last booted with (the start of its SHA-256). + #[serde(default)] + agent: Option, +} + +type Log<'a> = &'a (dyn Fn(String) + Send + Sync); + +pub struct FirecrackerDriver { + host: HostConfig, + root: PathBuf, + store: Store, + /// One for each image being pulled and each sandbox being prepared. + locks: Mutex>>>, +} + +/// Finds `program` on the PATH, or in the directories where Linux keeps +/// what administrators run, which users' PATHs may lack. +pub fn find_program(program: &str) -> Option { + if program.contains('/') { + let p = PathBuf::from(program); + return p.is_file().then_some(p); + } + super::process::which(program).or_else(|| { + ["/usr/sbin", "/sbin", "/usr/local/sbin", "/usr/bin", "/bin"] + .iter() + .map(|d| Path::new(d).join(program)) + .find(|p| p.is_file()) + }) +} + +/// Why this host can't run KVM VMs, if it can't. +fn kvm_problem() -> Option { + match std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") { + Ok(_) => None, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Some( + "this machine has no /dev/kvm: Firecracker needs a CPU with virtualization turned on, or nested virtualization in a VM".into(), + ), + Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => Some( + "this user may not use /dev/kvm: `sudo usermod -aG kvm $USER`, then log in again".into(), + ), + Err(e) => Some(format!("opening /dev/kvm: {e}")), + } +} + +/// Removes what is in `dir` for more than two days: what pulls left that +/// stopped halfway, when the host did. +fn remove_stale(dir: &Path) { + let Ok(entries) = std::fs::read_dir(dir) else { + return; + }; + for entry in entries.flatten() { + let old = entry + .metadata() + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.elapsed().ok()) + .is_some_and(|age| age > Duration::from_secs(2 * 24 * 60 * 60)); + if old { + let _ = std::fs::remove_dir_all(entry.path()); + } + } +} + +/// Makes an ext4 filesystem in a new sparse file of `gb` GiB at `path`, +/// whose root is root's, labelled `label`, with a journal or not. It never +/// writes over a file there, a sandbox's disk say. +async fn make_fs(path: &Path, gb: u64, label: &str, journal: bool) -> Result<()> { + let mkfs = find_program("mkfs.ext4").context("mkfs.ext4 is not installed (e2fsprogs)")?; + let file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .with_context(|| format!("making {}", path.display()))?; + file.set_len(gb * 1024 * 1024 * 1024)?; + drop(file); + let features = if journal { + "has_journal" + } else { + "^has_journal" + }; + let path_s = path.display().to_string(); + super::run_cmd( + &mkfs.display().to_string(), + &[ + "-q", + "-F", + "-L", + label, + "-m", + "0", + "-O", + features, + "-E", + "root_owner=0:0,lazy_itable_init=1,lazy_journal_init=1", + &path_s, + ], + ) + .await + .with_context(|| format!("making a filesystem in {}", path.display()))?; + Ok(()) +} + +impl FirecrackerDriver { + pub fn new(host: &HostConfig) -> Self { + let root = host.data_dir().join("firecracker"); + Self { + host: host.clone(), + store: Store::new(root.join("images")), + root, + locks: Mutex::new(HashMap::new()), + } + } + + /// The image store's lock ([`Store::lock`]), held while names move + /// between images, images go, and a new sandbox records the image it is + /// made from, so that none goes from under it. + async fn lock_images(&self) -> Result { + let store = self.store.clone(); + tokio::task::spawn_blocking(move || store.lock()).await? + } + + /// Makes the driver's directory, which only this user may read: it + /// holds the sandboxes' disks. + fn make_root(&self) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + std::fs::create_dir_all(&self.root) + .with_context(|| format!("making {}", self.root.display()))?; + let mode = std::fs::metadata(&self.root)?.permissions().mode(); + if mode & 0o077 != 0 { + std::fs::set_permissions(&self.root, std::fs::Permissions::from_mode(0o700))?; + } + Ok(()) + } + + fn cfg(&self) -> &FirecrackerConfig { + &self.host.firecracker + } + + fn lock(&self, key: &str) -> Arc> { + let mut locks = self.locks.lock().unwrap_or_else(PoisonError::into_inner); + locks.retain(|_, l| Arc::strong_count(l) > 1); + locks.entry(key.to_owned()).or_default().clone() + } + + fn sandboxes(&self) -> PathBuf { + self.root.join("sandboxes") + } + + fn vm(&self, name: &str) -> Result { + Vm::new(self.sandboxes().join(name)) + } + + fn record(&self, name: &str) -> Option { + let bytes = std::fs::read(self.sandboxes().join(name).join("sandbox.json")).ok()?; + serde_json::from_slice(&bytes).ok() + } + + /// Writes the record whole or not at all: a sandbox whose record can't + /// be read is one the host can't start. + fn save_record(&self, name: &str, record: &Record) -> Result<()> { + let path = self.sandboxes().join(name).join("sandbox.json"); + let tmp = path.with_extension(format!("{}.tmp", std::process::id())); + std::fs::write(&tmp, serde_json::to_vec_pretty(record)?)?; + std::fs::rename(&tmp, &path)?; + Ok(()) + } + + /// `passt`: the configured one, or the one installed. + fn passt(&self) -> Option { + match &self.cfg().passt { + Some(p) => p.is_file().then(|| p.clone()), + None => find_program("passt"), + } + } + + /// Firecracker: the configured one, or the pinned release, downloaded + /// once. + async fn firecracker(&self, log: Log<'_>) -> Result { + match &self.cfg().firecracker { + Some(p) if p.is_file() => Ok(p.clone()), + Some(p) => bail!( + "{} (firecracker.firecracker in host.toml) isn't there", + p.display() + ), + None => { + self.make_root()?; + let lock = self.lock("firecracker"); + let _held = lock.lock().await; + assets::download_firecracker(&self.root.join("bin"), log).await + } + } + } + + async fn kernel(&self, log: Log<'_>) -> Result { + let kernel = self + .cfg() + .kernel + .clone() + .unwrap_or_else(|| assets::KERNEL_IMAGE.into()); + self.make_root()?; + let lock = self.lock("kernel"); + let _held = lock.lock().await; + assets::kernel(&kernel, &self.root.join("kernels"), log).await + } + + /// The initramfs, and the start of the SHA-256 of the fctl-agent in it. + async fn initrd(&self) -> Result<(PathBuf, String)> { + let agent = crate::agentbin::linux_agent(&self.host) + .await + .context("getting fctl-agent for the VMs")?; + self.make_root()?; + let dir = self.root.join("initrd"); + let lock = self.lock("initrd"); + let _held = lock.lock().await; + tokio::task::spawn_blocking(move || { + let path = assets::initrd(&agent, &dir)?; + let key = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + Ok((path, key)) + }) + .await? + } + + pub async fn probe(&self) -> DriverInfo { + let info = |available: bool, detail: String, version: Option| DriverInfo { + name: "firecracker".into(), + available, + isolation: "vm".into(), + version, + detail: Some(detail), + }; + if !cfg!(target_os = "linux") { + return info( + false, + "Firecracker needs a Linux host with KVM".into(), + None, + ); + } + if !matches!(std::env::consts::ARCH, "x86_64" | "aarch64") { + return info( + false, + format!( + "Firecracker runs on x86_64 and aarch64, not {}", + std::env::consts::ARCH + ), + None, + ); + } + if let Some(why) = kvm_problem() { + return info(false, why, None); + } + if self.passt().is_none() { + return info( + false, + "passt is not installed (`sudo apt install passt`, or `sudo dnf install passt`): it gives the VMs their network".into(), + None, + ); + } + if find_program("mkfs.ext4").is_none() { + return info(false, "mkfs.ext4 is not installed (e2fsprogs)".into(), None); + } + let binary = match &self.cfg().firecracker { + Some(p) if !p.is_file() => { + return info( + false, + format!( + "{} (firecracker.firecracker in host.toml) isn't there", + p.display() + ), + None, + ); + } + Some(p) => Some(p.clone()), + None => { + Some(assets::pinned_firecracker(&self.root.join("bin"))).filter(|p| p.is_file()) + } + }; + let version = match &binary { + Some(b) => super::run_cmd(&b.display().to_string(), &["--version"]) + .await + .ok() + .and_then(|out| { + out.lines().next().map(|l| { + l.trim() + .trim_start_matches("Firecracker ") + .trim_start_matches('v') + .to_owned() + }) + }), + None => None, + }; + let mut later = Vec::new(); + if binary.is_none() { + later.push(format!("Firecracker {}", assets::FIRECRACKER_VERSION)); + } + match self.cfg().kernel.as_deref() { + Some(k) if k.starts_with('/') && !Path::new(k).is_file() => { + return info( + false, + format!("the kernel {k} (firecracker.kernel in host.toml) isn't there"), + version, + ); + } + Some(k) if k.starts_with('/') => {} + _ if self.root.join("kernels").is_dir() => {} + _ => later.push("the VMs' kernel".into()), + } + let detail = match later.as_slice() { + [] => "ready".into(), + [one] => format!("ready ({one} downloads with the first sandbox)"), + [a, b] => format!("ready ({a} and {b} download with the first sandbox)"), + _ => "ready".into(), + }; + info( + true, + detail, + version.or(Some(assets::FIRECRACKER_VERSION.into())), + ) + } + + /// Where the VMs' files are: in the host's data directory. + pub fn disk_spot(&self, data_dir: &Path) -> DiskSpot { + DiskSpot::Dir(if self.root.is_dir() { + self.root.clone() + } else { + data_dir.to_owned() + }) + } + + // Images. + + pub async fn has_image(&self, image: &str) -> bool { + self.store.lookup(image).is_some() + } + + pub async fn image(&self, image: &str) -> Result> { + Ok(self.store.lookup(image).map(|i| ImageInfo { + id: i.id, + labels: i.labels, + })) + } + + pub async fn image_size(&self, image: &str) -> Option { + let image = self.store.lookup(image)?; + use std::os::unix::fs::MetadataExt; + let meta = std::fs::metadata(self.store.rootfs(&image.id)).ok()?; + Some(meta.blocks() * 512) + } + + pub async fn tag_image(&self, image: &str, name: &str) -> Result<()> { + let _images = self.lock_images().await?; + let here = self + .store + .lookup(image) + .with_context(|| format!("{image} is not on this host"))?; + self.store.tag(name, &here.id) + } + + pub async fn images(&self, repository: &str) -> Result> { + Ok(self.store.names(repository)) + } + + /// The IDs of the images the sandboxes here were made from. + fn images_in_use(&self) -> Vec { + let Ok(entries) = std::fs::read_dir(self.sandboxes()) else { + return Vec::new(); + }; + entries + .flatten() + .filter_map(|e| self.record(&e.file_name().to_string_lossy())) + .map(|r| r.image) + .collect() + } + + /// Removes the name `image`, and the image once no name refers to it, + /// without force: as Docker, it keeps the last name of an image that a + /// sandbox uses, and fails. + pub async fn remove_image(&self, image: &str) -> Result<()> { + let _images = self.lock_images().await?; + let here = self + .store + .lookup(image) + .with_context(|| format!("{image} is not on this host"))?; + let names = self + .store + .refs() + .values() + .filter(|id| **id == here.id) + .count(); + if names <= 1 && self.images_in_use().contains(&here.id) { + bail!("a sandbox uses {image}"); + } + self.store.untag(image)?; + if !self.store.named(&here.id) { + self.store.remove(&here.id)?; + } + Ok(()) + } + + /// Removes the images no name refers to and no sandbox uses: what a + /// newer pull of their name left. + fn remove_unused(&self) { + let used = self.images_in_use(); + for id in self.store.ids() { + if !self.store.named(&id) + && !used.contains(&id) + && let Err(e) = self.store.remove(&id) + { + tracing::warn!("removing the image {id}: {e:#}"); + } + } + } + + /// Pulls `image`; `progress` prints what it does. + pub async fn pull(&self, image: &str, progress: bool) -> Result<()> { + let say = |line: String| { + if progress { + println!("{line}"); + } else { + tracing::info!("{line}"); + } + }; + self.pull_with(image, &say).await + } + + /// Pulls `image`, or `fallback` when `image` can't be pulled and isn't + /// here either; returns the image it pulled. + pub async fn pull_or_fallback( + &self, + image: &str, + fallback: Option<&str>, + progress: bool, + log: Log<'_>, + ) -> Result { + let error = match self.pull(image, progress).await { + Ok(()) => return Ok(image.to_owned()), + Err(e) => e, + }; + let Some(fallback) = fallback else { + return Err(error); + }; + if self.has_image(image).await { + return Err(error); + } + log(format!( + "{image} can't be pulled; pulling {fallback} instead" + )); + match self.pull(fallback, progress).await { + Ok(()) => Ok(fallback.to_owned()), + Err(_) => Err(error.context(format!( + "{image} can't be pulled, and neither can {fallback}" + ))), + } + } + + /// Pulls `image` from its registry: only its manifest when the image it + /// names is here, else its layers too, which a VM unpacks. + async fn pull_with(&self, image: &str, log: Log<'_>) -> Result<()> { + let key = images::canonical(image) + .with_context(|| format!("{image} isn't an image reference"))?; + self.make_root()?; + let lock = self.lock(&format!("pull {key}")); + let _held = lock.lock().await; + let registry = registry::Registry::new(); + let resolved = registry.resolve(image, std::env::consts::ARCH).await?; + if self.store.image(&resolved.id).is_some() { + let _images = self.lock_images().await?; + self.store.tag(image, &resolved.id)?; + self.remove_unused(); + return Ok(()); + } + let total: u64 = resolved.layers.iter().map(|l| l.size).sum(); + log(format!( + "Pulling {image}: {} layers, {} MB", + resolved.layers.len(), + total.div_ceil(1_000_000) + )); + // A directory of this pull's own: another pull of the same image, by + // another name or in another process, has another. + remove_stale(&self.root.join("downloads")); + let downloads = self.root.join("downloads").join(format!( + "{}-{}", + hex::encode(&Sha256::digest(resolved.id.as_bytes())[..8]), + hex::encode(fctl_domain::random_bytes::<6>()) + )); + let result = async { + let (rootfs, files, bytes) = self + .download_and_unpack(image, ®istry, &resolved, &downloads, log) + .await?; + let config = resolved.config.clone(); + let pulled = Image { + id: resolved.id.clone(), + reference: key, + user: config.user.filter(|u| !u.is_empty()), + env: config.env.unwrap_or_default(), + workdir: config.working_dir.filter(|w| !w.is_empty()), + labels: config.labels.unwrap_or_default(), + files, + bytes, + pulled_ms: vsock::now_ms(), + }; + let _images = self.lock_images().await?; + // Another pull may have brought the same image meanwhile, which + // sandboxes may use already. + if self.store.image(&pulled.id).is_some() { + self.store.tag(image, &pulled.id)?; + } else { + self.store.add(&pulled, &rootfs)?; + } + self.remove_unused(); + Ok::<_, anyhow::Error>((files, bytes)) + } + .await; + let _ = std::fs::remove_dir_all(&downloads); + let (files, bytes) = result?; + log(format!( + "Pulled {image}: {files} files, {} MB", + bytes.div_ceil(1_000_000) + )); + Ok(()) + } + + async fn download_and_unpack( + &self, + image: &str, + registry: ®istry::Registry, + resolved: ®istry::Resolved, + downloads: &Path, + log: Log<'_>, + ) -> Result<(PathBuf, u64, u64)> { + std::fs::create_dir_all(downloads)?; + let mut files = Vec::new(); + for (i, layer) in resolved.layers.iter().enumerate() { + let path = downloads.join(format!("layer-{i}")); + registry.blob(image, layer, &path).await?; + files.push(path); + } + log(format!("Unpacking {image} in a VM")); + let rootfs = downloads.join("rootfs.ext4"); + // What a pull that stopped halfway left. + let _ = std::fs::remove_file(&rootfs); + make_fs(&rootfs, IMAGE_FS_GB, "fctl-image", false).await?; + let layers: Vec = resolved + .layers + .iter() + .map(|l| fctl_proto::vm::Layer { + media_type: l.media_type.clone(), + size: l.size, + }) + .collect(); + let (files_n, bytes) = self.unpack(&rootfs, &layers, &files, log).await?; + Ok((rootfs, files_n, bytes)) + } + + /// Unpacks `layers`, the files `blobs`, onto the filesystem `rootfs` + /// in a VM booted for it; what it wrote: files and bytes. + async fn unpack( + &self, + rootfs: &Path, + layers: &[fctl_proto::vm::Layer], + blobs: &[PathBuf], + log: Log<'_>, + ) -> Result<(u64, u64)> { + let firecracker = self.firecracker(log).await?; + let kernel = self.kernel(log).await?; + let (initrd, _) = self.initrd().await?; + let name = format!( + "fctl-unpack-{}", + hex::encode(fctl_domain::random_bytes::<6>()) + ); + 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?; + let result = async { + vm.wait_ready().await?; + let within = + registry::LAYER_TIME * u32::try_from(blobs.len().max(1)).unwrap_or(u32::MAX); + vsock::unpack(&vm.vsock(), layers, blobs, within).await + } + .await; + let result = result.map_err(|e| { + let tail = vm.console_tail(); + if tail.is_empty() { + e + } else { + e.context(format!("the VM's console said:\n{tail}")) + } + }); + // It powers off once done. + vm.stop().await; + let _ = std::fs::remove_dir_all(&vm.dir); + result + } + + // Sandboxes. + + pub async fn exists(&self, name: &str) -> Result { + Ok(self.record(name).is_some()) + } + + /// The image a new sandbox starts from: `spec.image`, pulled when it + /// isn't here, else `spec.fallback_image`. + async fn image_for(&self, spec: &SandboxSpec, log: Log<'_>) -> Result { + if let Some(image) = self.store.lookup(&spec.image) { + return Ok(image); + } + let error = match self.pull_with(&spec.image, log).await { + Ok(()) => { + return self + .store + .lookup(&spec.image) + .with_context(|| format!("{} was pulled but isn't here", spec.image)); + } + Err(e) => e, + }; + let missing = format!("{} is not on this host and can't be pulled", spec.image); + let Some(fallback) = &spec.fallback_image else { + return Err(error.context(missing)); + }; + log(format!("{missing}; starting from {fallback} instead")); + if let Some(image) = self.store.lookup(fallback) { + return Ok(image); + } + self.pull_with(fallback, log) + .await + .map_err(|_| error.context(missing.clone()))?; + self.store.lookup(fallback).context(missing) + } + + /// Creates the sandbox, or starts the one there, and waits for its VM. + pub async fn ensure(&self, spec: &SandboxSpec, log: Log<'_>) -> Result { + let sb = Sandbox { + name: spec.name.clone(), + root: None, + }; + self.make_root()?; + let lock = self.lock(&format!("sandbox {}", spec.name)); + let _held = lock.lock().await; + let vm = self.vm(&spec.name)?; + if vm.running() { + let socket = vm.vsock(); + let answers = tokio::time::timeout(Duration::from_secs(10), vsock::hello(&socket)); + if matches!(answers.await, Ok(Ok(_))) { + return Ok(sb); + } + log(format!( + "Starting the sandbox {} again: its VM doesn't answer", + spec.name + )); + vm.kill().await; + } + let mut record = match self.record(&spec.name) { + Some(record) => { + log(format!("Starting the existing sandbox {}", spec.name)); + record + } + None => { + log(format!( + "Creating sandbox {} from {}", + spec.name, spec.image + )); + self.create(spec, &vm, log).await? + } + }; + // A sandbox whose making stopped after its record has no disk yet. + if !vm.dir.join("disk.ext4").exists() { + self.make_disk(&vm).await?; + } + let image = self.store.image(&record.image).with_context(|| { + format!( + "the image {} that {} was made from is gone", + record.reference, spec.name + ) + })?; + let firecracker = self.firecracker(log).await?; + let kernel = self.kernel(log).await?; + let (initrd, agent) = self.initrd().await?; + let passt = self + .passt() + .context("passt is not installed: it gives the VMs their network")?; + let boot = Spec { + kernel, + initrd, + boot: Boot { + mode: Mode::Sandbox, + name: spec.name.clone(), + time_ms: Some(vsock::now_ms()), + }, + drives: vec![ + Drive { + path: self.store.rootfs(&image.id), + writable: false, + }, + Drive { + path: vm.dir.join("disk.ext4"), + writable: true, + }, + ], + cpus: spec.cpus, + memory_mb: spec.memory_mb, + network: true, + }; + vm.start(&boot, &firecracker, Some(&passt)).await?; + vm.wait_ready().await?; + record.agent = Some(agent); + self.save_record(&spec.name, &record)?; + Ok(sb) + } + + /// A new sandbox's directory and record, which come before its disk + /// ([`make_disk`](Self::make_disk)), so that a disk is never without a + /// record: a disk without one is a sandbox whose record something else + /// removed, which the host leaves alone. + async fn create(&self, spec: &SandboxSpec, vm: &Vm, log: Log<'_>) -> Result { + if vm.dir.join("disk.ext4").exists() { + bail!( + "{} has a disk but no record of the image it was made from ({} is missing), so the host leaves it as it is", + spec.name, + vm.dir.join("sandbox.json").display() + ); + } + let pulled = self.image_for(spec, log).await?; + // Until the record says which image the sandbox has, nothing removes it. + let _images = self.lock_images().await?; + let image = self + .store + .image(&pulled.id) + .with_context(|| format!("{} went as the sandbox was made", pulled.reference))?; + self.make_root()?; + std::fs::create_dir_all(&vm.dir)?; + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&vm.dir, std::fs::Permissions::from_mode(0o700)); + let record = Record { + image: image.id.clone(), + reference: image.reference.clone(), + created_ms: vsock::now_ms(), + agent: None, + }; + self.save_record(&spec.name, &record)?; + Ok(record) + } + + /// The sandbox's own disk, made under another name and then put in + /// place, so that one that stopped halfway is never booted. + async fn make_disk(&self, vm: &Vm) -> Result<()> { + let disk = vm.dir.join("disk.ext4"); + let new = vm.dir.join("disk.ext4.new"); + let _ = std::fs::remove_file(&new); + make_fs( + &new, + u64::from(self.cfg().disk_gb.max(1)), + "fctl-disk", + true, + ) + .await?; + std::fs::rename(&new, &disk)?; + Ok(()) + } + + /// How programs run in the sandbox `name`: as its image says. + fn exec_for(&self, name: &str, argv: Vec) -> Exec { + let image = self + .record(name) + .and_then(|r| self.store.image(&r.image)) + .unwrap_or_default(); + Exec { + argv, + user: image.user, + env: image.env, + cwd: image.workdir, + ..Exec::default() + } + } + + fn sh(&self, name: &str, script: &str) -> Exec { + self.exec_for(name, vec!["sh".into(), "-c".into(), script.into()]) + } + + pub async fn install_agent(&self, sb: &Sandbox, binary: &Path) -> Result<()> { + // The VM's init put its own fctl-agent in place as it booted: the + // host's, unless the host was updated since. + let bytes = tokio::fs::read(binary).await?; + let key = hex::encode(&Sha256::digest(&bytes)[..8]); + if self.record(&sb.name).and_then(|r| r.agent) == Some(key.clone()) { + return Ok(()); + } + let vm = self.vm(&sb.name)?; + let exec = Exec { + argv: vec![ + "sh".into(), + "-c".into(), + format!( + "mkdir -p /opt/fctl/bin && cat > {AGENT_PATH}.new && chmod 755 {AGENT_PATH}.new && mv -f {AGENT_PATH}.new {AGENT_PATH}" + ), + ], + user: Some("root".into()), + cwd: Some("/".into()), + ..self.sh(&sb.name, "") + }; + let out = vsock::run(&vm.vsock(), exec, Some(&bytes)).await?; + if out.code != 0 { + bail!( + "copying fctl-agent into the sandbox failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ); + } + if let Some(mut record) = self.record(&sb.name) { + record.agent = Some(key); + self.save_record(&sb.name, &record)?; + } + Ok(()) + } + + pub async fn start_agent(&self, sb: &Sandbox) -> Result<()> { + let vm = self.vm(&sb.name)?; + vsock::detach(&vm.vsock(), self.sh(&sb.name, &serve_script(AGENT_PATH))).await + } + + pub async fn attach(&self, sb: &Sandbox) -> Result { + let vm = self.vm(&sb.name)?; + let started = + vsock::start(&vm.vsock(), self.sh(&sb.name, &attach_script(AGENT_PATH))).await?; + // Why an attach failed, in the host's log. + let name = sb.name.clone(); + let mut stderr = started.stderr; + tokio::spawn(async move { + use tokio::io::AsyncBufReadExt; + let mut lines = tokio::io::BufReader::new(&mut stderr).lines(); + while let Ok(Some(line)) = lines.next_line().await { + if !line.trim().is_empty() { + tracing::warn!("attaching to {name}: {}", line.trim()); + } + } + }); + Ok(AgentIo { + reader: Box::new(started.stdout), + writer: Box::new(started.stdin), + child: None, + }) + } + + pub async fn exec(&self, sb: &Sandbox, script: &str) -> Result { + let vm = self.vm(&sb.name)?; + let out = tokio::time::timeout( + super::COMMAND_TIMEOUT, + vsock::run(&vm.vsock(), self.sh(&sb.name, script), None), + ) + .await + .map_err(|_| super::TimedOut { + command: format!("sh -c {script} in {}", sb.name), + after: super::COMMAND_TIMEOUT, + })??; + if out.code != 0 { + bail!("{}", String::from_utf8_lossy(&out.stderr).trim()); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) + } + + pub async fn spawn(&self, sb: &Sandbox, script: &str) -> Result { + let vm = self.vm(&sb.name)?; + let started = vsock::start(&vm.vsock(), self.sh(&sb.name, script)).await?; + Ok(Running::vm(started)) + } + + 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; + Ok(()) + } + + pub async fn remove(&self, sb: &Sandbox) -> Result<()> { + let lock = self.lock(&format!("sandbox {}", sb.name)); + let _held = lock.lock().await; + self.vm(&sb.name)?.remove().await?; + let _images = self.lock_images().await?; + self.remove_unused(); + Ok(()) + } + + pub async fn list(&self) -> Result> { + let Ok(entries) = std::fs::read_dir(self.sandboxes()) else { + return Ok(Vec::new()); + }; + let mut out = Vec::new(); + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if !name.starts_with("fctl-") || self.record(&name).is_none() { + continue; + } + let running = self.vm(&name).is_ok_and(|vm| vm.running()); + out.push(SandboxInfo { name, running }); + } + Ok(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn driver(dir: &Path) -> FirecrackerDriver { + let host = HostConfig { + data_dir: Some(dir.to_owned()), + ..HostConfig::default() + }; + FirecrackerDriver::new(&host) + } + + #[tokio::test] + async fn names_and_sandboxes_keep_their_images() -> Result<()> { + let dir = tempfile::tempdir()?; + let d = driver(dir.path()); + let image = Image { + id: format!("sha256:{}", "2".repeat(64)), + reference: "ghcr.io/hyperstructure/sandbox:0.26.0".into(), + labels: [( + "org.opencontainers.image.revision".to_owned(), + "f392b5c".to_owned(), + )] + .into(), + ..Image::default() + }; + let rootfs = dir.path().join("rootfs"); + std::fs::write(&rootfs, b"ext4")?; + d.store.add(&image, &rootfs)?; + let info = d.image("ghcr.io/hyperstructure/sandbox:0.26.0").await?; + assert_eq!(info.map(|i| i.id), Some(image.id.clone())); + d.tag_image( + "ghcr.io/hyperstructure/sandbox:0.26.0", + "ghcr.io/hyperstructure/sandbox:0.26.0-replaced-222222222222", + ) + .await?; + assert_eq!(d.images("ghcr.io/hyperstructure/sandbox").await?.len(), 2); + // A sandbox made from it keeps its last name, as Docker does. + let sandbox = d.sandboxes().join("fctl-ses-01abc"); + std::fs::create_dir_all(&sandbox)?; + d.save_record( + "fctl-ses-01abc", + &Record { + image: image.id.clone(), + reference: image.reference.clone(), + created_ms: 1, + agent: None, + }, + )?; + d.remove_image("ghcr.io/hyperstructure/sandbox:0.26.0-replaced-222222222222") + .await?; + assert!( + d.remove_image("ghcr.io/hyperstructure/sandbox:0.26.0") + .await + .is_err() + ); + assert!(d.has_image("ghcr.io/hyperstructure/sandbox:0.26.0").await); + // The sandbox, stopped, is listed, and runs programs as its image says. + let listed = d.list().await?; + assert_eq!(listed.len(), 1); + assert!(!listed[0].running); + let exec = d.sh("fctl-ses-01abc", "true"); + assert_eq!(exec.argv, ["sh", "-c", "true"]); + Ok(()) + } + + #[tokio::test] + async fn never_makes_a_sandbox_over_a_disk_it_has_no_record_of() -> Result<()> { + let dir = tempfile::tempdir()?; + let d = driver(dir.path()); + let vm = d.vm("fctl-ses-01abc")?; + std::fs::create_dir_all(&vm.dir)?; + let disk = vm.dir.join("disk.ext4"); + std::fs::write(&disk, b"the session's files")?; + std::fs::write(vm.dir.join("sandbox.json"), b"{ half written")?; + let spec = SandboxSpec { + name: "fctl-ses-01abc".into(), + image: "docker.io/library/debian:trixie-slim".into(), + fallback_image: None, + cpus: 1, + memory_mb: 512, + cache: None, + }; + let log = |_: String| {}; + let e = d + .create(&spec, &vm, &log) + .await + .err() + .map(|e| e.to_string()); + assert!(e.is_some_and(|e| e.contains("has a disk but no record"))); + assert_eq!(std::fs::read(&disk)?, b"the session's files"); + // Records are written whole. + let record = Record { + image: "sha256:1".into(), + reference: "x".into(), + created_ms: 1, + agent: None, + }; + d.save_record("fctl-ses-01abc", &record)?; + assert_eq!(d.record("fctl-ses-01abc"), Some(record)); + // A sandbox whose disk was being made when the host stopped gets a + // new one, never the half-made one. + if find_program("mkfs.ext4").is_some() { + std::fs::remove_file(&disk)?; + std::fs::write(vm.dir.join("disk.ext4.new"), b"half made")?; + d.make_disk(&vm).await?; + assert!(!vm.dir.join("disk.ext4.new").exists()); + assert!(std::fs::metadata(&disk)?.len() > 1024 * 1024); + } + Ok(()) + } + + #[tokio::test] + async fn probes_what_the_host_lacks() { + let dir = tempfile::tempdir().ok(); + let d = driver(dir.as_ref().map_or(Path::new("/nonexistent"), |d| d.path())); + let info = d.probe().await; + assert_eq!(info.name, "firecracker"); + assert_eq!(info.isolation, "vm"); + // This sandbox has no KVM; elsewhere the detail says what is missing or that it's ready. + if !Path::new("/dev/kvm").exists() { + assert!(!info.available); + assert!(info.detail.unwrap_or_default().contains("/dev/kvm")); + } + } + + /// 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: + /// + /// ```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). + #[tokio::test] + #[ignore = "needs KVM, passt, a kernel and a static fctl-agent"] + async fn boots_a_sandbox() -> Result<()> { + use super::super::Driver; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let var = |k: &str| std::env::var(k).with_context(|| format!("{k} isn't set")); + 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), + agent_bin: Some(var("FCTL_TEST_FIRECRACKER_AGENT")?.into()), + ..HostConfig::default() + }; + cfg.firecracker.kernel = Some(var("FCTL_TEST_FIRECRACKER_KERNEL")?); + cfg.firecracker.disk_gb = 4; + let d = Driver::select("firecracker", &cfg).await?; + let probed = d.probe().await; + assert!(probed.available, "{probed:?}"); + let log = |line: String| eprintln!("{line}"); + let name = format!( + "fctl-test-{}", + hex::encode(fctl_domain::random_bytes::<4>()) + ); + const DEBIAN: &str = "docker.io/library/debian:trixie-slim"; + let image = std::env::var("FCTL_TEST_FIRECRACKER_IMAGE").unwrap_or_else(|_| DEBIAN.into()); + let spec = SandboxSpec { + name: name.clone(), + image: image.clone(), + fallback_image: None, + cpus: 2, + memory_mb: 1024, + cache: None, + }; + let started = std::time::Instant::now(); + let sb = d.ensure(&spec, &log).await?; + eprintln!("booted in {:?}", started.elapsed()); + let result = async { + // As the image says, with the VM's name, and its network. + let out = d.exec(&sb, "id -u; hostname; echo $HOME; pwd").await?; + eprintln!("as {:?}", out.lines().collect::>()); + if image == DEBIAN { + assert_eq!(out, format!("0\n{name}\n/root\n/\n")); + } + assert_eq!(out.lines().nth(1), Some(name.as_str())); + 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()); + let fetched = d + .exec( + &sb, + r#"exec bash -c 'exec 3<>/dev/tcp/example.com/80; printf "HEAD / HTTP/1.0\r\nHost: example.com\r\n\r\n" >&3; head -1 <&3'"#, + ) + .await?; + assert!(fetched.starts_with("HTTP/1."), "{fetched}"); + // A failing command says why; a program's input and output. + let failed = d.exec(&sb, "echo oops >&2; exit 3").await; + assert_eq!(failed.err().map(|e| e.to_string()).as_deref(), Some("oops")); + let mut cat = d.spawn(&sb, "cat").await?; + let mut stdin = cat.stdin.take().context("stdin")?; + stdin.write_all(b"through the vsock").await?; + stdin.shutdown().await?; + drop(stdin); + let mut echoed = String::new(); + cat.stdout.take().context("stdout")?.read_to_string(&mut echoed).await?; + assert_eq!(echoed, "through the vsock"); + assert_eq!(cat.wait().await?, Some(0)); + // fctl-agent, as sessions start it. + let agent = PathBuf::from(var("FCTL_TEST_FIRECRACKER_AGENT")?); + d.install_agent(&sb, &agent).await?; + d.start_agent(&sb).await?; + let mut io = d.attach(&sb).await?; + let mut first = [0u8; 1]; + let n = tokio::time::timeout(std::time::Duration::from_secs(60), io.reader.read(&mut first)).await??; + assert_eq!(n, 1, "fctl-agent said nothing"); + drop(io); + // A stopped sandbox keeps its disk, and starts again from it. + d.exec(&sb, "echo kept > \"$HOME/note\"").await?; + d.stop(&sb).await?; + let listed = d.list().await?; + assert!(listed.iter().any(|s| s.name == name && !s.running), "{listed:?}"); + d.ensure(&spec, &log).await?; + assert_eq!(d.exec(&sb, "cat \"$HOME/note\"").await?, "kept\n"); + Ok::<_, anyhow::Error>(()) + } + .await; + d.remove(&sb).await?; + assert!(!d.list().await?.iter().any(|s| s.name == name)); + result + } +} diff --git a/crates/fctl-host/src/driver/firecracker/registry.rs b/crates/fctl-host/src/driver/firecracker/registry.rs new file mode 100644 index 00000000..4cf4449e --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/registry.rs @@ -0,0 +1,661 @@ +//! Pulling images from their registries, as Docker does, without Docker: +//! the manifest for this machine's platform, the config, and the layers, +//! each checked against its digest. + +use anyhow::{Context, Result, bail}; +use fctl_client::HttpClient; +use fctl_domain::image::ImageRef; +use serde::Deserialize; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::path::Path; +use std::sync::Mutex; +use std::time::Duration; + +/// What a manifest may be, as registries name them: an index of the +/// platforms' manifests, or one platform's. +const ACCEPT: &str = "application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.oci.image.manifest.v1+json, application/vnd.docker.distribution.manifest.v2+json"; + +/// The largest manifest or config a registry may send. +const MAX_JSON: usize = 4 * 1024 * 1024; + +/// The largest layer, and how long one may take. +pub const MAX_LAYER: u64 = 64 * 1024 * 1024 * 1024; +pub const LAYER_TIME: Duration = Duration::from_secs(60 * 60); + +/// A blob: what it is, its digest and its size. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct Descriptor { + #[serde(default)] + pub media_type: String, + pub digest: String, + #[serde(default)] + pub size: u64, +} + +/// An image as its registry describes it for this machine. +#[derive(Clone, Debug)] +pub struct Resolved { + /// The config's digest: the image's ID, as Docker's. + pub id: String, + pub config: Config, + pub layers: Vec, +} + +/// What an image's config says about running it. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +pub struct Config { + #[serde(rename = "User", default)] + pub user: Option, + #[serde(rename = "Env", default)] + pub env: Option>, + #[serde(rename = "WorkingDir", default)] + pub working_dir: Option, + #[serde(rename = "Labels", default)] + pub labels: Option>, +} + +#[derive(Deserialize)] +struct ConfigFile { + #[serde(default)] + config: Config, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Manifest { + #[serde(default)] + media_type: Option, + #[serde(default)] + manifests: Option>, + #[serde(default)] + config: Option, + #[serde(default)] + layers: Option>, +} + +#[derive(Deserialize)] +struct Platformed { + digest: String, + #[serde(default)] + platform: Option, +} + +#[derive(Deserialize)] +struct Platform { + #[serde(default)] + os: String, + #[serde(default)] + architecture: String, +} + +/// An image's architecture, as registries name it: `arm64` for Rust's +/// `aarch64`. +pub fn architecture(arch: &str) -> &str { + match arch { + "aarch64" => "arm64", + "x86_64" => "amd64", + other => other, + } +} + +/// The registry and repository of `name` (`ghcr.io/acme/agent`), with +/// Docker Hub's API host for `docker.io`, and whether it speaks plain HTTP: +/// one on this machine does, as Docker allows. +fn endpoint(name: &str) -> Result<(String, &str)> { + let (registry, repository) = name + .split_once('/') + .context("an image name without a registry")?; + let host = registry.split(':').next().unwrap_or(registry); + let scheme = if host == "localhost" || host.starts_with("127.") || host == "[::1]" { + "http" + } else { + "https" + }; + let registry = if registry == "docker.io" { + "registry-1.docker.io" + } else { + registry + }; + Ok((format!("{scheme}://{registry}/v2/{repository}"), repository)) +} + +/// The parts of a `WWW-Authenticate: Bearer realm="…",service="…"` header. +fn challenge(header: &str) -> Option> { + let rest = header.trim().strip_prefix("Bearer ")?; + let mut out = BTreeMap::new(); + let mut s = rest; + while !s.is_empty() { + let (key, after) = s.split_once('=')?; + let key = key + .trim() + .trim_start_matches(',') + .trim() + .to_ascii_lowercase(); + let after = after.trim_start(); + let (value, rest) = match after.strip_prefix('"') { + Some(quoted) => { + let end = quoted.find('"')?; + ("ed[..end], "ed[end + 1..]) + } + None => match after.find(',') { + Some(i) => (&after[..i], &after[i..]), + None => (after, ""), + }, + }; + out.insert(key, value.to_owned()); + s = rest.trim_start_matches(',').trim_start(); + } + Some(out) +} + +/// The manifest of `os`/`arch` in an index. +fn pick(index: &[Platformed], os: &str, arch: &str) -> Option { + index + .iter() + .find(|m| { + m.platform + .as_ref() + .is_some_and(|p| p.os == os && p.architecture == arch) + }) + .map(|m| m.digest.clone()) +} + +/// `sha256:…` of `bytes`. +pub fn digest_of(bytes: &[u8]) -> String { + format!("sha256:{}", hex::encode(Sha256::digest(bytes))) +} + +/// `sha256:…` of the file at `path`. +pub fn file_digest(path: &Path) -> Result { + use std::io::Read; + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 1024 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + } + Ok(format!("sha256:{}", hex::encode(hasher.finalize()))) +} + +/// The credentials `docker login` keeps for `registry` in +/// `~/.docker/config.json` (`auths`, not credential helpers): the value +/// of a basic `Authorization`. +fn docker_login(registry: &str) -> Option { + let dir = std::env::var_os("DOCKER_CONFIG") + .map(std::path::PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| Path::new(&h).join(".docker")))?; + let text = std::fs::read_to_string(dir.join("config.json")).ok()?; + login_in(&text, registry) +} + +fn login_in(config: &str, registry: &str) -> Option { + let v: serde_json::Value = serde_json::from_str(config).ok()?; + let auths = v.get("auths")?.as_object()?; + let names: &[&str] = if registry == "docker.io" { + &[ + "https://index.docker.io/v1/", + "index.docker.io", + "docker.io", + ] + } else { + &[registry] + }; + let auth = names.iter().find_map(|n| { + auths + .get(*n) + .or_else(|| auths.get(&format!("https://{n}")))? + .get("auth")? + .as_str() + })?; + Some(format!("Basic {auth}")) +} + +/// A registry client for one pull. +pub struct Registry { + http: HttpClient, + /// Tokens for the repositories this pull read, by repository, with the + /// challenge each answers, to ask for another when one runs out. + tokens: Mutex>, +} + +impl Default for Registry { + fn default() -> Self { + Self::new() + } +} + +impl Registry { + pub fn new() -> Self { + Self { + http: HttpClient::new(Duration::from_secs(60)), + tokens: Mutex::new(BTreeMap::new()), + } + } + + fn token(&self, repository: &str) -> Option { + Some(self.tokens.lock().ok()?.get(repository)?.0.clone()) + } + + fn challenge(&self, repository: &str) -> Option { + Some(self.tokens.lock().ok()?.get(repository)?.1.clone()) + } + + /// Signs in for `repository` with `challenge`, and keeps the token. + async fn renew(&self, registry: &str, repository: &str, challenge: &str) -> Result<()> { + let token = self.sign_in(registry, repository, challenge).await?; + if let Ok(mut tokens) = self.tokens.lock() { + tokens.insert(repository.to_owned(), (token, challenge.to_owned())); + } + Ok(()) + } + + /// A GET of `url` for `name`, asking the registry's token service for a + /// token when it wants one, and following redirects (Docker Hub's blobs + /// are on a CDN), where the token doesn't go. + async fn get(&self, name: &str, url: &str, accept: &str) -> Result<(http::HeaderMap, Vec)> { + let (_, repository) = endpoint(name)?; + let registry = name.split('/').next().unwrap_or_default(); + let origin = |u: &str| url::Url::parse(u).ok().map(|u| u.origin()); + let mut current = url.to_owned(); + let mut signed_in = false; + for _ in 0..6 { + let token = self + .token(repository) + .filter(|_| origin(¤t) == origin(url)); + let (status, headers, body) = self + .http + .get_with(¤t, token.as_deref(), &[("accept", accept)]) + .await + .with_context(|| format!("reaching {registry}"))?; + if status.as_u16() == 401 && !signed_in && origin(¤t) == origin(url) { + let header = headers + .get(http::header::WWW_AUTHENTICATE) + .and_then(|v| v.to_str().ok()) + .unwrap_or_default(); + self.renew(registry, repository, header).await?; + signed_in = true; + continue; + } + if status.is_redirection() { + let location = headers + .get(http::header::LOCATION) + .and_then(|v| v.to_str().ok()) + .with_context(|| format!("{registry} redirected nowhere"))?; + current = url::Url::parse(¤t) + .and_then(|base| base.join(location)) + .context("the registry's redirect")? + .to_string(); + continue; + } + if !status.is_success() { + let why = String::from_utf8_lossy(&body) + .chars() + .take(300) + .collect::(); + bail!("{registry} answered {status}: {}", why.trim()); + } + if body.len() > MAX_JSON { + bail!("{registry} sent more than {} MiB", MAX_JSON / 1024 / 1024); + } + return Ok((headers, body.to_vec())); + } + bail!("{registry} redirected too often, or refused the token it gave") + } + + /// A token for pulling `repository`, from the service the registry's + /// challenge names: anonymous, or with the credentials of `docker login`. + async fn sign_in(&self, registry: &str, repository: &str, header: &str) -> Result { + let c = challenge(header) + .with_context(|| format!("{registry} asks to sign in, in a way fctl doesn't know"))?; + let realm = c + .get("realm") + .context("no realm in the registry's challenge")?; + let mut url = url::Url::parse(realm).context("the registry's token service")?; + { + let mut q = url.query_pairs_mut(); + if let Some(service) = c.get("service") { + q.append_pair("service", service); + } + q.append_pair("scope", &format!("repository:{repository}:pull")); + } + let login = docker_login(registry); + let mut headers = vec![("accept", "application/json")]; + if let Some(auth) = login.as_deref() { + headers.push(("authorization", auth)); + } + let (status, _, body) = self + .http + .get_with(url.as_str(), None, &headers) + .await + .with_context(|| format!("signing in to {registry}"))?; + if !status.is_success() { + bail!( + "{registry} gave no token to pull {repository} ({status}){}", + if login.is_none() { + ": a private image needs `docker login` on this machine" + } else { + "" + } + ); + } + let v: serde_json::Value = serde_json::from_slice(&body).context("the registry's token")?; + v.get("token") + .or_else(|| v.get("access_token")) + .and_then(serde_json::Value::as_str) + .map(str::to_owned) + .context("no token in the registry's answer") + } + + /// The image `reference` names, for `linux/`. + pub async fn resolve(&self, reference: &str, arch: &str) -> Result { + let r = ImageRef::parse(reference) + .with_context(|| format!("{reference} isn't an image reference"))?; + let (base, _) = endpoint(&r.name)?; + let wanted = r + .digest + .clone() + .unwrap_or_else(|| r.tag.clone().unwrap_or_else(|| "latest".into())); + let mut manifest_ref = wanted.clone(); + // An index points at a manifest, which points at no other. + for _ in 0..2 { + let url = format!("{base}/manifests/{manifest_ref}"); + let (_, body) = self.get(&r.name, &url, ACCEPT).await?; + if manifest_ref.starts_with("sha256:") && digest_of(&body) != manifest_ref { + bail!("the manifest of {reference} doesn't match its digest"); + } + let m: Manifest = serde_json::from_slice(&body) + .with_context(|| format!("reading the manifest of {reference}"))?; + if let Some(index) = &m.manifests { + manifest_ref = pick(index, "linux", architecture(arch)).with_context(|| { + format!("{reference} has no image for linux/{}", architecture(arch)) + })?; + continue; + } + let (Some(config), Some(layers)) = (m.config, m.layers) else { + bail!( + "{reference}'s manifest ({}) isn't one fctl reads", + m.media_type.unwrap_or_default() + ); + }; + let url = format!("{base}/blobs/{}", config.digest); + let (_, body) = self.get(&r.name, &url, "*/*").await?; + if digest_of(&body) != config.digest { + bail!("the config of {reference} doesn't match its digest"); + } + let file: ConfigFile = serde_json::from_slice(&body) + .with_context(|| format!("reading the config of {reference}"))?; + return Ok(Resolved { + id: config.digest, + config: file.config, + layers, + }); + } + bail!("{reference}'s index points at another index") + } + + /// Downloads the blob `layer` of the image `reference` to `to`, and + /// checks it against its digest. + pub async fn blob(&self, reference: &str, layer: &Descriptor, to: &Path) -> Result<()> { + let r = ImageRef::parse(reference) + .with_context(|| format!("{reference} isn't an image reference"))?; + let (base, repository) = endpoint(&r.name)?; + let url = format!("{base}/blobs/{}", layer.digest); + let registry = r.name.split('/').next().unwrap_or_default(); + let http = HttpClient::new(LAYER_TIME); + let mut renewed = false; + let size = loop { + let token = self.token(repository); + match http + .download_to(&url, token.as_deref(), &[], to, MAX_LAYER, LAYER_TIME) + .await + { + Ok(size) => break size, + // Tokens run out, minutes after they came: the layers of a + // large image may take longer. + Err(fctl_client::Error::Status { status: 401, .. }) if !renewed => { + let challenge = self.challenge(repository).with_context(|| { + format!("{registry} refused {} without a token", layer.digest) + })?; + self.renew(registry, repository, &challenge).await?; + renewed = true; + } + Err(e) => { + return Err( + anyhow::Error::from(e).context(format!("downloading {}", layer.digest)) + ); + } + } + }; + if layer.size > 0 && size != layer.size { + bail!( + "{} is {size} bytes rather than the {} its manifest says", + layer.digest, + layer.size + ); + } + let path = to.to_owned(); + let digest = tokio::task::spawn_blocking(move || file_digest(&path)).await??; + if digest != layer.digest { + bail!("{} doesn't match its digest", layer.digest); + } + Ok(()) + } +} + +/// The value of a basic `Authorization` for `user` and `password`. +#[cfg(test)] +fn basic(user: &str, password: &str) -> String { + use base64::Engine; + let encoded = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{password}")); + format!("Basic {encoded}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn registries_have_their_api_hosts() -> Result<()> { + assert_eq!( + endpoint("ghcr.io/hyperstructure/sandbox")?, + ( + "https://ghcr.io/v2/hyperstructure/sandbox".to_owned(), + "hyperstructure/sandbox" + ) + ); + assert_eq!( + endpoint("docker.io/library/debian")?.0, + "https://registry-1.docker.io/v2/library/debian" + ); + assert_eq!( + endpoint("localhost:5000/test/sandbox")?.0, + "http://localhost:5000/v2/test/sandbox" + ); + assert_eq!( + endpoint("127.0.0.1:5000/a/b")?.0, + "http://127.0.0.1:5000/v2/a/b" + ); + assert_eq!(architecture("aarch64"), "arm64"); + assert_eq!(architecture("x86_64"), "amd64"); + Ok(()) + } + + #[test] + fn reads_the_registrys_challenge() { + let c = challenge( + r#"Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:hyperstructure/sandbox:pull""#, + ); + assert_eq!( + c.as_ref().and_then(|c| c.get("realm")).map(String::as_str), + Some("https://ghcr.io/token") + ); + assert_eq!( + c.as_ref() + .and_then(|c| c.get("service")) + .map(String::as_str), + Some("ghcr.io") + ); + let unquoted = challenge("Bearer realm=https://auth.example/token, service=reg"); + assert_eq!( + unquoted.and_then(|c| c.get("service").cloned()).as_deref(), + Some("reg") + ); + assert_eq!(challenge(r#"Basic realm="x""#), None); + } + + #[test] + fn picks_this_machines_platform() -> Result<()> { + let index: Manifest = serde_json::from_str( + r#"{"mediaType":"application/vnd.oci.image.index.v1+json","manifests":[ + {"digest":"sha256:arm","platform":{"os":"linux","architecture":"arm64"}}, + {"digest":"sha256:amd","platform":{"os":"linux","architecture":"amd64"}}, + {"digest":"sha256:att","platform":{"os":"unknown","architecture":"unknown"}}]}"#, + )?; + let manifests = index.manifests.unwrap_or_default(); + assert_eq!( + pick(&manifests, "linux", "arm64").as_deref(), + Some("sha256:arm") + ); + assert_eq!( + pick(&manifests, "linux", "amd64").as_deref(), + Some("sha256:amd") + ); + assert_eq!(pick(&manifests, "linux", "riscv64"), None); + Ok(()) + } + + #[test] + fn uses_the_credentials_of_docker_login() { + use base64::Engine; + let config = format!( + r#"{{"auths":{{"ghcr.io":{{"auth":"{}"}},"https://index.docker.io/v1/":{{"auth":"aHViOnB3"}}}},"credsStore":"desktop"}}"#, + base64::engine::general_purpose::STANDARD.encode("ada:secret") + ); + assert_eq!(login_in(&config, "ghcr.io"), Some(basic("ada", "secret"))); + assert_eq!( + login_in(&config, "docker.io").as_deref(), + Some("Basic aHViOnB3") + ); + assert_eq!(login_in(&config, "quay.io"), None); + assert_eq!(login_in("not json", "ghcr.io"), None); + } + + #[test] + fn reads_what_an_image_says_about_running_it() -> Result<()> { + let file: ConfigFile = serde_json::from_str( + r#"{"architecture":"arm64","config":{"User":"agent","Env":["PATH=/usr/bin"],"WorkingDir":"/home/agent","Labels":{"org.opencontainers.image.revision":"f392b5c"}}}"#, + )?; + assert_eq!(file.config.user.as_deref(), Some("agent")); + assert_eq!(file.config.env, Some(vec!["PATH=/usr/bin".to_owned()])); + assert_eq!( + file.config + .labels + .and_then(|l| l.get("org.opencontainers.image.revision").cloned()) + .as_deref(), + Some("f392b5c") + ); + let bare: ConfigFile = serde_json::from_str(r#"{"config":{"Env":null}}"#)?; + assert_eq!(bare.config, Config::default()); + Ok(()) + } + + /// A registry on this machine that wants a token, whose first one runs + /// out after the manifest and the config: the layer needs another. + #[tokio::test] + async fn signs_in_again_when_a_token_runs_out() -> Result<()> { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + let layer = b"layer bytes".to_vec(); + let config = br#"{"config":{"User":"agent"}}"#.to_vec(); + let manifest = format!( + r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.manifest.v1+json","config":{{"digest":"{}","size":{}}},"layers":[{{"mediaType":"application/vnd.oci.image.layer.v1.tar","digest":"{}","size":{}}}]}}"#, + digest_of(&config), + config.len(), + digest_of(&layer), + layer.len() + ); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let port = listener.local_addr()?.port(); + let tokens_given = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let given = tokens_given.clone(); + let (manifest_c, config_c, layer_c) = (manifest.clone(), config.clone(), layer.clone()); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let (given, manifest, config, layer) = ( + given.clone(), + manifest_c.clone(), + config_c.clone(), + layer_c.clone(), + ); + tokio::spawn(async move { + let (r, mut w) = stream.into_split(); + let mut r = BufReader::new(r); + let mut first = String::new(); + let _ = r.read_line(&mut first).await; + let mut auth = String::new(); + loop { + let mut line = String::new(); + if r.read_line(&mut line).await.unwrap_or(0) == 0 || line == "\r\n" { + break; + } + if let Some(v) = line.to_ascii_lowercase().strip_prefix("authorization: ") { + auth = v.trim().to_owned(); + } + } + let path = first + .split_whitespace() + .nth(1) + .unwrap_or_default() + .to_owned(); + // Token 1 is good for two requests, token 2 for the rest. + let good = auth == "bearer token-2" || auth == "bearer token-1"; + let (status, body, extra) = if path.starts_with("/token") { + let n = given.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1; + ( + "200 OK", + format!(r#"{{"token":"token-{n}"}}"#).into_bytes(), + String::new(), + ) + } else if !good + || (path.contains("/blobs/") + && path.ends_with(&digest_of(&layer)) + && auth == "bearer token-1") + { + let challenge = format!( + "WWW-Authenticate: Bearer realm=\"http://127.0.0.1:{port}/token\",service=\"fake\"\r\n" + ); + ("401 Unauthorized", b"{}".to_vec(), challenge) + } else if path.contains("/manifests/") { + ("200 OK", manifest.into_bytes(), String::new()) + } else if path.ends_with(&digest_of(&config)) { + ("200 OK", config, String::new()) + } else { + ("200 OK", layer, String::new()) + }; + let head = format!( + "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n{extra}\r\n", + body.len() + ); + let _ = w.write_all(head.as_bytes()).await; + let _ = w.write_all(&body).await; + }); + } + }); + let reference = format!("127.0.0.1:{port}/acme/agent:1"); + let registry = Registry::new(); + let resolved = registry.resolve(&reference, "aarch64").await?; + assert_eq!(resolved.id, digest_of(&config)); + assert_eq!(resolved.config.user.as_deref(), Some("agent")); + let dir = tempfile::tempdir()?; + let to = dir.path().join("layer"); + registry.blob(&reference, &resolved.layers[0], &to).await?; + assert_eq!(std::fs::read(&to)?, layer); + assert_eq!(tokens_given.load(std::sync::atomic::Ordering::SeqCst), 2); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/firecracker/vm.rs b/crates/fctl-host/src/driver/firecracker/vm.rs new file mode 100644 index 00000000..0e3a0988 --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/vm.rs @@ -0,0 +1,508 @@ +//! A microVM's processes on the host: Firecracker, and `passt` for its +//! network. Both run in process groups of their own, so that restarting the +//! host (whose service stops only its main process) leaves them running. + +use super::vsock; +use anyhow::{Context, Result, 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::path::{Path, PathBuf}; +use std::process::Stdio; +use std::time::{Duration, Instant}; + +/// How long a VM may take to boot to its init. Natively it takes a second +/// or two; nested in another VM without hardware help, much longer. +pub const BOOT_TIMEOUT: Duration = Duration::from_secs(180); + +/// How long a VM may take to stop once its init is asked to. +const STOP_TIMEOUT: Duration = Duration::from_secs(30); + +/// 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 +/// (its devices are MMIO); aarch64 has neither. +fn kernel_args() -> String { + let common = "console=ttyS0 panic=1 nomodule quiet rdinit=/init"; + if cfg!(target_arch = "x86_64") { + format!("{common} reboot=k i8042.noaux i8042.nomux i8042.dumbkbd swiotlb=noforce pci=off") + } else { + common.to_owned() + } +} + +/// A disk for the VM: its file, and whether the VM may write to it. +#[derive(Clone, Debug)] +pub struct Drive { + pub path: PathBuf, + pub writable: bool, +} + +/// What to boot. +#[derive(Clone, Debug)] +pub struct Spec { + pub kernel: PathBuf, + pub initrd: PathBuf, + pub boot: Boot, + /// `/dev/vda`, `/dev/vdb`, … in this order. + pub drives: Vec, + pub cpus: u32, + pub memory_mb: u32, + /// Whether the VM gets a network (`passt`). + pub network: bool, +} + +/// A microVM's files: `dir` keeps its configuration, its console's log and +/// the processes' ids; `run`, a short path (unix sockets' paths are +/// limited to about 100 bytes), its sockets. +#[derive(Clone, Debug)] +pub struct Vm { + pub dir: PathBuf, + pub run: PathBuf, +} + +/// Where VMs' sockets go: a directory of this user's in /tmp, private. +/// One that another user made first is theirs, and refused. +fn socket_base() -> Result { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let user = std::env::var("USER").unwrap_or_else(|_| "fctl".into()); + let user: String = user + .chars() + .filter(char::is_ascii_alphanumeric) + .take(16) + .collect(); + let dir = PathBuf::from(format!("/tmp/fctl-{user}")); + std::fs::create_dir_all(&dir)?; + let meta = std::fs::symlink_metadata(&dir)?; + let me = std::fs::metadata("/proc/self") + .map(|m| m.uid()) + .context("finding this process's user")?; + if !meta.is_dir() || meta.uid() != me { + bail!("{} isn't a directory of this user's", dir.display()); + } + if meta.mode() & 0o077 != 0 { + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)) + .with_context(|| format!("making {} private", dir.display()))?; + } + Ok(dir) +} + +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 }) + } + + pub fn api(&self) -> PathBuf { + self.run.join("api.sock") + } + + pub fn vsock(&self) -> PathBuf { + 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") + } + + fn pid_file(&self, what: &str) -> PathBuf { + self.dir.join(format!("{what}.pid")) + } + + /// The process `what` started for this VM, while it runs: its id file + /// names it, and its command line has this VM's sockets, which a process + /// that took the id later wouldn't. One that is still being started has + /// no command line yet, for a moment, but an executable. + fn pid(&self, what: &str) -> Option { + let pid: u32 = std::fs::read_to_string(self.pid_file(what)) + .ok()? + .trim() + .parse() + .ok()?; + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let zombie = stat + .rsplit_once(')') + .is_some_and(|(_, rest)| rest.trim_start().starts_with('Z')); + let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?; + 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(); + let mine = starting + || cmdline + .split(|b| *b == 0) + .any(|arg| String::from_utf8_lossy(arg).starts_with(&ours)); + (mine && !zombie).then_some(pid) + } + + /// Whether the VM runs. + pub fn running(&self) -> bool { + 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<()> { + self.kill().await; + let started = self.start_processes(spec, firecracker, passt).await; + if started.is_err() { + self.kill().await; + } + started + } + + async fn start_processes( + &self, + spec: &Spec, + firecracker: &Path, + passt: Option<&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, &spec.boot.name).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())?; + let mut cmd = std::process::Command::new(firecracker); + cmd.arg("--api-sock") + .arg(self.api()) + .arg("--config-file") + .arg(&config) + .args(["--id", &spec.boot.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()))?; + 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, name: &str) -> 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)) + .stdin(Stdio::null()) + .stdout(log.try_clone()?) + .stderr(log); + spawn_detached(&mut cmd, &self.pid_file("passt")) + .with_context(|| format!("starting {}", passt.display()))?; + let until = Instant::now() + Duration::from_secs(10); + while !self.net().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(); + bail!("passt did not start: {}", said.trim()); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + Ok(()) + } + + /// Firecracker's configuration for `spec`. + pub fn config(&self, spec: &Spec) -> Value { + let drives: Vec = spec + .drives + .iter() + .enumerate() + .map(|(i, d)| { + let mut drive = json!({ + "drive_id": format!("vd{}", char::from(b'a' + u8::try_from(i).unwrap_or(25).min(25))), + "path_on_host": d.path, + "is_root_device": false, + "is_read_only": !d.writable, + }); + if d.writable { + // The session's writes reach the host's disk when the + // VM flushes them, and what it deletes goes from it. + drive["cache_type"] = json!("Writeback"); + drive["discard"] = json!(true); + } + drive + }) + .collect(); + json!({ + "boot-source": { + "kernel_image_path": spec.kernel, + "initrd_path": spec.initrd, + "boot_args": format!("{} {}", kernel_args(), spec.boot.params()), + }, + "drives": drives, + "machine-config": { + "vcpu_count": spec.cpus.clamp(1, 32), + "mem_size_mib": spec.memory_mb.max(256), + "smt": false, + }, + "vsock": { "guest_cid": 3, "uds_path": self.vsock() }, + // Memory the VM frees goes back to the host. + "balloon": { "amount_mib": 0, "deflate_on_oom": true, "free_page_reporting": true }, + "entropy": {}, + }) + } + + /// 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(); + let lines: Vec<&str> = text.lines().filter(|l| !l.trim().is_empty()).collect(); + lines[lines.len().saturating_sub(12)..].join("\n") + } + + /// Waits for the VM's init to answer. + pub async fn wait_ready(&self) -> Result { + let result = vsock::wait_ready(&self.vsock(), BOOT_TIMEOUT, || self.running()).await; + if let Err(e) = &result { + let tail = self.console_tail(); + self.kill().await; + if !tail.is_empty() { + bail!("{e:#}; its console said:\n{tail}"); + } + } + result + } + + /// Asks the VM's init to stop it, and stops what is left. + pub async fn stop(&self) { + if self.running() { + let asked = + tokio::time::timeout(Duration::from_secs(10), vsock::shutdown(&self.vsock())).await; + if !matches!(asked, Ok(Ok(()))) { + tracing::debug!("{} didn't take the request to stop", self.dir.display()); + } + let until = Instant::now() + STOP_TIMEOUT; + while self.running() && Instant::now() < until { + tokio::time::sleep(Duration::from_millis(100)).await; + } + } + self.kill().await; + } + + /// 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)); + } + let _ = std::fs::remove_dir_all(&self.run); + } + + /// Stops the VM and removes its files. + pub async fn remove(&self) -> Result<()> { + self.stop().await; + match std::fs::remove_dir_all(&self.dir) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => { + Err(e).with_context(|| format!("removing {}", self.dir.display())) + } + _ => Ok(()), + } + } +} + +/// The arguments of `passt` for a VM named `name` whose frames come to +/// `socket`. +fn passt_args(socket: &Path, name: &str) -> Vec { + let mask = PREFIX.to_string(); + vec![ + "--foreground".into(), + "--quiet".into(), + "--socket".into(), + socket.display().to_string(), + "--address".into(), + Ipv4Addr::from(ADDRESS).to_string(), + "--netmask".into(), + mask, + "--gateway".into(), + Ipv4Addr::from(GATEWAY).to_string(), + "--dns-forward".into(), + 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(), + ] +} + +/// Starts `cmd` in a process group of its own, writes its id to +/// `pid_file`, and reaps it when it exits while this host runs. +fn spawn_detached(cmd: &mut std::process::Command, pid_file: &Path) -> Result { + use std::os::unix::process::CommandExt; + cmd.process_group(0); + let mut child = cmd.spawn()?; + let pid = child.id(); + std::fs::write(pid_file, pid.to_string())?; + std::thread::spawn(move || { + let _ = child.wait(); + }); + Ok(pid) +} + +/// What a VM to unpack an image boots. +pub fn unpack_spec(kernel: PathBuf, initrd: PathBuf, name: &str, rootfs: &Path) -> Spec { + Spec { + kernel, + initrd, + boot: Boot { + mode: Mode::Unpack, + name: name.into(), + time_ms: Some(vsock::now_ms()), + }, + drives: vec![Drive { + path: rootfs.to_owned(), + writable: true, + }], + cpus: 2, + memory_mb: 1024, + network: false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn firecracker_gets_the_vms_disks_size_and_vsock() -> Result<()> { + let vm = Vm { + dir: PathBuf::from("/data/firecracker/sandboxes/fctl-ses-1"), + run: PathBuf::from("/tmp/fctl-ada/vm-0123"), + }; + let spec = Spec { + kernel: "/k/vmlinux".into(), + initrd: "/i/1.cpio".into(), + boot: Boot { + mode: Mode::Sandbox, + name: "fctl-ses-1".into(), + time_ms: Some(5), + }, + drives: vec![ + Drive { + path: "/img/rootfs.ext4".into(), + writable: false, + }, + Drive { + path: "/sb/disk.ext4".into(), + writable: true, + }, + ], + cpus: 64, + memory_mb: 4096, + network: true, + }; + let c = vm.config(&spec); + assert_eq!( + c["boot-source"]["boot_args"], + format!( + "{} fctl.mode=sandbox fctl.name=fctl-ses-1 fctl.time=5", + kernel_args() + ) + ); + assert_eq!(c["drives"][0]["drive_id"], "vda"); + assert_eq!(c["drives"][0]["is_read_only"], true); + assert!(c["drives"][0].get("discard").is_none()); + assert_eq!(c["drives"][1]["drive_id"], "vdb"); + assert_eq!(c["drives"][1]["discard"], true); + 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"), "fctl-ses-1").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" + ); + } + + #[test] + fn a_vm_runs_only_while_its_process_does() -> Result<()> { + let dir = tempfile::tempdir()?; + let vm = Vm::new(dir.path().join("fctl-ses-x"))?; + assert!(vm.run.starts_with("/tmp")); + std::fs::create_dir_all(&vm.dir)?; + assert!(!vm.running()); + // A process whose command line has the VM's socket directory. + let mut child = std::process::Command::new("sh") + .args(["-c", "sleep 30; true", &vm.api().display().to_string()]) + .spawn()?; + std::fs::write(vm.pid_file("firecracker"), child.id().to_string())?; + assert!(vm.running()); + // Another process with that id isn't the VM's. + std::fs::write(vm.pid_file("firecracker"), std::process::id().to_string())?; + assert!(!vm.running()); + child.kill()?; + child.wait()?; + Ok(()) + } + + /// Stand-ins: a `passt` that makes its socket's path and waits, and a + /// Firecracker that waits. + #[tokio::test] + async fn starting_again_stops_what_the_last_boot_left() -> Result<()> { + use crate::driver::fake::write_script; + let dir = tempfile::tempdir()?; + let passt = dir.path().join("passt"); + // Without `exec`, so that their command lines keep the sockets. + write_script( + &passt, + "#!/bin/sh\nfor a; do [ \"$prev\" = --socket ] && touch \"$a\"; prev=$a; done\nsleep 60\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() { + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert_eq!(vm.pid("passt"), first_passt); + vm.start(&spec, &firecracker, Some(&passt)).await?; + let alive = |pid: u32| { + std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| { + !s.rsplit_once(')') + .is_some_and(|(_, r)| r.trim_start().starts_with('Z')) + }) + }; + assert!( + first_passt.is_some_and(|p| !alive(p)), + "the first passt still runs" + ); + assert!(vm.pid("passt").is_some() && vm.running()); + // 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()); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/firecracker/vsock.rs b/crates/fctl-host/src/driver/firecracker/vsock.rs new file mode 100644 index 00000000..b357814e --- /dev/null +++ b/crates/fctl-host/src/driver/firecracker/vsock.rs @@ -0,0 +1,578 @@ +//! Talking to a VM's init through Firecracker's vsock socket +//! ([`fctl_proto::vm`]). + +use anyhow::{Context, Result, bail}; +use fctl_proto::vm::{Exec, MAX_LINE, PORT, Reply, Request, frame}; +use std::path::Path; +use std::pin::Pin; +use std::sync::Arc; +use std::task::{Context as TaskContext, Poll}; +use std::time::{Duration, Instant}; +use tokio::io::{ + AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, DuplexStream, + ReadBuf, +}; +use tokio::net::UnixStream; +use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf}; +use tokio::sync::oneshot; + +pub type Reader = BufReader; + +/// How long the VM may take to take a request and answer it, what follows +/// aside: an init that takes longer is stuck, and nothing that waits for it +/// may hang with it. +pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// Connects to `port` in the VM whose vsock socket is `socket`. +pub async fn connect(socket: &Path, port: u32) -> Result<(Reader, OwnedWriteHalf)> { + let stream = UnixStream::connect(socket) + .await + .with_context(|| format!("connecting to {}", socket.display()))?; + let (r, mut w) = stream.into_split(); + w.write_all(format!("CONNECT {port}\n").as_bytes()).await?; + let mut r = BufReader::new(r); + let mut line = Vec::new(); + (&mut r).take(64).read_until(b'\n', &mut line).await?; + if !line.starts_with(b"OK ") { + bail!("nothing in the VM answers on port {port} yet"); + } + Ok((r, w)) +} + +/// Reads one reply line. +pub async fn read_reply(r: &mut Reader) -> Result { + let mut line = Vec::new(); + r.take(MAX_LINE as u64).read_until(b'\n', &mut line).await?; + if line.is_empty() { + bail!("the VM closed the connection"); + } + serde_json::from_slice(&line).context("reading the VM's reply") +} + +/// Sends `request` to the init within [`REQUEST_TIMEOUT`]; returns the +/// connection and the init's first reply, or the error it says. +pub async fn request(socket: &Path, request: &Request) -> Result<(Reader, OwnedWriteHalf)> { + let (r, w, reply) = ask(socket, request).await?; + if let Some(e) = reply.error { + bail!("{e}"); + } + Ok((r, w)) +} + +/// Sends `request` and reads the first reply, within [`REQUEST_TIMEOUT`]. +async fn ask(socket: &Path, request: &Request) -> Result<(Reader, OwnedWriteHalf, Reply)> { + let asking = async { + let (mut r, mut w) = connect(socket, PORT).await?; + let mut line = serde_json::to_vec(request)?; + line.push(b'\n'); + w.write_all(&line).await?; + let reply = read_reply(&mut r).await?; + Ok::<_, anyhow::Error>((r, w, reply)) + }; + tokio::time::timeout(REQUEST_TIMEOUT, asking) + .await + .map_err(|_| { + anyhow::anyhow!( + "the VM didn't answer within {} seconds", + REQUEST_TIMEOUT.as_secs() + ) + })? +} + +/// The host's clock, which VMs follow. +pub fn now_ms() -> i64 { + crate::expiry::now_ms() +} + +/// The init's version, when it answers. +pub async fn hello(socket: &Path) -> Result { + let hello = Request::Hello { + now_ms: Some(now_ms()), + }; + let (_, _, reply) = ask(socket, &hello).await?; + Ok(reply.version.unwrap_or_default()) +} + +/// Waits for the init to answer, for at most `within`; `alive` says whether +/// the VM still runs. +pub async fn wait_ready( + socket: &Path, + within: Duration, + alive: impl Fn() -> bool, +) -> Result { + let until = Instant::now() + within; + loop { + let last = match tokio::time::timeout(Duration::from_secs(5), hello(socket)).await { + Ok(Ok(version)) => return Ok(version), + Ok(Err(e)) => e, + Err(_) => anyhow::anyhow!("no answer within 5 seconds"), + }; + if !alive() { + bail!("the VM stopped while it booted"); + } + if Instant::now() > until { + bail!( + "the VM did not answer within {} seconds: {last:#}", + within.as_secs() + ); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } +} + +async fn send_frame(w: &mut OwnedWriteHalf, kind: u8, data: &[u8]) -> std::io::Result<()> { + w.write_all(&frame::header(kind, data.len())).await?; + w.write_all(data).await +} + +/// What a program wrote, and how it exited. +#[derive(Debug, Default)] +pub struct Output { + pub code: i32, + pub stdout: Vec, + pub stderr: Vec, +} + +/// The most output [`run`] keeps of a program. +const MAX_OUTPUT: usize = 64 * 1024 * 1024; + +/// Runs `exec` with `input`, to its end. +pub async fn run(socket: &Path, mut exec: Exec, input: Option<&[u8]>) -> Result { + exec.stdin = input.is_some(); + exec.now_ms = Some(now_ms()); + let (mut r, mut w) = request(socket, &Request::Exec(exec)).await?; + let feed = async { + if let Some(input) = input { + for chunk in input.chunks(frame::MAX) { + send_frame(&mut w, frame::STDIN, chunk).await?; + } + send_frame(&mut w, frame::STDIN_END, &[]).await?; + } + // The write half stays open: the init stops a program whose host + // went away. + std::future::pending::>().await + }; + let read = async { + let mut out = Output::default(); + let mut buf = vec![0u8; frame::MAX]; + loop { + let mut header = [0u8; 5]; + r.read_exact(&mut header) + .await + .context("the VM closed the connection before the program exited")?; + let (kind, len) = frame::parse(header).context("a frame too long")?; + r.read_exact(&mut buf[..len]).await?; + let data = &buf[..len]; + match kind { + frame::STDOUT if out.stdout.len() + len <= MAX_OUTPUT => { + out.stdout.extend_from_slice(data); + } + frame::STDERR if out.stderr.len() + len <= MAX_OUTPUT => { + out.stderr.extend_from_slice(data); + } + frame::EXIT => { + out.code = data + .get(..4) + .and_then(|b| b.try_into().ok()) + .map(i32::from_be_bytes) + .unwrap_or(1); + return Ok::(out); + } + _ => {} + } + } + }; + tokio::select! { + out = read => out, + e = feed => Err(e.err().map(anyhow::Error::from).unwrap_or_else(|| anyhow::anyhow!("closed"))), + } +} + +/// Starts `exec` without waiting for it, with nothing in or out. +pub async fn detach(socket: &Path, mut exec: Exec) -> Result<()> { + exec.detach = true; + exec.stdin = false; + exec.now_ms = Some(now_ms()); + request(socket, &Request::Exec(exec)).await.map(drop) +} + +/// The tasks that carry a program's input and output, stopped when nothing +/// holds the program's pipes any more: the connection closes, and the init +/// stops the program. +pub struct Tasks(Vec>); + +impl Drop for Tasks { + fn drop(&mut self) { + for t in &self.0 { + t.abort(); + } + } +} + +/// A pipe of a program in a VM, which keeps its tasks running. +pub struct Pipe { + inner: T, + _tasks: Arc, +} + +impl AsyncRead for Pipe { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} + +impl AsyncWrite for Pipe { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, buf) + } + + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + + fn poll_shutdown( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } +} + +/// A program in a VM, with its input and output as pipes. +pub struct Started { + pub stdin: Pipe, + pub stdout: Pipe, + pub stderr: Pipe, + /// Its exit code, or `None` when the connection closed first. + pub exit: oneshot::Receiver>, +} + +/// Starts `exec` with its input and output piped. +pub async fn start(socket: &Path, mut exec: Exec) -> Result { + exec.stdin = true; + exec.detach = false; + exec.now_ms = Some(now_ms()); + let (mut from_vm, mut to_vm) = request(socket, &Request::Exec(exec)).await?; + let (stdin, mut stdin_rx) = tokio::io::duplex(256 * 1024); + let (mut stdout_tx, stdout) = tokio::io::duplex(256 * 1024); + let (mut stderr_tx, stderr) = tokio::io::duplex(64 * 1024); + let (exit_tx, exit) = oneshot::channel(); + let output = tokio::spawn(async move { + let mut buf = vec![0u8; frame::MAX]; + let mut code = None; + loop { + let mut header = [0u8; 5]; + if from_vm.read_exact(&mut header).await.is_err() { + break; + } + let Some((kind, len)) = frame::parse(header) else { + break; + }; + if from_vm.read_exact(&mut buf[..len]).await.is_err() { + break; + } + let data = &buf[..len]; + match kind { + // A reader that went away takes nothing more. + frame::STDOUT => { + let _ = stdout_tx.write_all(data).await; + } + frame::STDERR => { + let _ = stderr_tx.write_all(data).await; + } + frame::EXIT => { + code = data + .get(..4) + .and_then(|b| b.try_into().ok()) + .map(i32::from_be_bytes); + break; + } + _ => {} + } + } + let _ = exit_tx.send(code); + }); + let input = tokio::spawn(async move { + let mut buf = vec![0u8; 64 * 1024]; + loop { + match stdin_rx.read(&mut buf).await { + Ok(0) | Err(_) => break, + Ok(n) => { + if send_frame(&mut to_vm, frame::STDIN, &buf[..n]) + .await + .is_err() + { + return; + } + } + } + } + let _ = send_frame(&mut to_vm, frame::STDIN_END, &[]).await; + // Holds the connection open until the pipes go. + std::future::pending::<()>().await; + }); + let tasks = Arc::new(Tasks(vec![output, input])); + Ok(Started { + stdin: Pipe { + inner: stdin, + _tasks: tasks.clone(), + }, + stdout: Pipe { + inner: stdout, + _tasks: tasks.clone(), + }, + stderr: Pipe { + inner: stderr, + _tasks: tasks, + }, + exit, + }) +} + +/// Asks a VM booted to unpack an image to unpack `layers`, whose bytes are +/// the files `blobs`, and sends them, within `within`; what it wrote: files +/// and bytes. A VM that fails stops reading and says why, which is the +/// error rather than the write that failed after it. +pub async fn unpack( + socket: &Path, + layers: &[fctl_proto::vm::Layer], + blobs: &[std::path::PathBuf], + within: Duration, +) -> Result<(u64, u64)> { + let unpacking = Request::Unpack { + layers: layers.to_vec(), + }; + let (mut r, mut w) = request(socket, &unpacking).await?; + let work = async { + let sent = async { + for blob in blobs { + let mut file = tokio::fs::File::open(blob).await?; + tokio::io::copy(&mut file, &mut w).await?; + } + w.flush().await + } + .await; + match (sent, read_reply(&mut r).await) { + (_, Ok(Reply { error: Some(e), .. })) => bail!("{e}"), + (Err(e), _) => Err(anyhow::Error::from(e).context("sending a layer to the VM")), + (Ok(()), Ok(reply)) => Ok((reply.files.unwrap_or(0), reply.bytes.unwrap_or(0))), + (Ok(()), Err(e)) => Err(e), + } + }; + tokio::time::timeout(within, work).await.map_err(|_| { + anyhow::anyhow!( + "unpacking the image took more than {} minutes", + within.as_secs() / 60 + ) + })? +} + +/// Asks the init to stop the VM. +pub async fn shutdown(socket: &Path) -> Result<()> { + request(socket, &Request::Shutdown).await.map(drop) +} + +#[cfg(test)] +mod tests { + use super::*; + use tokio::net::UnixListener; + + /// A stand-in for Firecracker's socket and the init behind it: takes + /// `CONNECT`, then answers each request as `answer` does. + async fn fake_vm(dir: &Path, answer: F) -> Result + where + F: Fn(Request, Reader, OwnedWriteHalf) -> Fut + Send + Sync + 'static, + Fut: std::future::Future + Send, + { + let socket = dir.join("v.sock"); + let listener = UnixListener::bind(&socket)?; + let answer = Arc::new(answer); + tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let answer = answer.clone(); + tokio::spawn(async move { + let (r, mut w) = stream.into_split(); + let mut r = BufReader::new(r); + let mut line = String::new(); + if r.read_line(&mut line).await.is_err() || line != format!("CONNECT {PORT}\n") + { + return; + } + let _ = w.write_all(b"OK 1073741824\n").await; + line.clear(); + if r.read_line(&mut line).await.is_err() { + return; + } + if let Ok(request) = serde_json::from_str::(&line) { + answer(request, r, w).await; + } + }); + } + }); + Ok(socket) + } + + async fn reply(w: &mut OwnedWriteHalf, r: &Reply) { + let mut line = serde_json::to_vec(r).unwrap_or_default(); + line.push(b'\n'); + let _ = w.write_all(&line).await; + } + + #[tokio::test] + async fn runs_programs_and_carries_their_output() -> Result<()> { + let dir = tempfile::tempdir()?; + // Echoes its input to stdout, says something on stderr, exits 3. + let socket = fake_vm(dir.path(), |request, mut r, mut w| async move { + let Request::Exec(exec) = request else { + return reply(&mut w, &Reply::failed("not exec")).await; + }; + if exec.argv.first().map(String::as_str) == Some("missing") { + return reply(&mut w, &Reply::failed("starting it: not found")).await; + } + reply(&mut w, &Reply::default()).await; + let mut input = Vec::new(); + loop { + let mut header = [0u8; 5]; + if r.read_exact(&mut header).await.is_err() { + return; + } + let Some((kind, len)) = frame::parse(header) else { + return; + }; + let mut data = vec![0u8; len]; + if r.read_exact(&mut data).await.is_err() { + return; + } + match kind { + frame::STDIN => input.extend(data), + _ => break, + } + } + let _ = send_frame(&mut w, frame::STDOUT, &input).await; + let _ = send_frame(&mut w, frame::STDERR, b"warned").await; + let _ = send_frame(&mut w, frame::EXIT, &3i32.to_be_bytes()).await; + }) + .await?; + let exec = Exec { + argv: vec!["cat".into()], + ..Exec::default() + }; + let out = run(&socket, exec.clone(), Some(b"hello")).await?; + assert_eq!(out.code, 3); + assert_eq!(out.stdout, b"hello"); + assert_eq!(out.stderr, b"warned"); + let missing = Exec { + argv: vec!["missing".into()], + ..Exec::default() + }; + let e = run(&socket, missing, None) + .await + .err() + .map(|e| e.to_string()); + assert_eq!(e.as_deref(), Some("starting it: not found")); + // Started: input through its pipe, output through the others. + let mut started = start(&socket, exec).await?; + started.stdin.write_all(b"piped").await?; + started.stdin.shutdown().await?; + drop(started.stdin); + let mut stdout = String::new(); + started.stdout.read_to_string(&mut stdout).await?; + assert_eq!(stdout, "piped"); + assert_eq!(started.exit.await.ok().flatten(), Some(3)); + Ok(()) + } + + #[tokio::test] + async fn waits_for_the_init_and_says_when_nothing_answers() -> Result<()> { + let dir = tempfile::tempdir()?; + let gone = dir.path().join("none.sock"); + let e = wait_ready(&gone, Duration::from_millis(300), || true).await; + assert!(e.is_err()); + let stopped = wait_ready(&gone, Duration::from_secs(30), || false).await; + assert_eq!( + stopped.err().map(|e| e.to_string()).as_deref(), + Some("the VM stopped while it booted") + ); + let socket = fake_vm(dir.path(), |request, _, mut w| async move { + if matches!(request, Request::Hello { now_ms: Some(_) }) { + reply( + &mut w, + &Reply { + version: Some("0.27.0".into()), + ..Reply::default() + }, + ) + .await; + } + }) + .await?; + assert_eq!( + wait_ready(&socket, Duration::from_secs(5), || true).await?, + "0.27.0" + ); + Ok(()) + } + + /// A VM that unpacks: one that takes it all and says what it wrote, + /// and one that fails halfway, says why and hangs up. + #[tokio::test] + async fn unpacking_says_why_the_vm_stopped() -> Result<()> { + let dir = tempfile::tempdir()?; + let blob = dir.path().join("layer"); + std::fs::write(&blob, vec![7u8; 8 * 1024 * 1024])?; + let layers = [fctl_proto::vm::Layer { + media_type: "application/vnd.oci.image.layer.v1.tar".into(), + size: 8 * 1024 * 1024, + }]; + let ok_dir = dir.path().join("ok"); + std::fs::create_dir_all(&ok_dir)?; + let ok = fake_vm(&ok_dir, |request, mut r, mut w| async move { + let Request::Unpack { layers } = request else { + return; + }; + reply(&mut w, &Reply::default()).await; + let mut rest = vec![0u8; layers.iter().map(|l| l.size as usize).sum()]; + if r.read_exact(&mut rest).await.is_ok() { + let done = Reply { + files: Some(3), + bytes: Some(10), + ..Reply::default() + }; + reply(&mut w, &done).await; + } + }) + .await?; + let blobs = [blob.clone()]; + assert_eq!( + unpack(&ok, &layers, &blobs, Duration::from_secs(30)).await?, + (3, 10) + ); + let failing_dir = dir.path().join("failing"); + std::fs::create_dir_all(&failing_dir)?; + let failing = fake_vm(&failing_dir, |_, mut r, mut w| async move { + reply(&mut w, &Reply::default()).await; + let mut some = vec![0u8; 1024]; + let _ = r.read_exact(&mut some).await; + reply( + &mut w, + &Reply::failed("unpacking layer 1 of 1: No space left on device"), + ) + .await; + }) + .await?; + let e = unpack(&failing, &layers, &blobs, Duration::from_secs(30)).await; + assert_eq!( + e.err().map(|e| e.to_string()).as_deref(), + Some("unpacking layer 1 of 1: No space left on device") + ); + Ok(()) + } +} diff --git a/crates/fctl-host/src/driver/mod.rs b/crates/fctl-host/src/driver/mod.rs index 2bd736c2..9417d0b7 100644 --- a/crates/fctl-host/src/driver/mod.rs +++ b/crates/fctl-host/src/driver/mod.rs @@ -5,18 +5,21 @@ //! |---|---|---| //! | `apple` | a lightweight VM per session | Apple `container`, Apple silicon, macOS 26+ | //! | `docker` | a container per session | Docker, OrbStack, Colima, Podman (`docker` CLI) | +//! | `firecracker` | a microVM per session | Linux with KVM; experimental | //! | `lima` | a VM per session, cloned from `fctl-base` | experimental | //! | `process` | none | development and trusted hosts | pub mod container; #[cfg(test)] pub(crate) mod fake; +pub mod firecracker; pub mod lima; pub mod process; pub use container::ImageInfo; use crate::caches::{self, Spot}; +use crate::config::HostConfig; use anyhow::Result; use fctl_proto::runner::{DriverInfo, SandboxSize}; use std::path::{Path, PathBuf}; @@ -93,6 +96,59 @@ impl std::fmt::Display for DiskSpot { } } +/// A program running in a sandbox, with its input and output piped. +pub struct Running { + pub stdin: Option>, + pub stdout: Option>, + pub stderr: Option>, + exit: Exit, +} + +enum Exit { + /// The runtime's command (`docker exec`, `limactl shell`), or the + /// program itself with the process driver; killed when dropped. + Child(tokio::process::Child), + /// A program in a microVM, whose exit code comes over the vsock. + Vm(tokio::sync::oneshot::Receiver>), +} + +impl Running { + pub fn child(mut child: tokio::process::Child) -> Self { + Self { + stdin: child + .stdin + .take() + .map(|s| Box::new(s) as Box), + stdout: child + .stdout + .take() + .map(|s| Box::new(s) as Box), + stderr: child + .stderr + .take() + .map(|s| Box::new(s) as Box), + exit: Exit::Child(child), + } + } + + pub fn vm(started: firecracker::vsock::Started) -> Self { + Self { + stdin: Some(Box::new(started.stdin)), + stdout: Some(Box::new(started.stdout)), + stderr: Some(Box::new(started.stderr)), + exit: Exit::Vm(started.exit), + } + } + + /// Waits for it to exit; its exit code, when it says one. + pub async fn wait(&mut self) -> Result> { + match &mut self.exit { + Exit::Child(child) => Ok(child.wait().await?.code()), + Exit::Vm(exit) => Ok(exit.await.ok().flatten()), + } + } +} + /// A byte channel to fctl-agent. pub struct AgentIo { pub reader: Box, @@ -151,12 +207,17 @@ pub fn attach_script(agent: &str) -> String { pub enum Driver { Process(process::ProcessDriver), Container(container::ContainerDriver), + Firecracker(firecracker::FirecrackerDriver), Lima(lima::LimaDriver), } impl Driver { - /// The driver named in the configuration (`auto` picks the best available). - pub async fn select(name: &str, data_dir: &Path, agent_bin: Option) -> Result { + /// The driver `name`, with `cfg`'s settings (`auto` picks the best + /// available; it never picks Firecracker, which hosts choose). + pub async fn select(name: &str, cfg: &HostConfig) -> Result { + let data_dir = cfg.data_dir(); + let data_dir = data_dir.as_path(); + let agent_bin = cfg.agent_bin.clone(); let pick = |n: &str| -> Option { match n { "process" => Some(Driver::Process(process::ProcessDriver::new( @@ -165,6 +226,9 @@ impl Driver { ))), "apple" => Some(Driver::Container(container::ContainerDriver::apple())), "docker" => Some(Driver::Container(container::ContainerDriver::docker())), + "firecracker" => Some(Driver::Firecracker(firecracker::FirecrackerDriver::new( + cfg, + ))), "lima" => Some(Driver::Lima(lima::LimaDriver::new())), _ => None, } @@ -172,7 +236,7 @@ impl Driver { if name != "auto" { return pick(name).ok_or_else(|| { anyhow::anyhow!( - "unknown driver `{name}` (use apple, docker, lima, process or auto)" + "unknown driver `{name}` (use apple, docker, firecracker, lima, process or auto)" ) }); } @@ -190,22 +254,29 @@ impl Driver { } /// Every driver this host could use, for the runner's hello. - pub async fn probe_all(data_dir: &Path) -> Vec { - let (apple, docker, lima, process) = ( + pub async fn probe_all(cfg: &HostConfig) -> Vec { + let (apple, docker, firecracker, lima, process) = ( container::ContainerDriver::apple(), container::ContainerDriver::docker(), + firecracker::FirecrackerDriver::new(cfg), lima::LimaDriver::new(), - process::ProcessDriver::new(data_dir, None), + process::ProcessDriver::new(&cfg.data_dir(), None), + ); + let (apple, docker, firecracker, lima, process) = tokio::join!( + apple.probe(), + docker.probe(), + firecracker.probe(), + lima.probe(), + process.probe() ); - let (apple, docker, lima, process) = - tokio::join!(apple.probe(), docker.probe(), lima.probe(), process.probe()); - vec![apple, docker, lima, process] + vec![apple, docker, firecracker, lima, process] } pub fn name(&self) -> &'static str { match self { Self::Process(_) => "process", Self::Container(c) => c.flavor_name(), + Self::Firecracker(_) => "firecracker", Self::Lima(_) => "lima", } } @@ -218,6 +289,12 @@ impl Driver { /// Whether sandboxes are made from images (Lima clones its base VM, and /// the process driver has none). pub fn uses_images(&self) -> bool { + matches!(self, Self::Container(_) | Self::Firecracker(_)) + } + + /// Whether it builds images from Dockerfiles (Firecracker pulls them + /// only). + pub fn builds_images(&self) -> bool { matches!(self, Self::Container(_)) } @@ -225,6 +302,7 @@ impl Driver { pub async fn has_image(&self, image: &str) -> bool { match self { Self::Container(d) => d.has_image(image).await, + Self::Firecracker(d) => d.has_image(image).await, _ => false, } } @@ -233,6 +311,7 @@ impl Driver { pub async fn pull(&self, image: &str, progress: bool) -> Result<()> { match self { Self::Container(d) => d.pull(image, progress).await, + Self::Firecracker(d) => d.pull(image, progress).await, _ => anyhow::bail!("the {} driver does not use images", self.name()), } } @@ -248,6 +327,7 @@ impl Driver { ) -> Result { match self { Self::Container(d) => d.pull_or_fallback(image, fallback, progress, log).await, + Self::Firecracker(d) => d.pull_or_fallback(image, fallback, progress, log).await, _ => anyhow::bail!("the {} driver does not use images", self.name()), } } @@ -256,6 +336,7 @@ impl Driver { pub async fn image(&self, image: &str) -> Result> { match self { Self::Container(d) => d.image(image).await, + Self::Firecracker(d) => d.image(image).await, _ => Ok(None), } } @@ -264,6 +345,7 @@ impl Driver { pub async fn tag_image(&self, image: &str, name: &str) -> Result<()> { match self { Self::Container(d) => d.tag_image(image, name).await, + Self::Firecracker(d) => d.tag_image(image, name).await, _ => anyhow::bail!("the {} driver does not use images", self.name()), } } @@ -272,6 +354,7 @@ impl Driver { pub async fn images(&self, repository: &str) -> Result> { match self { Self::Container(d) => d.images(repository).await, + Self::Firecracker(d) => d.images(repository).await, _ => Ok(Vec::new()), } } @@ -284,6 +367,7 @@ impl Driver { ) -> Result<()> { match self { Self::Container(d) => d.build(job, log).await, + Self::Firecracker(_) => anyhow::bail!("the firecracker driver builds no images"), _ => anyhow::bail!("the {} driver does not use images", self.name()), } } @@ -292,6 +376,7 @@ impl Driver { pub async fn image_size(&self, image: &str) -> Option { match self { Self::Container(d) => d.image_size(image).await, + Self::Firecracker(d) => d.image_size(image).await, _ => None, } } @@ -301,6 +386,7 @@ impl Driver { pub async fn remove_image(&self, image: &str) -> Result<()> { match self { Self::Container(d) => d.remove_image(image).await, + Self::Firecracker(d) => d.remove_image(image).await, _ => Ok(()), } } @@ -309,6 +395,7 @@ impl Driver { pub async fn sandbox_exists(&self, name: &str) -> Result { match self { Self::Container(d) => d.exists(name).await, + Self::Firecracker(d) => d.exists(name).await, _ => Ok(false), } } @@ -317,6 +404,7 @@ impl Driver { match self { Self::Process(d) => d.probe().await, Self::Container(d) => d.probe().await, + Self::Firecracker(d) => d.probe().await, Self::Lima(d) => d.probe().await, } } @@ -339,12 +427,13 @@ impl Driver { /// Where sandboxes keep their files: Apple's `container` its app root, /// Lima its home, Docker its root directory (on macOS inside its VM), - /// and the process driver `data_dir`. `None` when the Docker daemon - /// doesn't answer. + /// Firecracker and the process driver `data_dir`. `None` when the Docker + /// daemon doesn't answer. pub async fn disk_spot(&self, data_dir: &Path) -> Option { match self { Self::Process(_) => Some(DiskSpot::Dir(data_dir.to_owned())), Self::Container(d) => d.disk_spot(data_dir).await, + Self::Firecracker(d) => Some(d.disk_spot(data_dir)), Self::Lima(_) => Some(DiskSpot::Dir( lima::home() .filter(|h| h.is_dir()) @@ -372,9 +461,10 @@ impl Driver { /// Where `project`'s package caches are with this driver: a Docker /// volume, or a directory in `data_dir`, which Apple's `container` - /// mounts and the process driver's agents use. `None` with Lima, and - /// for a directory that Apple's `container` can't mount, whose path has - /// a comma. + /// mounts and the process driver's agents use. `None` with Lima and + /// Firecracker, whose VMs share no files with the host, and for a + /// directory that Apple's `container` can't mount, whose path has a + /// comma. pub fn cache_spot(&self, project: &str, data_dir: &Path) -> Option { let dir = caches::dir(data_dir, project); match self { @@ -383,7 +473,7 @@ impl Driver { } Self::Container(_) => (!dir.to_string_lossy().contains(',')).then_some(Spot::Dir(dir)), Self::Process(_) => Some(Spot::Dir(dir)), - Self::Lima(_) => None, + Self::Firecracker(_) | Self::Lima(_) => None, } } @@ -400,7 +490,7 @@ impl Driver { match self { Self::Container(d) if d.flavor_name() == "docker" => d.cache_volumes().await, Self::Container(_) | Self::Process(_) => Ok(caches::dirs(data_dir)), - Self::Lima(_) => Ok(Vec::new()), + Self::Firecracker(_) | Self::Lima(_) => Ok(Vec::new()), } } @@ -445,6 +535,7 @@ impl Driver { match self { Self::Process(d) => d.ensure(spec).await, Self::Container(d) => d.ensure(spec, log).await, + Self::Firecracker(d) => d.ensure(spec, log).await, Self::Lima(d) => d.ensure(spec, log).await, } } @@ -454,6 +545,7 @@ impl Driver { match self { Self::Process(_) => Ok(()), Self::Container(d) => d.install_agent(sb, binary).await, + Self::Firecracker(d) => d.install_agent(sb, binary).await, Self::Lima(d) => d.install_agent(sb, binary).await, } } @@ -463,6 +555,7 @@ impl Driver { match self { Self::Process(d) => d.start_agent(sb).await, Self::Container(d) => d.start_agent(sb).await, + Self::Firecracker(d) => d.start_agent(sb).await, Self::Lima(d) => d.start_agent(sb).await, } } @@ -472,6 +565,7 @@ impl Driver { match self { Self::Process(d) => d.attach(sb).await, Self::Container(d) => d.attach(sb).await, + Self::Firecracker(d) => d.attach(sb).await, Self::Lima(d) => d.attach(sb).await, } } @@ -481,16 +575,18 @@ impl Driver { match self { Self::Process(d) => d.exec(sb, script).await, Self::Container(d) => d.exec(sb, script).await, + Self::Firecracker(d) => d.exec(sb, script).await, Self::Lima(d) => d.exec(sb, script).await, } } /// Runs an interactive command (stdin/stdout piped). - pub async fn spawn(&self, sb: &Sandbox, script: &str) -> Result { + pub async fn spawn(&self, sb: &Sandbox, script: &str) -> Result { match self { - Self::Process(d) => d.spawn(sb, script).await, - Self::Container(d) => d.spawn(sb, script).await, - Self::Lima(d) => d.spawn(sb, script).await, + Self::Process(d) => d.spawn(sb, script).await.map(Running::child), + Self::Container(d) => d.spawn(sb, script).await.map(Running::child), + Self::Firecracker(d) => d.spawn(sb, script).await, + Self::Lima(d) => d.spawn(sb, script).await.map(Running::child), } } @@ -500,6 +596,7 @@ impl Driver { match self { Self::Process(d) => d.stop(sb).await, Self::Container(d) => d.stop(sb).await, + Self::Firecracker(d) => d.stop(sb).await, Self::Lima(d) => d.stop(sb).await, } } @@ -508,6 +605,7 @@ impl Driver { match self { Self::Process(d) => d.remove(sb).await, Self::Container(d) => d.remove(sb).await, + Self::Firecracker(d) => d.remove(sb).await, Self::Lima(d) => d.remove(sb).await, } } @@ -517,6 +615,7 @@ impl Driver { match self { Self::Process(d) => d.list().await, Self::Container(d) => d.list().await, + Self::Firecracker(d) => d.list().await, Self::Lima(d) => d.list().await, } } diff --git a/crates/fctl-host/src/image.rs b/crates/fctl-host/src/image.rs index 93e03d0f..91926bab 100644 --- a/crates/fctl-host/src/image.rs +++ b/crates/fctl-host/src/image.rs @@ -30,6 +30,11 @@ pub async fn build( ); return Ok(()); } + if driver.name() == "firecracker" { + bail!( + "The firecracker driver builds no images: it pulls them from their registries (`fctl host image pull`)" + ); + } let info = driver.probe().await; // Lima only needs limactl here: its base VM is what this builds. if !info.available && !(driver.name() == "lima" && info.version.is_some()) { diff --git a/crates/fctl-host/src/login.rs b/crates/fctl-host/src/login.rs index 11c7e99f..0e801627 100644 --- a/crates/fctl-host/src/login.rs +++ b/crates/fctl-host/src/login.rs @@ -89,10 +89,7 @@ async fn login( let stderr = child.stderr.take().context("login stderr")?; let mut stdin = child.stdin.take().context("login stdin")?; let (line_tx, mut line_rx) = mpsc::unbounded_channel::(); - for reader in [ - Box::new(stdout) as Box, - Box::new(stderr), - ] { + for reader in [stdout, stderr] { let tx = line_tx.clone(); tokio::spawn(async move { // The CLI prompts without a newline; split on prompts too. diff --git a/crates/fctl-host/src/session.rs b/crates/fctl-host/src/session.rs index 8f72234e..60cde4c4 100644 --- a/crates/fctl-host/src/session.rs +++ b/crates/fctl-host/src/session.rs @@ -86,7 +86,7 @@ impl HostCtx { /// The images and builds this host's sessions may start from. pub fn images(&self) -> Images { - self.cfg.images(self.driver.uses_images()) + self.cfg.images(self.driver.builds_images()) } pub fn runner_id(&self) -> RunnerId { @@ -116,7 +116,7 @@ impl HostCtx { pub async fn refresh_facts(&self) { let data_dir = self.cfg.data_dir(); let (drivers, size, spot) = tokio::join!( - Driver::probe_all(&data_dir), + Driver::probe_all(&self.cfg), self.driver.measure(), self.driver.disk_spot(&data_dir) ); @@ -655,7 +655,7 @@ async fn prepare( let (image, fallback_image) = match want { // A sandbox that is here already keeps the image it was made from. ImageWant::Build(_) - if ctx.driver.uses_images() && !ctx.driver.sandbox_exists(&name).await? => + if ctx.driver.builds_images() && !ctx.driver.sandbox_exists(&name).await? => { uplink.state(state( SessionStatus::Provisioning, diff --git a/crates/fctl-proto/src/lib.rs b/crates/fctl-proto/src/lib.rs index 74c67de5..520e1407 100644 --- a/crates/fctl-proto/src/lib.rs +++ b/crates/fctl-proto/src/lib.rs @@ -14,6 +14,7 @@ //! | [`uplink`] | SessionDO ⇄ hosts (one connection per session) | //! | [`agent`] | hosts ⇄ fctl-agent inside a sandbox, and `fctl` ⇄ fctl-agent within it | //! | [`tickets`] | tickets in a project's tracker, whatever the tracker, and Linear's connections | +//! | [`vm`] | hosts ⇄ the init of a Firecracker microVM, over its vsock | pub mod agent; pub mod api; @@ -25,6 +26,7 @@ pub mod session; pub mod tickets; pub mod uplink; pub mod viewer; +pub mod vm; #[cfg(feature = "ts")] mod ts_export; diff --git a/crates/fctl-proto/src/vm.rs b/crates/fctl-proto/src/vm.rs new file mode 100644 index 00000000..504352ea --- /dev/null +++ b/crates/fctl-proto/src/vm.rs @@ -0,0 +1,277 @@ +//! Host ⇄ the init of a Firecracker microVM (`fctl-agent` as the VM's PID 1), +//! over the VM's vsock. +//! +//! Firecracker puts a VM's vsock on the host as a unix socket. The host +//! connects to it, asks for [`PORT`] (`CONNECT 1024\n`, which Firecracker +//! answers with `OK \n`) and sends one [`Request`], a line of JSON. +//! The init answers with a [`Reply`] line. After an [`Request::Exec`] it +//! accepted, the connection carries [`frame`]s both ways until the program +//! 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. +//! +//! 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 +//! answers a request it doesn't know with an error. + +use serde::{Deserialize, Serialize}; +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`). +pub const NET_PORT: u32 = 1025; + +/// The VM's network, as the host's `passt` gives it: the VM's address and +/// prefix, the gateway, and the address that forwards DNS queries to the +/// host's resolver. +pub const ADDRESS: [u8; 4] = [10, 0, 2, 15]; +pub const PREFIX: u8 = 24; +pub const GATEWAY: [u8; 4] = [10, 0, 2, 2]; +pub const DNS: [u8; 4] = [10, 0, 2, 3]; +/// passt's MTU: large frames carry more per trip through the vsock. +pub const MTU: u32 = 65520; + +/// The longest request or reply line either side reads. +pub const MAX_LINE: usize = 1024 * 1024; + +/// What a VM boots to, from the kernel's command line (`fctl.mode=`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Mode { + /// A session's sandbox: the image's root filesystem (`/dev/vda`, read + /// only) under the sandbox's own disk (`/dev/vdb`). + Sandbox, + /// Unpacks an image's layers onto `/dev/vda`, then powers off. + Unpack, +} + +/// 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). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Boot { + pub mode: Mode, + pub name: String, + pub time_ms: Option, +} + +impl Boot { + /// The parameters for the kernel's command line. + pub fn params(&self) -> String { + let mode = match self.mode { + Mode::Sandbox => "sandbox", + Mode::Unpack => "unpack", + }; + let mut p = format!("fctl.mode={mode} fctl.name={}", self.name); + if let Some(t) = self.time_ms { + p.push_str(&format!(" fctl.time={t}")); + } + p + } + + /// Reads them back from `/proc/cmdline`. `None` without `fctl.mode`. + pub fn parse(cmdline: &str) -> Option { + let mut mode = None; + let mut name = String::from("fctl"); + let mut time_ms = None; + 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(Self { + mode: mode?, + name, + time_ms, + }) + } +} + +/// What the host asks the init. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum Request { + /// Whether the init is up; the reply says its version. + Hello { + /// The host's clock, which the VM's follows. + #[serde(default)] + now_ms: Option, + }, + /// Runs a program. + Exec(Exec), + /// Unpacks an image's layers, which follow, onto the VM's disk (only in + /// a VM booted to [`Mode::Unpack`]). + Unpack { layers: Vec }, + /// Stops every program, flushes the disks and powers the VM off. + Shutdown, +} + +/// A program to run, as `docker exec` runs one: as the image's user, with +/// its environment and in its working directory, unless the request says +/// otherwise. +#[skip_serializing_none] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Exec { + pub argv: Vec, + /// `name`, `uid`, `name:group` or `uid:gid`. Unset: root. + #[serde(default)] + pub user: Option, + /// `KEY=value`: the image's environment. The init adds `HOME` (the + /// user's), `HOSTNAME` and a `PATH` when they are missing. + #[serde(default)] + pub env: Vec, + /// Unset: `/`, as for an image without a working directory. + #[serde(default)] + pub cwd: Option, + /// Whether the host sends the program's input ([`frame::STDIN`]); + /// without it, the program reads nothing. + #[serde(default)] + pub stdin: bool, + /// Starts it in the background, with no input or output, and answers at + /// once. + #[serde(default)] + pub detach: bool, + /// The host's clock, which the VM's follows. + #[serde(default)] + pub now_ms: Option, +} + +/// A layer of an image, as its manifest describes it. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Layer { + /// `application/vnd.oci.image.layer.v1.tar+gzip`, or Docker's. + pub media_type: String, + /// Bytes, as they follow the request. + pub size: u64, +} + +/// The init's answer. +#[skip_serializing_none] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Reply { + /// Why the request failed; absent when it didn't. + #[serde(default)] + pub error: Option, + /// The init's version of fctl (to `hello`). + #[serde(default)] + pub version: Option, + /// What unpacking wrote (its second reply): files and bytes. + #[serde(default)] + pub files: Option, + #[serde(default)] + pub bytes: Option, +} + +impl Reply { + pub fn failed(error: impl Into) -> Self { + Self { + error: Some(error.into()), + ..Self::default() + } + } +} + +/// The frames a program's input and output travel in: a kind (1 byte), a +/// length (4 bytes, big endian) and that many bytes. +pub mod frame { + /// Host → VM: input for the program. + pub const STDIN: u8 = 0; + /// Host → VM: the end of its input. + pub const STDIN_END: u8 = 1; + /// VM → host: what it writes to its standard output. + pub const STDOUT: u8 = 2; + /// VM → host: what it writes to its standard error. + pub const STDERR: u8 = 3; + /// VM → host: its exit code (4 bytes, big endian, signed): 128 and the + /// signal's number for one a signal ended. The last frame. + pub const EXIT: u8 = 4; + + /// The most bytes one frame carries. + pub const MAX: usize = 1024 * 1024; + + /// A frame's first five bytes. + pub fn header(kind: u8, len: usize) -> [u8; 5] { + let len = u32::try_from(len.min(MAX)) + .unwrap_or(u32::MAX) + .to_be_bytes(); + [kind, len[0], len[1], len[2], len[3]] + } + + /// The kind and length in a frame's first five bytes; `None` for a + /// length over [`MAX`]. + pub fn parse(header: [u8; 5]) -> Option<(u8, usize)> { + let len = u32::from_be_bytes([header[1], header[2], header[3], header[4]]) as usize; + (len <= MAX).then_some((header[0], len)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn boot_parameters_round_trip_through_the_command_line() { + let boot = Boot { + mode: Mode::Sandbox, + name: "fctl-ses-01abc".into(), + time_ms: Some(1_761_700_000_000), + }; + let cmdline = format!( + "console=ttyS0 reboot=k panic=1 {} rdinit=/init", + boot.params() + ); + assert_eq!(Boot::parse(&cmdline), Some(boot)); + let unpack = Boot::parse("fctl.mode=unpack quiet"); + assert_eq!( + unpack.map(|b| (b.mode, b.name)), + Some((Mode::Unpack, "fctl".into())) + ); + assert_eq!(Boot::parse("console=ttyS0 root=/dev/vda"), None); + } + + #[test] + fn requests_are_tagged_and_take_missing_fields() -> serde_json::Result<()> { + let exec = Request::Exec(Exec { + argv: vec!["sh".into(), "-c".into(), "true".into()], + user: Some("agent".into()), + ..Exec::default() + }); + let line = serde_json::to_string(&exec)?; + assert_eq!( + line, + r#"{"type":"exec","argv":["sh","-c","true"],"user":"agent","env":[],"stdin":false,"detach":false}"# + ); + assert_eq!(serde_json::from_str::(&line)?, exec); + assert_eq!( + serde_json::from_str::(r#"{"type":"exec","argv":["true"]}"#)?, + Request::Exec(Exec { + argv: vec!["true".into()], + ..Exec::default() + }) + ); + assert_eq!( + serde_json::from_str::(r#"{"type":"hello"}"#)?, + Request::Hello { now_ms: None } + ); + // An init that doesn't know a request says so. + assert!(serde_json::from_str::(r#"{"type":"snapshot"}"#).is_err()); + assert_eq!(serde_json::to_string(&Reply::default())?, "{}"); + Ok(()) + } + + #[test] + fn frames_say_their_kind_and_length() { + let h = frame::header(frame::STDOUT, 300); + assert_eq!(h, [2, 0, 0, 1, 44]); + assert_eq!(frame::parse(h), Some((frame::STDOUT, 300))); + assert_eq!(frame::parse([2, 0xff, 0xff, 0xff, 0xff]), None); + } +} diff --git a/crates/fctl/src/cmd/host.rs b/crates/fctl/src/cmd/host.rs index b6876122..2622160e 100644 --- a/crates/fctl/src/cmd/host.rs +++ b/crates/fctl/src/cmd/host.rs @@ -20,7 +20,7 @@ pub enum HostCmd { /// Runner name (default: the hostname). #[arg(long)] name: Option, - /// apple, docker, lima, process, or auto. + /// apple, docker, firecracker, lima, process, or auto. #[arg(long, default_value = "auto")] driver: String, /// Maximum concurrent sessions. @@ -220,10 +220,13 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { Some(config::api(Some(&server)).context(SIGN_IN)?) }; // `auto` picks like the daemon does, except that it never settles for - // the process driver. + // the process driver; neither picks Firecracker, which a host's + // owner chooses. let driver = if driver == "auto" { - let infos = Driver::probe_all(&cfg.data_dir()).await; - let runtimes = infos.iter().filter(|i| i.name != "process"); + let infos = Driver::probe_all(&cfg).await; + let runtimes = infos + .iter() + .filter(|i| i.name != "process" && i.name != "firecracker"); match runtimes.clone().find(|i| i.available) { Some(info) => info.name.clone(), None => { @@ -233,6 +236,9 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { let detail = info.detail.as_deref().unwrap_or_default(); why.push_str(&format!("\n {}: {detail}", info.name)); } + if infos.iter().any(|i| i.name == "firecracker" && i.available) { + why.push_str("\nFirecracker is ready: --driver firecracker runs each session in a microVM of its own."); + } bail!( "{why}\nInstall one, or pass --driver process to run agents without isolation." ); @@ -241,7 +247,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { } else { driver }; - let d = Driver::select(&driver, &cfg.data_dir(), cfg.agent_bin.clone()).await?; + let d = Driver::select(&driver, &cfg).await?; if build_image { fctl_host::image::build(&d, &cfg.image(), &cfg.download_base, None).await?; } @@ -313,7 +319,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { cfg.image() )) ); - let images = cfg.images(true); + let images = cfg.images(d.builds_images()); println!( "{}", style::dim(&format!( @@ -357,9 +363,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { HostCmd::Status => { let cfg = HostConfig::load()?; let (installed, running) = service::status(); - let driver = Driver::select(&cfg.driver, &cfg.data_dir(), None) - .await - .ok(); + let driver = Driver::select(&cfg.driver, &cfg).await.ok(); let (sandbox, (spot, free)) = match &driver { Some(d) => ( Some(cfg.sandbox_limits(d.resources().await)), @@ -417,7 +421,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { println!("updates: {}", updates_line(&cfg)); println!("claude: {}", claude_line(&cfg)); if let Some(d) = &driver { - let images = cfg.images(d.uses_images()); + let images = cfg.images(d.builds_images()); println!( "images: {}; {}", image::describe_allowed(images.allowed.as_deref()), @@ -470,7 +474,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { }, HostCmd::Image(ImageCmd::Pull) => { let cfg = HostConfig::load().unwrap_or_default(); - let d = Driver::select(&cfg.driver, &cfg.data_dir(), cfg.agent_bin.clone()).await?; + let d = Driver::select(&cfg.driver, &cfg).await?; if !d.uses_images() { bail!( "The {} driver doesn't use images{}", @@ -536,7 +540,7 @@ pub async fn run(server: Option<&str>, cmd: HostCmd, json: bool) -> Result<()> { }) => { let cfg = HostConfig::load().unwrap_or_default(); let name = driver.unwrap_or(cfg.driver.clone()); - let d = Driver::select(&name, &cfg.data_dir(), cfg.agent_bin.clone()).await?; + let d = Driver::select(&name, &cfg).await?; let tag = tag.unwrap_or_else(|| cfg.image()); fctl_host::image::build(&d, &tag, &cfg.download_base, source.as_deref()).await } @@ -762,7 +766,7 @@ async fn running_sandboxes() -> usize { let Ok(cfg) = HostConfig::load() else { return 0; }; - let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), cfg.agent_bin.clone()).await else { + let Ok(d) = Driver::select(&cfg.driver, &cfg).await else { return 0; }; d.list() @@ -781,7 +785,7 @@ async fn stop_sandboxes_here(json: bool) { let Ok(cfg) = HostConfig::load() else { return; }; - let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), cfg.agent_bin.clone()).await else { + let Ok(d) = Driver::select(&cfg.driver, &cfg).await else { return; }; let Ok(list) = d.list().await else { return }; @@ -1192,7 +1196,7 @@ async fn doctor() -> Result<()> { ); } } - for d in Driver::probe_all(&cfg.data_dir()).await { + for d in Driver::probe_all(&cfg).await { let line = format!( "driver {}: {}", d.name, @@ -1204,7 +1208,7 @@ async fn doctor() -> Result<()> { println!("{} {}", style::dim("·"), style::dim(&line)); } } - if let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), None).await + if let Ok(d) = Driver::select(&cfg.driver, &cfg).await && d.uses_images() && d.probe().await.available { @@ -1245,19 +1249,19 @@ async fn doctor() -> Result<()> { &problems_with_images.join("; "), ); if cfg.allowed_builds.is_some() - && let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), None).await - && !d.uses_images() + && let Ok(d) = Driver::select(&cfg.driver, &cfg).await + && !d.builds_images() { println!( "{} {}", style::dim("·"), style::dim(&format!( - "allowed_builds: the {} driver uses no images, so this host builds none", + "allowed_builds: the {} driver builds no images, so this host builds none", d.name() )) ); } - if let Ok(d) = Driver::select(&cfg.driver, &cfg.data_dir(), None).await + if let Ok(d) = Driver::select(&cfg.driver, &cfg).await && let (Some(spot), free) = disk_here(&cfg, &d).await { match (free, cfg.min_free_disk_mb()) { 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 new file mode 100644 index 00000000..ecc6565c --- /dev/null +++ b/docs/adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md @@ -0,0 +1,92 @@ +# 0070: Linux hosts run sandboxes in Firecracker microVMs + +2026-10-29 · accepted + +## Context + +[0003](0003-hosts-dial-out.md) gave every session its own sandbox, a VM +where the platform has one: Apple's `container` on Apple silicon, Lima +elsewhere on macOS. On Linux, sessions ran in Docker containers, which +share the host's kernel: a bug in it, or in the container runtime, is a way +out of the sandbox for an agent that runs with its permission prompts off, +and Docker's daemon is root's. Lima runs a full VM per session on Linux +too, but it clones a base VM prepared by hand, boots for a minute or more, +runs no images, and is experimental. + +The roadmap had "Linux hosts with Firecracker microVMs". Session #536 was +asked to explore everything that has to come together for Firecracker to +be a seamless driver for the Linux hosts whose owners want each agent in a +microVM of its own. + +## Decision + +- **A `firecracker` driver, which a host's owner chooses** (`fctl host + install --driver firecracker`). `auto` keeps choosing among Apple's + `container`, Docker and Lima, so that updating fctl changes no host's + driver. +- **Nothing runs as root.** Firecracker runs as the host's user, who needs + `/dev/kvm` (the `kvm` group), `passt` and e2fsprogs. The host downloads + Firecracker itself, at the release fctl pins (1.17.0, checked against its + SHA-256), unless `host.toml` names a binary. It runs without + Firecracker's jailer, which needs root; Firecracker's own seccomp filters + still apply. +- **The same images as Docker, pulled without Docker.** The host reads an + image's manifest for its platform, its config and its layers from the + registry, each checked against its digest, anonymously or with the + credentials of `docker login`. A short-lived VM booted for it unpacks the + layers, whiteouts and all, onto an ext4 filesystem, as root there: + owners, modes, setuid bits and capabilities stay as the image has them, + without root on the host, and no file of an image touches the host's + filesystem. Projects' own images run as with Docker; building images + (`allowed_builds`) is for later. +- **An image's filesystem is shared; each sandbox has a disk.** The + sandboxes made from an image share its filesystem, read only, and each + has its own sparse ext4 disk (`disk_gb`, 64 GiB unless `host.toml` says + 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. +- **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 + (the kernel's filesystems, a hostname, DNS), reaps orphans, and keeps a + server on the VM's vsock that runs what the host asks as `docker exec` + does: as the image's user, with its environment, in its working + directory. The host needs no SSH, and the image nothing of fctl's. +- **The network goes through `passt`, without root.** The VM's `eth0` is + a TAP device inside the VM, whose frames fctl-agent carries over the + vsock to a `passt` of the VM's own on the host, which makes them the + host's own connections, as Podman's rootless networking does. The host + gets no bridge, TAP device or firewall rule; VMs reach neither each + other nor the host's loopback, and nothing reaches them from outside. +- **hyperstructure/sandbox publishes the kernel.** Linux's long-term 6.18 + with Firecracker's guest configuration, built for both architectures and + published as an image, `ghcr.io/hyperstructure/sandbox-kernel:`, + whose version each fctl release pins. `host.toml` can name another image + or a file. +- **VMs outlive the host's process.** Firecracker and `passt` run in + process groups of their own, as the process driver's agents do, which + the service doesn't stop with the host (`KillMode=process`), so + restarting or updating the host leaves sessions running. The host finds + their VMs by their sockets when it starts and attaches again. + +## Consequences + +- A Linux host's sessions each get a kernel of their own, from the + default image or their project's, once its owner has added themselves to + `kvm` and installed `passt`. +- A VM escape would run as the host's user, who can read the runner's + token and any Claude token kept on the host, as a container escape can + with Docker. Running Firecracker through its jailer, as another user in + a chroot, needs a host that runs as root, and is for later. +- Firecracker's VMs share no filesystem with the host, so they get no + package caches, as Lima's don't. +- An image's first pull takes longer than Docker's (it unpacks in a VM), + and each image takes all its size on disk: images share no layers. +- A VM holds the memory its guest has touched, but for what its balloon + 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. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8e61b7e5..9050ff50 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -75,3 +75,4 @@ supersede an earlier one. Copy the newest record to start a new one. | [0067](0067-review-agents-sum-pull-requests-up-in-their-descriptions.md) | Review agents sum pull requests up in their descriptions | | [0068](0068-projects-choose-whether-drafts-get-reviews.md) | Projects choose whether drafts get reviews | | [0069](0069-releases-start-their-sandbox-image-and-homebrew-bump-as-a-github-app.md) | Releases start their sandbox image and Homebrew bump, as a GitHub App | +| [0070](0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md) | Linux hosts run sandboxes in Firecracker microVMs | diff --git a/docs/agents.md b/docs/agents.md index c9214a86..c3818981 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -523,8 +523,9 @@ archive SESSION` takes it out of the lists. ### Bring a machine online On the machine, by its owner: install a driver (Apple's `container` on -macOS 26 with Apple silicon, then `container system start`; Lima; or -Docker), then: +macOS 26 with Apple silicon, then `container system start`; Lima; Docker; +or on Linux with KVM, `passt` and `e2fsprogs` for `fctl host install +--driver firecracker`), then: ```sh curl -fsSL https://fctl.sh/install | sh diff --git a/docs/architecture.md b/docs/architecture.md index b69b7104..a817e4ff 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -24,10 +24,11 @@ boundary. │ │ control WS │ session uplink WS (one per session) │ ┌──────────────┴─────────────┴───────────────┐ │ │ fctl host (Rust daemon on your machine) │ - │ │ ├─ drivers: apple · docker · lima · proc │ + │ │ ├─ drivers: apple · docker · firecracker │ + │ │ │ · lima · process │ │ │ └─ per session: sandbox + attach channel │ │ └──────────────┬─────────────────────────────┘ - │ │ framed JSON over exec/unix socket + │ │ framed JSON over exec, a unix socket or a vsock │ ┌──────────────┴─────────────────────────────┐ │ │ sandbox (VM) │ │ │ fctl-agent (supervisor, journal) │ @@ -2787,8 +2788,8 @@ repository to build one from (`image_build`: a Dockerfile and its context, or a dev container configuration). Hosts send the images they run besides their own (`HostHello.allowed_images`: references, `/*` prefixes, digest pins; absent: any) and the repositories they build images from -(`allowed_builds`; absent: none, and always absent with Lima or the process -driver). FleetDO reads each queued session's image with its size +(`allowed_builds`; absent: none, and always absent with Firecracker, Lima or +the process driver). FleetDO reads each queued session's image with its size (`fctl_domain::image::ImageWant`) and only assigns it to a runner whose lists take it (`fctl_domain::schedule::pick`); a session that none online takes stays queued with the reason. The host checks its lists again before @@ -2806,6 +2807,7 @@ be reached. | Driver | Isolation | Host | |---|---|---| | `apple` | one lightweight VM per session (Apple `container`) | Apple silicon, macOS 26+ | +| `firecracker` | one microVM per session, with a kernel of its own ([Firecracker](#firecracker)) | Linux with KVM | | `lima` | one full VM per session | macOS, Linux | | `docker` | containers in Docker/OrbStack/Colima (a VM on macOS) | macOS, Linux | | `process` | none: a directory and a process | development, trusted hosts | @@ -2821,7 +2823,8 @@ limits (older versions) take any size. The host passes the size it applied to fctl-agent (`AgentConfig.sandbox`), which tells Claude: with Docker, `nproc` and `free` show the VM, not the sandbox's cgroup limits, and with Apple's `container`, `nproc` counts one CPU more than the sandbox may use. -The process driver limits nothing. +A Firecracker sandbox is a VM of exactly that size. The process driver +limits nothing. An Apple `container` sandbox is a VM of its own. Apple's runtime gives the VM one CPU and 128 MiB more than the sandbox's size, for the guest kernel @@ -2901,7 +2904,7 @@ It also keeps `min_free_disk_gb` free on the disk where the sandboxes' files are: Apple's `container` app root (from `container system status`), Lima's home, Docker's root directory, or with Docker on macOS the disk in its VM, where `df` runs in a short-lived container of the host's image, and -the data directory with the process driver. It measures every 30 seconds +the data directory with Firecracker and the process driver. It measures every 30 seconds (in Docker's VM every five minutes). Below the floor: - The sweep removes the other stopped sandboxes too, those stopped longest @@ -2924,6 +2927,75 @@ conversation to resume, so Claude starts a new one with the session's original task, and the agent numbers its events after the ones the control plane already has (`first_agent_seq`). +### Firecracker + +On Linux hosts with KVM, the `firecracker` driver runs each sandbox in a +[Firecracker](https://firecracker-microvm.github.io) microVM with a kernel +of its own, from the same images as Docker, without Docker and without +root ([ADR 0070](adr/0070-linux-hosts-run-sandboxes-in-firecracker-microvms.md), +`crates/fctl-host/src/driver/firecracker`). A host's owner chooses it +(`fctl host install --driver firecracker`; `auto` never does). It needs +`/dev/kvm` (the `kvm` group), `passt` and `mkfs.ext4`; it downloads +Firecracker itself, at the release fctl pins (1.17.0, checked against its +SHA-256), and the VMs' kernel, Linux 6.18 with Firecracker's guest +configuration, which hyperstructure/sandbox publishes as an image +(`ghcr.io/hyperstructure/sandbox-kernel:`), unless the +`[firecracker]` table of `host.toml` names others. Everything it keeps is +in `firecracker/` in the host's data directory. + +- **Images.** The host reads an image's manifest for its platform, its + config and its layers from the registry, each checked against its + digest (`registry.rs`): anonymously, or with the credentials of `docker + login` (its `auths`, not credential helpers), over plain HTTP only for a + registry on the machine itself. A VM booted for it (`fctl.mode=unpack`) + unpacks the layers onto a new ext4 filesystem, as root there, with their + whiteouts: owners, modes, setuid bits and capabilities stay the image's, + and no file of the image touches the host's filesystem. Each image keeps + its filesystem, read only, and what its config says about running it + (user, environment, working directory, labels), under its config's + digest, as Docker's image ID; names refer to images as Docker's tags do + (`images.rs`). A pull whose image is here already reads only its + manifest, so refreshing the default image works as with Docker. Removing + a name keeps the last one of an image that a sandbox uses. Images share + no layers, and the driver builds none. +- **Sandboxes.** A sandbox is a directory with its own disk, a sparse ext4 + file of `disk_gb` (64 GiB by default) that takes what the session + writes. Its VM's init lays it over the image's filesystem with overlayfs, + and the disk gives the host back what the session deletes (discard). + Stopping a sandbox keeps its disk; starting it again boots from it, with + the size the session asks for then. +- **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 + bring (the kernel's filesystems, the hostname, `/etc/hosts`, + `/etc/resolv.conf`, 1,048,576 open files), and keeps `fctl-agent + vm-serve` running and reaps the programs whose parents exit first. The + host talks to `vm-serve` through Firecracker's vsock socket + (`fctl_proto::vm`): it runs a program as `docker exec` would, as the + image's user with its environment and working directory, in a session of + its own, which it stops when the host goes away; it carries the + program's input and output in frames; and it stops the VM: every + program, then the disks written out, then a reset, which ends + Firecracker. The VM's clock follows the host's, which each request + carries. +- **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. +- **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 + keeps and the sockets in their command lines, in a private directory of + the user's in `/tmp` (sockets' paths are limited to about 100 bytes). + A VM's console goes to `console.log` in its directory. + +The VMs share no files with the host, so they get no +[package caches](#package-caches). Firecracker runs as the host's user, +without its jailer, which needs root: a VM escape would run as that user. + ### Package caches A project can share its package managers' downloads between its sessions @@ -2941,7 +3013,8 @@ and the host checks. `caches/`, that each sandbox bind-mounts: Apple's named volumes are ext4 images, which two running VMs must not mount at once. Both appear at `/var/cache/fctl`. The process driver's agents use the - directory where it is, and Lima's VMs get none. The mount is made with + directory where it is, and Firecracker's and Lima's VMs get none: they + share no files with the host. The mount is made with the sandbox, so a sandbox made before its project turned caches on gets none until the session's next one. Docker makes a new volume's root root's, so the host gives it to the image's user (`id -u` in the diff --git a/docs/cli.md b/docs/cli.md index ce95843e..2c541bc1 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -390,7 +390,8 @@ only what is new. The runner keeps them for the project up to its owner's limit, 10 GiB unless `host.toml` says otherwise, empties them past it, and removes them two weeks after a session last used them ([Hosts](#hosts)). Sessions get them on runners with the Docker or Apple container driver -(and the process driver), not Lima, and review agents never do. A session +(and the process driver), not Firecracker or Lima, and review agents never +do. A session in a sandbox made before the project turned them on gets them in its next sandbox. @@ -708,6 +709,7 @@ your secrets manager writes. ```sh fctl host install # register this machine and start the service fctl host install --driver lima --capacity 2 --build-image +fctl host install --driver firecracker # Linux with KVM: each session in a microVM of its own fctl host install --cpus 4 --memory 8g --max-cpus 8 --max-memory 12g # sandbox sizes fctl host install --name studio-mac --image ghcr.io/acme/agent:1 # its name (default: the hostname), and the image for projects that choose none fctl host install --allow-image 'ghcr.io/acme/*' --allow-build 'acme/*' # what projects may run and build @@ -760,14 +762,15 @@ prints the end of it on both. `fctl host install` checks the driver before it registers anything: if the driver can't run sessions (Apple's `container` or Lima isn't installed, a service isn't running), it says what to fix and stops. `--driver auto` (the -default) picks the first ready one of apple, docker and lima, never the -process driver, and the driver it checked goes into the host's settings in +default) picks the first ready one of apple, docker and lima, never +firecracker, which a host's owner chooses, or the process driver, and the +driver it checked goes into the host's settings in `~/.config/fctl/host.toml`: ```toml server = "https://app.fctl.sh" name = "studio-mac" -driver = "apple" # apple | lima | docker | process | auto (picks at every start) +driver = "apple" # apple | lima | docker | firecracker | process | auto (picks at every start) capacity = 4 # concurrent sessions # image = "ghcr.io/acme/agent:1" # unset: the published image of the host's version cpus = 4 # per sandbox, when the project sets none @@ -783,8 +786,30 @@ keep_caches_days = 14 # then remove the caches of a project with no session h build_timeout_minutes = 60 max_build_mb = 20480 # the largest image a build may make auto_update = true # update fctl to the version the control plane runs (false: `fctl self update`) + +[firecracker] # with the firecracker driver +# 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 +``` + +On Linux, `--driver firecracker` runs each session in a +[Firecracker](https://firecracker-microvm.github.io) microVM with a kernel +of its own, from the same images as Docker, with nothing running as root. +It needs KVM that your user may use, and two packages: + +```sh +sudo usermod -aG kvm $USER # then log in again; `ls -l /dev/kvm` shows the group +sudo apt install passt e2fsprogs # or dnf, pacman: passt gives the VMs their network +fctl host install --driver firecracker ``` +The host downloads Firecracker and the VMs' kernel itself, and pulls +images without Docker: a short-lived VM unpacks each, so its first pull +takes a little longer than Docker's. Its sandboxes get no package caches +and it builds no images; projects' own images run as with Docker. +[Architecture](architecture.md#firecracker) has the details. + Sessions start from their project's image or, without one, the host's: unless `image` sets another, the published image of the host's own version, `ghcr.io/hyperstructure/sandbox:`, which the host pulls when it @@ -825,7 +850,8 @@ shows its 512 GiB disk image rather than what the Mac has free. The host keeps `min_free_disk_gb` free (20 GiB unless `host.toml` says otherwise) on the disk where its sandboxes are: Apple's `container` app root, Lima's `~/.lima`, Docker's root directory or, with Docker on macOS, -the disk inside its VM, and the data directory with the process driver. It +the disk inside its VM, and the data directory with Firecracker and the +process driver. It measures every 30 seconds (inside Docker's VM every five minutes, since that starts a container). With less free than that: diff --git a/docs/getting-started.md b/docs/getting-started.md index 3394b02e..20bebbad 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -158,7 +158,10 @@ Any Mac with Apple silicon (or a Linux box) can be a host. On the Mac: ``` On older macOS, install [Lima](https://lima-vm.io) (`brew install lima`) - instead; on Linux, Docker. + instead; on Linux, Docker, or for a microVM of its own for each session, + KVM and `passt` ([Firecracker](cli.md#hosts): `sudo usermod -aG kvm + $USER`, `sudo apt install passt e2fsprogs`, and `--driver firecracker` + below). 2. Register the machine for a workspace you are in, and start the host service (or pass `--token` with a runner token from the workspace's diff --git a/docs/llms.txt b/docs/llms.txt index 4bc8284d..fdc4547a 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -8,7 +8,7 @@ fctl is open source under the MIT license: https://github.com/hyperstructure/fct ## What fctl gives you -- **Unattended agents in sandboxes.** Each session runs Claude Code with permission prompts off inside its own Linux VM or container on a runner (a Mac with Apple's `container`, Lima, or Docker). The agent clones the project's repository, works on a branch named `fctl/-`, commits, and fctl pushes after every turn; it opens a pull request when the task is done, unless the project turns that off. +- **Unattended agents in sandboxes.** Each session runs Claude Code with permission prompts off inside its own Linux VM or container on a runner (a Mac with Apple's `container`, Lima, Docker, or a Linux machine's Firecracker microVMs). The agent clones the project's repository, works on a branch named `fctl/<number>-<title>`, commits, and fctl pushes after every turn; it opens a pull request when the task is done, unless the project turns that off. - **Live, steerable work.** Every event is journaled and streamed: follow a session in the web app, in a terminal (`fctl attach`), or in the Claude apps (Remote Control, with a full Claude login). Message the agent at any time (with files), interrupt its turn, stop it, resume it later in the same sandbox and conversation. - **Work that starts itself.** Schedules (cron, once at a time, or only when asked), Linear (assign or mention fctl on an issue), GitHub Actions and any tool that can make an HTTP request with an access token. - **Agents that finish the job.** Follow-ups bring an agent back to the pull request it opened when someone who can write to the repository mentions `@fctl` or `@agent`, a check fails, the pull request conflicts with its base branch, or it merges or closes. Built-in review agents review every new commit of pull requests and hand their findings to the agent that opened the pull request. @@ -24,7 +24,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · GitHub webhooks │ control plane (an instance) users, workspaces, projects, sessions' event logs, │ (hosts dial out) scheduling, credentials, GitHub App, Linear app - fctl host on a machine (runner) one sandbox per session: apple · lima · docker · process + fctl host on a machine (runner) one sandbox per session: apple · lima · docker · firecracker · process │ fctl-agent + Claude Code in the sandbox: journals events, pushes, reports git state ``` @@ -43,7 +43,7 @@ web app · fctl CLI · HTTP API · Claude apps · Linear · GitHub webhooks - **Task**: the first message of a session. **Turn**: one round of Claude's work, from a message to the `result` that ends it. **Message**: what a person or tool sends a session at any time; it reaches the agent at its next step, and a stopped session resumes for it. - **Agent**: Claude Code running in a session's sandbox. **Review agent**: an agent that reviews a pull request's commit and posts findings through fctl. In these docs "agent" means one of these unless it says otherwise. - **Runner** (`rnr_…`): a machine registered with an instance, running `fctl host`. It belongs to the person who registered it and runs the sessions of the workspaces it is added to: everyone's there (added by an admin) or only its owner's (added by a member, or `--personal`). -- **Host**: the `fctl host` daemon (and the machine). **Driver**: how a host makes sandboxes: `apple` (a lightweight VM per session, Apple silicon, macOS 26+), `lima` (a full VM), `docker` (a container; on macOS inside Docker's VM), `process` (no isolation, development only). +- **Host**: the `fctl host` daemon (and the machine). **Driver**: how a host makes sandboxes: `apple` (a lightweight VM per session, Apple silicon, macOS 26+), `lima` (a full VM), `docker` (a container; on macOS inside Docker's VM), `firecracker` (a microVM per session with a kernel of its own, Linux with KVM, chosen with `--driver firecracker`), `process` (no isolation, development only). - **Sandbox**: the VM or container a session runs in. Its user is `agent`, the repository is at `~/workspace`, other repositories go in `~/repos/<owner>/<name>`, attachments in `~/attachments/`. A stopped session keeps its sandbox (72 hours by default) so a resume continues the same conversation. - **Image**: what sandboxes start from: `ghcr.io/hyperstructure/sandbox:<version>` by default (Debian with git, gh, Python and uv, Rust, Node.js, TypeScript, Bun, Playwright with its browsers, Claude Code and fctl), or the project's own, or one built from a Dockerfile or devcontainer.json in its repository. - **Claude connection** (`crd_…`): a person's Claude subscription credential: a full Claude login (Remote Control works), a long-lived token from `claude setup-token`, or a token kept on their runners that fctl never sees. @@ -192,7 +192,7 @@ Each recipe says who does what: some steps take a person with a role in the proj 9. **GitHub Issues as the tracker**: the default; agents use `gh issue` in the repositories they write to. `fctl projects set -p my-app --tickets github --tickets-repo owner/name` keeps them to one repository's issues (through `fctl ticket` when they write to other repositories too); `--tickets none` keeps them away from trackers. A maintainer can start a session that reaches GitHub's issues whatever the tracker says, to move them into Linear, say (`fctl run --github-issues`). 10. **Plan or review without changes**: `fctl run -p my-app -d --github read "Plan the move to Postgres: what changes, in what order, what can break."` or a project-wide cap: `fctl projects set -p my-app --github comment`. 11. **Set up a project** (a workspace admin): `fctl projects create "My app" --repo my-org/my-app -w acme`, then `fctl projects set -p my-app --setup-script 'npm ci' --idle-timeout 30 --pr-descriptions balanced`, more repositories with `fctl projects repos add my-org/my-lib --write -p my-app`, an image with `--image ghcr.io/acme/agent:1` or `--build Dockerfile`, size with `--cpus 8 --memory 16g`, shared package caches with `--package-caches on`, its agents' instructions, model and effort with `--instructions-file agents.md --model opus --effort high`, opening pull requests when they finish with `--auto-pull-request on|off`, how they handle pull requests and issues with `--pr-instructions-file prs.md` (`fctl projects show my-app --pr-instructions` prints fctl's rules to start from), Remote Control and claude.ai connectors with `--remote-control on|off --connectors on|off`, and its name, description and default branch with `--name "Web app" --description "The storefront" --default-branch develop`. Secrets: `fctl projects secrets set STRIPE_KEY -p my-app`, the value typed at its prompt or piped in; `fctl projects secrets -p my-app` lists their names. People: `fctl projects members add grace@example.com --role maintainer -p my-app` (`viewer`, `editor`, `maintainer`, `owner`), `fctl projects members role …`, `fctl projects members remove …`. -12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`), Lima, or Docker; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait`, `fctl host undrain`. +12. **Bring a machine online** (its owner, at its terminal): install Apple's `container` (macOS 26+, `container system start`), Lima, or Docker, or on Linux with KVM `passt` and `e2fsprogs` for `--driver firecracker`; then `fctl login`, `fctl host install --workspace acme` (or `--token fctl_rt_…` from the workspace's Runners tab), `fctl host doctor`, `fctl host status`. Maintenance: `fctl host drain --wait`, `fctl host undrain`. 13. **Dashboards and reports**: a token with `--access read` lists sessions, transcripts, memory and retrospectives and starts nothing: `fctl sessions --active --json`, `fctl retro list -p my-app --json`, `fctl search "flaky test" --json`, `fctl logs my-app#12 --json`. 14. **Keep agents informed**: `fctl memory add -p my-app "Deploys happen on Thursdays: merge migrations by Tuesday."`; read what they learned with `fctl memory -p my-app` and `fctl retro list -p my-app --outcome blocked`. 15. **Hand a session to someone** (its owners): `fctl share <session> grace@example.com` lets someone in its workspace view it and message its agent (`--role viewer` only views it, `--role owner` also stops, resumes, archives and shares it), `fctl share <session>` lists who it is shared with, `fctl unshare <session> grace@example.com` takes it back. Anyone who can message the agent can have it hand over the sandbox's secrets and tokens. `fctl archive <session>` takes a finished session out of the lists and stops follow-ups reaching it (`fctl unarchive`, `fctl sessions --archived`). diff --git a/docs/sandbox-images.md b/docs/sandbox-images.md index ddf7c860..05f5eab3 100644 --- a/docs/sandbox-images.md +++ b/docs/sandbox-images.md @@ -81,6 +81,11 @@ pull` pulls it now. While the version's image can't be pulled, it pulls image build` prepares with the image's provisioning script, on Lima's Debian 13 (Debian 12 with Lima older than 2.0, which lacks it). The process driver uses no image. +- **Firecracker** hosts pull the same images without Docker, and unpack + each in a short-lived microVM into a filesystem that the sandboxes made + from it share, read only; they boot a kernel that hyperstructure/sandbox + publishes too, `ghcr.io/hyperstructure/sandbox-kernel:<version>`. They + build no images ([Architecture](architecture.md#firecracker)). - **Disk.** The host removes the default images that sessions no longer start from: builds that a newer one replaced, other versions' images, and `latest` once the version's image is there. It does that when it starts, @@ -92,7 +97,7 @@ pull` pulls it now. While the version's image can't be pulled, it pulls newer one replaced keeps the name `<tag>-replaced-<the start of its ID>` until then. Apple's `container` gives each sandbox its own copy of the image's filesystem, so the host removes them right away, and stopped - sandboxes still start. + sandboxes still start. Firecracker keeps them as Docker does. ## Its layout @@ -220,10 +225,13 @@ ENV DOTNET_ROOT=/home/agent/.dotnet \ registry: run `docker login ghcr.io` (with Apple container, `container registry login ghcr.io`) on each host, as the user its service runs as. fctl sends no registry credentials. For GHCR, a token - with `read:packages` is enough. + with `read:packages` is enough. Firecracker hosts read the credentials + `docker login` keeps in `~/.docker/config.json` (but not those of a + credential helper), so `docker login` there needs Docker's CLI only. Lima runners don't use images: their sessions run in a clone of the VM -`fctl host image build` prepared. The process driver uses none either. +`fctl host image build` prepared. The process driver uses none either, and +Firecracker runners build none. ## Building it from the repository diff --git a/docs/security.md b/docs/security.md index aa8b2bed..bbf75b31 100644 --- a/docs/security.md +++ b/docs/security.md @@ -209,10 +209,20 @@ owner and purpose), so a value copied between rows does not decrypt. ## Sandboxes -Each session runs in its own Linux VM (Apple container or Lima) or container -(Docker). The agent runs Claude Code with permission prompts off, because the -sandbox is the boundary: it can do anything inside its VM, and nothing -outside it except through these channels: +Each session runs in its own Linux VM (Apple container, Firecracker or +Lima) or container (Docker). The agent runs Claude Code with permission +prompts off, because the sandbox is the boundary: it can do anything inside +its VM, and nothing outside it except through these channels: + +- **Firecracker VMs** have a kernel of their own, as Apple's and Lima's + do, where a Docker container shares the host's: a kernel bug in the + sandbox stays there. They share no files with the host, and the host + runs what it runs in them through their vsock, not SSH. Firecracker runs + as the host's user, with its seccomp filters but without its jailer, + which needs root: a VM escape would run as that user, who can read the + runner's token, as a container escape can with Docker. Their images + unpack in a VM of their own, so a crafted layer can't reach the host's + filesystem. - **Lima VMs** get none of the mounts of Lima's templates, which give each VM the home directory of whoever runs the host (read only) and a @@ -236,9 +246,11 @@ outside it except through these channels: workspace's; a Docker that can't make the network leaves them on its default one, and the host says so in its log. With Docker Desktop and OrbStack, containers still reach the host's loopback - (`host.docker.internal`). Apple's `container` VMs share its network: on - a runner that serves more than one workspace, keep to Docker where that - matters. + (`host.docker.internal`). Firecracker VMs each reach the network through + a `passt` of their own, which makes their connections the host's: they + reach neither each other nor the host's loopback. Apple's `container` + VMs share its network: on a runner that serves more than one workspace, + keep to Docker or Firecracker where that matters. - **GitHub.** Installation tokens for the project's repositories and no others, within the GitHub accounts and repositories its workspace may use, valid for an hour and refreshed on demand