From 38d14355d5dd45efed7f2545d123169b2ac3bc16 Mon Sep 17 00:00:00 2001 From: diviocity Date: Mon, 30 Nov 2026 03:49:38 +0100 Subject: [PATCH] Build native ports in dependency order against fresh signed SDKs --- BOOTSTRAP.md | 9 +++ tools/build-queue.py | 179 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 188 insertions(+) create mode 100644 tools/build-queue.py diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index 04e546a..dfde4ab 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -61,3 +61,12 @@ On the operator machine, `~/.local/state/vinix/ports/musl-busybox-CqkBEA/foundat The x86_64 SQLite 3.48.0-1 build used 724 MiB at peak under the 1 GiB limit. Its recipe creates an FTS5 database with the target shell and reads it through the target shared library. A fresh signed installation of SQLite, musl, readline, ncurses and zlib passed commit, rollback, search and integrity checks. All eight dynamic executables in that root relocated. The worker keeps the install and query logs in `foundation/signed-sqlite-02`, receipt SHA-256 `660aec4a9ed85889b15c79eab19439c8364cb7bc870f6809bdff26dd1732938e`. The installed x86_64 XBPS 0.59.2-1 tools created a package, indexed it, installed it into an empty directory and read its version from the local database. The fixture compared the installed bytes with the input. Its 13-package signed root contained 57 target ELFs. See `foundation/signed-xbps-01`, receipt SHA-256 `c54c52e01e076177f73be1830574c3c256d6af8627679d1b24353f145cf1f078`. + +For later builds, `tools/build-queue.py` uses the source order and a verified bootstrap feed. Place the input archives and a `NAME.sha256` receipt for each in `$work/artifacts`. Configure the host compiler and signing tools as for a single native build, then select the ports to build. The worker uses this command form. + +```sh +python3 tools/build-queue.py --reserve-mib 6144 "$arch" "$plan/order.tsv" "$ports" "$work" \ + "$test_keys" "$auditor" "$vpac_builder" "$compile_lock" zlib make openssl +``` + +Each port gets a fresh, signed SDK containing its transitive prerequisites. The queue records recipe and dependency hashes, compiler logs and ELF page results. A subsequent port consumes an archive after its final checksum is available. Exit status 2 reports outstanding input packages. Rerunning reuses verified outputs and reclaims interrupted scratch directories. The worker built musl-fts, resumed it, and rejected an incorrect input version and a damaged receipt in `foundation/queue-test-03`, receipt SHA-256 `1de747944bd569219494cd127fc1f42cf110f7b0ad2a4e513099249a2e0b3bb1`. Two concurrent resumptions passed in `foundation/queue-resume-04`, receipt SHA-256 `a58a80c0050294666d4ecd41ce5c2affc371c5fbeb58fc672e98a9b7c8c3b14b`. diff --git a/tools/build-queue.py b/tools/build-queue.py new file mode 100644 index 0000000..0ae83e6 --- /dev/null +++ b/tools/build-queue.py @@ -0,0 +1,179 @@ +"""Build selected native Vile ports in dependency order against clean signed SDKs.""" +import argparse +import csv +import fcntl +import hashlib +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile + + +SCRATCH_MARKER = ".vinix-build-queue" + + +def digest(path): + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def read_graph(path): + with path.open() as stream: + return {row["package"]: row for row in csv.DictReader(stream, delimiter="\t")} + + +def record_limits(output): + membership = Path("/proc/self/cgroup") + if not membership.is_file(): + return + for line in membership.read_text().splitlines(): + if not line.startswith("0::"): + continue + group = Path("/sys/fs/cgroup") / line[3:].lstrip("/") + with output.open("w") as stream: + for field in ("cpu.max", "memory.max", "memory.peak", "memory.events"): + if (group / field).is_file(): + stream.write(f"{field}\n{(group / field).read_text()}") + + +def prerequisites(name, graph): + required = set() + todo = [name] + while todo: + item = todo.pop() + if graph[item]["stage"] == "pending": + raise ValueError(f"unresolved recipe {item}, see edges.tsv") + for dep in filter(None, graph[item]["depends_on"].split(",")): + if dep not in required: + required.add(dep) + todo.append(dep) + if name in required: + raise ValueError(f"dependency cycle at {name}") + return sorted(required) + + +def archive_from_receipt(artifacts, name, version, arch): + checksum, filename = (artifacts / (name + ".sha256")).read_text().split() + if filename not in (f"{name}-{version}-{arch}.pkg.tar.zst", f"{name}-{version}-any.pkg.tar.zst"): + raise ValueError(f"{name}: receipt does not match source version {version}") + return artifacts / filename, checksum + + +def build(args, name, version, receipts, logs, artifacts): + # Each package gets its own SDK and source directory. Keep the small + # evidence files and signed input hashes after recycling the scratch space. + scripts = Path(__file__).resolve().parents[1] / "tests" + with tempfile.TemporaryDirectory(prefix=name + "-", dir=args.work / "scratch") as tmp: + area = Path(tmp) + (area / SCRATCH_MARKER).touch() + sdk = area / "sdk" + recipe = area / "port" + shutil.copytree(args.recipes / name, recipe) + with (logs / (name + "-recipe.sha256")).open("w") as source: + for file in sorted(recipe.rglob("*")): + if file.is_file(): + source.write(f"{digest(file)} {file.relative_to(recipe)}\n") + manifest = area / "manifest" + env = dict(os.environ, VPAC_TARGET_ARCH=args.arch, VPAC_MAKEPKG_ROOT=str(sdk / "client/root"), + VPAC_MAKEPKG_DB=str(sdk / "client/db"), VINIX_SYSROOT=str(sdk / "client/root")) + env["PKG_CONFIG_SYSROOT_DIR"] = env["VINIX_SYSROOT"] + env["PKG_CONFIG_LIBDIR"] = ":".join(env["VINIX_SYSROOT"] + d for d in ("/usr/lib/pkgconfig", "/usr/share/pkgconfig")) + with (logs / (name + "-build.log")).open("w") as log: + def run(cmd, **kwargs): + subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, check=True, **kwargs) + try: + run([sys.executable, scripts / "combined-feed.py", args.arch, args.keys, args.auditor, sdk, *receipts]) + finally: + for filename in ("selection.tsv", "audit.log", "install.log", "publish.log"): + if (sdk / filename).is_file(): + shutil.copyfile(sdk / filename, logs / (name + "-sdk-" + filename)) + command = [args.vpac, "--native-build", recipe / "PKGBUILD.vile", manifest] + if args.arch != os.uname().machine: + command.append("--target=" + args.arch) + run(["flock", args.lock, *command], env=env) + archive, = [Path(p) for p in manifest.read_text().splitlines() if p] + metadata = subprocess.check_output(["bsdtar", "-xOf", archive, ".PKGINFO"], text=True) + fields = dict(line.split(" = ", 1) for line in metadata.splitlines() if " = " in line) + arch = fields["arch"] + if (arch not in (args.arch, "any") or fields["pkgname"] != name or fields["pkgver"] != version + or archive.name != f"{name}-{version}-{arch}.pkg.tar.zst"): + raise ValueError(f"{name}: archive does not match the source plan") + with (logs / (name + "-pages.tsv")).open("w") as report: + subprocess.run([sys.executable, scripts / "archive-pages.py", args.arch, archive], + check=True, stdout=report, stderr=log) + output = artifacts / archive.name + checksum = digest(archive) + if output.exists() and digest(output) != checksum: + raise ValueError(f"{name}: conflicting archive for version {version}") + if not output.exists(): + os.replace(archive, output) + receipt = artifacts / (name + ".sha256") + receipt.with_suffix(".new").write_text(f"{checksum} {output.name}\n") + receipt.with_suffix(".new").replace(receipt) + + +def run_queue(args): + graph = read_graph(args.order) + artifacts, logs = args.work / "artifacts", args.work / "logs" + for directory in (artifacts, logs, args.work / "scratch"): + directory.mkdir(exist_ok=True, parents=True) + # The workspace lock excludes another active queue. A killed build can + # leave its private SDK behind; retain unrelated directories in scratch. + for old in (args.work / "scratch").iterdir(): + if not old.is_symlink() and old.is_dir() and (old / SCRATCH_MARKER).is_file(): + shutil.rmtree(old) + pending = list(dict.fromkeys(args.packages)) + dependencies = {name: prerequisites(name, graph) for name in pending} + failed = [] + while pending: + progress = False + for name in pending.copy(): + receipt = artifacts / (name + ".sha256") + if receipt.exists(): + archive, expected = archive_from_receipt(artifacts, name, graph[name]["version"], args.arch) + if digest(archive) != expected: + raise ValueError(f"{name}: archive checksum mismatch") + else: + receipts = [artifacts / (dep + ".sha256") for dep in dependencies[name]] + if not all(path.exists() for path in receipts): + continue + if not receipts: + raise ValueError(f"{name}: requires a bootstrap SDK") + for dep in dependencies[name]: + # combined-feed verifies the bytes before installing the SDK. + archive_from_receipt(artifacts, dep, graph[dep]["version"], args.arch) + if shutil.disk_usage(args.work).free < args.reserve_mib * 1024**2: + raise RuntimeError("build volume reached its configured free-space reserve") + print(f"Building {name} {graph[name]['version']}", flush=True) + record_limits(logs / (name + "-cgroup-before")) + try: + build(args, name, graph[name]["version"], receipts, logs, artifacts) + except (subprocess.CalledProcessError, ValueError, OSError) as error: + failed.append(name) + print(f"Failed {name}: {error}. See {logs / (name + '-build.log')}", file=sys.stderr, flush=True) + finally: + record_limits(logs / (name + "-cgroup-after")) + pending.remove(name) + progress = True + if not progress: + break + for name in pending: + missing = [dep for dep in dependencies[name] if not (artifacts / (dep + ".sha256")).exists()] + print(f"{name} awaits {', '.join(missing)}", flush=True) + return 1 if failed else 2 if pending else 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("arch", choices=("aarch64", "x86_64")) + for name in ("order", "recipes", "work", "keys", "auditor", "vpac", "lock"): + parser.add_argument(name, type=lambda p: Path(p).resolve()) + parser.add_argument("--reserve-mib", type=int, default=0) + parser.add_argument("packages", nargs="+") + args = parser.parse_args() + args.work.mkdir(exist_ok=True, parents=True) + with (args.work / "queue.lock").open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + sys.exit(run_queue(args)) -- 2.56.1