"""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))