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())
+134
View File
@@ -0,0 +1,134 @@
//! Inject: inspect a podman image's config, infer the default command, and
//! inject distro-agnostic /slim/ scripts (init + exec) into the mounted rootfs.
use anyhow::{Context, Result, anyhow};
use serde::Deserialize;
use std::fs;
use std::path::Path;
use crate::command::cmd;
const SLIM_INIT: &str = include_str!("scripts/slim-init.sh");
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct Config {
#[serde(default)]
cmd: Option<Vec<String>>,
#[serde(default)]
entrypoint: Option<Vec<String>>,
#[serde(default)]
env: Option<Vec<String>>,
#[serde(default)]
working_dir: Option<String>,
}
pub fn inspect_config(image: &str) -> Result<Config> {
let json = cmd(&[
"podman",
"image",
"inspect",
image,
"--format",
"{{json .Config}}",
])?;
let config: Config = serde_json::from_str(json.trim())
.with_context(|| anyhow!("failed to parse image inspect output for '{image}'"))?;
Ok(config)
}
/// Infer the command string from the image config.
///
/// Concatenates ENTRYPOINT + CMD (Docker semantics). If neither is present,
/// falls back to `/bin/sh`.
pub fn infer_command(config: &Config) -> String {
let entrypoint = config.entrypoint.as_deref().filter(|e| !e.is_empty());
let cmd = config.cmd.as_deref().filter(|c| !c.is_empty());
let parts: Vec<String> = match (entrypoint, cmd) {
(Some(ep), Some(c)) => {
let mut parts = ep.to_vec();
parts.extend(c.iter().cloned());
parts
}
(Some(ep), None) => ep.to_vec(),
(None, Some(c)) => c.to_vec(),
(None, None) => vec!["/bin/sh".to_string()],
};
if parts.len() == 3 && (parts[0] == "/bin/sh" || parts[0] == "sh") && parts[1] == "-c" {
parts[2].clone()
} else {
shell_join(&parts)
}
}
pub fn env(config: &Config) -> Vec<String> {
config.env.clone().unwrap_or_default()
}
pub fn working_dir(config: &Config) -> Option<&str> {
config.working_dir.as_deref()
}
fn shell_escape(s: &str) -> String {
format!("'{}'", s.replace('\'', "'\\''"))
}
fn shell_join(parts: &[String]) -> String {
parts
.iter()
.map(|p| shell_escape(p))
.collect::<Vec<_>>()
.join(" ")
}
/// Generate the /slim/exec script from a command string, env vars, and working dir.
pub fn build_exec_script(command: &str, env: &[String], working_dir: Option<&str>) -> String {
let mut lines = String::from("#!/bin/sh\n");
if let Some(dir) = working_dir.filter(|d| !d.is_empty()) {
lines.push_str(&format!("cd {} 2>/dev/null\n", shell_escape(dir)));
}
for var in env {
if let Some((key, val)) = var.split_once('=') {
lines.push_str(&format!(
"export {}={}\n",
shell_escape(key),
shell_escape(val)
));
}
}
lines.push_str(&format!("exec /bin/sh -c {}\n", shell_escape(command)));
lines
}
/// Inject /slim/init and /slim/exec into a mounted container image rootfs.
pub fn inject(mount_path: &Path, exec_script: &str) -> Result<()> {
let mount_str = mount_path.to_str().context("mount path is not UTF-8")?;
let init_temp = tempfile::NamedTempFile::new()?;
let exec_temp = tempfile::NamedTempFile::new()?;
fs::write(init_temp.path(), SLIM_INIT)?;
fs::write(exec_temp.path(), exec_script)?;
let init_src = init_temp
.path()
.to_str()
.context("temp path is not UTF-8")?;
let exec_src = exec_temp
.path()
.to_str()
.context("temp path is not UTF-8")?;
let init_dest = format!("{mount_str}/slim/init");
let exec_dest = format!("{mount_str}/slim/exec");
cmd(&[
"podman", "unshare", "--", "install", "-D", "-m", "755", init_src, &init_dest,
])?;
cmd(&[
"podman", "unshare", "--", "install", "-D", "-m", "755", exec_src, &exec_dest,
])?;
Ok(())
}
+2 -2
View File
@@ -2,7 +2,7 @@ mod build;
mod command;
mod forward;
mod image;
mod meta;
mod inject;
mod qemu;
mod registry;
@@ -12,7 +12,7 @@ use clap::{Parser, Subcommand};
use crate::{build::BuildCmd, image::ImageCmd, qemu::RunCmd};
#[derive(Parser, Debug)]
#[command(about = "Build bootable initrd VMs from container images")]
#[command(about = "Turn containers into bootable VMs")]
struct Cli {
#[command(subcommand)]
command: Commands,
-28
View File
@@ -1,28 +0,0 @@
use std::fs;
use serde::{Deserialize, Serialize};
use crate::registry::registry_dir;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Meta {
/// Path to the init program
pub init: String,
}
const FILENAME: &str = "meta.toml";
impl Meta {
pub fn load(image: &str) -> anyhow::Result<Self> {
let path = registry_dir(image)?.join(FILENAME);
let s = fs::read_to_string(path)?;
Ok(toml::from_str(&s)?)
}
pub fn save(&self, image: &str) -> anyhow::Result<()> {
let path = registry_dir(image)?.join(FILENAME);
let s = toml::to_string_pretty(self)?;
fs::write(path, &s)?;
Ok(())
}
}
+36 -25
View File
@@ -1,13 +1,17 @@
//! QEMU: boot a registry entry with qemu-system-x86_64 using direct kernel
//! boot (-kernel/-initrd).
//! boot (-kernel/-initrd or -drive). The kernel is shared across all VMs
//! at $XDG_DATA_HOME/slim-rs/registry/vmlinuz. A universal /slim/init script (injected
//! at build time) handles VM bootstrap; /slim/exec runs the container's
//! CMD/ENTRYPOINT. Runtime overrides are delivered as `slim.cmd=<base64>`
//! on the kernel cmdline.
use anyhow::{Context, Result, bail};
use base64::Engine;
use clap::Args;
use std::{fmt::Write as _, process::Command};
use crate::{
forward::PortForward,
meta::Meta,
registry::{registry_base_dir, registry_dir},
};
@@ -23,6 +27,11 @@ pub struct RunCmd {
/// Forward ports from host to guest. Example: `tcp:0.0.0.0:80-:8080`
#[clap(long)]
forward: Vec<PortForward>,
/// Override the command to exec in the VM (base64-encoded on the kernel
/// cmdline as slim.cmd=<b64>). Overrides the CMD inferred at build time.
#[clap(long)]
cmd: Option<String>,
}
pub(crate) fn run(
@@ -30,6 +39,7 @@ pub(crate) fn run(
name,
memory,
forward,
cmd,
}: RunCmd,
) -> Result<()> {
let reg_dir = registry_dir(&name)?;
@@ -38,40 +48,40 @@ pub(crate) fn run(
let qcow2_path = reg_dir.join("image.qcow2");
if !vmlinuz_path.exists() {
// TODO: guide user in how to set up a kernel
bail!("No kernel available.")
bail!(
"No kernel available. Place a vmlinuz at {}",
vmlinuz_path.display()
);
}
let meta = Meta::load(&name).context("Failed to load meta.toml. Run `slim build` first.")?;
// TODO: sanity-check for spaces
let init_arg = format!("init={}", meta.init);
let fs_args;
let mut cmdline = vec![
"console=ttyS0,115200",
"rw",
"earlyprintk=serial",
"nokaslr",
&init_arg,
"devtmpfs.mount=1", // Automatically mount /dev at boot
let mut cmdline: Vec<String> = vec![
"console=ttyS0,115200".into(),
"rw".into(),
"earlyprintk=serial".into(),
"nokaslr".into(),
"init=/slim/init".into(),
"devtmpfs.mount=1".into(), // Automatically mount /dev at boot
];
let fs_args;
let qcow2_arg = format!("file={},format=qcow2,if=virtio", qcow2_path.display());
if qcow2_path.exists() {
fs_args = vec!["-drive", &qcow2_arg];
cmdline.extend_from_slice(&["root=/dev/vda", "rootfstype=ext4"]);
fs_args = vec!["-drive".to_string(), qcow2_arg];
cmdline.extend(["root=/dev/vda".to_string(), "rootfstype=ext4".to_string()]);
} else if initrd_path.exists() {
fs_args = vec!["-initrd", initrd_path.to_str().context("Invalid UTF-8")?];
cmdline.push("root=/dev/ram0");
let initrd_str = initrd_path.to_str().context("Invalid UTF-8")?.to_string();
fs_args = vec!["-initrd".to_string(), initrd_str];
cmdline.push("root=/dev/ram0".into());
} else {
bail!("Registry missing rootfs/initrd for '{name}'. Run `slim build` first.");
}
if let Some(cmd) = &cmd {
let encoded = base64::engine::general_purpose::STANDARD.encode(cmd.as_bytes());
cmdline.push(format!("slim.cmd={encoded}"));
}
println!("Booting {name} from registry: {}", reg_dir.display());
println!(
" qemu-system-x86_64 -m 256 -nographic -kernel {} -initrd {} -append 'console=ttyS0'",
vmlinuz_path.display(),
initrd_path.display()
);
let cmdline = cmdline.join(" ");
@@ -90,8 +100,9 @@ pub(crate) fn run(
.args(["-m", &memory])
.arg("-kernel")
.arg(vmlinuz_path.as_os_str())
.args(fs_args)
.args(&fs_args)
.args(["-snapshot"])
.args(["-no-reboot"])
.args(["-append", &cmdline])
.args(["-nographic"])
.args(["-nic", &network]);
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
# slim universal init - distro-agnostic VM bootstrap.
# Injected by `slim build` at /slim/init and invoked via init=/slim/init.
# === Devices & special filesystems ===
[ -c /dev/console ] || mknod -m 600 /dev/console c 5 1
mkdir -p /proc /sys /dev/pts /dev/shm
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devpts devpts /dev/pts
mount -t tmpfs tmpfs /dev/shm
mount -t tmpfs tmpfs /run -o mode=755
mount -t tmpfs tmpfs /tmp -o mode=1777
# === cgroup2 ===
mkdir -p /sys/fs/cgroup
mount -t cgroup2 none /sys/fs/cgroup 2>/dev/null || echo "mount cgroup2 failed"
# shellcheck disable=SC2013 # word-splitting is intentional: controllers are space-separated
for c in $(cat /sys/fs/cgroup/cgroup.controllers 2>/dev/null); do
echo "+$c" > /sys/fs/cgroup/cgroup.subtree_control 2>/dev/null || echo "enable cgroup controller $c failed"
done
# === Rootless container prerequisites (best-effort) ===
mount --make-rshared / 2>/dev/null || echo "make-rshared / failed"
chmod u+s /usr/bin/newuidmap /usr/bin/newgidmap 2>/dev/null || echo "chmod newuidmap/newgidmap failed"
# === Timezone ===
ln -sf /usr/share/zoneinfo/Europe/Stockholm /etc/localtime 2>/dev/null || echo "set timezone failed"
# === Networking (QEMU slirp: guest 10.0.2.15/24, gw 10.0.2.2, dns 10.0.2.3) ===
ip link set lo up 2>/dev/null || echo "ip link set lo up failed"
ip link set eth0 up 2>/dev/null || echo "ip link set eth0 up failed"
ip addr add 10.0.2.15/24 dev eth0 2>/dev/null || echo "ip addr add eth0 failed"
ip route add default via 10.0.2.2 2>/dev/null || echo "ip route add default failed"
echo nameserver 10.0.2.3 > /etc/resolv.conf
# === Execute the configured command ===
# If slim.cmd=<base64> is on the kernel cmdline, decode and exec it.
# Otherwise, exec /slim/exec (generated from the image's CMD/ENTRYPOINT).
# shellcheck disable=SC2013 # word-splitting is intentional: cmdline tokens are space-separated
for tok in $(cat /proc/cmdline 2>/dev/null); do
case "$tok" in
slim.cmd=*)
v=${tok#slim.cmd=}
decoded=$(printf '%s' "$v" | base64 -d 2>/dev/null) \
|| decoded=$(printf '%s' "$v" | openssl base64 -d 2>/dev/null) \
|| echo "base64 decode failed"
if [ -n "$decoded" ]; then
exec /bin/sh -c "$decoded"
fi
;;
esac
done
exec /slim/exec