Repository navigation
feat(minvmd): add boot command and VMM child subcommand #339
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
6c4be65
e101111
fe4b131
792665a
9917771
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| //! `minvmd boot` subcommand (R2.3, R2.4). | ||
| //! | ||
| //! The parent process: | ||
| //! 1. Resolves kernel and rootfs paths from env vars (fail-fast validation). | ||
| //! 2. Creates a UNIX socket at a unique temp path and begins listening (the | ||
| //! READY-marker socket). | ||
| //! 3. Fork-execs `minvmd __krun-vmm` with `MINVMD_MARKER_SOCK` pointing to | ||
| //! that socket so the VMM child can register it with libkrun. | ||
| //! 4. Writes the child PID to `vmm.pid` in the state directory. | ||
| //! 5. Waits up to 5 s for the guest to connect and write `READY\n` on the | ||
| //! marker socket (R2.4). On success prints `vm-up` to stdout. | ||
| //! 6. With `--foreground`: stays alive until the VMM child exits, propagating | ||
| //! its exit code. | ||
| //! | ||
| //! On Linux this subcommand bails immediately with a "macOS only" error so the | ||
| //! Linux-only CI stays green. | ||
|
|
||
| use anyhow::{Result, bail}; | ||
|
|
||
| /// Run the `boot` subcommand. | ||
| /// | ||
| /// `foreground`: if true, block until the VMM child process exits after the VM | ||
| /// is confirmed up. | ||
| pub fn run(foreground: bool) -> Result<()> { | ||
| #[cfg(target_os = "macos")] | ||
| return run_macos(foreground); | ||
|
|
||
| #[cfg(not(target_os = "macos"))] | ||
| { | ||
| let _ = foreground; | ||
| bail!("`minvmd boot` is macOS-only; this Linux build is a no-op stub"); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(target_os = "macos")] | ||
| fn run_macos(foreground: bool) -> Result<()> { | ||
| use std::io::{BufRead, BufReader}; | ||
| use std::os::unix::net::UnixListener; | ||
| use std::path::PathBuf; | ||
| use std::time::Duration; | ||
|
|
||
| use anyhow::Context as _; | ||
|
|
||
| use crate::cmd::MARKER_SOCK_ENV; | ||
| use crate::image::{resolve_kernel_path, resolve_rootfs_path}; | ||
| use crate::state::StateDir; | ||
|
|
||
| // Fail-fast: resolve paths before spawning anything. | ||
| let _kernel = resolve_kernel_path().context("resolving kernel path")?; | ||
| let _rootfs = resolve_rootfs_path().context("resolving rootfs path")?; | ||
|
|
||
| // Create the marker socket under /tmp with a PID + random nonce to prevent | ||
| // predictable-path TOCTOU attacks (local-only risk, but cheap to harden). | ||
| let nonce = { | ||
| use std::io::Read as _; | ||
| let mut buf = [0u8; 4]; | ||
| let _ = std::fs::File::open("/dev/urandom").and_then(|mut f| f.read_exact(&mut buf)); | ||
| u32::from_le_bytes(buf) | ||
| }; | ||
| let marker_sock_path = PathBuf::from(format!( | ||
| "/tmp/minvmd-marker-{}-{nonce:08x}.sock", | ||
| std::process::id() | ||
| )); | ||
|
|
||
| // Remove any stale socket from a previous run. | ||
| let _ = std::fs::remove_file(&marker_sock_path); | ||
|
|
||
| let listener = | ||
| UnixListener::bind(&marker_sock_path).context("binding READY-marker unix socket")?; | ||
| listener | ||
| .set_nonblocking(false) | ||
| .context("setting listener to blocking")?; | ||
|
|
||
| // Spawn `minvmd __krun-vmm` — the VMM child that calls krun_start_enter. | ||
| let exe = std::env::current_exe().context("resolving current executable path")?; | ||
| let mut child = std::process::Command::new(&exe) | ||
| .arg("__krun-vmm") | ||
| .env(MARKER_SOCK_ENV, &marker_sock_path) | ||
| // Inherit MINVMD_KERNEL_PATH and MINVMD_ROOTFS_PATH from environment. | ||
| .spawn() | ||
| .with_context(|| format!("spawning VMM child: {}", exe.display()))?; | ||
|
|
||
| let child_pid = child.id(); | ||
| tracing::info!(pid = child_pid, "VMM child spawned"); | ||
|
|
||
| // Write vmm.pid to the state directory (R2.3). | ||
| let state_dir = StateDir::new(StateDir::default_path()).context("opening state dir")?; | ||
| let vmm_pid_path = state_dir.vmm_pid_path(); | ||
| std::fs::write(&vmm_pid_path, format!("{child_pid}\n")).context("writing vmm.pid")?; | ||
|
|
||
| // Wait for the READY marker from the guest (R2.4): up to 5 s. | ||
| const READY_TIMEOUT: Duration = Duration::from_secs(5); | ||
|
|
||
| // Run the accept loop in a separate thread so we can apply a wall-clock | ||
| // timeout without platform-specific socket options. | ||
| let (tx, rx) = std::sync::mpsc::channel::<Result<(), String>>(); | ||
| let sock_path_clone = marker_sock_path.clone(); | ||
| std::thread::spawn(move || { | ||
| let result = (|| -> Result<(), String> { | ||
| let (stream, _) = listener | ||
| .accept() | ||
| .map_err(|e| format!("accept on READY-marker socket: {e}"))?; | ||
| let mut reader = BufReader::new(stream); | ||
| let mut line = String::new(); | ||
| reader | ||
| .read_line(&mut line) | ||
| .map_err(|e| format!("reading READY marker: {e}"))?; | ||
| let trimmed = line.trim(); | ||
| if trimmed != "READY" { | ||
| return Err(format!("expected READY on marker socket, got {trimmed:?}")); | ||
| } | ||
| Ok(()) | ||
| })(); | ||
| let _ = tx.send(result); | ||
| let _ = std::fs::remove_file(&sock_path_clone); | ||
| }); | ||
|
|
||
| match rx.recv_timeout(READY_TIMEOUT) { | ||
| Ok(Ok(())) => { | ||
| println!("vm-up"); | ||
| } | ||
| Ok(Err(e)) => { | ||
| let _ = child.kill(); | ||
| let _ = child.wait(); | ||
| let _ = std::fs::remove_file(&vmm_pid_path); | ||
| let _ = std::fs::remove_file(&marker_sock_path); | ||
| bail!("boot failed: {e}"); | ||
| } | ||
| Err(_timeout) => { | ||
| let _ = child.kill(); | ||
| let _ = child.wait(); | ||
| let _ = std::fs::remove_file(&vmm_pid_path); | ||
| let _ = std::fs::remove_file(&marker_sock_path); | ||
| bail!("boot timed out waiting for READY marker after 5 s"); | ||
| } | ||
| } | ||
|
|
||
| if foreground { | ||
| let status = child.wait().context("waiting for VMM child")?; | ||
| if !status.success() { | ||
| let code = status.code().unwrap_or(-1); | ||
| bail!("VMM child exited with code {code}"); | ||
| } | ||
| } | ||
|
|
||
| Ok(()) | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| //! CLI subcommand implementations for `minvmd`. | ||
|
|
||
| pub mod boot; | ||
| pub mod vmm_child; | ||
|
|
||
| /// vsock port used by the VMM child to signal the parent that the guest is up. | ||
| /// | ||
| /// The guest's init writes `READY\n` to this vsock port; libkrun forwards the | ||
| /// connection to the host UNIX socket registered by the parent before spawning | ||
| /// the VMM child. The parent reads `READY` to confirm boot (R2.4). | ||
| /// | ||
| /// Must match the guest rootfs's READY/agent port. The canonical value is | ||
| /// `7350` — both the guest rootfs manifest (`etc/minvmd/manifest`: | ||
| /// `vsock_port_ready=7350`) and the reference impl (min-ctl: cold boot to a TCP | ||
| /// connection on `127.0.0.1:7350`) use it. The host previously used `9799`, | ||
| /// which no guest emits on, so the READY marker never arrived. | ||
| pub const VSOCK_MARKER_PORT: u32 = 7350; | ||
|
|
||
| /// Environment variable that carries the host-side UNIX socket path for the | ||
| /// READY marker from the parent to the VMM child. | ||
| pub const MARKER_SOCK_ENV: &str = "MINVMD_MARKER_SOCK"; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| //! `minvmd __krun-vmm` hidden subcommand (R2.3). | ||
| //! | ||
| //! This is the VMM child process that calls `krun_start_enter`. It is spawned | ||
| //! by `minvmd boot` and is not intended to be run directly by users (hence the | ||
| //! double-underscore prefix). | ||
| //! | ||
| //! On macOS: | ||
| //! 1. Reads kernel and rootfs from `MINVMD_KERNEL_PATH` / `MINVMD_ROOTFS_PATH`. | ||
| //! 2. Reads the READY-m 10000 arker socket path from `MINVMD_MARKER_SOCK`. | ||
| //! 3. Creates and configures a libkrun context. | ||
| //! 4. Registers the marker socket as the host-side endpoint for | ||
| //! `VSOCK_MARKER_PORT`: when the guest's init connects to that vsock port | ||
| //! and writes `READY\n`, libkrun forwards the data through to the host | ||
| //! UNIX socket where the parent is listening (R2.4). | ||
| //! 5. Calls `krun_start_enter`, which boots the VM. On success libkrun | ||
| //! `exit()`s with the guest workload's exit code and never returns here. | ||
| //! | ||
| //! On Linux this subcommand bails immediately with a "macOS only" error. | ||
|
|
||
| use anyhow::{Result, bail}; | ||
|
|
||
| /// Run the `__krun-vmm` subcommand. | ||
| pub fn run() -> Result<()> { | ||
| #[cfg(target_os = "macos")] | ||
| return run_macos(); | ||
|
|
||
| #[cfg(not(target_os = "macos"))] | ||
| bail!("`minvmd __krun-vmm` is macOS-only; this Linux build is a no-op stub"); | ||
| } | ||
|
|
||
| #[cfg(target_os = "macos")] | ||
| fn run_macos() -> Result<()> { | ||
| use anyhow::Context as _; | ||
|
|
||
| use crate::cmd::{MARKER_SOCK_ENV, VSOCK_MARKER_PORT}; | ||
| use crate::image::{resolve_kernel_path, resolve_rootfs_path}; | ||
| use crate::krun::Context; | ||
| use crate::vm::VmConfig; | ||
|
|
||
| let kernel = resolve_kernel_path().context("resolving kernel path")?; | ||
| let rootfs = resolve_rootfs_path().context("resolving rootfs path")?; | ||
| let marker_sock = std::env::var(MARKER_SOCK_ENV).with_context(|| { | ||
| format!("reading {MARKER_SOCK_ENV}: VMM child must be spawned by `minvmd boot`") | ||
| })?; | ||
|
|
||
| let mut ctx = Context::create().context("krun_create_ctx")?; | ||
| // Default 2 vcpus and 512 MiB RAM; the boot command may expose these as | ||
| // flags in a future change. | ||
| let cfg = VmConfig::new(2, 512, kernel, rootfs); | ||
| cfg.apply(&mut ctx) | ||
| .context("applying VmConfig to krun context")?; | ||
|
|
||
| // Register the READY-marker vsock port. When the guest's init connects to | ||
| // VSOCK_MARKER_PORT and writes `READY\n`, libkrun forwards the connection | ||
| // to the host UNIX socket at `marker_sock`, where the parent is listening | ||
| // (R2.4). | ||
| ctx.add_vsock_port(VSOCK_MARKER_PORT, &marker_sock) | ||
| .context("registering READY-marker vsock port")?; | ||
|
|
||
| tracing::info!( | ||
| port = VSOCK_MARKER_PORT, | ||
| sock = %marker_sock, | ||
| "READY-marker vsock port registered; calling krun_start_enter" | ||
| ); | ||
|
|
||
| // start_enter consumes the context and boots the VM. On success, libkrun | ||
| // exit()s the process with the guest workload's exit code and never | ||
| // returns. On failure it returns a VmError; we surface it as an anyhow | ||
| // error so the parent can observe the child's non-zero exit. | ||
| let err = ctx.start_enter(); | ||
| bail!("krun_start_enter returned unexpectedly: {err}"); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| //! Boot end-to-end test: READY-marker round-trip (R2.4). | ||
| //! | ||
| //! Gates: | ||
| //! - `#[cfg(target_os = "macos")]`: libkrun is macOS-only. | ||
| //! - `#[ignore]`: skipped by default; run with `cargo test -- --include-ignored`. | ||
| //! - `MINVMD_E2E=1`: even with `--include-ignored`, the test self-skips unless | ||
| //! this env var is set (prevents accidental VM boot on a dev machine without | ||
| //! a kernel and rootfs). | ||
| //! - `MINVMD_KERNEL_PATH` and `MINVMD_ROOTFS_PATH` must be set to the paths of | ||
| //! the `virtio-linux` kernel image and Alpine minirootfs respectively. | ||
| //! | ||
| //! The test spawns `minvmd boot --foreground`, waits up to 10 s for the | ||
| //! `vm-up` marker on stdout, then kills the child. A `vm-up` line confirms | ||
| //! that the guest's init wrote `READY\n` to the vsock marker port and the | ||
| //! parent received it (R2.4). | ||
|
|
||
| #![cfg(target_os = "macos")] | ||
|
|
||
| use serial_test::serial; | ||
| use std::io::{BufRead, BufReader}; | ||
| use std::process::{Command, Stdio}; | ||
| use std::time::Duration; | ||
|
|
||
| #[test] | ||
| #[serial] | ||
| #[ignore = "gated MINVMD_E2E=1; requires Mac with libkrun, kernel, and rootfs"] | ||
| fn boot_e2e_ready_marker_round_trip() { | ||
|
Comment on lines
+24
to
+27
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Isolate this E2E from the developer’s real This test launches the real Also applies to: 38-44 🤖 Prompt for AI Agents |
||
| if std::env::var("MINVMD_E2E").as_deref() != Ok("1") { | ||
| eprintln!("boot_e2e: MINVMD_E2E != 1, skipping"); | ||
| return; | ||
| } | ||
|
|
||
| for var in &["MINVMD_KERNEL_PATH", "MINVMD_ROOTFS_PATH"] { | ||
| assert!( | ||
| std::env::var(var).is_ok(), | ||
| "boot_e2e: {var} must be set when MINVMD_E2E=1" | ||
| ); | ||
| } | ||
|
|
||
| let state_dir = tempfile::TempDir::new().expect("creating isolated state dir"); | ||
|
|
||
| let exe = env!("CARGO_BIN_EXE_minvmd"); | ||
| let mut child = Command::new(exe) | ||
| .args(["boot", "--foreground"]) | ||
| .env("XDG_STATE_HOME", state_dir.path()) | ||
| .stdout(Stdio::piped()) | ||
| .stderr(Stdio::inherit()) | ||
| .spawn() | ||
| .expect("spawning minvmd boot --foreground"); | ||
|
|
||
| let stdout = child.stdout.take().expect("child stdout"); | ||
| let (tx, rx) = std::sync::mpsc::channel::<bool>(); | ||
| std::thread::spawn(move || { | ||
| let reader = BufReader::new(stdout); | ||
| for line in reader.lines().map_while(Result::ok) { | ||
| if line.trim() == "vm-up" { | ||
| let _ = tx.send(true); | ||
| return; | ||
| } | ||
| } | ||
| let _ = tx.send(false); | ||
| }); | ||
|
|
||
| let got_vm_up = rx.recv_timeout(Duration::from_secs(10)).unwrap_or(false); | ||
|
|
||
| let _ = child.kill(); | ||
| let _ = child.wait(); | ||
|
|
||
| assert!( | ||
| got_vm_up, | ||
| "boot_e2e: did not receive 'vm-up' within 10 s; \ | ||
| check that the guest rootfs writes READY\\n to vsock port {}", | ||
| minvmd::cmd::VSOCK_MARKER_PORT, | ||
| ); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LOW · correctness
On the timeout and error paths,
child.kill()is called but the marker socket file at/tmp/minvmd-marker-{pid}.sockis not cleaned up. The accept thread is still blocked onlistener.accept()and never reaches itsremove_filecall (line 105). The socket file leaks on disk until the nextbootinvocation cleans it via the stale-socket removal at line 56.Since the process
bail!s immediately after, the leaked thread is reclaimed by process exit and the stale file is handled by the next run — so this is a cosmetic leak, not a functional bug. Adefer-style cleanup (or an explicitremove_filein the error/timeout arms) would make the cleanup path airtight.