8000 feat(minvmd): add image resolution and VM configuration builder by gominimal-aw-bot[bot] · Pull Request #337 · gominimal/minimal · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
4 changes: 2 additions & 2 deletions crates/minvmd/src/bin/krun_smoke_child.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ fn main() -> Result<(), minvmd::VmError> {

#[cfg(target_os = "macos")]
fn run_macos() -> Result<(), minvmd::VmError> {
use minvmd::krun::{Context, KRUN_KERNEL_FORMAT_IMAGE_BZ2, KRUN_KERNEL_FORMAT_IMAGE_GZ};
use minvmd::krun::{Context, KRUN_KERNEL_FORMAT_ELF, KRUN_KERNEL_FORMAT_IMAGE_GZ};

eprintln!("STAGE: create_ctx");
let mut ctx = Context::create()?;
Expand Down Expand Up @@ -69,7 +69,7 @@ fn run_macos() -> Result<(), minvmd::VmError> {
let format = if cfg!(target_arch = "aarch64") {
KRUN_KERNEL_FORMAT_IMAGE_GZ
} else {
KRUN_KERNEL_FORMAT_IMAGE_BZ2
KRUN_KERNEL_FORMAT_ELF
};
eprintln!("STAGE: set_kernel path={kernel} format={format}");
ctx.set_kernel(&kernel, format, None::<&std::path::Path>, None)?;
Expand Down
9 changes: 8 additions & 1 deletion crates/minvmd/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ pub enum VmError {
/// process with the guest workload's exit code), so a non-negative
/// return is a protocol violation. `ret` is the raw libkrun return.
StartEnterReturnedUnexpectedly { ret: i32 },

/// A required environment variable was unset or empty.
MissingEnv { var: &'static str },
}

impl fmt::Display for VmError {
Expand Down Expand Up @@ -58,6 +61,9 @@ impl fmt::Display for VmError {
"krun_start_enter returned {ret} but libkrun's docs say it only returns on error"
)
}
Self::MissingEnv { var } => {
write!(f, "required environment variable {var} is unset or empty")
}
}
}
}
Expand All @@ -68,7 +74,8 @@ impl std::error::Error for VmError {
Self::Backend { source, .. } => Some(source),
Self::NulInPath { .. }
| Self::NulInString { .. }
| Self::StartEnterReturnedUnexpectedly { .. } => None,
| Self::StartEnterReturnedUnexpectedly { .. }
| Self::MissingEnv { .. } => None,
}
}
}
Expand Down
136 changes: 136 additions & 0 deletions crates/minvmd/src/image.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//! Kernel and rootfs image resolution.
//!
//! Paths are supplied at runtime via environment variables so the binary is
//! not tied to a fixed install layout.

use std::path::PathBuf;

use crate::error::VmError;

