From f7ca39117a8f8de29012c36fbc649bbd4ba51fe6 Mon Sep 17 00:00:00 2001 From: Marvin Date: Tue, 25 Aug 2026 19:53:47 +0000 Subject: [PATCH] slim-rs v1: initrd build + qemu run via podman image mount --- .gitignore | 4 ++ Cargo.toml | 15 +++++ src/main.rs | 156 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.toml create mode 100644 src/main.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c7b48af --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/target/ +/target/debug/ +/target/release/ +Cargo.lock diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..92da267 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "slim" +version = "0.1.0" +edition = "2021" + +[dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive"] } +flate2 = "1" +walkdir = "2" +cpio = "0.2" +xdg = "2" + +[dev-dependencies] +tempfile = "3" diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..eaac44e --- /dev/null +++ b/src/main.rs @@ -0,0 +1,156 @@ +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; +use std::fs::{self, File}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[derive(Parser, Debug)] +#[command(name = "slim")] +#[command(about = "Build bootable initrd VMs from container images")] +struct Cli { + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand, Debug)] +enum Commands { + /// Build initrd from an image (podman image must exist) + Build { + /// Image name (e.g. alpine:3.15 or slim:tag) + image: String, + /// Size hint (unused in v1 initrd) + #[arg(short = 's', long, default_value = "512")] + _size: String, + }, + /// Launch the VM via QEMU using registry artifacts + Run { + /// Image tag / registry subdir name + name: String, + }, +} + +fn main() -> Result<()> { + let cli = Cli::parse(); + match cli.command { + Commands::Build { image, _size: _ } => { + build(&image)?; + } + Commands::Run { name } => { + run(&name)?; + } + } + Ok(()) +} + +fn registry_dir(image: &str) -> PathBuf { + let base = xdg::BaseDirectories::with_prefix("slim-rs").unwrap(); + base.place_data_file(format!("registry/{}/vmlinuz", image)).unwrap(); + base.place_data_file(format!("registry/{}/initrd", image)).unwrap().parent().unwrap().to_path_buf() +} + +fn build(image: &str) -> Result<()> { + // Step 1: mount via podman unshare (verified in Slice 0) + let output = Command::new("podman") + .args(["unshare", "--", "podman", "image", "mount", image]) + .output() + .context("Failed to run podman unshare image mount")?; + let mount_path_str = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if mount_path_str.is_empty() { + anyhow::bail!("podman image mount returned empty path"); + } + let mount_path = Path::new(&mount_path_str); + println!("Mounted at: {}", mount_path.display()); + + // Step 2: find vmlinuz + let vmlinuz_src = mount_path.join("vmlinuz"); + if !vmlinuz_src.exists() { + anyhow::bail!("Image missing required /vmlinuz. Place kernel at /vmlinuz in Containerfile."); + } + + // Step 3: prepare registry dir + let reg_dir = registry_dir(image); + fs::create_dir_all(®_dir)?; + println!("Registry: {}", reg_dir.display()); + + // Copy vmlinuz out + let vmlinuz_dst = reg_dir.join("vmlinuz"); + fs::copy(&vmlinuz_src, &vmlinuz_dst).context("Copy vmlinuz to registry")?; + println!("Copied vmlinuz -> {}", vmlinuz_dst.display()); + + // Step 4: create initrd via cpio binary (using system cpio for reliability) + let initrd_raw = reg_dir.join("initrd.tmp"); + let initrd_path = reg_dir.join("initrd"); + + // Build cpio from rootfs (excluding vmlinuz since it is separate kernel) + let mut find_cmd = Command::new("find") + .arg(".") + .current_dir(mount_path) + .stdout(Stdio::piped()) + .spawn() + .context("Failed to spawn find")?; + let find_stdout = find_cmd.stdout.take().unwrap(); + + let mut cpio_cmd = Command::new("cpio") + .args(["-o", "-H", "newc"]) + .current_dir(mount_path) + .stdin(Stdio::from(find_stdout)) + .stdout(Stdio::from(File::create(&initrd_raw)?)) + .spawn() + .context("Failed to spawn cpio")?; + + let find_status = find_cmd.wait()?; + let cpio_status = cpio_cmd.wait()?; + if !find_status.success() || !cpio_status.success() { + anyhow::bail!("find or cpio failed"); + } + + // Gzip initrd + let initrd_file = fs::File::open(&initrd_raw)?; + let mut initrd_writer = flate2::write::GzEncoder::new(File::create(&initrd_path)?, flate2::Compression::default()); + std::io::copy(&mut std::io::BufReader::new(initrd_file), &mut initrd_writer)?; + initrd_writer.finish()?; + fs::remove_file(&initrd_raw)?; + println!("Created initrd -> {}", initrd_path.display()); + + // Unmount image + let _ = Command::new("podman") + .args(["unshare", "--", "podman", "image", "unmount", image]) + .output(); + println!("Unmounted image."); + + Ok(()) +} + +fn run(name: &str) -> Result<()> { + let reg_dir = registry_dir(name); + let vmlinuz_path = reg_dir.join("vmlinuz"); + let initrd_path = reg_dir.join("initrd"); + if !vmlinuz_path.exists() || !initrd_path.exists() { + anyhow::bail!( + "Registry missing vmlinuz/initrd for '{}'. Run `slim build` first.", + name + ); + } + println!("Booting {} from registry: {}", name, reg_dir.display()); + println!( + " qemu-system-x86_64 -m 256 -nographic -kernel {} -initrd {} -append 'console=ttyS0'", + vmlinuz_path.display(), + initrd_path.display() + ); + // Launch with a 5-second timeout for quick smoke verification + let status = Command::new("timeout") + .args(["5", "qemu-system-x86_64", + "-m", "256", + "-nographic", + "-kernel", vmlinuz_path.to_str().unwrap(), + "-initrd", initrd_path.to_str().unwrap(), + "-append", "console=ttyS0"]) + .status() + .context("Failed to launch qemu-system-x86_64")?; + if status.success() { + println!("QEMU exited cleanly (timeout or normal exit)."); + } else { + println!("QEMU exited with non-zero status (timeout/expected for initrd boot without init)."); + } + Ok(()) +}