| 1 | """Boot a package root on a disposable ext2 volume with a small matching initramfs.""" |
| 2 | import argparse |
| 3 | import hashlib |
| 4 | import os |
| 5 | from pathlib import Path |
| 6 | import shutil |
| 7 | import subprocess |
| 8 | import tempfile |
| 9 | import uuid |
| 10 | |
| 11 | |
| 12 | def digest(path): |
| 13 | with path.open("rb") as stream: |
| 14 | return hashlib.file_digest(stream, "sha256").hexdigest() |
| 15 | |
| 16 | |
| 17 | def prepare(args): |
| 18 | work = args.work |
| 19 | if args.root == Path("/") or work.is_relative_to(args.root): |
| 20 | raise ValueError("use a separate package root and a new worker output directory") |
| 21 | work.mkdir() |
| 22 | seed = work / "seed" |
| 23 | (seed / "bin").mkdir(parents=True) |
| 24 | shutil.copy2(args.root / "bin/busybox", seed / "bin/busybox") |
| 25 | identity = f"vinix-ports-{uuid.uuid4()}\n" |
| 26 | (seed / ".vinix-image-id").write_text(identity) |
| 27 | disk = work / "root.ext2" |
| 28 | with tempfile.TemporaryDirectory(dir=work) as tmp, (work / "format.log").open("x") as log: |
| 29 | root = Path(tmp) / "root" |
| 30 | copy_mode = ["-al"] if args.link_inputs else ["-a", "--reflink=auto"] |
| 31 | subprocess.run(["cp", *copy_mode, args.root, root], check=True) |
| 32 | for item in ("dev", "proc", "tmp", "run"): |
| 33 | directory = root / item |
| 34 | if directory.is_symlink(): |
| 35 | raise ValueError(f"invalid mount point: {directory}") |
| 36 | directory.mkdir(exist_ok=True) |
| 37 | (root / "tmp").chmod(0o1777) |
| 38 | launcher = "usr/libexec/vinix-version-check" if args.desktop_init else "etc/inittab" |
| 39 | for dest in (".vinix-image-id", "userland-check.sh", launcher): |
| 40 | if os.path.lexists(root / dest): |
| 41 | raise ValueError(f"fixture would overwrite /{dest}") |
| 42 | (root / ".vinix-image-id").write_text(identity) |
| 43 | # Only the ext2 copy prints the identity. A fallback into the seed |
| 44 | # initramfs runs the original fixture and cannot satisfy this check. |
| 45 | with (root / "userland-check.sh").open("xb") as script, args.fixture.open("rb") as fixture: |
| 46 | script.write(b'#!/bin/sh\nIFS= read -r volume_id </.vinix-image-id || exit 1\n' |
| 47 | b'echo "VPAC DISK ROOT $volume_id"\n') |
| 48 | shutil.copyfileobj(fixture, script) |
| 49 | console = "/dev/console" if args.arch == "aarch64" else "/dev/com1" |
| 50 | command = f"exec /bin/sh /userland-check.sh >{console} 2>&1" |
| 51 | launch = root / launcher |
| 52 | if launch.parent.resolve() != launch.parent: |
| 53 | raise ValueError(f"fixture launcher parent is a symlink: /{launcher}") |
| 54 | launch.parent.mkdir(parents=True, exist_ok=True) |
| 55 | if args.desktop_init: |
| 56 | launch.write_text(f"#!/bin/sh\n{command}\n") |
| 57 | launch.chmod(0o755) |
| 58 | else: |
| 59 | launch.write_text(f"::sysinit:/bin/sh -c '{command}'\n") |
| 60 | # Account for the staged files and the files the guest will install. |
| 61 | trees = [root, args.space_for] if args.space_for else [root] |
| 62 | usage = sum(int(subprocess.check_output(["du", "-sB1", tree], text=True).split()[0]) for tree in trees) |
| 63 | entries = sum(1 + sum(len(dirs) + len(files) for _, dirs, files in os.walk(tree)) for tree in trees) |
| 64 | mib = 1024**2 |
| 65 | size = (usage * 5 // 4 + 64 * mib + mib - 1) // mib * mib |
| 66 | with disk.open("xb") as output: |
| 67 | output.truncate(size) |
| 68 | mkfs = shutil.which("mke2fs") or "/usr/sbin/mke2fs" |
| 69 | # fakeroot covers both the ownership changes and mke2fs's input reads. |
| 70 | subprocess.run(["fakeroot", "--", "sh", "-ec", 'chown -Rh 0:0 "$1"; shift; exec "$@"', "disk-root", |
| 71 | root, mkfs, "-q", "-F", "-t", "ext2", "-b", "4096", "-I", "128", "-N", |
| 72 | str(max(4096, entries * 2)), "-O", |
| 73 | "filetype,sparse_super,^has_journal,^resize_inode,^dir_index,^extent,^64bit,^metadata_csum", |
| 74 | "-d", root, disk], check=True, stdout=log, stderr=subprocess.STDOUT) |
| 75 | fsck = shutil.which("e2fsck") or "/usr/sbin/e2fsck" |
| 76 | subprocess.run([fsck, "-fn", disk], check=True, stdout=log, stderr=subprocess.STDOUT) |
| 77 | debug = shutil.which("debugfs") or "/usr/sbin/debugfs" |
| 78 | actual = subprocess.check_output([debug, "-R", "cat /.vinix-image-id", disk], text=True, stderr=log) |
| 79 | if actual != identity: |
| 80 | raise ValueError("ext2 disk identity differs from the boot seed") |
| 81 | stat = subprocess.check_output([debug, "-R", "stat /bin/busybox", disk], text=True, stderr=log) |
| 82 | fields = next(line.split() for line in stat.splitlines() if line.startswith("User:")) |
| 83 | if int(fields[1]) or int(fields[3]): |
| 84 | raise ValueError("packaged BusyBox on ext2 must be owned by root") |
| 85 | return seed, disk |
| 86 | |
| 87 | |
| 88 | def run(args): |
| 89 | work = args.work |
| 90 | seed, disk = prepare(args) |
| 91 | mode = "--aarch64-disk-fixture" if args.arch == "aarch64" else "--disk-fixture" |
| 92 | with (work / "boot.log").open("x") as log: |
| 93 | subprocess.run([args.boot, seed, args.iso, work / "guest", mode, args.fixture, disk], |
| 94 | check=True, stdout=log, stderr=subprocess.STDOUT) |
| 95 | with (work / "receipts.sha256").open("x") as receipt: |
| 96 | for item in (work / "format.log", work / "boot.log", work / "guest/serial.log", disk, args.fixture): |
| 97 | receipt.write(f"{digest(item)} {item}\n") |
| 98 | |
| 99 | |
| 100 | if __name__ == "__main__": |
| 101 | parser = argparse.ArgumentParser(description=__doc__) |
| 102 | parser.add_argument("arch", choices=("x86_64", "aarch64")) |
| 103 | parser.add_argument("--desktop-init", action="store_true", |
| 104 | help="launch the fixture through the native desktop PID 1 hook") |
| 105 | parser.add_argument("--space-for", type=lambda path: Path(path).resolve(), |
| 106 | help="reserve bytes and inodes for a separate installed package tree") |
| 107 | parser.add_argument("--link-inputs", action="store_true", |
| 108 | help="stage immutable input files with hard links on the same build volume") |
| 109 | for arg in ("root", "fixture", "iso", "boot", "work"): |
| 110 | parser.add_argument(arg, type=lambda path: Path(path).resolve()) |
| 111 | run(parser.parse_args()) |
| 112 | |