/// Arch-appropriate libkrun kernel format constant.
///
/// - `aarch64`: `virtio-linux` ships `Image.gz` → `KRUN_KERNEL_FORMAT_IMAGE_GZ`
/// - `x86_64`: `virtio-linux` ships `bzImage` → `KRUN_KERNEL_FORMAT_ELF`
#[cfg(target_os = "macos")]
pub fn kernel_format() -> u32 {
#[cfg(target_arch = "aarch64")]
{
crate::krun::KRUN_KERNEL_FORMAT_IMAGE_GZ
}
#[cfg(target_arch = "x86_64")]
{
crate::krun::KRUN_KERNEL_FORMAT_ELF
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/// Resolve the kernel path from `MINVMD_KERNEL_PATH`.
///
/// Returns `VmError::MissingEnv` when the variable is unset or empty.
pub fn resolve_kernel_path() -> Result<PathBuf, VmError> {
let val = std::env::var("MINVMD_KERNEL_PATH").map_err(|_| VmError::MissingEnv {
var: "MINVMD_KERNEL_PATH",
})?;
if val.is_empty() {
return Err(VmError::MissingEnv {
var: "MINVMD_KERNEL_PATH",
});
}
Ok(PathBuf::from(val))
}

/// Resolve the rootfs path from `MINVMD_ROOTFS_PATH`.
///
/// Returns `VmError::MissingEnv` when the variable is unset or empty.
pub fn resolve_rootfs_path() -> Result<PathBuf, VmError> {
let val = std::env::var("MINVMD_ROOTFS_PATH").map_err(|_| VmError::MissingEnv {
var: "MINVMD_ROOTFS_PATH",
})?;
if val.is_empty() {
return Err(VmError::MissingEnv {
var: "MINVMD_ROOTFS_PATH",
});
}
Ok(PathBuf::from(val))
}

#[cfg(test)]
mod tests {
use std::sync::Mutex;

use super::*;

// Serialise all tests that mutate MINVMD_KERNEL_PATH so they don't race
// when `cargo test` runs them in parallel.
static KERNEL_PATH_LOCK: Mutex<()> = Mutex::new(());

#[test]
fn resolve_kernel_path_errors_on_missing_env() {
let _g = KERNEL_PATH_LOCK.lock().unwrap();
unsafe { std::env::remove_var("MINVMD_KERNEL_PATH") };
let err = resolve_kernel_path().unwrap_err();
assert!(
matches!(
err,
Comment on lines +70 to +73
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.

MEDIUM — Correctness

Three tests in this file (resolve_kernel_path_errors_on_missing_env, resolve_kernel_path_returns_path_when_set, resolve_kernel_path_errors_on_empty_env) all mutate the MINVMD_KERNEL_PATH environment variable via unsafe blocks. The SAFETY comment states "single-threaded test", but cargo test runs tests in parallel by default — nothing in the test harness enforces single-threaded execution for these tests.

If two of these tests run concurrently, one may set the var while the other expects it unset, causing nondeterministic failures. Consider either:

  • Adding #[serial] from the serial_test crate to each env-mutating test, or
  • Extracting the env var name into a per-test unique key so they don't collide.

VmError::MissingEnv {
var: "MINVMD_KERNEL_PATH"
}
),
"expected MissingEnv, got {err:?}"
);
}

#[test]
fn resolve_kernel_path_returns_path_when_set() {
let _g = KERNEL_PATH_LOCK.lock().unwrap();
unsafe { std::env::set_var("MINVMD_KERNEL_PATH", "/boot/Image.gz") };
let path = resolve_kernel_path().unwrap();
assert_eq!(path, std::path::PathBuf::from("/boot/Image.gz"));
unsafe { std::env::remove_var("MINVMD_KERNEL_PATH") };
}

#[test]
fn resolve_kernel_path_errors_on_empty_env() {
let _g = KERNEL_PATH_LOCK.lock().unwrap();
unsafe { std::env::set_var("MINVMD_KERNEL_PATH", "") };
let err = resolve_kernel_path().unwrap_err();
assert!(
matches!(
err,
VmError::MissingEnv {
var: "MINVMD_KERNEL_PATH"
}
),
"expected MissingEnv, got {err:?}"
);
unsafe { std::env::remove_var("MINVMD_KERNEL_PATH") };
}

#[test]
fn resolve_rootfs_path_errors_on_missing_env() {
unsafe { std::env::remove_var("MINVMD_ROOTFS_PATH") };
let err = resolve_rootfs_path().unwrap_err();
assert!(
matches!(
err,
VmError::MissingEnv {
var: "MINVMD_ROOTFS_PATH"
}
),
"expected MissingEnv, got {err:?}"
);
}

#[cfg(target_os = "macos")]
#[test]
fn kernel_format_is_valid() {
let fmt = kernel_format();
let valid = [
crate::krun::KRUN_KERNEL_FORMAT_ELF,
crate::krun::KRUN_KERNEL_FORMAT_IMAGE_GZ,
];
assert!(
valid.contains(&fmt),
"unexpected kernel format constant {fmt}"
);
}
}
2 changes: 1 addition & 1 deletion crates/minvmd/src/krun/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ mod ctx;
mod raw;

pub use ctx::Context;
pub use raw::{KRUN_KERNEL_FORMAT_IMAGE_BZ2, KRUN_KERNEL_FORMAT_IMAGE_GZ};
pub use raw::{KRUN_KERNEL_FORMAT_ELF, KRUN_KERNEL_FORMAT_IMAGE_GZ};
11 changes: 7 additions & 4 deletions crates/minvmd/src/krun/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,14 @@ use crate::error::VmError;
// Kernel format constants from libkrun.h, used by `krun_set_kernel`. We only
// model the formats minvmd actually targets:
// - aarch64 `virtio-linux` ships `Image.gz` → `KRUN_KERNEL_FORMAT_IMAGE_GZ`
// - x86_64 `virtio-linux` ships `bzImage` → `KRUN_KERNEL_FORMAT_IMAGE_BZ2`
// - x86_64 `virtio-linux` ships `bzImage` → `KRUN_KERNEL_FORMAT_ELF`
//
// libkrun.h also defines RAW=0, ELF=1, PE_GZ=2, IMAGE_ZSTD=5 — added as
// needed.
pub const KRUN_KERNEL_FORMAT_IMAGE_BZ2: u32 = 3;
// Note: `IMAGE_BZ2` (=3) is for bzip2-compressed blobs, not the Linux bzImage
// container format. bzImage is loaded as ELF by libkrun.
//
// libkrun.h also defines RAW=0, PE_GZ=2, IMAGE_BZ2=3, IMAGE_ZSTD=5 — added
// as needed.
pub const KRUN_KERNEL_FORMAT_ELF: u32 = 1;
pub const KRUN_KERNEL_FORMAT_IMAGE_GZ: u32 = 4;

// SAFETY: every function in this block is an `extern "C"` declaration that
Expand Down
2 changes: 2 additions & 0 deletions crates/minvmd/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
//! compiles on both platforms.

pub mod error;
pub mod image;
pub mod lifecycle;
pub mod state;
pub mod vm;

#[cfg(target_os = "macos")]
pub mod krun;
Expand Down
81 changes: 81 additions & 0 deletions crates/minvmd/src/vm.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
//! VM configuration builder.
//!
//! [`VmConfig`] collects the parameters needed to configure a libkrun context
//! (vcpus, RAM, kernel, rootfs). No network device is added in v0.1; gvproxy/
//! TSI integration is tracked in #160.

use std::path::PathBuf;

/// Configuration parameters for a single microVM.
///
/// Build with [`VmConfig::new`] and apply to a libkrun
/// [`Context`][crate::krun::Context] with [`VmConfig::apply`].
#[derive(Debug, Clone)]
pub struct VmConfig {
/// Number of virtual CPUs.
pub num_vcpus: u8,
/// RAM in mebibytes.
pub ram_mib: u32,
/// Kernel image path.
pub kernel_path: PathBuf,
/// Rootfs directory path.
pub rootfs_path: PathBuf,
}

impl VmConfig {
/// Construct a new `VmConfig`.
#[must_use]
pub fn new(num_vcpus: u8, ram_mib: u32, kernel_path: PathBuf, rootfs_path: PathBuf) -> Self {
Self {
num_vcpus,
ram_mib,
kernel_path,
rootfs_path,
}
}

/// Apply this configuration to an existing libkrun [`Context`][crate::krun::Context].
///
/// Configures vcpus, RAM, kernel (with arch-appropriate format), and
/// rootfs. No network device is added (R2.5).
#[cfg(target_os = "macos")]
pub fn apply(&self, ctx: &mut crate::krun::Context) -> Result<(), crate::error::VmError> {
ctx.set_vm_config(self.num_vcpus, self.ram_mib)?;
ctx.set_kernel(
&self.kernel_path,
crate::image::kernel_format(),
None::<&std::path::Path>,
None,
)?;
ctx.set_root(&self.rootfs_path)?;
// R2.5: no network device in v0.1.
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn vm_config_stores_fields() {
let cfg = VmConfig::new(
2,
512,
PathBuf::from("/boot/Image.gz"),
PathBuf::from("/var/lib/alpine"),
);
assert_eq!(cfg.num_vcpus, 2);
assert_eq!(cfg.ram_mib, 512);
assert_eq!(cfg.kernel_path, PathBuf::from("/boot/Image.gz"));
assert_eq!(cfg.rootfs_path, PathBuf::from("/var/lib/alpine"));
}

#[test]
fn vm_config_clone() {
let cfg = VmConfig::new(1, 256, PathBuf::from("/k"), PathBuf::from("/r"));
let cfg2 = cfg.clone();
assert_eq!(cfg.num_vcpus, cfg2.num_vcpus);
assert_eq!(cfg.ram_mib, cfg2.ram_mib);
}
}
Loading
0