| 1 | """Build selected native Vile ports in dependency order against clean signed SDKs.""" |
| 2 | import argparse |
| 3 | import csv |
| 4 | import errno |
| 5 | import fcntl |
| 6 | import hashlib |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import shutil |
| 10 | import subprocess |
| 11 | import sys |
| 12 | import tempfile |
| 13 | |
| 14 | |
| 15 | SCRATCH_MARKER = ".vinix-build-queue" |
| 16 | |
| 17 | |
| 18 | def digest(path): |
| 19 | with path.open("rb") as stream: |
| 20 | return hashlib.file_digest(stream, "sha256").hexdigest() |
| 21 | |
| 22 | |
| 23 | def read_graph(path): |
| 24 | with path.open() as stream: |
| 25 | return {row["package"]: row for row in csv.DictReader(stream, delimiter="\t")} |
| 26 | |
| 27 | |
| 28 | def record_limits(output): |
| 29 | membership = Path("/proc/self/cgroup") |
| 30 | if not membership.is_file(): |
| 31 | return |
| 32 | for line in membership.read_text().splitlines(): |
| 33 | if not line.startswith("0::"): |
| 34 | continue |
| 35 | group = Path("/sys/fs/cgroup") / line[3:].lstrip("/") |
| 36 | with output.open("w") as stream: |
| 37 | for field in ("cpu.max", "memory.max", "memory.peak", "memory.events"): |
| 38 | if (group / field).is_file(): |
| 39 | stream.write(f"{field}\n{(group / field).read_text()}") |
| 40 | |
| 41 | |
| 42 | def prerequisites(name, graph): |
| 43 | required = set() |
| 44 | todo = [name] |
| 45 | while todo: |
| 46 | item = todo.pop() |
| 47 | if graph[item]["stage"] == "pending": |
| 48 | raise ValueError(f"unresolved recipe {item}, see edges.tsv") |
| 49 | for dep in filter(None, graph[item]["depends_on"].split(",")): |
| 50 | if dep not in required: |
| 51 | required.add(dep) |
| 52 | todo.append(dep) |
| 53 | if name in required: |
| 54 | raise ValueError(f"dependency cycle at {name}") |
| 55 | return sorted(required) |
| 56 | |
| 57 | |
| 58 | def archive_from_receipt(artifacts, name, version, arch): |
| 59 | checksum, filename = (artifacts / (name + ".sha256")).read_text().split() |
| 60 | if filename not in (f"{name}-{version}-{arch}.pkg.tar.zst", f"{name}-{version}-any.pkg.tar.zst"): |
| 61 | raise ValueError(f"{name}: receipt does not match source version {version}") |
| 62 | return artifacts / filename, checksum |
| 63 | |
| 64 | |
| 65 | def archive_fields(archive, member): |
| 66 | metadata = subprocess.check_output(["bsdtar", "-xOf", archive, member], text=True) |
| 67 | return dict(line.split(" = ", 1) for line in metadata.splitlines() if " = " in line) |
| 68 | |
| 69 | |
| 70 | def check_archive(archive, name, version, arch): |
| 71 | fields = archive_fields(archive, ".PKGINFO") |
| 72 | machine = fields["arch"] |
| 73 | if (machine not in (arch, "any") or fields["pkgname"] != name or fields["pkgver"] != version |
| 74 | or archive.name != f"{name}-{version}-{machine}.pkg.tar.zst"): |
| 75 | raise ValueError(f"{name}: archive does not match the source plan") |
| 76 | |
| 77 | |
| 78 | def record_archive(artifacts, name, filename, checksum): |
| 79 | receipt = artifacts / (name + ".sha256") |
| 80 | receipt.with_suffix(".new").write_text(f"{checksum} {filename}\n") |
| 81 | receipt.with_suffix(".new").replace(receipt) |
| 82 | |
| 83 | |
| 84 | def reuse_archive(args, artifacts, logs, name, version, recipe_name): |
| 85 | recipe = args.recipes / recipe_name / "PKGBUILD.vile" |
| 86 | if not recipe.is_file(): |
| 87 | return |
| 88 | filename = f"{name}-{version}" |
| 89 | inputs = set() |
| 90 | for pool in args.reuse: |
| 91 | receipt = pool / (name + ".sha256") |
| 92 | if not receipt.is_file(): |
| 93 | continue |
| 94 | checksum, candidate = receipt.read_text().split() |
| 95 | if candidate in (f"{filename}-{args.arch}.pkg.tar.zst", f"{filename}-any.pkg.tar.zst"): |
| 96 | inputs.add((checksum, pool / candidate)) |
| 97 | if not inputs: |
| 98 | return |
| 99 | if len({checksum for checksum, _ in inputs}) != 1: |
| 100 | raise ValueError(f"{name}: distinct reuse archives for version {version}") |
| 101 | expected_recipe = digest(recipe) |
| 102 | for checksum, archive in sorted(inputs): |
| 103 | if digest(archive) != checksum: |
| 104 | raise ValueError(f"{name}: reusable archive checksum mismatch: {archive}") |
| 105 | check_archive(archive, name, version, args.arch) |
| 106 | if archive_fields(archive, ".BUILDINFO").get("pkgbuild_sha256sum") != expected_recipe: |
| 107 | raise ValueError(f"{name}: reusable archive uses different recipe bytes at version {version}") |
| 108 | checksum, archive = min(inputs) |
| 109 | output = artifacts / archive.name |
| 110 | if not output.exists(): |
| 111 | try: |
| 112 | os.link(archive, output) |
| 113 | except OSError as error: |
| 114 | if error.errno != errno.EXDEV: |
| 115 | raise |
| 116 | with tempfile.NamedTemporaryFile(dir=artifacts) as staged: |
| 117 | shutil.copyfile(archive, staged.name) |
| 118 | if digest(Path(staged.name)) != checksum: |
| 119 | raise ValueError(f"{name}: reusable archive changed during copy") |
| 120 | os.link(staged.name, output) |
| 121 | if digest(output) != checksum: |
| 122 | raise ValueError(f"{name}: conflicting archive for version {version}") |
| 123 | with (logs / (name + "-pages.tsv")).open("w") as report: |
| 124 | subprocess.run([sys.executable, Path(__file__).resolve().parents[1] / "tests/archive-pages.py", |
| 125 | args.arch, output], stdout=report, check=True) |
| 126 | record_archive(artifacts, name, archive.name, checksum) |
| 127 | print(f"Reused {name} {version} from {archive.parent}", flush=True) |
| 128 | |
| 129 | |
| 130 | def build(args, recipe_name, outputs, receipts, logs, artifacts): |
| 131 | # Each package gets its own SDK and source directory. Keep the small |
| 132 | # evidence files and signed input hashes after recycling the scratch space. |
| 133 | scripts = Path(__file__).resolve().parents[1] / "tests" |
| 134 | with tempfile.TemporaryDirectory(prefix=recipe_name + "-", dir=args.work / "scratch") as tmp: |
| 135 | area = Path(tmp) |
| 136 | (area / SCRATCH_MARKER).touch() |
| 137 | sdk = area / "sdk" |
| 138 | recipe = area / "port" |
| 139 | shutil.copytree(args.recipes / recipe_name, recipe) |
| 140 | with (logs / (recipe_name + "-recipe.sha256")).open("w") as source: |
| 141 | for file in sorted(recipe.rglob("*")): |
| 142 | if file.is_file(): |
| 143 | source.write(f"{digest(file)} {file.relative_to(recipe)}\n") |
| 144 | manifest = area / "manifest" |
| 145 | env = dict(os.environ, VPAC_TARGET_ARCH=args.arch, VPAC_MAKEPKG_ROOT=str(sdk / "client/root"), |
| 146 | VPAC_MAKEPKG_DB=str(sdk / "client/db"), VINIX_SYSROOT=str(sdk / "client/root")) |
| 147 | env["PKG_CONFIG_SYSROOT_DIR"] = env["VINIX_SYSROOT"] |
| 148 | env["PKG_CONFIG_LIBDIR"] = ":".join(env["VINIX_SYSROOT"] + d for d in ("/usr/lib/pkgconfig", "/usr/share/pkgconfig")) |
| 149 | with (logs / (recipe_name + "-build.log")).open("w") as log: |
| 150 | def run(cmd, **kwargs): |
| 151 | subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, check=True, **kwargs) |
| 152 | try: |
| 153 | feed = [sys.executable, scripts / "combined-feed.py", args.arch, args.keys, args.auditor, sdk, *receipts] |
| 154 | if args.arch != os.uname().machine: |
| 155 | feed.append("--cross-sdk") |
| 156 | run(feed) |
| 157 | finally: |
| 158 | for filename in ("selection.tsv", "audit.log", "install.log", "publish.log"): |
| 159 | if (sdk / filename).is_file(): |
| 160 | shutil.copyfile(sdk / filename, logs / (recipe_name + "-sdk-" + filename)) |
| 161 | command = [args.vpac, "--native-build", recipe / "PKGBUILD.vile", manifest] |
| 162 | if args.arch != os.uname().machine: |
| 163 | command.append("--target=" + args.arch) |
| 164 | run(["flock", args.lock, *command], env=env) |
| 165 | archives = {} |
| 166 | for path in manifest.read_text().splitlines(): |
| 167 | archive = Path(path) |
| 168 | name = archive_fields(archive, ".PKGINFO")["pkgname"] |
| 169 | if name not in outputs or name in archives: |
| 170 | raise ValueError(f"{recipe_name}: unexpected build output {name}") |
| 171 | version = outputs[name] |
| 172 | check_archive(archive, name, version, args.arch) |
| 173 | with (logs / (name + "-pages.tsv")).open("w") as report: |
| 174 | subprocess.run([sys.executable, scripts / "archive-pages.py", args.arch, archive], |
| 175 | check=True, stdout=report, stderr=log) |
| 176 | checksum = digest(archive) |
| 177 | output = artifacts / archive.name |
| 178 | if output.exists() and digest(output) != checksum: |
| 179 | raise ValueError(f"{name}: conflicting archive for version {version}") |
| 180 | archives[name] = (archive, output, checksum) |
| 181 | if archives.keys() != outputs.keys(): |
| 182 | raise ValueError(f"{recipe_name}: missing build outputs {sorted(outputs.keys() - archives.keys())}") |
| 183 | for archive, output, _ in archives.values(): |
| 184 | if not output.exists(): |
| 185 | os.replace(archive, output) |
| 186 | for name, (_, output, checksum) in archives.items(): |
| 187 | record_archive(artifacts, name, output.name, checksum) |
| 188 | |
| 189 | |
| 190 | def run_queue(args): |
| 191 | graph = read_graph(args.order) |
| 192 | artifacts, logs = args.work / "artifacts", args.work / "logs" |
| 193 | for directory in (artifacts, logs, args.work / "scratch"): |
| 194 | directory.mkdir(exist_ok=True, parents=True) |
| 195 | # The workspace lock excludes another active queue. A killed build can |
| 196 | # leave its private SDK behind; retain unrelated directories in scratch. |
| 197 | for old in (args.work / "scratch").iterdir(): |
| 198 | if not old.is_symlink() and old.is_dir() and (old / SCRATCH_MARKER).is_file(): |
| 199 | shutil.rmtree(old) |
| 200 | pending = list(dict.fromkeys(args.packages)) |
| 201 | dependencies = {name: prerequisites(name, graph) for name in pending} |
| 202 | recipes = {} |
| 203 | recipe_names = {} |
| 204 | for name, row in graph.items(): |
| 205 | recipe = row.get("source_recipe") or name |
| 206 | if Path(recipe).name != recipe or recipe in ("", ".", ".."): |
| 207 | raise ValueError(f"{name}: invalid source recipe directory {recipe!r}") |
| 208 | recipe_names[name] = recipe |
| 209 | recipes.setdefault(recipe, {})[name] = row["version"] |
| 210 | reusable = set(pending) |
| 211 | for deps in dependencies.values(): |
| 212 | reusable.update(deps) |
| 213 | for name in sorted(reusable): |
| 214 | if args.reuse and not (artifacts / (name + ".sha256")).exists(): |
| 215 | reuse_archive(args, artifacts, logs, name, graph[name]["version"], recipe_names[name]) |
| 216 | failed = set() |
| 217 | while pending: |
| 218 | progress = False |
| 219 | for name in pending.copy(): |
| 220 | if name in failed: |
| 221 | pending.remove(name) |
| 222 | continue |
| 223 | receipt = artifacts / (name + ".sha256") |
| 224 | if receipt.exists(): |
| 225 | archive, expected = archive_from_receipt(artifacts, name, graph[name]["version"], args.arch) |
| 226 | if digest(archive) != expected: |
| 227 | raise ValueError(f"{name}: archive checksum mismatch") |
| 228 | else: |
| 229 | receipts = [artifacts / (dep + ".sha256") for dep in dependencies[name]] |
| 230 | if not all(path.exists() for path in receipts): |
| 231 | continue |
| 232 | if not receipts: |
| 233 | raise ValueError(f"{name}: requires a bootstrap SDK") |
| 234 | for dep in dependencies[name]: |
| 235 | # combined-feed verifies the bytes before installing the SDK. |
| 236 | archive_from_receipt(artifacts, dep, graph[dep]["version"], args.arch) |
| 237 | if shutil.disk_usage(args.work).free < args.reserve_mib * 1024**2: |
| 238 | raise RuntimeError("build volume reached its configured free-space reserve") |
| 239 | recipe = recipe_names[name] |
| 240 | print(f"Building {recipe} {graph[name]['version']}", flush=True) |
| 241 | record_limits(logs / (recipe + "-cgroup-before")) |
| 242 | try: |
| 243 | build(args, recipe, recipes[recipe], receipts, logs, artifacts) |
| 244 | except (subprocess.CalledProcessError, ValueError, OSError) as error: |
| 245 | failed.update(recipes[recipe]) |
| 246 | print(f"Failed {recipe}: {error}. See {logs / (recipe + '-build.log')}", file=sys.stderr, flush=True) |
| 247 | finally: |
| 248 | record_limits(logs / (recipe + "-cgroup-after")) |
| 249 | pending.remove(name) |
| 250 | progress = True |
| 251 | if not progress: |
| 252 | break |
| 253 | for name in pending: |
| 254 | missing = [dep for dep in dependencies[name] if not (artifacts / (dep + ".sha256")).exists()] |
| 255 | print(f"{name} awaits {', '.join(missing)}", flush=True) |
| 256 | return 1 if failed else 2 if pending else 0 |
| 257 | |
| 258 | |
| 259 | if __name__ == "__main__": |
| 260 | parser = argparse.ArgumentParser(description=__doc__) |
| 261 | parser.add_argument("arch", choices=("aarch64", "x86_64")) |
| 262 | for name in ("order", "recipes", "work", "keys", "auditor", "vpac", "lock"): |
| 263 | help_text = "recipe directory such as ports/, or the exact snapshot used for the plan" if name == "recipes" else None |
| 264 | parser.add_argument(name, type=lambda p: Path(p).resolve(), help=help_text) |
| 265 | parser.add_argument("--reserve-mib", type=int, default=0) |
| 266 | parser.add_argument("--reuse", action="append", type=lambda p: Path(p).resolve(), default=[], |
| 267 | metavar="ARTIFACT_DIR", help="reuse exact verified build receipts from another queue") |
| 268 | parser.add_argument("packages", nargs="+") |
| 269 | args = parser.parse_args() |
| 270 | args.work.mkdir(exist_ok=True, parents=True) |
| 271 | with (args.work / "queue.lock").open("a") as lock: |
| 272 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 273 | sys.exit(run_queue(args)) |
| 274 | |