Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
589afef4f5 |
No files matched your search
@@ -1,10 +0,0 @@
|
|||||||
# Build context: deny everything, then allow only what the Containerfile needs.
|
|
||||||
# Keeps the linux submodule (and example/, .gitea/, README, etc.) out of the build.
|
|
||||||
*
|
|
||||||
!Cargo.toml
|
|
||||||
!Cargo.lock
|
|
||||||
!src/
|
|
||||||
!src/**
|
|
||||||
!init/
|
|
||||||
!init/**
|
|
||||||
!kernel/config
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
[submodule "linux"]
|
|
||||||
path = kernel/linux
|
|
||||||
url = https://github.com/torvalds/linux.git
|
|
||||||
shallow = true
|
|
||||||
Generated
+24
-57
@@ -66,37 +66,15 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "base64"
|
name = "base64"
|
||||||
version = "0.23.1"
|
version = "0.22.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
|
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
version = "2.13.2"
|
version = "2.13.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "boco"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"base64",
|
|
||||||
"clap",
|
|
||||||
"flate2",
|
|
||||||
"serde",
|
|
||||||
"serde_json",
|
|
||||||
"tempfile",
|
|
||||||
"xdg",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "boco-init"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"base64",
|
|
||||||
"nix",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cfg-if"
|
name = "cfg-if"
|
||||||
@@ -104,12 +82,6 @@ version = "1.0.4"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cfg_aliases"
|
|
||||||
version = "0.2.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "clap"
|
name = "clap"
|
||||||
version = "4.6.6"
|
version = "4.6.6"
|
||||||
@@ -183,13 +155,12 @@ checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "flate2"
|
name = "flate2"
|
||||||
version = "1.1.10"
|
version = "1.1.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
|
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"crc32fast",
|
"crc32fast",
|
||||||
"miniz_oxide",
|
"miniz_oxide",
|
||||||
"zlib-rs",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -241,26 +212,14 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.9.1"
|
version = "0.8.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"adler2",
|
"adler2",
|
||||||
"simd-adler32",
|
"simd-adler32",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "nix"
|
|
||||||
version = "0.31.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
|
|
||||||
dependencies = [
|
|
||||||
"bitflags",
|
|
||||||
"cfg-if",
|
|
||||||
"cfg_aliases",
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
@@ -359,6 +318,20 @@ version = "0.3.10"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "slim"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"base64",
|
||||||
|
"clap",
|
||||||
|
"flate2",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"tempfile",
|
||||||
|
"xdg",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "strsim"
|
name = "strsim"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -367,9 +340,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "3.0.5"
|
version = "3.0.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9"
|
checksum = "e6275cddf4610d1775e6d1fe9469b2e77d0f39fd98fb7450901b821e0c53649f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
@@ -422,12 +395,6 @@ version = "3.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2fb433233f2df9344722454bc7e96465c9d03bff9d77c248f9e7523fe79585b5"
|
checksum = "2fb433233f2df9344722454bc7e96465c9d03bff9d77c248f9e7523fe79585b5"
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zlib-rs"
|
|
||||||
version = "0.6.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "zmij"
|
name = "zmij"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
|
|||||||
+2
-10
@@ -1,19 +1,11 @@
|
|||||||
[workspace]
|
|
||||||
members = [".", "init"]
|
|
||||||
|
|
||||||
[profile.release]
|
|
||||||
opt-level = "z"
|
|
||||||
lto = true
|
|
||||||
strip = true
|
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "boco"
|
name = "slim"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.104"
|
anyhow = "1.0.104"
|
||||||
base64 = "0.23"
|
base64 = "0.22"
|
||||||
clap = { version = "4.6.6", features = ["derive"] }
|
clap = { version = "4.6.6", features = ["derive"] }
|
||||||
flate2 = "1.1.9"
|
flate2 = "1.1.9"
|
||||||
serde = { version = "1.0.229", features = ["derive"] }
|
serde = { version = "1.0.229", features = ["derive"] }
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
# boco runner: compiles boco (static musl) AND the shared boco kernel (vmlinuz)
|
|
||||||
# with the slim config checked into the boco repo, then serves as the runtime
|
|
||||||
# image for `boco build` / `boco boot` under podman.
|
|
||||||
#
|
|
||||||
# Runtime requirements (boco shells out to nested rootless podman):
|
|
||||||
# --device /dev/kvm KVM accel for the VMs (entrypoint chmods it)
|
|
||||||
# --device /dev/net/tun only if nested container runs need pasta networking
|
|
||||||
# volume at /home/boco/.local/share/boco persistent registry (images+kernel)
|
|
||||||
# NO --privileged: the container's own userns (single mapping) is what makes
|
|
||||||
# nested `podman unshare` work; ignore_chown_errors handles unmapped uids.
|
|
||||||
#
|
|
||||||
# Kernel source: pinned tarball linux-7.2 (= 8d3ae59288f1e7d58d76558a6ee96d533bc5019f,
|
|
||||||
# verified == refs/tags/v7.2{} via git ls-remote), sha256-checked.
|
|
||||||
|
|
||||||
FROM alpine:edge AS build
|
|
||||||
RUN apk add --no-cache rust cargo git
|
|
||||||
WORKDIR /src
|
|
||||||
COPY . .
|
|
||||||
# alpine's rust targets x86_64-alpine-linux-musl natively (static, no glibc dep)
|
|
||||||
RUN cargo build --release -p boco -p boco-init \
|
|
||||||
&& strip target/release/boco target/release/boco-init
|
|
||||||
|
|
||||||
FROM alpine:3.22 AS kernel
|
|
||||||
# g++ for host tools, libelf for objtool, openssl for extract-cert
|
|
||||||
RUN apk add --no-cache make gcc g++ musl-dev perl flex bison bc \
|
|
||||||
elfutils-dev openssl-dev findutils tar xz zstd curl linux-headers diffutils
|
|
||||||
WORKDIR /kbuild
|
|
||||||
# Pinned upstream tarball: linux-7.2.tar.xz, sha256
|
|
||||||
# f9fef3d14c0df53819026f4be74459835c2a0b0dcbf5b5bbd9ea19f0829402b3.
|
|
||||||
# (Equivalent to the upstream shallow pin 8d3ae59288f1e7d58d76558a6ee96d533bc5019f
|
|
||||||
# = refs/tags/v7.2{} — verified via `git ls-remote`; the tarball avoids
|
|
||||||
# a multi-GB shallow clone through flaky slirp NAT.)
|
|
||||||
RUN curl -fsSLo /tmp/linux-7.2.tar.xz https://cdn.kernel.org/pub/linux/kernel/v7.x/linux-7.2.tar.xz \
|
|
||||||
&& echo "f9fef3d14c0df53819026f4be74459835c2a0b0dcbf5b5bbd9ea19f0829402b3 /tmp/linux-7.2.tar.xz" | sha256sum -c - \
|
|
||||||
&& tar -xJf /tmp/linux-7.2.tar.xz \
|
|
||||||
&& mv linux-7.2 linux
|
|
||||||
# Install the slim kernel config checked into the boco repo; olddefconfig
|
|
||||||
# normalizes it against this tree and fails nothing silently afterwards.
|
|
||||||
COPY kernel/config /kbuild/linux/.config
|
|
||||||
RUN make -C linux olddefconfig HOSTCC=gcc CC=gcc \
|
|
||||||
&& grep -qE '^(# )?CONFIG_MODULES' linux/.config
|
|
||||||
RUN make -C linux -j"$(nproc)" bzImage HOSTCC=gcc CC=gcc \
|
|
||||||
&& cp linux/arch/x86/boot/bzImage /vmlinuz \
|
|
||||||
&& ls -lh /vmlinuz
|
|
||||||
|
|
||||||
FROM alpine:3.22
|
|
||||||
RUN apk add --no-cache \
|
|
||||||
qemu-system-x86_64 qemu-img virtiofsd \
|
|
||||||
podman fuse3 openssh-client ca-certificates iptables ip6tables \
|
|
||||||
e2fsprogs cpio passt \
|
|
||||||
&& adduser -D -s /bin/sh boco \
|
|
||||||
&& echo boco:100000:65536 > /etc/subuid \
|
|
||||||
&& echo boco:100000:65536 > /etc/subgid \
|
|
||||||
&& mkdir -p /etc/containers \
|
|
||||||
&& printf '[storage]\ndriver = "vfs"\nrunroot = "/run/containers/storage"\ngraphroot = "/var/lib/containers/storage"\n[storage.options]\nignore_chown_errors = "true"\n' > /etc/containers/storage.conf \
|
|
||||||
&& printf '#!/bin/sh\n[ -e /dev/kvm ] && chmod 666 /dev/kvm\nexec /usr/local/bin/boco "$@"\n' > /usr/local/bin/entrypoint.sh \
|
|
||||||
&& chmod 755 /usr/local/bin/entrypoint.sh
|
|
||||||
COPY --from=build /src/target/release/boco /usr/local/bin/boco
|
|
||||||
COPY --from=build /src/target/release/boco-init /home/boco/.local/share/boco/boco-init
|
|
||||||
COPY --from=kernel /vmlinuz /home/boco/.local/share/boco/vmlinuz
|
|
||||||
RUN chmod 755 /usr/local/bin/boco /home/boco/.local/share/boco/boco-init /home/boco/.local/share/boco/vmlinuz
|
|
||||||
ENV XDG_DATA_HOME=/home/boco/.local/share
|
|
||||||
WORKDIR /data
|
|
||||||
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
|
|
||||||
CMD ["image", "list"]
|
|
||||||
@@ -1,41 +1,32 @@
|
|||||||
# boco
|
# slim
|
||||||
|
|
||||||
Turn container images into bootable VMs
|
Turning containers into bootable VMs
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
```Dockerfile
|
|
||||||
# ./example/alpine/Containerfile
|
|
||||||
FROM alpine:latest
|
|
||||||
CMD ["/bin/sh"]
|
|
||||||
```
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Build the container
|
# Build the container
|
||||||
podman build ./example/alpine -t boco-alpine
|
podman build ./example/alpine -t slim-alpine
|
||||||
|
|
||||||
# Make the container bootable. boco injects a custom init program,
|
# Make the container bootable. slim injects /slim/init and /slim/exec,
|
||||||
# then packs the rootfs as a qcow2 disk.
|
# then packs the rootfs as a qcow2 disk.
|
||||||
boco build qcow2 boco-alpine
|
slim build qcow2 slim-alpine
|
||||||
|
|
||||||
# Boot the image using QEMU, and drop into /bin/sh.
|
# Boot the image using QEMU. The container's CMD runs automatically.
|
||||||
boco boot boco-alpine
|
slim run slim-alpine
|
||||||
|
|
||||||
|
# Override the command at runtime (base64-encoded on the kernel cmdline):
|
||||||
|
slim run slim-alpine --cmd '/bin/sh'
|
||||||
|
|
||||||
|
# Override the command at build time (baked into /slim/exec):
|
||||||
|
slim build qcow2 slim-alpine --cmd '/bin/sh'
|
||||||
|
|
||||||
# Cleanup
|
# Cleanup
|
||||||
boco image rm boco-alpine
|
slim image rm slim-alpine
|
||||||
podman image rm boco-alpine
|
podman image rm slim-alpine
|
||||||
```
|
|
||||||
|
|
||||||
Can also be used to boot a more traditional systemd-based VM:
|
|
||||||
|
|
||||||
```Dockerfile
|
|
||||||
FROM archlinux:latest
|
|
||||||
|
|
||||||
# This works! Although you should probably add a user or some services.
|
|
||||||
CMD ["/sbin/init"]
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Kernel
|
## Kernel
|
||||||
|
|
||||||
boco boots VMs using a shared kernel at `$XDG_DATA_HOME/boco/registry/vmlinuz`.
|
slim boots VMs using a shared kernel at `$XDG_DATA_HOME/slim-rs/vmlinuz`.
|
||||||
Place a suitable x86 bzImage there before running `boco boot`.
|
Place a suitable x86 bzImage there before running `slim run`.
|
||||||
Regular → Executable
+29
-222
@@ -1,12 +1,11 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
# Test script for boco - boots containers and verifies CMD inference/override.
|
# Test script for slim - boots containers and verifies CMD inference/override.
|
||||||
# Requires: podman, qemu-system-x86_64, KVM, curl, and a kernel at
|
# Requires: podman, qemu-system-x86_64, KVM, curl, and a kernel at
|
||||||
# $XDG_DATA_HOME/boco/registry/vmlinuz.
|
# $XDG_DATA_HOME/slim-rs/vmlinuz.
|
||||||
set -u
|
set -u
|
||||||
|
|
||||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||||
TARGET_DIR="${CARGO_TARGET_DIR:-$SCRIPT_DIR/../target}"
|
SLIM_BIN="$SCRIPT_DIR/../target/debug/slim"
|
||||||
BOCO_BIN="$TARGET_DIR/debug/boco"
|
|
||||||
TIMEOUT=120
|
TIMEOUT=120
|
||||||
|
|
||||||
pass=0
|
pass=0
|
||||||
@@ -34,7 +33,7 @@ check_output() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cleanup() {
|
cleanup() {
|
||||||
"$BOCO_BIN" image rm "$1" >/dev/null 2>&1 || true
|
"$SLIM_BIN" image rm "$1" >/dev/null 2>&1 || true
|
||||||
podman image rm "$2" >/dev/null 2>&1 || true
|
podman image rm "$2" >/dev/null 2>&1 || true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,48 +51,48 @@ test_distro() {
|
|||||||
cat > "$work/Containerfile.infer" <<EOF
|
cat > "$work/Containerfile.infer" <<EOF
|
||||||
FROM $from
|
FROM $from
|
||||||
$extra_setup
|
$extra_setup
|
||||||
CMD ["/bin/sh", "-c", "echo CMD_INFERRED_OK; wget -q -O /dev/null http://1.1.1.1 2>/dev/null && echo CONN_OK; wget -q -O /dev/null http://example.org 2>/dev/null && echo DNS_OK; poweroff -f"]
|
CMD ["/bin/sh", "-c", "echo CMD_INFERRED_OK; ping -c1 1.1.1.1 >/dev/null 2>&1 && echo PING_OK; ping -c1 example.org >/dev/null 2>&1 && echo DNS_OK; poweroff -f"]
|
||||||
EOF
|
EOF
|
||||||
img="boco-test-$distro-infer"
|
img="slim-test-$distro-infer"
|
||||||
if podman build -t "$img" -f "$work/Containerfile.infer" >/dev/null 2>&1; then
|
if podman build -t "$img" -f "$work/Containerfile.infer" >/dev/null 2>&1; then
|
||||||
"$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1
|
"$SLIM_BIN" build qcow2 "$img" >/dev/null 2>&1
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" 2>&1 || true)
|
output=$(timeout "$TIMEOUT" "$SLIM_BIN" run "$img" 2>&1 || true)
|
||||||
check_output "$output" "CMD_INFERRED_OK" "$distro CMD-inferred"
|
check_output "$output" "CMD_INFERRED_OK" "$distro CMD-inferred"
|
||||||
check_output "$output" "CONN_OK" "$distro connect to 1.1.1.1"
|
check_output "$output" "PING_OK" "$distro ping 1.1.1.1"
|
||||||
check_output "$output" "DNS_OK" "$distro DNS lookup"
|
check_output "$output" "DNS_OK" "$distro DNS lookup"
|
||||||
else
|
else
|
||||||
report fail "$distro CMD-inferred (podman build failed)"
|
report fail "$distro CMD-inferred (podman build failed)"
|
||||||
fi
|
fi
|
||||||
cleanup "$img" "$img"
|
cleanup "$img" "$img"
|
||||||
|
|
||||||
# === Test 2: boco boot --cmd override ===
|
# === Test 2: slim run --cmd override ===
|
||||||
echo "-- Test 2: boco boot --cmd override"
|
echo "-- Test 2: slim run --cmd override"
|
||||||
cat > "$work/Containerfile.run" <<EOF
|
cat > "$work/Containerfile.run" <<EOF
|
||||||
FROM $from
|
FROM $from
|
||||||
$extra_setup
|
$extra_setup
|
||||||
CMD ["/bin/sh", "-c", "echo SHOULD_NOT_APPEAR; poweroff -f"]
|
CMD ["/bin/sh", "-c", "echo SHOULD_NOT_APPEAR; poweroff -f"]
|
||||||
EOF
|
EOF
|
||||||
img="boco-test-$distro-run"
|
img="slim-test-$distro-run"
|
||||||
if podman build -t "$img" -f "$work/Containerfile.run" >/dev/null 2>&1; then
|
if podman build -t "$img" -f "$work/Containerfile.run" >/dev/null 2>&1; then
|
||||||
"$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1
|
"$SLIM_BIN" build qcow2 "$img" >/dev/null 2>&1
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" --cmd 'echo RUN_OVERRIDE_OK; poweroff -f' 2>&1 || true)
|
output=$(timeout "$TIMEOUT" "$SLIM_BIN" run "$img" --cmd 'echo RUN_OVERRIDE_OK; poweroff -f' 2>&1 || true)
|
||||||
check_output "$output" "RUN_OVERRIDE_OK" "$distro boot --cmd override"
|
check_output "$output" "RUN_OVERRIDE_OK" "$distro run --cmd override"
|
||||||
else
|
else
|
||||||
report fail "$distro boot --cmd override (podman build failed)"
|
report fail "$distro run --cmd override (podman build failed)"
|
||||||
fi
|
fi
|
||||||
cleanup "$img" "$img"
|
cleanup "$img" "$img"
|
||||||
|
|
||||||
# === Test 3: boco build --cmd override ===
|
# === Test 3: slim build --cmd override ===
|
||||||
echo "-- Test 3: boco build --cmd override"
|
echo "-- Test 3: slim build --cmd override"
|
||||||
cat > "$work/Containerfile.build" <<EOF
|
cat > "$work/Containerfile.build" <<EOF
|
||||||
FROM $from
|
FROM $from
|
||||||
$extra_setup
|
$extra_setup
|
||||||
CMD ["/bin/sh", "-c", "echo SHOULD_NOT_APPEAR; poweroff -f"]
|
CMD ["/bin/sh", "-c", "echo SHOULD_NOT_APPEAR; poweroff -f"]
|
||||||
EOF
|
EOF
|
||||||
img="boco-test-$distro-build"
|
img="slim-test-$distro-build"
|
||||||
if podman build -t "$img" -f "$work/Containerfile.build" >/dev/null 2>&1; then
|
if podman build -t "$img" -f "$work/Containerfile.build" >/dev/null 2>&1; then
|
||||||
"$BOCO_BIN" build qcow2 "$img" --cmd 'echo BUILD_OVERRIDE_OK; poweroff -f' >/dev/null 2>&1
|
"$SLIM_BIN" build qcow2 "$img" --cmd 'echo BUILD_OVERRIDE_OK; poweroff -f' >/dev/null 2>&1
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" 2>&1 || true)
|
output=$(timeout "$TIMEOUT" "$SLIM_BIN" run "$img" 2>&1 || true)
|
||||||
check_output "$output" "BUILD_OVERRIDE_OK" "$distro build --cmd override"
|
check_output "$output" "BUILD_OVERRIDE_OK" "$distro build --cmd override"
|
||||||
else
|
else
|
||||||
report fail "$distro build --cmd override (podman build failed)"
|
report fail "$distro build --cmd override (podman build failed)"
|
||||||
@@ -103,146 +102,15 @@ EOF
|
|||||||
rm -rf "$work"
|
rm -rf "$work"
|
||||||
}
|
}
|
||||||
|
|
||||||
test_user() {
|
|
||||||
echo "=== Testing USER directive ==="
|
|
||||||
|
|
||||||
work="$(mktemp -d)"
|
|
||||||
img="boco-test-user"
|
|
||||||
|
|
||||||
cat > "$work/Containerfile" <<'EOF'
|
|
||||||
FROM alpine:latest
|
|
||||||
RUN adduser -D -u 1500 testuser
|
|
||||||
USER testuser
|
|
||||||
CMD ["/bin/sh", "-c", "echo USER_BUILD_OK:$(id -u):$(whoami); poweroff -f"]
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "-- Building container image with USER directive..."
|
|
||||||
if ! podman build --network=none -t "$img" -f "$work/Containerfile" >/dev/null 2>&1; then
|
|
||||||
report fail "USER directive (podman build failed)"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Test 1: build-time CMD runs as USER"
|
|
||||||
"$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1
|
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" 2>&1 || true)
|
|
||||||
check_output "$output" "USER_BUILD_OK:1500:testuser" "USER build-time CMD runs as testuser"
|
|
||||||
|
|
||||||
echo "-- Test 2: boot --cmd override runs as USER"
|
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" --cmd 'echo USER_RUN_OK:$(id -u):$(whoami); poweroff -f' 2>&1 || true)
|
|
||||||
check_output "$output" "USER_RUN_OK:1500:testuser" "USER boot --cmd override runs as testuser"
|
|
||||||
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
rm -rf "$work"
|
|
||||||
}
|
|
||||||
|
|
||||||
test_mount() {
|
|
||||||
echo "=== Testing --mount (virtio-fs shares) ==="
|
|
||||||
|
|
||||||
work="$(mktemp -d)"
|
|
||||||
|
|
||||||
# --- Image 1: no WORKINGDIR, test host:guest and multi-mount ---
|
|
||||||
img="boco-test-mount"
|
|
||||||
share_dir="$work/share"
|
|
||||||
share_dir2="$work/share2"
|
|
||||||
guest_dir="/mnt/guest"
|
|
||||||
guest_dir2="/mnt/guest2"
|
|
||||||
|
|
||||||
mkdir -p "$share_dir" "$share_dir2"
|
|
||||||
echo "hello from host" > "$share_dir/testfile.txt"
|
|
||||||
echo "second share" > "$share_dir2/testfile2.txt"
|
|
||||||
|
|
||||||
cat > "$work/Containerfile" <<'EOF'
|
|
||||||
FROM alpine:latest
|
|
||||||
CMD ["/bin/sh", "-c", "poweroff -f"]
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "-- Building container image (no WORKINGDIR)..."
|
|
||||||
if ! podman build --network=none -t "$img" -f "$work/Containerfile" >/dev/null 2>&1; then
|
|
||||||
report fail "--mount (podman build failed)"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Building boco VM..."
|
|
||||||
if ! "$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1; then
|
|
||||||
report fail "--mount (boco build failed)"
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
share_canon=$(readlink -f "$share_dir")
|
|
||||||
share_canon2=$(readlink -f "$share_dir2")
|
|
||||||
|
|
||||||
echo "-- Test 1: --mount host:guest (absolute guest path, multi-mount)..."
|
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" \
|
|
||||||
--mount "${share_dir}:${guest_dir}" \
|
|
||||||
--mount "${share_dir2}:${guest_dir2}" \
|
|
||||||
--cmd "mount -v; cat ${guest_dir}/testfile.txt 2>/dev/null || echo NO_FILE; cat ${guest_dir2}/testfile2.txt 2>/dev/null || echo NO_FILE2; echo MOUNT_VERIFY_DONE; poweroff -f" \
|
|
||||||
2>&1 || true)
|
|
||||||
|
|
||||||
check_output "$output" "type virtiofs" "--mount virtiofs filesystem in mount list"
|
|
||||||
check_output "$output" "hello from host" "--mount file accessible at guest path"
|
|
||||||
check_output "$output" "second share" "--mount second file accessible at guest path"
|
|
||||||
check_output "$output" "MOUNT_VERIFY_DONE" "--mount VM ran to completion"
|
|
||||||
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
|
|
||||||
# --- Image 2: with WORKINGDIR, test relative guest path ---
|
|
||||||
img="boco-test-mount-wd"
|
|
||||||
share_dir3="$work/share3"
|
|
||||||
|
|
||||||
mkdir -p "$share_dir3"
|
|
||||||
echo "relative share" > "$share_dir3/relfile.txt"
|
|
||||||
|
|
||||||
cat > "$work/Containerfile.wd" <<'EOF'
|
|
||||||
FROM alpine:latest
|
|
||||||
WORKDIR /app
|
|
||||||
CMD ["/bin/sh", "-c", "poweroff -f"]
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "-- Building container image (WORKINGDIR /app)..."
|
|
||||||
if ! podman build --network=none -t "$img" -f "$work/Containerfile.wd" >/dev/null 2>&1; then
|
|
||||||
report fail "--mount relative (podman build failed)"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Building boco VM..."
|
|
||||||
if ! "$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1; then
|
|
||||||
report fail "--mount relative (boco build failed)"
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Test 2: --mount host:relative-guest (resolved against WORKINGDIR)..."
|
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" \
|
|
||||||
--mount "${share_dir3}:data" \
|
|
||||||
--cmd "mount -v; cat /app/data/relfile.txt 2>/dev/null || echo NO_REL_FILE; echo REL_VERIFY_DONE; poweroff -f" \
|
|
||||||
2>&1 || true)
|
|
||||||
|
|
||||||
check_output "$output" "type virtiofs" "--mount relative virtiofs filesystem in mount list"
|
|
||||||
check_output "$output" "relative share" "--mount relative file accessible at WORKINGDIR/data"
|
|
||||||
check_output "$output" "REL_VERIFY_DONE" "--mount relative VM ran to completion"
|
|
||||||
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
# Safety net: virtiofsd should exit when QEMU disconnects, but
|
|
||||||
# ensure no daemons linger if a boot failed mid-way.
|
|
||||||
pkill -f virtiofsd 2>/dev/null || true
|
|
||||||
rm -rf "$work"
|
|
||||||
}
|
|
||||||
|
|
||||||
test_service() {
|
test_service() {
|
||||||
echo "=== Testing nextcloud service ==="
|
echo "=== Testing nextcloud service ==="
|
||||||
|
|
||||||
img="boco-test-nextcloud"
|
img="slim-test-nextcloud"
|
||||||
host_port=18080
|
host_port=18080
|
||||||
work="$(mktemp -d)"
|
work="$(mktemp -d)"
|
||||||
|
|
||||||
cat > "$work/Containerfile" <<'EOF'
|
cat > "$work/Containerfile" <<'EOF'
|
||||||
FROM docker.io/library/nextcloud:32-apache
|
FROM nextcloud:32-apache
|
||||||
RUN apt-get update && apt-get install -y --no-install-recommends iproute2 && rm -rf /var/lib/apt/lists/*
|
RUN apt-get update && apt-get install -y --no-install-recommends iproute2 && rm -rf /var/lib/apt/lists/*
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
@@ -253,16 +121,16 @@ EOF
|
|||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "-- Building boco VM..."
|
echo "-- Building slim VM..."
|
||||||
if ! "$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1; then
|
if ! "$SLIM_BIN" build qcow2 "$img" >/dev/null 2>&1; then
|
||||||
report fail "nextcloud service (boco build failed)"
|
report fail "nextcloud service (slim build failed)"
|
||||||
cleanup "$img" "$img"
|
cleanup "$img" "$img"
|
||||||
rm -rf "$work"
|
rm -rf "$work"
|
||||||
return
|
return
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "-- Booting VM with port forward (host :${host_port} -> guest :80)..."
|
echo "-- Booting VM with port forward (host :${host_port} -> guest :80)..."
|
||||||
setsid timeout 300 "$BOCO_BIN" boot "$img" \
|
setsid timeout 300 "$SLIM_BIN" run "$img" \
|
||||||
--forward "tcp:0.0.0.0:${host_port}-:80" \
|
--forward "tcp:0.0.0.0:${host_port}-:80" \
|
||||||
--memory 2048M >/dev/null 2>&1 &
|
--memory 2048M >/dev/null 2>&1 &
|
||||||
vm_pid=$!
|
vm_pid=$!
|
||||||
@@ -296,75 +164,14 @@ EOF
|
|||||||
rm -rf "$work"
|
rm -rf "$work"
|
||||||
}
|
}
|
||||||
|
|
||||||
test_systemd() {
|
echo "Building slim..."
|
||||||
echo "=== Testing systemd as init ==="
|
|
||||||
|
|
||||||
work="$(mktemp -d)"
|
|
||||||
img="boco-test-systemd"
|
|
||||||
|
|
||||||
cat > "$work/boco-test.service" <<'SVC'
|
|
||||||
[Unit]
|
|
||||||
Description=boco systemd test
|
|
||||||
After=multi-user.target
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
Type=oneshot
|
|
||||||
ExecStart=/bin/sh -c "echo SYSTEMD_TEST_OK > /dev/console; sleep 1; systemctl poweroff"
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
SVC
|
|
||||||
|
|
||||||
cat > "$work/Containerfile" <<EOF
|
|
||||||
FROM archlinux:latest
|
|
||||||
COPY boco-test.service /etc/systemd/system/boco-test.service
|
|
||||||
RUN mkdir -p /etc/systemd/system/multi-user.target.wants && \
|
|
||||||
ln -sf /etc/systemd/system/boco-test.service \
|
|
||||||
/etc/systemd/system/multi-user.target.wants/boco-test.service
|
|
||||||
CMD ["/sbin/init"]
|
|
||||||
EOF
|
|
||||||
|
|
||||||
echo "-- Building container image with systemd..."
|
|
||||||
if ! podman build -t "$img" "$work" >/dev/null 2>&1; then
|
|
||||||
report fail "systemd as init (podman build failed)"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Building boco VM..."
|
|
||||||
if ! "$BOCO_BIN" build qcow2 "$img" >/dev/null 2>&1; then
|
|
||||||
report fail "systemd as init (boco build failed)"
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
rm -rf "$work"
|
|
||||||
return
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "-- Booting VM (systemd as PID 1)..."
|
|
||||||
output=$(timeout "$TIMEOUT" "$BOCO_BIN" boot "$img" 2>&1 || true)
|
|
||||||
check_output "$output" "SYSTEMD_TEST_OK" "systemd boots and runs service"
|
|
||||||
check_output "$output" "reboot: Power down" "systemd shuts down cleanly"
|
|
||||||
|
|
||||||
cleanup "$img" "$img"
|
|
||||||
rm -rf "$work"
|
|
||||||
}
|
|
||||||
|
|
||||||
echo "Building boco..."
|
|
||||||
cargo build 2>&1
|
cargo build 2>&1
|
||||||
cargo build --release -p boco-init --target x86_64-unknown-linux-musl 2>&1
|
|
||||||
cp "$TARGET_DIR/x86_64-unknown-linux-musl/release/boco-init" \
|
|
||||||
"${XDG_DATA_HOME:-$HOME/.local/share}/boco/boco-init"
|
|
||||||
|
|
||||||
test_distro "alpine" "alpine:latest" ""
|
test_distro "alpine" "alpine:latest" ""
|
||||||
test_distro "archlinux" "archlinux:latest" "RUN pacman -Sy --noconfirm iproute2 wget; pacman -Sc --noconfirm"
|
test_distro "archlinux" "archlinux:latest" "RUN pacman -Sy --noconfirm iputils iproute2 util-linux; pacman -Sc --noconfirm"
|
||||||
|
|
||||||
test_user
|
|
||||||
|
|
||||||
test_mount
|
|
||||||
|
|
||||||
test_service
|
test_service
|
||||||
|
|
||||||
test_systemd
|
|
||||||
|
|
||||||
echo ""
|
echo ""
|
||||||
echo "=== Results: $pass passed, $fail failed ==="
|
echo "=== Results: $pass passed, $fail failed ==="
|
||||||
[ "$fail" -eq 0 ]
|
[ "$fail" -eq 0 ]
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "boco-init"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
base64 = "0.23"
|
|
||||||
nix = { version = "0.31", features = ["mount", "fs", "process", "user", "reboot"] }
|
|
||||||
@@ -1,423 +0,0 @@
|
|||||||
//! boco universal init.
|
|
||||||
//!
|
|
||||||
//! Injected by `boco build` at /boco/init and invoked via init=/boco/init.
|
|
||||||
//! Sets up devices, filesystems, networking, and virtio-fs shares, then
|
|
||||||
//! execs the container's CMD/ENTRYPOINT (or a runtime override) with
|
|
||||||
//! execvp so the command becomes PID 1 directly.
|
|
||||||
|
|
||||||
use base64::Engine;
|
|
||||||
use nix::mount::{MsFlags, mount};
|
|
||||||
use nix::sys::reboot::{RebootMode, reboot};
|
|
||||||
use nix::sys::stat::{Mode, SFlag, makedev, mknod};
|
|
||||||
use nix::sys::wait::waitpid;
|
|
||||||
use nix::unistd::{ForkResult, Gid, Uid, User, execvp, fork, setgid, setuid};
|
|
||||||
use std::env;
|
|
||||||
use std::ffi::CString;
|
|
||||||
use std::fs;
|
|
||||||
use std::os::unix::fs::PermissionsExt;
|
|
||||||
use std::path::Path;
|
|
||||||
use std::process::Command;
|
|
||||||
|
|
||||||
fn warn(msg: &str) {
|
|
||||||
eprintln!("boco-init: {msg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run a fallible operation, logging on error.
|
|
||||||
fn try_io<F, T>(label: &str, f: F)
|
|
||||||
where
|
|
||||||
F: FnOnce() -> std::io::Result<T>,
|
|
||||||
{
|
|
||||||
if let Err(e) = f() {
|
|
||||||
warn(&format!("{label}: {e}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run a command, logging on error or non-zero exit.
|
|
||||||
fn try_cmd(label: &str, cmd: &mut Command) {
|
|
||||||
match cmd.status() {
|
|
||||||
Ok(status) => {
|
|
||||||
if !status.success() {
|
|
||||||
warn(&format!("{label}: exited with {status}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => warn(&format!("{label}: {e}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The kernel passes a minimal environment to init. Set a default PATH
|
|
||||||
/// so that `ip` and other tools can be found by name.
|
|
||||||
fn ensure_path() {
|
|
||||||
if env::var("PATH").is_err() {
|
|
||||||
// SAFETY: we are single-threaded before fork/exec.
|
|
||||||
unsafe {
|
|
||||||
env::set_var(
|
|
||||||
"PATH",
|
|
||||||
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn find_in_path(prog: &str) -> Option<String> {
|
|
||||||
let path = env::var("PATH").ok()?;
|
|
||||||
for dir in path.split(':') {
|
|
||||||
let candidate = format!("{dir}/{prog}");
|
|
||||||
if Path::new(&candidate).exists() {
|
|
||||||
return Some(candidate);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn try_mount(
|
|
||||||
source: Option<&str>,
|
|
||||||
target: &str,
|
|
||||||
fstype: Option<&str>,
|
|
||||||
flags: MsFlags,
|
|
||||||
data: Option<&str>,
|
|
||||||
) {
|
|
||||||
if let Err(e) = mount(source, target, fstype, flags, data) {
|
|
||||||
warn(&format!("mount {target}: {e}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_filesystems() {
|
|
||||||
if !Path::new("/dev/console").exists() {
|
|
||||||
try_io("mknod /dev/console", || {
|
|
||||||
mknod(
|
|
||||||
"/dev/console",
|
|
||||||
SFlag::S_IFCHR,
|
|
||||||
Mode::S_IRUSR | Mode::S_IWUSR,
|
|
||||||
makedev(5, 1),
|
|
||||||
)
|
|
||||||
.map_err(std::io::Error::from)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let dirs = [
|
|
||||||
"/proc",
|
|
||||||
"/sys",
|
|
||||||
"/dev/pts",
|
|
||||||
"/dev/shm",
|
|
||||||
"/run",
|
|
||||||
"/tmp",
|
|
||||||
"/sys/fs/cgroup",
|
|
||||||
];
|
|
||||||
for d in &dirs {
|
|
||||||
try_io(&format!("mkdir {d}"), || fs::create_dir_all(d));
|
|
||||||
}
|
|
||||||
|
|
||||||
try_mount(Some("proc"), "/proc", Some("proc"), MsFlags::empty(), None);
|
|
||||||
try_mount(Some("sysfs"), "/sys", Some("sysfs"), MsFlags::empty(), None);
|
|
||||||
try_mount(
|
|
||||||
Some("devpts"),
|
|
||||||
"/dev/pts",
|
|
||||||
Some("devpts"),
|
|
||||||
MsFlags::empty(),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
try_mount(
|
|
||||||
Some("tmpfs"),
|
|
||||||
"/dev/shm",
|
|
||||||
Some("tmpfs"),
|
|
||||||
MsFlags::empty(),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
try_mount(
|
|
||||||
Some("tmpfs"),
|
|
||||||
"/run",
|
|
||||||
Some("tmpfs"),
|
|
||||||
MsFlags::empty(),
|
|
||||||
Some("mode=755"),
|
|
||||||
);
|
|
||||||
try_mount(
|
|
||||||
Some("tmpfs"),
|
|
||||||
"/tmp",
|
|
||||||
Some("tmpfs"),
|
|
||||||
MsFlags::empty(),
|
|
||||||
Some("mode=1777"),
|
|
||||||
);
|
|
||||||
|
|
||||||
// cgroup2
|
|
||||||
try_mount(
|
|
||||||
Some("cgroup2"),
|
|
||||||
"/sys/fs/cgroup",
|
|
||||||
Some("cgroup2"),
|
|
||||||
MsFlags::empty(),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
if let Ok(controllers) = fs::read_to_string("/sys/fs/cgroup/cgroup.controllers") {
|
|
||||||
for c in controllers.split_whitespace() {
|
|
||||||
try_io("write cgroup.subtree_control", || {
|
|
||||||
fs::write("/sys/fs/cgroup/cgroup.subtree_control", format!("+{c}"))
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_rootless_prereqs() {
|
|
||||||
// make-rshared /
|
|
||||||
if let Err(e) =
|
|
||||||
mount::<str, str, str, str>(None, "/", None, MsFlags::MS_REC | MsFlags::MS_SHARED, None)
|
|
||||||
{
|
|
||||||
warn(&format!("make-rshared /: {e}"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// chmod u+s newuidmap newgidmap
|
|
||||||
for bin in &["/usr/bin/newuidmap", "/usr/bin/newgidmap"] {
|
|
||||||
match fs::metadata(bin) {
|
|
||||||
Ok(meta) => {
|
|
||||||
let mut perms = meta.permissions();
|
|
||||||
perms.set_mode(perms.mode() | 0o4000);
|
|
||||||
try_io(&format!("chmod u+s {bin}"), || {
|
|
||||||
fs::set_permissions(bin, perms)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
|
||||||
Err(e) => warn(&format!("stat {bin}: {e}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_timezone() {
|
|
||||||
try_io("symlink timezone", || {
|
|
||||||
std::os::unix::fs::symlink("/usr/share/zoneinfo/Europe/Stockholm", "/etc/localtime")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_networking() {
|
|
||||||
let ip = find_in_path("ip").unwrap_or_else(|| "/sbin/ip".to_string());
|
|
||||||
try_cmd(
|
|
||||||
"ip link set lo up",
|
|
||||||
Command::new(&ip).args(["link", "set", "lo", "up"]),
|
|
||||||
);
|
|
||||||
try_cmd(
|
|
||||||
"ip link set eth0 up",
|
|
||||||
Command::new(&ip).args(["link", "set", "eth0", "up"]),
|
|
||||||
);
|
|
||||||
try_cmd(
|
|
||||||
"ip addr add 10.0.2.15/24 dev eth0",
|
|
||||||
Command::new(&ip).args(["addr", "add", "10.0.2.15/24", "dev", "eth0"]),
|
|
||||||
);
|
|
||||||
try_cmd(
|
|
||||||
"ip route add default via 10.0.2.2",
|
|
||||||
Command::new(&ip).args(["route", "add", "default", "via", "10.0.2.2"]),
|
|
||||||
);
|
|
||||||
try_io("write /etc/resolv.conf", || {
|
|
||||||
fs::write("/etc/resolv.conf", "nameserver 10.0.2.3\n")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn setup_virtiofs_shares(workdir: &str) {
|
|
||||||
let cmdline = match fs::read_to_string("/proc/cmdline") {
|
|
||||||
Ok(c) => c,
|
|
||||||
Err(e) => {
|
|
||||||
warn(&format!("read /proc/cmdline: {e}"));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let b64 = base64::engine::general_purpose::STANDARD;
|
|
||||||
|
|
||||||
for tok in cmdline.split_whitespace() {
|
|
||||||
if let Some(rest) = tok.strip_prefix("boco.mount=") {
|
|
||||||
let Some((tag, dest_b64)) = rest.split_once(':') else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let dest = match b64.decode(dest_b64) {
|
|
||||||
Ok(bytes) => match String::from_utf8(bytes) {
|
|
||||||
Ok(s) => s,
|
|
||||||
Err(e) => {
|
|
||||||
warn(&format!("virtiofs: invalid UTF-8 in guest path: {e}"));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => {
|
|
||||||
warn(&format!("virtiofs: base64 decode failed: {e}"));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Resolve relative guest paths against WORKINGDIR
|
|
||||||
let dest = if dest.starts_with('/') {
|
|
||||||
dest
|
|
||||||
} else {
|
|
||||||
format!("{}/{}", workdir, dest)
|
|
||||||
};
|
|
||||||
|
|
||||||
try_io(&format!("mkdir {dest}"), || fs::create_dir_all(&dest));
|
|
||||||
try_mount(Some(tag), &dest, Some("virtiofs"), MsFlags::empty(), None);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_file_opt(path: &str) -> Option<String> {
|
|
||||||
fs::read_to_string(path)
|
|
||||||
.ok()
|
|
||||||
.filter(|s| !s.trim().is_empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn split_null_delimited(data: &[u8]) -> Vec<String> {
|
|
||||||
data.split(|&b| b == 0)
|
|
||||||
.filter(|s| !s.is_empty())
|
|
||||||
.map(|s| String::from_utf8_lossy(s).into_owned())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn read_argv() -> Vec<String> {
|
|
||||||
// Check for runtime override: boco.cmd=<base64(null-delimited argv)>
|
|
||||||
let b64 = base64::engine::general_purpose::STANDARD;
|
|
||||||
if let Ok(cmdline) = fs::read_to_string("/proc/cmdline") {
|
|
||||||
for tok in cmdline.split_whitespace() {
|
|
||||||
if let Some(rest) = tok.strip_prefix("boco.cmd=")
|
|
||||||
&& let Ok(decoded) = b64.decode(rest)
|
|
||||||
{
|
|
||||||
let argv = split_null_delimited(&decoded);
|
|
||||||
if !argv.is_empty() {
|
|
||||||
return argv;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fall back to build-time argv from /boco/exec
|
|
||||||
match fs::read("/boco/exec") {
|
|
||||||
Ok(data) => {
|
|
||||||
let argv = split_null_delimited(&data);
|
|
||||||
if !argv.is_empty() {
|
|
||||||
return argv;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => warn(&format!("read /boco/exec: {e}")),
|
|
||||||
}
|
|
||||||
|
|
||||||
warn("no command found, falling back to /bin/sh");
|
|
||||||
vec!["/bin/sh".to_string()]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_env() {
|
|
||||||
if let Ok(data) = fs::read("/boco/env") {
|
|
||||||
for entry in split_null_delimited(&data) {
|
|
||||||
if let Some((key, val)) = entry.split_once('=') {
|
|
||||||
// SAFETY: we are single-threaded before fork/exec.
|
|
||||||
unsafe { env::set_var(key, val) };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn apply_workdir() {
|
|
||||||
if let Some(dir) = read_file_opt("/boco/workdir") {
|
|
||||||
try_io("set working directory", || env::set_current_dir(&dir));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct UserSpec {
|
|
||||||
uid: Uid,
|
|
||||||
gid: Gid,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_user(spec: &str) -> Option<UserSpec> {
|
|
||||||
let (user_part, gid_part) = match spec.split_once(':') {
|
|
||||||
Some((u, g)) => (u, Some(g)),
|
|
||||||
None => (spec, None),
|
|
||||||
};
|
|
||||||
|
|
||||||
let (uid, default_gid) = if let Ok(numeric) = user_part.parse::<u32>() {
|
|
||||||
let user = User::from_uid(Uid::from_raw(numeric)).ok().flatten();
|
|
||||||
let gid = user
|
|
||||||
.as_ref()
|
|
||||||
.map(|u| u.gid)
|
|
||||||
.unwrap_or(Gid::from_raw(numeric));
|
|
||||||
(Uid::from_raw(numeric), gid)
|
|
||||||
} else {
|
|
||||||
let user = User::from_name(user_part).ok().flatten()?;
|
|
||||||
(user.uid, user.gid)
|
|
||||||
};
|
|
||||||
|
|
||||||
let gid = match gid_part {
|
|
||||||
Some(g) => match g.parse::<u32>() {
|
|
||||||
Ok(n) => Gid::from_raw(n),
|
|
||||||
Err(_) => default_gid,
|
|
||||||
},
|
|
||||||
None => default_gid,
|
|
||||||
};
|
|
||||||
|
|
||||||
Some(UserSpec { uid, gid })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn exec_command(argv: &[String], user: Option<UserSpec>) -> ! {
|
|
||||||
let cstrings: Vec<CString> = argv
|
|
||||||
.iter()
|
|
||||||
.map(|s| CString::new(s.as_str()).unwrap_or_default())
|
|
||||||
.collect();
|
|
||||||
let c_prog = cstrings[0].clone();
|
|
||||||
let c_refs: Vec<&CString> = cstrings.iter().collect();
|
|
||||||
|
|
||||||
match user {
|
|
||||||
None => {
|
|
||||||
// No privilege drop: exec directly, PID 1 becomes the command.
|
|
||||||
let Err(e) = execvp(&c_prog, &c_refs);
|
|
||||||
warn(&format!("execvp {}: {e}", argv[0]));
|
|
||||||
let _ = reboot(RebootMode::RB_POWER_OFF);
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
Some(user) => {
|
|
||||||
// Drop privileges in a child so PID 1 (root) can poweroff afterwards.
|
|
||||||
match unsafe { fork() } {
|
|
||||||
Ok(ForkResult::Child) => {
|
|
||||||
// setgid before setuid to avoid losing privileges
|
|
||||||
if let Err(e) = setgid(user.gid) {
|
|
||||||
warn(&format!("setgid: {e}"));
|
|
||||||
}
|
|
||||||
if let Err(e) = setuid(user.uid) {
|
|
||||||
warn(&format!("setuid: {e}"));
|
|
||||||
}
|
|
||||||
let Err(e) = execvp(&c_prog, &c_refs);
|
|
||||||
warn(&format!("execvp {}: {e}", argv[0]));
|
|
||||||
std::process::exit(127);
|
|
||||||
}
|
|
||||||
Ok(ForkResult::Parent { child }) => {
|
|
||||||
let _ = waitpid(child, None);
|
|
||||||
let _ = reboot(RebootMode::RB_POWER_OFF);
|
|
||||||
std::process::exit(0);
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
warn(&format!("fork: {e}"));
|
|
||||||
let _ = reboot(RebootMode::RB_POWER_OFF);
|
|
||||||
std::process::exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
ensure_path();
|
|
||||||
|
|
||||||
// === Devices & special filesystems ===
|
|
||||||
setup_filesystems();
|
|
||||||
|
|
||||||
// === Rootless container prerequisites (best-effort) ===
|
|
||||||
setup_rootless_prereqs();
|
|
||||||
|
|
||||||
// === Timezone ===
|
|
||||||
setup_timezone();
|
|
||||||
|
|
||||||
// === Networking ===
|
|
||||||
setup_networking();
|
|
||||||
|
|
||||||
// === virtio-fs shares ===
|
|
||||||
let workdir = read_file_opt("/boco/workdir").unwrap_or_default();
|
|
||||||
setup_virtiofs_shares(&workdir);
|
|
||||||
|
|
||||||
// === Environment & working directory ===
|
|
||||||
apply_env();
|
|
||||||
apply_workdir();
|
|
||||||
|
|
||||||
// === Resolve user for privilege drop ===
|
|
||||||
let user = read_file_opt("/boco/user").and_then(|spec| resolve_user(&spec));
|
|
||||||
|
|
||||||
// === Execute the configured command ===
|
|
||||||
let argv = read_argv();
|
|
||||||
exec_command(&argv, user);
|
|
||||||
}
|
|
||||||
-4083
File diff suppressed because it is too large.
Load diff
-1
Submodule kernel/linux deleted from 8d3ae59288.
+20
-44
@@ -1,4 +1,4 @@
|
|||||||
//! Build: mount a podman image, inject /boco/ scripts, and pack the rootfs
|
//! Build: mount a podman image, inject /slim/ scripts, and pack the rootfs
|
||||||
//! as a gzipped cpio initrd or qcow2 disk in the registry.
|
//! as a gzipped cpio initrd or qcow2 disk in the registry.
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
@@ -41,28 +41,19 @@ pub(crate) fn build(
|
|||||||
}: BuildCmd,
|
}: BuildCmd,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let image = &name;
|
let image = &name;
|
||||||
let container = format!("boco-build-{}", image.replace(':', "-"));
|
let mount_path = mount_image(image)?;
|
||||||
|
|
||||||
let mount_path = mount_container(image, &container)?;
|
|
||||||
println!("Mounted at: {}", mount_path.display());
|
println!("Mounted at: {}", mount_path.display());
|
||||||
|
|
||||||
let result = build_inner(&kind, image, &mount_path, cmd_override);
|
let result = build_inner(&kind, image, &mount_path, cmd_override);
|
||||||
|
|
||||||
let unmounted = cmd(&[
|
let unmounted = cmd(&[
|
||||||
"podman",
|
"podman", "unshare", "--", "podman", "image", "unmount", image,
|
||||||
"unshare",
|
|
||||||
"--",
|
|
||||||
"podman",
|
|
||||||
"container",
|
|
||||||
"unmount",
|
|
||||||
&container,
|
|
||||||
])
|
])
|
||||||
.is_ok();
|
.is_ok();
|
||||||
let removed = cmd(&["podman", "rm", &container]).is_ok();
|
if unmounted {
|
||||||
if unmounted && removed {
|
println!("Unmounted image.");
|
||||||
println!("Unmounted and removed container.");
|
|
||||||
} else {
|
} else {
|
||||||
eprintln!("warning: failed to clean up container '{container}'");
|
eprintln!("warning: failed to unmount image '{}'", image);
|
||||||
}
|
}
|
||||||
|
|
||||||
result
|
result
|
||||||
@@ -75,18 +66,12 @@ fn build_inner(
|
|||||||
cmd: Option<String>,
|
cmd: Option<String>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let config = inject::inspect_config(image)?;
|
let config = inject::inspect_config(image)?;
|
||||||
let argv = match cmd {
|
let command = cmd.unwrap_or_else(|| inject::infer_command(&config));
|
||||||
Some(s) => vec!["/bin/sh".into(), "-c".into(), s],
|
let env = inject::env(&config);
|
||||||
None => inject::infer_argv(&config),
|
let working_dir = inject::working_dir(&config);
|
||||||
};
|
let exec_script = inject::build_exec_script(&command, &env, working_dir);
|
||||||
inject::inject(
|
inject::inject(mount_path, &exec_script)?;
|
||||||
mount_path,
|
println!("Injected /slim/ (init + exec)");
|
||||||
&argv,
|
|
||||||
&config.env,
|
|
||||||
config.user.as_deref(),
|
|
||||||
config.working_dir.as_deref(),
|
|
||||||
)?;
|
|
||||||
println!("Injected /boco/ (init + exec)");
|
|
||||||
|
|
||||||
match kind {
|
match kind {
|
||||||
ImageKind::Initrd => build_initrd(image, mount_path),
|
ImageKind::Initrd => build_initrd(image, mount_path),
|
||||||
@@ -94,22 +79,13 @@ fn build_inner(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mount_container(image: &str, container: &str) -> Result<PathBuf> {
|
fn mount_image(image: &str) -> Result<PathBuf> {
|
||||||
cmd(&["podman", "create", "--name", container, image, "/bin/true"])?;
|
let mount_path = cmd(&["podman", "unshare", "--", "podman", "image", "mount", image])?;
|
||||||
let mount_path = cmd(&[
|
|
||||||
"podman",
|
|
||||||
"unshare",
|
|
||||||
"--",
|
|
||||||
"podman",
|
|
||||||
"container",
|
|
||||||
"mount",
|
|
||||||
container,
|
|
||||||
])?;
|
|
||||||
Ok(PathBuf::from(mount_path.trim()))
|
Ok(PathBuf::from(mount_path.trim()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Copy a directory onto a new raw disk image with EXT4.
|
/// Copy a directory onto a new raw disk image with EXT4.
|
||||||
fn to_raw_ext4(dir: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
|
fn to_raw_ext4(dir: &Path) -> Result<NamedTempFile> {
|
||||||
let dir = dir.to_str().context("Invalid UTF-8")?;
|
let dir = dir.to_str().context("Invalid UTF-8")?;
|
||||||
let du_out = cmd(&["podman", "unshare", "--", "du", "-sk", dir])?;
|
let du_out = cmd(&["podman", "unshare", "--", "du", "-sk", dir])?;
|
||||||
|
|
||||||
@@ -127,7 +103,7 @@ fn to_raw_ext4(dir: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
|
|||||||
+ 64 * gb; // Add some spare capacity for activities
|
+ 64 * gb; // Add some spare capacity for activities
|
||||||
let size = size.to_string();
|
let size = size.to_string();
|
||||||
|
|
||||||
let raw_file = NamedTempFile::new_in(tmp_dir)?;
|
let raw_file = NamedTempFile::new()?;
|
||||||
let raw_path = raw_file.path().to_str().context("Invalid UTF-8")?;
|
let raw_path = raw_file.path().to_str().context("Invalid UTF-8")?;
|
||||||
cmd(&["podman", "unshare", "--", "truncate", "-s", &size, raw_path])?;
|
cmd(&["podman", "unshare", "--", "truncate", "-s", &size, raw_path])?;
|
||||||
cmd(&[
|
cmd(&[
|
||||||
@@ -144,9 +120,9 @@ fn to_raw_ext4(dir: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Copy a directory onto a new qcow2 disk image with EXT4.
|
/// Copy a directory onto a new qcow2 disk image with EXT4.
|
||||||
fn to_qcow2_ext4(mount_path: &Path, tmp_dir: &Path) -> Result<NamedTempFile> {
|
fn to_qcow2_ext4(mount_path: &Path) -> Result<NamedTempFile> {
|
||||||
let raw = to_raw_ext4(mount_path, tmp_dir)?;
|
let raw = to_raw_ext4(mount_path)?;
|
||||||
let qcow2 = NamedTempFile::new_in(tmp_dir)?;
|
let qcow2 = NamedTempFile::new()?;
|
||||||
let raw_path = raw.path().to_str().context("Invalid UTF-8")?;
|
let raw_path = raw.path().to_str().context("Invalid UTF-8")?;
|
||||||
let qcow2_path = qcow2.path().to_str().context("Invalid UTF-8")?;
|
let qcow2_path = qcow2.path().to_str().context("Invalid UTF-8")?;
|
||||||
cmd(&[
|
cmd(&[
|
||||||
@@ -160,7 +136,7 @@ fn build_qcow2(image: &str, mount_path: &Path) -> Result<()> {
|
|||||||
fs::create_dir_all(®_dir)?;
|
fs::create_dir_all(®_dir)?;
|
||||||
println!("Registry: {}", reg_dir.display());
|
println!("Registry: {}", reg_dir.display());
|
||||||
|
|
||||||
let qcow2 = to_qcow2_ext4(mount_path, ®_dir)?;
|
let qcow2 = to_qcow2_ext4(mount_path)?;
|
||||||
|
|
||||||
fs::copy(qcow2.path(), reg_dir.join("image.qcow2"))
|
fs::copy(qcow2.path(), reg_dir.join("image.qcow2"))
|
||||||
.context("Failed to copy qcow2 image to registry")?;
|
.context("Failed to copy qcow2 image to registry")?;
|
||||||
|
|||||||
+85
-66
@@ -1,6 +1,5 @@
|
|||||||
//! Inject: inspect a podman image's config, infer the default command argv,
|
//! Inject: inspect a podman image's config, infer the default command, and
|
||||||
//! and inject the boco init binary + null-delimited argv/env files into the
|
//! inject distro-agnostic /slim/ scripts (init + exec) into the mounted rootfs.
|
||||||
//! mounted rootfs.
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow};
|
use anyhow::{Context, Result, anyhow};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
@@ -8,21 +7,20 @@ use std::fs;
|
|||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
|
|
||||||
use crate::command::cmd;
|
use crate::command::cmd;
|
||||||
use crate::registry::init_binary_path;
|
|
||||||
|
const SLIM_INIT: &str = include_str!("scripts/slim-init.sh");
|
||||||
|
|
||||||
#[derive(Debug, Default, Deserialize)]
|
#[derive(Debug, Default, Deserialize)]
|
||||||
#[serde(rename_all = "PascalCase")]
|
#[serde(rename_all = "PascalCase")]
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub cmd: Vec<String>,
|
cmd: Option<Vec<String>>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub entrypoint: Vec<String>,
|
entrypoint: Option<Vec<String>>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub env: Vec<String>,
|
env: Option<Vec<String>>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub working_dir: Option<String>,
|
working_dir: Option<String>,
|
||||||
#[serde(default)]
|
|
||||||
pub user: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn inspect_config(image: &str) -> Result<Config> {
|
pub fn inspect_config(image: &str) -> Result<Config> {
|
||||||
@@ -39,77 +37,98 @@ pub fn inspect_config(image: &str) -> Result<Config> {
|
|||||||
Ok(config)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Infer the command argv from the image config.
|
/// Infer the command string from the image config.
|
||||||
///
|
///
|
||||||
/// Concatenates ENTRYPOINT + CMD (Docker semantics). If neither is present,
|
/// Concatenates ENTRYPOINT + CMD (Docker semantics). If neither is present,
|
||||||
/// falls back to `["/bin/sh"]`.
|
/// falls back to `/bin/sh`.
|
||||||
pub fn infer_argv(config: &Config) -> Vec<String> {
|
pub fn infer_command(config: &Config) -> String {
|
||||||
let parts: Vec<String> = config
|
let entrypoint = config.entrypoint.as_deref().filter(|e| !e.is_empty());
|
||||||
.entrypoint
|
let cmd = config.cmd.as_deref().filter(|c| !c.is_empty());
|
||||||
.iter()
|
|
||||||
.chain(config.cmd.iter())
|
|
||||||
.cloned()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
if parts.is_empty() {
|
let parts: Vec<String> = match (entrypoint, cmd) {
|
||||||
vec!["/bin/sh".into()]
|
(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 {
|
} else {
|
||||||
parts
|
shell_join(&parts)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Join items as null-delimited bytes.
|
pub fn env(config: &Config) -> Vec<String> {
|
||||||
pub fn null_delimited(items: &[String]) -> Vec<u8> {
|
config.env.clone().unwrap_or_default()
|
||||||
let mut data = Vec::new();
|
}
|
||||||
for item in items {
|
|
||||||
data.extend_from_slice(item.as_bytes());
|
pub fn working_dir(config: &Config) -> Option<&str> {
|
||||||
data.push(0);
|
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)));
|
||||||
}
|
}
|
||||||
data
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Install `content` into the mounted rootfs at `<mount>/boco/<name>` with
|
/// Inject /slim/init and /slim/exec into a mounted container image rootfs.
|
||||||
/// the given mode.
|
pub fn inject(mount_path: &Path, exec_script: &str) -> Result<()> {
|
||||||
fn install_into_rootfs(mount: &str, name: &str, mode: &str, content: &[u8]) -> Result<()> {
|
|
||||||
let temp = tempfile::NamedTempFile::new()?;
|
|
||||||
fs::write(temp.path(), content)?;
|
|
||||||
let src = temp.path().to_str().context("temp path is not UTF-8")?;
|
|
||||||
let dest = format!("{mount}/boco/{name}");
|
|
||||||
cmd(&[
|
|
||||||
"podman", "unshare", "--", "install", "-D", "-m", mode, src, &dest,
|
|
||||||
])?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Inject /boco/init (binary), /boco/exec (null-delimited argv), /boco/env
|
|
||||||
/// (null-delimited env), and optionally /boco/user and /boco/workdir into a
|
|
||||||
/// mounted container image rootfs.
|
|
||||||
pub fn inject(
|
|
||||||
mount_path: &Path,
|
|
||||||
argv: &[String],
|
|
||||||
env: &[String],
|
|
||||||
user: Option<&str>,
|
|
||||||
working_dir: Option<&str>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let mount_str = mount_path.to_str().context("mount path is not UTF-8")?;
|
let mount_str = mount_path.to_str().context("mount path is not UTF-8")?;
|
||||||
|
|
||||||
let init_binary = fs::read(init_binary_path()?).context("Failed to read boco-init binary")?;
|
let init_temp = tempfile::NamedTempFile::new()?;
|
||||||
let exec_data = null_delimited(argv);
|
let exec_temp = tempfile::NamedTempFile::new()?;
|
||||||
let env_data = null_delimited(env);
|
fs::write(init_temp.path(), SLIM_INIT)?;
|
||||||
|
fs::write(exec_temp.path(), exec_script)?;
|
||||||
|
|
||||||
install_into_rootfs(mount_str, "init", "755", &init_binary)?;
|
let init_src = init_temp
|
||||||
install_into_rootfs(mount_str, "exec", "644", &exec_data)?;
|
.path()
|
||||||
if !env_data.is_empty() {
|
.to_str()
|
||||||
install_into_rootfs(mount_str, "env", "644", &env_data)?;
|
.context("temp path is not UTF-8")?;
|
||||||
}
|
let exec_src = exec_temp
|
||||||
|
.path()
|
||||||
|
.to_str()
|
||||||
|
.context("temp path is not UTF-8")?;
|
||||||
|
|
||||||
if let Some(user) = user.filter(|u| !u.is_empty()) {
|
let init_dest = format!("{mount_str}/slim/init");
|
||||||
install_into_rootfs(mount_str, "user", "644", user.as_bytes())?;
|
let exec_dest = format!("{mount_str}/slim/exec");
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(dir) = working_dir.filter(|d| !d.is_empty()) {
|
cmd(&[
|
||||||
install_into_rootfs(mount_str, "workdir", "644", dir.as_bytes())?;
|
"podman", "unshare", "--", "install", "-D", "-m", "755", init_src, &init_dest,
|
||||||
}
|
])?;
|
||||||
|
cmd(&[
|
||||||
|
"podman", "unshare", "--", "install", "-D", "-m", "755", exec_src, &exec_dest,
|
||||||
|
])?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
+5
-6
@@ -5,12 +5,11 @@ mod image;
|
|||||||
mod inject;
|
mod inject;
|
||||||
mod qemu;
|
mod qemu;
|
||||||
mod registry;
|
mod registry;
|
||||||
mod virtiofs;
|
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
|
|
||||||
use crate::{build::BuildCmd, image::ImageCmd, qemu::BootCmd};
|
use crate::{build::BuildCmd, image::ImageCmd, qemu::RunCmd};
|
||||||
|
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(about = "Turn containers into bootable VMs")]
|
#[command(about = "Turn containers into bootable VMs")]
|
||||||
@@ -24,8 +23,8 @@ enum Commands {
|
|||||||
/// Build initrd from an image (podman image must exist)
|
/// Build initrd from an image (podman image must exist)
|
||||||
Build(BuildCmd),
|
Build(BuildCmd),
|
||||||
/// Launch a previously built VM via QEMU.
|
/// Launch a previously built VM via QEMU.
|
||||||
Boot(BootCmd),
|
Run(RunCmd),
|
||||||
/// List boco images in the registry
|
/// List slim images in the registry
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
Image(ImageCmd),
|
Image(ImageCmd),
|
||||||
}
|
}
|
||||||
@@ -36,8 +35,8 @@ fn main() -> Result<()> {
|
|||||||
Commands::Build(cmd) => {
|
Commands::Build(cmd) => {
|
||||||
build::build(cmd)?;
|
build::build(cmd)?;
|
||||||
}
|
}
|
||||||
Commands::Boot(cmd) => {
|
Commands::Run(cmd) => {
|
||||||
qemu::boot(cmd)?;
|
qemu::run(cmd)?;
|
||||||
}
|
}
|
||||||
Commands::Image(cmd) => {
|
Commands::Image(cmd) => {
|
||||||
image::run(cmd)?;
|
image::run(cmd)?;
|
||||||
|
|||||||
+19
-82
@@ -1,4 +1,9 @@
|
|||||||
//! See [`boot`]
|
//! QEMU: boot a registry entry with qemu-system-x86_64 using direct kernel
|
||||||
|
//! boot (-kernel/-initrd or -drive). The kernel is shared across all VMs
|
||||||
|
//! at $XDG_DATA_HOME/slim-rs/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 anyhow::{Context, Result, bail};
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
@@ -7,12 +12,11 @@ use std::{fmt::Write as _, process::Command};
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
forward::PortForward,
|
forward::PortForward,
|
||||||
registry::{registry_dir, vmlinuz_path},
|
registry::{registry_base_dir, registry_dir},
|
||||||
virtiofs::{self, VirtiofsShare},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Args, Debug)]
|
#[derive(Args, Debug)]
|
||||||
pub struct BootCmd {
|
pub struct RunCmd {
|
||||||
/// Image tag / registry subdir name
|
/// Image tag / registry subdir name
|
||||||
name: String,
|
name: String,
|
||||||
|
|
||||||
@@ -25,39 +29,27 @@ pub struct BootCmd {
|
|||||||
forward: Vec<PortForward>,
|
forward: Vec<PortForward>,
|
||||||
|
|
||||||
/// Override the command to exec in the VM (base64-encoded on the kernel
|
/// Override the command to exec in the VM (base64-encoded on the kernel
|
||||||
/// cmdline as `boco.cmd=<b64>`). Overrides the CMD inferred at build time.
|
/// cmdline as slim.cmd=<b64>). Overrides the CMD inferred at build time.
|
||||||
#[clap(long)]
|
#[clap(long)]
|
||||||
cmd: Option<String>,
|
cmd: Option<String>,
|
||||||
|
|
||||||
/// Share a host directory into the VM via virtio-fs. Format:
|
|
||||||
/// `<host-path>` or `<host-path>:<guest-path>`. When the guest path is
|
|
||||||
/// omitted, the host path is used. Non-absolute guest paths are
|
|
||||||
/// relative to the image's WORKINGDIR. Can be repeated.
|
|
||||||
#[clap(long)]
|
|
||||||
mount: Vec<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Invoke `qemu` to boot a boco image. See [`BootCmd`] for options
|
pub(crate) fn run(
|
||||||
///
|
RunCmd {
|
||||||
/// This uses qemu's direct-kernel-boot with `-kernel`, so it does not require a bootloader.
|
|
||||||
/// The boco image is just an ext4 rootfs.
|
|
||||||
pub(crate) fn boot(
|
|
||||||
BootCmd {
|
|
||||||
name,
|
name,
|
||||||
memory,
|
memory,
|
||||||
forward,
|
forward,
|
||||||
cmd,
|
cmd,
|
||||||
mount,
|
}: RunCmd,
|
||||||
}: BootCmd,
|
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let reg_dir = registry_dir(&name)?;
|
let reg_dir = registry_dir(&name)?;
|
||||||
let vmlinuz_path = vmlinuz_path()?;
|
let vmlinuz_path = registry_base_dir()?.join("vmlinuz");
|
||||||
let initrd_path = reg_dir.join("initrd");
|
let initrd_path = reg_dir.join("initrd");
|
||||||
let qcow2_path = reg_dir.join("image.qcow2");
|
let qcow2_path = reg_dir.join("image.qcow2");
|
||||||
if !vmlinuz_path.exists() {
|
if !vmlinuz_path.exists() {
|
||||||
// TODO: guide user in how to set up a kernel
|
// TODO: guide user in how to set up a kernel
|
||||||
bail!(
|
bail!(
|
||||||
"No kernel available. Expected vmlinuz at {}",
|
"No kernel available. Place a vmlinuz at {}",
|
||||||
vmlinuz_path.display()
|
vmlinuz_path.display()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -67,7 +59,7 @@ pub(crate) fn boot(
|
|||||||
"rw".into(),
|
"rw".into(),
|
||||||
"earlyprintk=serial".into(),
|
"earlyprintk=serial".into(),
|
||||||
"nokaslr".into(),
|
"nokaslr".into(),
|
||||||
"init=/boco/init".into(),
|
"init=/slim/init".into(),
|
||||||
"devtmpfs.mount=1".into(), // Automatically mount /dev at boot
|
"devtmpfs.mount=1".into(), // Automatically mount /dev at boot
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -81,65 +73,14 @@ pub(crate) fn boot(
|
|||||||
fs_args = vec!["-initrd".to_string(), initrd_str];
|
fs_args = vec!["-initrd".to_string(), initrd_str];
|
||||||
cmdline.push("root=/dev/ram0".into());
|
cmdline.push("root=/dev/ram0".into());
|
||||||
} else {
|
} else {
|
||||||
bail!("Registry missing rootfs/initrd for '{name}'. Run `boco build` first.");
|
bail!("Registry missing rootfs/initrd for '{name}'. Run `slim build` first.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(cmd) = &cmd {
|
if let Some(cmd) = &cmd {
|
||||||
let argv = ["/bin/sh".to_string(), "-c".to_string(), cmd.clone()];
|
let encoded = base64::engine::general_purpose::STANDARD.encode(cmd.as_bytes());
|
||||||
let data: Vec<u8> = argv.join("\0").into_bytes();
|
cmdline.push(format!("slim.cmd={encoded}"));
|
||||||
let encoded = base64::engine::general_purpose::STANDARD.encode(&data);
|
|
||||||
cmdline.push(format!("boco.cmd={encoded}"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build virtio-fs shares for each `--mount`. Each share gets its own
|
|
||||||
// virtiofsd daemon under `podman unshare` (rootless UID mapping) and a
|
|
||||||
// matching `-chardev socket` + `-device vhost-user-fs-pci` pair on the
|
|
||||||
// QEMU side. The guest destination path is passed on the kernel cmdline
|
|
||||||
// as `boco.mount=<tag>:<base64(guest_path)>` and resolved by /boco/init.
|
|
||||||
let mut shares: Vec<VirtiofsShare> = Vec::with_capacity(mount.len());
|
|
||||||
let mut fsdev_args: Vec<String> = Vec::new();
|
|
||||||
for (i, spec) in mount.iter().enumerate() {
|
|
||||||
let (host_path, guest_path) = match spec.split_once(':') {
|
|
||||||
Some((h, g)) => (h, g.to_string()),
|
|
||||||
None => (spec.as_str(), spec.to_string()),
|
|
||||||
};
|
|
||||||
let share = virtiofs::spawn_share(i, host_path, guest_path)?;
|
|
||||||
let tag = share.tag.clone();
|
|
||||||
let chardev = format!("char{i}");
|
|
||||||
let socket = share
|
|
||||||
.socket_path()
|
|
||||||
.to_str()
|
|
||||||
.context("socket path is not UTF-8")?
|
|
||||||
.to_string();
|
|
||||||
let dest_b64 =
|
|
||||||
base64::engine::general_purpose::STANDARD.encode(share.guest_path.as_bytes());
|
|
||||||
|
|
||||||
fsdev_args.push("-chardev".into());
|
|
||||||
fsdev_args.push(format!("socket,id={chardev},path={socket}"));
|
|
||||||
fsdev_args.push("-device".into());
|
|
||||||
fsdev_args.push(format!(
|
|
||||||
"vhost-user-fs-pci,queue-size=1024,chardev={chardev},tag={tag}"
|
|
||||||
));
|
|
||||||
cmdline.push(format!("boco.mount={tag}:{dest_b64}"));
|
|
||||||
|
|
||||||
shares.push(share);
|
|
||||||
}
|
|
||||||
|
|
||||||
// vhost-user devices require shared guest RAM so virtiofsd (a separate
|
|
||||||
// process) can DMA into it.
|
|
||||||
let memory_args: Vec<String> = if shares.is_empty() {
|
|
||||||
vec!["-m".into(), memory.clone()]
|
|
||||||
} else {
|
|
||||||
vec![
|
|
||||||
"-m".into(),
|
|
||||||
memory.clone(),
|
|
||||||
"-object".into(),
|
|
||||||
format!("memory-backend-memfd,id=mem,size={memory},share=on"),
|
|
||||||
"-numa".into(),
|
|
||||||
"node,memdev=mem".into(),
|
|
||||||
]
|
|
||||||
};
|
|
||||||
|
|
||||||
println!("Booting {name} from registry: {}", reg_dir.display());
|
println!("Booting {name} from registry: {}", reg_dir.display());
|
||||||
|
|
||||||
let cmdline = cmdline.join(" ");
|
let cmdline = cmdline.join(" ");
|
||||||
@@ -156,11 +97,10 @@ pub(crate) fn boot(
|
|||||||
command
|
command
|
||||||
.args(["-accel", "kvm"])
|
.args(["-accel", "kvm"])
|
||||||
.args(["-cpu", "host", "-smp", "cpus=8"])
|
.args(["-cpu", "host", "-smp", "cpus=8"])
|
||||||
.args(&memory_args)
|
.args(["-m", &memory])
|
||||||
.arg("-kernel")
|
.arg("-kernel")
|
||||||
.arg(vmlinuz_path.as_os_str())
|
.arg(vmlinuz_path.as_os_str())
|
||||||
.args(&fs_args)
|
.args(&fs_args)
|
||||||
.args(&fsdev_args)
|
|
||||||
.args(["-snapshot"])
|
.args(["-snapshot"])
|
||||||
.args(["-no-reboot"])
|
.args(["-no-reboot"])
|
||||||
.args(["-append", &cmdline])
|
.args(["-append", &cmdline])
|
||||||
@@ -173,9 +113,6 @@ pub(crate) fn boot(
|
|||||||
.status()
|
.status()
|
||||||
.context("Failed to launch qemu-system-x86_64")?;
|
.context("Failed to launch qemu-system-x86_64")?;
|
||||||
|
|
||||||
// Ensure virtiofsd daemons are torn down even on error returns below.
|
|
||||||
drop(shares);
|
|
||||||
|
|
||||||
match status.code() {
|
match status.code() {
|
||||||
Some(0) => println!("QEMU exited cleanly."),
|
Some(0) => println!("QEMU exited cleanly."),
|
||||||
Some(126) | Some(127) => {
|
Some(126) | Some(127) => {
|
||||||
|
|||||||
+4
-16
@@ -1,12 +1,12 @@
|
|||||||
//! Registry: local storage of built VM artifacts under
|
//! Registry: local storage of built VM artifacts under
|
||||||
//! `$XDG_DATA_HOME/boco/registry/<image>/`.
|
//! `$XDG_DATA_HOME/slim-rs/registry/<image>/`.
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
use std::{fs, io, path::PathBuf};
|
use std::{fs, io, path::PathBuf};
|
||||||
|
|
||||||
/// Validate a user-supplied image name before it is used in a registry path.
|
/// Validate a user-supplied image name before it is used in a registry path.
|
||||||
///
|
///
|
||||||
/// The name becomes a directory under `$XDG_DATA_HOME/boco/registry/`, so
|
/// The name becomes a directory under `$XDG_DATA_HOME/slim-rs/registry/`, so
|
||||||
/// path separators and `.`/`..` would allow escaping that directory.
|
/// path separators and `.`/`..` would allow escaping that directory.
|
||||||
/// Allow-list: ASCII alphanumerics plus `.`, `_`, `:`, `-` (covers image
|
/// Allow-list: ASCII alphanumerics plus `.`, `_`, `:`, `-` (covers image
|
||||||
/// refs like `alpine:3.15`).
|
/// refs like `alpine:3.15`).
|
||||||
@@ -26,24 +26,12 @@ pub(crate) fn validate_image_name(name: &str) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn vmlinuz_path() -> Result<PathBuf> {
|
|
||||||
let base = xdg::BaseDirectories::with_prefix("boco");
|
|
||||||
base.place_data_file("vmlinuz")
|
|
||||||
.context("Failed to create XDG_DATA_HOME subdirectory")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn registry_base_dir() -> Result<PathBuf> {
|
pub(crate) fn registry_base_dir() -> Result<PathBuf> {
|
||||||
let base = xdg::BaseDirectories::with_prefix("boco");
|
let base = xdg::BaseDirectories::with_prefix("slim-rs");
|
||||||
base.create_data_directory("registry")
|
base.create_data_directory("registry")
|
||||||
.context("Failed to create XDG_DATA_HOME subdirectory")
|
.context("Failed to create XDG_DATA_HOME subdirectory")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn init_binary_path() -> Result<PathBuf> {
|
|
||||||
let base = xdg::BaseDirectories::with_prefix("boco");
|
|
||||||
base.get_data_file("boco-init")
|
|
||||||
.context("boco-init not found in XDG data dir")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn registry_dir(image: &str) -> Result<PathBuf> {
|
pub(crate) fn registry_dir(image: &str) -> Result<PathBuf> {
|
||||||
validate_image_name(image)?;
|
validate_image_name(image)?;
|
||||||
let base = registry_base_dir()?;
|
let base = registry_base_dir()?;
|
||||||
@@ -68,7 +56,7 @@ mod tests {
|
|||||||
fn accepts_valid_image_names() {
|
fn accepts_valid_image_names() {
|
||||||
for name in [
|
for name in [
|
||||||
"alpine:3.15",
|
"alpine:3.15",
|
||||||
"boco",
|
"slim",
|
||||||
"mock-vm",
|
"mock-vm",
|
||||||
"my_vm",
|
"my_vm",
|
||||||
"a.b.c",
|
"a.b.c",
|
||||||
|
|||||||
@@ -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
|
||||||
-222
@@ -1,222 +0,0 @@
|
|||||||
//! Virtiofs: spawn and manage one virtiofsd daemon per `--mount` share.
|
|
||||||
//!
|
|
||||||
//! virtiofsd is a vhost-user device backend that runs in a separate
|
|
||||||
//! process from QEMU and serves files from a host directory over the
|
|
||||||
//! FUSE protocol via a UNIX socket. boco spawns one daemon per share,
|
|
||||||
//! hands the socket path to QEMU via `-chardev socket,path=...`, and
|
|
||||||
//! cleans up when the VM exits.
|
|
||||||
//!
|
|
||||||
//! To serve files owned by arbitrary guest UIDs (e.g. when an image
|
|
||||||
//! uses the `USER` directive) without running as root, virtiofsd is
|
|
||||||
//! launched under `podman unshare` in a user namespace with
|
|
||||||
//! `--sandbox chroot`. This reuses rootless podman's existing
|
|
||||||
//! subuid/subgid mapping: guest UID 0 maps to the invoking user, and
|
|
||||||
//! other guest UIDs map into the subuid range, so each guest UID
|
|
||||||
//! becomes a distinct host UID.
|
|
||||||
//!
|
|
||||||
//! Lifecycle: boco spawns all virtiofsd children before launching QEMU,
|
|
||||||
//! waits for each listening socket to appear, then drops the
|
|
||||||
//! [`VirtiofsShare`] guard after QEMU returns — `Drop` sends SIGTERM,
|
|
||||||
//! waits briefly, escalates to SIGKILL, and `TempDir` removes the
|
|
||||||
//! socket files. On signals that kill boco directly (SIGINT/SIGTERM
|
|
||||||
//! without a handler), the guard does not run and the daemons linger;
|
|
||||||
//! callers like `example/test.sh` should `pkill virtiofsd` in cleanup.
|
|
||||||
|
|
||||||
use std::path::{Path, PathBuf};
|
|
||||||
use std::process::{Child, Command, Stdio};
|
|
||||||
use std::thread;
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
|
|
||||||
use anyhow::{Context, Result, anyhow, bail};
|
|
||||||
use tempfile::TempDir;
|
|
||||||
|
|
||||||
use crate::command::cmd;
|
|
||||||
|
|
||||||
/// Locations searched for the virtiofsd binary, in order.
|
|
||||||
const VIRTIOFSD_CANDIDATES: &[&str] = &[
|
|
||||||
"/usr/libexec/virtiofsd",
|
|
||||||
"/usr/lib/qemu/virtiofsd",
|
|
||||||
"/usr/lib/virtiofsd",
|
|
||||||
];
|
|
||||||
|
|
||||||
/// How long to wait for virtiofsd to create its listening socket.
|
|
||||||
const SOCKET_READY_TIMEOUT: Duration = Duration::from_secs(5);
|
|
||||||
const SOCKET_POLL_INTERVAL: Duration = Duration::from_millis(10);
|
|
||||||
/// Grace period after SIGTERM before escalating to SIGKILL.
|
|
||||||
const STOP_GRACE: Duration = Duration::from_secs(2);
|
|
||||||
|
|
||||||
/// A running virtiofsd daemon plus the resources it owns.
|
|
||||||
///
|
|
||||||
/// `Drop` stops the daemon and removes its socket. The `TempDir`
|
|
||||||
/// holding the socket is owned by the share so its path stays valid
|
|
||||||
/// for the lifetime of `socket`.
|
|
||||||
pub struct VirtiofsShare {
|
|
||||||
/// Tag advertised to the guest (e.g. `boco0`).
|
|
||||||
pub tag: String,
|
|
||||||
/// Guest-side mount destination, as supplied by the user (may be
|
|
||||||
/// relative to the image's WORKINGDIR; resolved by the guest init).
|
|
||||||
pub guest_path: String,
|
|
||||||
socket: PathBuf,
|
|
||||||
child: Option<Child>,
|
|
||||||
_dir: TempDir,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Locate the virtiofsd binary.
|
|
||||||
///
|
|
||||||
/// Searches well-known distro paths first, then falls back to `$PATH`
|
|
||||||
/// lookup via `command -v`.
|
|
||||||
pub fn find_virtiofsd() -> Result<PathBuf> {
|
|
||||||
for path in VIRTIOFSD_CANDIDATES {
|
|
||||||
if Path::new(path).exists() {
|
|
||||||
return Ok(PathBuf::from(path));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let which = cmd(&["sh", "-c", "command -v virtiofsd"])?;
|
|
||||||
let trimmed = which.trim();
|
|
||||||
if trimmed.is_empty() {
|
|
||||||
bail!(
|
|
||||||
"virtiofsd not found. Install it (often shipped with qemu, or \
|
|
||||||
build https://gitlab.com/virtio-fs/virtiofsd) and ensure it is \
|
|
||||||
in PATH or at one of: {}",
|
|
||||||
VIRTIOFSD_CANDIDATES.join(", ")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(PathBuf::from(trimmed))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn resolve_host_dir(host: &str) -> Result<PathBuf> {
|
|
||||||
let path = Path::new(host)
|
|
||||||
.canonicalize()
|
|
||||||
.with_context(|| format!("Cannot resolve mount path '{host}'"))?;
|
|
||||||
if !path.is_dir() {
|
|
||||||
bail!("Mount source '{}' is not a directory", path.display());
|
|
||||||
}
|
|
||||||
Ok(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wait for `socket` to appear as a filesystem entry.
|
|
||||||
fn wait_for_socket(socket: &Path) -> Result<()> {
|
|
||||||
let start = Instant::now();
|
|
||||||
while start.elapsed() < SOCKET_READY_TIMEOUT {
|
|
||||||
if socket.exists() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
thread::sleep(SOCKET_POLL_INTERVAL);
|
|
||||||
}
|
|
||||||
bail!(
|
|
||||||
"virtiofsd did not create socket at {} within {:.1}s",
|
|
||||||
socket.display(),
|
|
||||||
SOCKET_READY_TIMEOUT.as_secs_f64()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Spawn one virtiofsd daemon for a share.
|
|
||||||
///
|
|
||||||
/// `index` becomes the suffix of the tag (`boco{index}`) and is used to
|
|
||||||
/// derive a unique socket filename.
|
|
||||||
pub fn spawn_share(index: usize, host_path: &str, guest_path: String) -> Result<VirtiofsShare> {
|
|
||||||
let virtiofsd = find_virtiofsd()?;
|
|
||||||
let canonical = resolve_host_dir(host_path)?;
|
|
||||||
let host_str = canonical
|
|
||||||
.to_str()
|
|
||||||
.context("Mount source path is not valid UTF-8")?;
|
|
||||||
let virtiofsd_str = virtiofsd
|
|
||||||
.to_str()
|
|
||||||
.context("virtiofsd path is not valid UTF-8")?;
|
|
||||||
|
|
||||||
let dir = TempDir::new()?;
|
|
||||||
let tag = format!("boco{index}"); // short tag to fit on cmdline
|
|
||||||
let socket = dir.path().join(format!("{tag}.sock"));
|
|
||||||
|
|
||||||
// TODO: Make rootless mode optional
|
|
||||||
|
|
||||||
// Run virtiofsd under `podman unshare` so it can serve files owned
|
|
||||||
// by arbitrary guest UIDs without root, mapping them into the host
|
|
||||||
// user's subuid range. `--sandbox chroot` is required because the
|
|
||||||
// outer `podman unshare` already entered a user namespace (nested
|
|
||||||
// user namespaces are not allowed); chroot still prevents symlink
|
|
||||||
// escapes from the shared dir.
|
|
||||||
let mut command = Command::new("podman");
|
|
||||||
command
|
|
||||||
.args(["unshare", "--", virtiofsd_str, "--socket-path"])
|
|
||||||
.arg(&socket)
|
|
||||||
.args([
|
|
||||||
"--shared-dir",
|
|
||||||
host_str,
|
|
||||||
"--tag",
|
|
||||||
&tag,
|
|
||||||
"--sandbox",
|
|
||||||
"chroot",
|
|
||||||
"--cache",
|
|
||||||
"auto",
|
|
||||||
])
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::null())
|
|
||||||
.stderr(Stdio::inherit());
|
|
||||||
|
|
||||||
println!("{command:?}");
|
|
||||||
let child = command
|
|
||||||
.spawn()
|
|
||||||
.with_context(|| format!("Failed to spawn virtiofsd: {command:?}"))?;
|
|
||||||
|
|
||||||
wait_for_socket(&socket)
|
|
||||||
.with_context(|| anyhow!("virtiofsd for share '{tag}' failed to become ready"))?;
|
|
||||||
|
|
||||||
Ok(VirtiofsShare {
|
|
||||||
tag,
|
|
||||||
guest_path,
|
|
||||||
socket,
|
|
||||||
child: Some(child),
|
|
||||||
_dir: dir,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl VirtiofsShare {
|
|
||||||
/// Socket path to pass to QEMU's `-chardev socket,path=...`.
|
|
||||||
pub fn socket_path(&self) -> &Path {
|
|
||||||
&self.socket
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Send SIGTERM, wait briefly, then SIGKILL if still alive.
|
|
||||||
fn stop(&mut self) {
|
|
||||||
let Some(child) = self.child.as_mut() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
// SIGTERM first for a graceful exit.
|
|
||||||
let pid = child.id();
|
|
||||||
let _ = Command::new("kill")
|
|
||||||
.arg("-TERM")
|
|
||||||
.arg(pid.to_string())
|
|
||||||
.stdin(Stdio::null())
|
|
||||||
.stdout(Stdio::null())
|
|
||||||
.stderr(Stdio::null())
|
|
||||||
.status();
|
|
||||||
|
|
||||||
let start = Instant::now();
|
|
||||||
while start.elapsed() < STOP_GRACE {
|
|
||||||
match child.try_wait() {
|
|
||||||
Ok(Some(_)) => {
|
|
||||||
self.child = None;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
Ok(None) => thread::sleep(Duration::from_millis(50)),
|
|
||||||
Err(_) => break,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Escalate to SIGKILL.
|
|
||||||
if let Some(child) = self.child.as_mut() {
|
|
||||||
let _ = child.kill();
|
|
||||||
let _ = child.wait();
|
|
||||||
}
|
|
||||||
self.child = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drop for VirtiofsShare {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
self.stop();
|
|
||||||
// TempDir drop removes the socket file and its parent dir.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user