Inject universal /slim/init instead of requiring container-specific setup
CI / build (pull_request) Successful in 36s
CI / build (push) Successful in 13s

slim now works with any Containerfile by injecting distro-agnostic scripts
at build time:

- /slim/init: mounts special filesystems, configures networking (static
  QEMU slirp), sets up cgroup2, timezone, and rootless container prereqs.
  Parses slim.cmd=<base64> from the kernel cmdline for runtime overrides,
  otherwise execs /slim/exec.

- /slim/exec: generated from the image's CMD/ENTRYPOINT (via podman image
  inspect), overridable via --cmd at build and run time.

Changes:
- New src/inject.rs: inspect image config, infer command, generate
  /slim/exec script, inject /slim/ into mounted rootfs
- New src/scripts/slim-init.sh: the universal init script (include_str!)
- build.rs: rename --init to --cmd, inject scripts before packing,
  drop Meta::save, restructure to ensure unmount always runs
- qemu.rs: hardcode init=/slim/init, add --cmd (base64 on cmdline),
  drop Meta::load, add -no-reboot
- Remove src/meta.rs and meta.toml (no longer needed)
- Cargo.toml: add serde_json + base64, remove unused walkdir + cpio + toml
- Example Containerfiles simplified to plain FROM + CMD
- New example/test.sh for manual verification
- README updated for new workflow
This commit was merged in pull request #6.
This commit is contained in:
2026-09-08 21:58:01 +02:00
parent 506213ed9a
commit c2a9f00fc0
14 changed files with 526 additions and 287 deletions
+67 -29
View File
@@ -1,5 +1,5 @@
//! Build: mount a podman image, extract vmlinuz, and pack the rootfs as a
//! gzipped cpio initrd in the registry.
//! Build: mount a podman image, inject /slim/ scripts, and pack the rootfs
//! as a gzipped cpio initrd or qcow2 disk in the registry.
use anyhow::{Context, Result, bail};
use clap::{Args, ValueEnum};
@@ -11,7 +11,7 @@ use std::process::{Command, Stdio};
use tempfile::NamedTempFile;
use crate::command::cmd;
use crate::meta::Meta;
use crate::inject;
use crate::registry::registry_dir;
#[derive(Args, Debug)]
@@ -21,10 +21,10 @@ pub struct BuildCmd {
/// 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,
/// Override the command to exec in the VM. Inferred from the image's
/// CMD/ENTRYPOINT if not provided.
#[clap(long)]
cmd: Option<String>,
}
#[derive(ValueEnum, Clone, Debug)]
@@ -33,39 +33,77 @@ enum ImageKind {
Initrd,
}
pub(crate) fn build(BuildCmd { kind, name, init }: BuildCmd) -> Result<()> {
pub(crate) fn build(
BuildCmd {
kind,
name,
cmd: cmd_override,
}: BuildCmd,
) -> Result<()> {
let image = &name;
let mount_path = mount_image(image)?;
let container = format!("slim-build-{}", image.replace(':', "-"));
let mount_path = mount_container(image, &container)?;
println!("Mounted at: {}", mount_path.display());
// Keep the build result so the image is unmounted even when the build fails.
let result = match kind {
ImageKind::Initrd => build_initrd(image, &mount_path),
ImageKind::Qcow2 => build_qcow2(image, &mount_path),
};
let result = build_inner(&kind, image, &mount_path, cmd_override);
let unmounted = cmd(&[
"podman", "unshare", "--", "podman", "image", "unmount", image,
"podman",
"unshare",
"--",
"podman",
"container",
"unmount",
&container,
])
.is_ok();
if unmounted {
println!("Unmounted image.");
let removed = cmd(&["podman", "rm", &container]).is_ok();
if unmounted && removed {
println!("Unmounted and removed container.");
} else {
eprintln!("warning: failed to unmount image '{}'", image);
eprintln!("warning: failed to clean up container '{container}'");
}
Meta { init }.save(image)?;
result
}
fn mount_image(image: &str) -> Result<PathBuf> {
let mount_path = cmd(&["podman", "unshare", "--", "podman", "image", "mount", image])?;
fn build_inner(
kind: &ImageKind,
image: &str,
mount_path: &Path,
cmd: Option<String>,
) -> Result<()> {
let config = inject::inspect_config(image)?;
let command = cmd.unwrap_or_else(|| inject::infer_command(&config));
let env = inject::env(&config);
let working_dir = inject::working_dir(&config);
let exec_script = inject::build_exec_script(&command, &env, working_dir);
inject::inject(mount_path, &exec_script)?;
println!("Injected /slim/ (init + exec)");
match kind {
ImageKind::Initrd => build_initrd(image, mount_path),
ImageKind::Qcow2 => build_qcow2(image, mount_path),
}
}
fn mount_container(image: &str, container: &str) -> Result<PathBuf> {
cmd(&["podman", "create", "--name", container, image, "/bin/true"])?;
let mount_path = cmd(&[
"podman",
"unshare",
"--",
"podman",
"container",
"mount",
container,
])?;
Ok(PathBuf::from(mount_path.trim()))
}
/// Copy a directory onto a new raw disk image with EXT4.
fn to_raw_ext4(dir: &Path) -> Result<NamedTempFile> {
fn to_raw_ext4(dir: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
let dir = dir.to_str().context("Invalid UTF-8")?;
let du_out = cmd(&["podman", "unshare", "--", "du", "-sk", dir])?;
@@ -83,7 +121,7 @@ fn to_raw_ext4(dir: &Path) -> Result<NamedTempFile> {
+ 64 * gb; // Add some spare capacity for activities
let size = size.to_string();
let raw_file = NamedTempFile::new()?;
let raw_file = NamedTempFile::new_in(tmp_dir)?;
let raw_path = raw_file.path().to_str().context("Invalid UTF-8")?;
cmd(&["podman", "unshare", "--", "truncate", "-s", &size, raw_path])?;
cmd(&[
@@ -100,9 +138,9 @@ fn to_raw_ext4(dir: &Path) -> Result<NamedTempFile> {
}
/// 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()?;
fn to_qcow2_ext4(mount_path: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
let raw = to_raw_ext4(mount_path, tmp_dir)?;
let qcow2 = NamedTempFile::new_in(tmp_dir)?;
let raw_path = raw.path().to_str().context("Invalid UTF-8")?;
let qcow2_path = qcow2.path().to_str().context("Invalid UTF-8")?;
cmd(&[
@@ -116,7 +154,7 @@ fn build_qcow2(image: &str, mount_path: &Path) -> Result<()> {
fs::create_dir_all(&reg_dir)?;
println!("Registry: {}", reg_dir.display());
let qcow2 = to_qcow2_ext4(mount_path)?;
let qcow2 = to_qcow2_ext4(mount_path, &reg_dir)?;
fs::copy(qcow2.path(), reg_dir.join("image.qcow2"))
.context("Failed to copy qcow2 image to registry")?;
@@ -134,7 +172,7 @@ fn build_initrd(image: &str, mount_path: &Path) -> Result<()> {
// Pack the rootfs as a gzipped newc cpio archive. The cpio pipeline
// runs inside the namespace, its stdout is compressed here.
let initrd_path = reg_dir.join("initrd");
let script = r#"cd "$1" && find . -not -path ./vmlinuz | cpio -o -H newc"#;
let script = r#"cd "$1" && find . | cpio -o -H newc"#;
let mut cpio = Command::new("podman")
.args(["unshare", "--", "sh", "-c", script, "sh", mount_path])
.stdout(Stdio::piped())