8000 feat(minvmd): add boot command and VMM child subcommand by gominimal-aw-bot[bot] · Pull Request #339 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/minvmd/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ tracing.workspace = true
tracing-subscriber.workspace = true

[dev-dependencies]
serial_test.workspace = true
tempfile.workspace = true
147 changes: 147 additions & 0 deletions crates/minvmd/src/cmd/boot.rs
7438
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}");
}
Comment on lines +118 to +128
Copy link
Copy Markdown
Contributor Author

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}.sock is not cleaned up. The accept thread is still blocked on listener.accept() and never reaches its remove_file call (line 105). The socket file leaks on disk until the next boot invocation 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. A defer-style cleanup (or an explicit remove_file in the error/timeout arms) would make the cleanup path airtight.

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(())
}
21 changes: 21 additions & 0 deletions crates/minvmd/src/cmd/mod.rs
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";
72 changes: 72 additions & 0 deletions crates/minvmd/src/cmd/vmm_child.rs
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}");
}
1 change: 1 addition & 0 deletions crates/minvmd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
//! since it links libkrun; portable surface (errors, state, image resolution)
//! compiles on both platforms.

pub mod cmd;
pub mod error;
pub mod image;
pub mod lifecycle;
Expand Down
17 changes: 12 additions & 5 deletions crates/minvmd/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
//! `minvmd` CLI entry point. Currently a skeleton: only `completions` is
//! wired. `boot`, `run`, `status`, `stop`, and the hidden `__krun-vmm` child
//! subcommand land in follow-up changes. The crate compiles on macOS (real)
//! and Linux (stub); Linux-only `bail!` paths land alongside the subcommands
//! that need them, so they never silently no-op.
//! `minvmd` CLI entry point.

use anyhow::Result;
use clap::{CommandFactory, Parser, Subcommand};
Expand All @@ -19,11 +15,20 @@ struct Cli {

#[derive(Subcommand)]
enum Command {
/// Boot the microVM and wait until the guest is up.
Boot {
/// Stay in the foreground until the VMM child exits.
#[arg(long)]
foreground: bool,
},
/// Generate shell completion script.
Completions {
/// Shell to generate completions for.
shell: Shell,
},
/// Hidden VMM child subcommand — spawned by `boot`, not for direct use.
#[command(name = "__krun-vmm", hide = true)]
KrunVmm,
}

fn main() -> Result<()> {
Expand All @@ -36,11 +41,13 @@ fn main() -> Result<()> {
let cli = Cli::parse();

match cli.command {
Command::Boot { foreground } => minvmd::cmd::boot::run(foreground),
Command::Completions { shell } => {
let mut cmd = Cli::command();
let name = cmd.get_name().to_string();
clap_complete::generate(shell, &mut cmd, name, &mut std::io::stdout());
Ok(())
}
Command::KrunVmm => minvmd::cmd::vmm_child::run(),
}
}
75 changes: 75 additions & 0 deletions crates/minvmd/tests/boot_e2e.rs
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
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Isolate this E2E from the developer’s real minvmd state.

This test launches the real boot path, and boot writes vmm.pid under StateDir::default_path(). Because the child inherits the ambient HOME/XDG state environment here, an opt-in local run can clobber the caller’s real state and race any other stateful E2Es. Please run it against an isolated home/state directory and serialize it with other stateful tests. Based on learnings: "Acquire fresh MINIMAL_HOME via test_support::with_isolated_home for tests that mutate process-wide state" and "Tests that mutate global state (MINCTL_HOME, env vars, on-disk caches) must be marked with #[serial]."

Also applies to: 38-44

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/minvmd/tests/boot_e2e.rs` around lines 23 - 25, The
boot_e2e_ready_marker_round_trip test launches the real boot path which writes
vmm.pid under StateDir::default_path() and can clobber the developer’s real
HOME/XDG state; wrap this test (and the other stateful E2E tests in the same
file) to use an isolated home by acquiring a fresh MINIMAL_HOME via
test_support::with_isolated_home and ensure the test is serialized by adding
#[serial] so it doesn’t race other stateful tests; update the
boot_e2e_ready_marker_round_trip test to call test_support::with_isolated_home
(providing the isolated env) and annotate it with #[serial] so
StateDir::default_path() and any created vmm.pid are scoped to the isolated
directory.

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,
);
}
Loading
0