"""Build selected native Vile ports in dependency order against clean signed SDKs.""" import argparse import csv import errno 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 archive_fields(archive, member): metadata = subprocess.check_output(["bsdtar", "-xOf", archive, member], text=True) return dict(line.split(" = ", 1) for line in metadata.splitlines() if " = " in line) def check_archive(archive, name, version, arch): fields = archive_fields(archive, ".PKGINFO") machine = fields["arch"] if (machine not in (arch, "any") or fields["pkgname"] != name or fields["pkgver"] != version or archive.name != f"{name}-{version}-{machine}.pkg.tar.zst"): raise ValueError(f"{name}: archive does not match the source plan") def record_archive(artifacts, name, filename, checksum): receipt = artifacts / (name + ".sha256") receipt.with_suffix(".new").write_text(f"{checksum} {filename}\n") receipt.with_suffix(".new").replace(receipt) def reuse_archive(args, artifacts, logs, name, version, recipe_name): recipe = args.recipes / recipe_name / "PKGBUILD.vile" if not recipe.is_file(): return filename = f"{name}-{version}" inputs = set() for pool in args.reuse: receipt = pool / (name + ".sha256") if not receipt.is_file(): continue checksum, candidate = receipt.read_text().split() if candidate in (f"{filename}-{args.arch}.pkg.tar.zst", f"{filename}-any.pkg.tar.zst"): inputs.add((checksum, pool / candidate)) if not inputs: return if len({checksum for checksum, _ in inputs}) != 1: raise ValueError(f"{name}: distinct reuse archives for version {version}") expected_recipe = digest(recipe) for checksum, archive in sorted(inputs): if digest(archive) != checksum: raise ValueError(f"{name}: reusable archive checksum mismatch: {archive}") check_archive(archive, name, version, args.arch) if archive_fields(archive, ".BUILDINFO").get("pkgbuild_sha256sum") != expected_recipe: raise ValueError(f"{name}: reusable archive uses different recipe bytes at version {version}") checksum, archive = min(inputs) output = artifacts / archive.name if not output.exists(): try: os.link(archive, output) except OSError as error: if error.errno != errno.EXDEV: raise with tempfile.NamedTemporaryFile(dir=artifacts) as staged: shutil.copyfile(archive, staged.name) if digest(Path(staged.name)) != checksum: raise ValueError(f"{name}: reusable archive changed during copy") os.link(staged.name, output) if digest(output) != checksum: raise ValueError(f"{name}: conflicting archive for version {version}") with (logs / (name + "-pages.tsv")).open("w") as report: subprocess.run([sys.executable, Path(__file__).resolve().parents[1] / "tests/archive-pages.py", args.arch, output], stdout=report, check=True) record_archive(artifacts, name, archive.name, checksum) print(f"Reused {name} {version} from {archive.parent}", flush=True) def build(args, recipe_name, outputs, 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=recipe_name + "-", dir=args.work / "scratch") as tmp: area = Path(tmp) (area / SCRATCH_MARKER).touch() sdk = area / "sdk" recipe = area / "port" shutil.copytree(args.recipes / recipe_name, recipe) with (logs / (recipe_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 / (recipe_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 / (recipe_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) archives = {} for path in manifest.read_text().splitlines(): archive = Path(path) name = archive_fields(archive, ".PKGINFO")["pkgname"] if name not in outputs or name in archives: raise ValueError(f"{recipe_name}: unexpected build output {name}") version = outputs[name] check_archive(archive, name, version, args.arch) 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) checksum = digest(archive) output = artifacts / archive.name if output.exists() and digest(output) != checksum: raise ValueError(f"{name}: conflicting archive for version {version}") archives[name] = (archive, output, checksum) if archives.keys() != outputs.keys(): raise ValueError(f"{recipe_name}: missing build outputs {sorted(outputs.keys() - archives.keys())}") for archive, output, _ in archives.values(): if not output.exists(): os.replace(archive, output) for name, (_, output, checksum) in archives.items(): record_archive(artifacts, name, output.name, checksum) 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} recipes = {} recipe_names = {} for name, row in graph.items(): recipe = row.get("source_recipe") or name if Path(recipe).name != recipe or recipe in ("", ".", ".."): raise ValueError(f"{name}: invalid source recipe directory {recipe!r}") recipe_names[name] = recipe recipes.setdefault(recipe, {})[name] = row["version"] reusable = set(pending) for deps in dependencies.values(): reusable.update(deps) for name in sorted(reusable): if args.reuse and not (artifacts / (name + ".sha256")).exists(): reuse_archive(args, artifacts, logs, name, graph[name]["version"], recipe_names[name]) failed = set() while pending: progress = False for name in pending.copy(): if name in failed: pending.remove(name) continue 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") recipe = recipe_names[name] print(f"Building {recipe} {graph[name]['version']}", flush=True) record_limits(logs / (recipe + "-cgroup-before")) try: build(args, recipe, recipes[recipe], receipts, logs, artifacts) except (subprocess.CalledProcessError, ValueError, OSError) as error: failed.update(recipes[recipe]) print(f"Failed {recipe}: {error}. See {logs / (recipe + '-build.log')}", file=sys.stderr, flush=True) finally: record_limits(logs / (recipe + "-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("--reuse", action="append", type=lambda p: Path(p).resolve(), default=[], metavar="ARTIFACT_DIR", help="reuse exact verified build receipts from another queue") 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))