"""Boot a package root on a disposable ext2 volume with a small matching initramfs.""" import argparse import hashlib import os from pathlib import Path import shutil import subprocess import tempfile import uuid def digest(path): with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def prepare(args): work = args.work if args.root == Path("/") or work.is_relative_to(args.root): raise ValueError("use a separate package root and a new worker output directory") work.mkdir() seed = work / "seed" (seed / "bin").mkdir(parents=True) shutil.copy2(args.root / "bin/busybox", seed / "bin/busybox") identity = f"vinix-ports-{uuid.uuid4()}\n" (seed / ".vinix-image-id").write_text(identity) disk = work / "root.ext2" with tempfile.TemporaryDirectory(dir=work) as tmp, (work / "format.log").open("x") as log: root = Path(tmp) / "root" subprocess.run(["cp", "-a", "--reflink=auto", args.root, root], check=True) for item in ("dev", "proc", "tmp", "run"): directory = root / item if directory.is_symlink(): raise ValueError(f"invalid mount point: {directory}") directory.mkdir(exist_ok=True) (root / "tmp").chmod(0o1777) launcher = "usr/libexec/vinix-version-check" if args.desktop_init else "etc/inittab" for dest in (".vinix-image-id", "userland-check.sh", launcher): if os.path.lexists(root / dest): raise ValueError(f"fixture would overwrite /{dest}") (root / ".vinix-image-id").write_text(identity) # Only the ext2 copy prints the identity. A fallback into the seed # initramfs runs the original fixture and cannot satisfy this check. with (root / "userland-check.sh").open("xb") as script, args.fixture.open("rb") as fixture: script.write(b'#!/bin/sh\nIFS= read -r volume_id {console} 2>&1" launch = root / launcher if launch.parent.resolve() != launch.parent: raise ValueError(f"fixture launcher parent is a symlink: /{launcher}") launch.parent.mkdir(parents=True, exist_ok=True) if args.desktop_init: launch.write_text(f"#!/bin/sh\n{command}\n") launch.chmod(0o755) else: launch.write_text(f"::sysinit:/bin/sh -c '{command}'\n") # Account for the staged files and the files the guest will install. trees = [root, args.space_for] if args.space_for else [root] usage = sum(int(subprocess.check_output(["du", "-sB1", tree], text=True).split()[0]) for tree in trees) entries = sum(1 + sum(len(dirs) + len(files) for _, dirs, files in os.walk(tree)) for tree in trees) mib = 1024**2 size = (usage * 5 // 4 + 64 * mib + mib - 1) // mib * mib with disk.open("xb") as output: output.truncate(size) mkfs = shutil.which("mke2fs") or "/usr/sbin/mke2fs" # fakeroot covers both the ownership changes and mke2fs's input reads. subprocess.run(["fakeroot", "--", "sh", "-ec", 'chown -Rh 0:0 "$1"; shift; exec "$@"', "disk-root", root, mkfs, "-q", "-F", "-t", "ext2", "-b", "4096", "-I", "128", "-N", str(max(4096, entries * 2)), "-O", "filetype,sparse_super,^has_journal,^resize_inode,^dir_index,^extent,^64bit,^metadata_csum", "-d", root, disk], check=True, stdout=log, stderr=subprocess.STDOUT) fsck = shutil.which("e2fsck") or "/usr/sbin/e2fsck" subprocess.run([fsck, "-fn", disk], check=True, stdout=log, stderr=subprocess.STDOUT) debug = shutil.which("debugfs") or "/usr/sbin/debugfs" actual = subprocess.check_output([debug, "-R", "cat /.vinix-image-id", disk], text=True, stderr=log) if actual != identity: raise ValueError("ext2 disk identity differs from the boot seed") stat = subprocess.check_output([debug, "-R", "stat /bin/busybox", disk], text=True, stderr=log) fields = next(line.split() for line in stat.splitlines() if line.startswith("User:")) if int(fields[1]) or int(fields[3]): raise ValueError("packaged BusyBox on ext2 must be owned by root") return seed, disk def run(args): work = args.work seed, disk = prepare(args) mode = "--aarch64-disk-fixture" if args.arch == "aarch64" else "--disk-fixture" with (work / "boot.log").open("x") as log: subprocess.run([args.boot, seed, args.iso, work / "guest", mode, args.fixture, disk], check=True, stdout=log, stderr=subprocess.STDOUT) with (work / "receipts.sha256").open("x") as receipt: for item in (work / "format.log", work / "boot.log", work / "guest/serial.log", disk, args.fixture): receipt.write(f"{digest(item)} {item}\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("arch", choices=("x86_64", "aarch64")) parser.add_argument("--desktop-init", action="store_true", help="launch the fixture through the native desktop PID 1 hook") parser.add_argument("--space-for", type=lambda path: Path(path).resolve(), help="reserve bytes and inodes for a separate installed package tree") for arg in ("root", "fixture", "iso", "boot", "work"): parser.add_argument(arg, type=lambda path: Path(path).resolve()) run(parser.parse_args())