Add qcow2 support
CI / build (push) Successful in 13s

This commit is contained in:
2026-08-30 17:08:08 +02:00
parent 46a86116b0
commit 286def05c1
7 changed files with 303 additions and 50 deletions
+95 -22
View File
@@ -2,19 +2,46 @@
//! gzipped cpio initrd in the registry.
use anyhow::{Context, Result, bail};
use clap::{Args, ValueEnum};
use flate2::write::GzEncoder;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tempfile::NamedTempFile;
use crate::command::cmd;
use crate::meta::Meta;
use crate::registry::registry_dir;
pub(crate) fn build(image: &str) -> Result<()> {
#[derive(Args, Debug)]
pub struct BuildCmd {
kind: ImageKind,
/// Image tag / registry subdir name
name: String,
/// The path to the `init` program for the VM.
// TODO: infer init based on `COMMAND`/`ENTRYPOINT`?
#[clap(long, default_value = "/sbin/init")]
init: String,
}
#[derive(ValueEnum, Clone, Debug)]
enum ImageKind {
Qcow2,
Initrd,
}
pub(crate) fn build(BuildCmd { kind, name, init }: BuildCmd) -> Result<()> {
let image = &name;
let mount_path = mount_image(image)?;
println!("Mounted at: {}", mount_path.display());
// Keep the build result so the image is unmounted even when the build fails.
let result = build_artifacts(image, &mount_path);
let result = match kind {
ImageKind::Initrd => build_initrd(image, &mount_path),
ImageKind::Qcow2 => build_qcow2(image, &mount_path),
};
let unmounted = Command::new("podman")
.args(["unshare", "--", "podman", "image", "unmount", image])
@@ -26,38 +53,84 @@ pub(crate) fn build(image: &str) -> Result<()> {
eprintln!("warning: failed to unmount image '{}'", image);
}
Meta { init }.save(image)?;
result
}
fn mount_image(image: &str) -> Result<PathBuf> {
let output = Command::new("podman")
.args(["unshare", "--", "podman", "image", "mount", image])
.output()
.context("Failed to run podman image mount")?;
let mount_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !output.status.success() || mount_path.is_empty() {
bail!(
"podman image mount failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
);
}
Ok(PathBuf::from(mount_path))
let mount_path = cmd(&["podman", "unshare", "--", "podman", "image", "mount", image])?;
Ok(PathBuf::from(mount_path.trim()))
}
fn build_artifacts(image: &str, mount_path: &Path) -> Result<()> {
/// Copy a directory onto a new raw disk image with EXT4.
fn to_raw_ext4(dir: &Path) -> Result<NamedTempFile> {
let dir = dir.to_str().context("Invalid UTF-8")?;
let du_out = cmd(&["podman", "unshare", "--", "du", "-sk", dir])?;
let used_kb: u64 = du_out
.split_whitespace()
.next()
.context("du produced no output")?
.parse()
.context("failed to parse du output")?;
let used = used_kb * 1024;
let mb = 1024 * 1024;
let size = used
+ (used / 10) // Add 10%
+ 64 * mb; // Add some margin
let size = size.to_string();
let raw_file = NamedTempFile::new()?;
let raw_path = raw_file.path().to_str().context("Invalid UTF-8")?;
cmd(&["podman", "unshare", "--", "truncate", "-s", &size, raw_path])?;
cmd(&[
"podman",
"unshare",
"--",
"mkfs.ext4",
"-F",
"-d",
dir,
raw_path,
])?;
Ok(raw_file)
}
/// Copy a directory onto a new qcow2 disk image with EXT4.
fn to_qcow2_ext4(mount_path: &Path) -> Result<NamedTempFile> {
let raw = to_raw_ext4(mount_path)?;
let qcow2 = NamedTempFile::new()?;
let raw_path = raw.path().to_str().context("Invalid UTF-8")?;
let qcow2_path = qcow2.path().to_str().context("Invalid UTF-8")?;
cmd(&[
"qemu-img", "convert", "-f", "raw", "-O", "qcow2", raw_path, qcow2_path,
])?;
Ok(qcow2)
}
fn build_qcow2(image: &str, mount_path: &Path) -> Result<()> {
let reg_dir = registry_dir(image)?;
fs::create_dir_all(&reg_dir)?;
println!("Registry: {}", reg_dir.display());
let qcow2 = to_qcow2_ext4(mount_path)?;
fs::copy(qcow2.path(), reg_dir.join("image.qcow2"))
.context("Failed to copy qcow2 image to registry")?;
Ok(())
}
fn build_initrd(image: &str, mount_path: &Path) -> Result<()> {
let mount_path = mount_path.to_str().context("mount path is not UTF-8")?;
let vmlinuz_src = format!("{mount_path}/vmlinuz");
// The rootless overlay mount only exists inside podman unshare's user
// namespace, so every read of the rootfs must run there; pipes still
// cross the namespace boundary.
let has_kernel = Command::new("podman")
.args(["unshare", "--", "test", "-f", &vmlinuz_src])
.status()
.context("Failed to check for /vmlinuz inside the image mount")?;
if !has_kernel.success() {
bail!("Image missing required /vmlinuz. Place kernel at /vmlinuz in Containerfile.");
}
let _has_kernel = cmd(&["podman", "unshare", "--", "test", "-f", &vmlinuz_src])
.context("Image missing required /vmlinuz. Place kernel at /vmlinuz in Containerfile.")?;
let reg_dir = registry_dir(image)?;
fs::create_dir_all(&reg_dir)?;