vinix-ports / tools / build-queue.py
179 lines · 161 sloc · 8.49 KB
Raw
1"""Build selected native Vile ports in dependency order against clean signed SDKs."""
2import argparse
3import csv
4import fcntl
5import hashlib
6import os
7from pathlib import Path
8import shutil
9import subprocess
10import sys
11import tempfile
12
13
14SCRATCH_MARKER = ".vinix-build-queue"
15
16
17def digest(path):
18 with path.open("rb") as stream:
19 return hashlib.file_digest(stream, "sha256").hexdigest()
20
21
22def read_graph(path):
23 with path.open() as stream:
24 return {row["package"]: row for row in csv.DictReader(stream, delimiter="\t")}
25
26
27def record_limits(output):
28 membership = Path("/proc/self/cgroup")
29 if not membership.is_file():
30 return
31 for line in membership.read_text().splitlines():
32 if not line.startswith("0::"):
33 continue
34 group = Path("/sys/fs/cgroup") / line[3:].lstrip("/")
35 with output.open("w") as stream:
36 for field in ("cpu.max", "memory.max", "memory.peak", "memory.events"):
37 if (group / field).is_file():
38 stream.write(f"{field}\n{(group / field).read_text()}")
39
40
41def prerequisites(name, graph):
42 required = set()
43 todo = [name]
44 while todo:
45 item = todo.pop()
46 if graph[item]["stage"] == "pending":
47 raise ValueError(f"unresolved recipe {item}, see edges.tsv")
48 for dep in filter(None, graph[item]["depends_on"].split(",")):
49 if dep not in required:
50 required.add(dep)
51 todo.append(dep)
52 if name in required:
53 raise ValueError(f"dependency cycle at {name}")
54 return sorted(required)
55
56
57def archive_from_receipt(artifacts, name, version, arch):
58 checksum, filename = (artifacts / (name + ".sha256")).read_text().split()
59 if filename not in (f"{name}-{version}-{arch}.pkg.tar.zst", f"{name}-{version}-any.pkg.tar.zst"):
60 raise ValueError(f"{name}: receipt does not match source version {version}")
61 return artifacts / filename, checksum
62
63
64def build(args, name, version, receipts, logs, artifacts):
65 # Each package gets its own SDK and source directory. Keep the small
66 # evidence files and signed input hashes after recycling the scratch space.
67 scripts = Path(__file__).resolve().parents[1] / "tests"
68 with tempfile.TemporaryDirectory(prefix=name + "-", dir=args.work / "scratch") as tmp:
69 area = Path(tmp)
70 (area / SCRATCH_MARKER).touch()
71 sdk = area / "sdk"
72 recipe = area / "port"
73 shutil.copytree(args.recipes / name, recipe)
74 with (logs / (name + "-recipe.sha256")).open("w") as source:
75 for file in sorted(recipe.rglob("*")):
76 if file.is_file():
77 source.write(f"{digest(file)} {file.relative_to(recipe)}\n")
78 manifest = area / "manifest"
79 env = dict(os.environ, VPAC_TARGET_ARCH=args.arch, VPAC_MAKEPKG_ROOT=str(sdk / "client/root"),
80 VPAC_MAKEPKG_DB=str(sdk / "client/db"), VINIX_SYSROOT=str(sdk / "client/root"))
81 env["PKG_CONFIG_SYSROOT_DIR"] = env["VINIX_SYSROOT"]
82 env["PKG_CONFIG_LIBDIR"] = ":".join(env["VINIX_SYSROOT"] + d for d in ("/usr/lib/pkgconfig", "/usr/share/pkgconfig"))
83 with (logs / (name + "-build.log")).open("w") as log:
84 def run(cmd, **kwargs):
85 subprocess.run(cmd, stdout=log, stderr=subprocess.STDOUT, check=True, **kwargs)
86 try:
87 run([sys.executable, scripts / "combined-feed.py", args.arch, args.keys, args.auditor, sdk, *receipts])
88 finally:
89 for filename in ("selection.tsv", "audit.log", "install.log", "publish.log"):
90 if (sdk / filename).is_file():
91 shutil.copyfile(sdk / filename, logs / (name + "-sdk-" + filename))
92 command = [args.vpac, "--native-build", recipe / "PKGBUILD.vile", manifest]
93 if args.arch != os.uname().machine:
94 command.append("--target=" + args.arch)
95 run(["flock", args.lock, *command], env=env)
96 archive, = [Path(p) for p in manifest.read_text().splitlines() if p]
97 metadata = subprocess.check_output(["bsdtar", "-xOf", archive, ".PKGINFO"], text=True)
98 fields = dict(line.split(" = ", 1) for line in metadata.splitlines() if " = " in line)
99 arch = fields["arch"]
100 if (arch not in (args.arch, "any") or fields["pkgname"] != name or fields["pkgver"] != version
101 or archive.name != f"{name}-{version}-{arch}.pkg.tar.zst"):
102 raise ValueError(f"{name}: archive does not match the source plan")
103 with (logs / (name + "-pages.tsv")).open("w") as report:
104 subprocess.run([sys.executable, scripts / "archive-pages.py", args.arch, archive],
105 check=True, stdout=report, stderr=log)
106 output = artifacts / archive.name
107 checksum = digest(archive)
108 if output.exists() and digest(output) != checksum:
109 raise ValueError(f"{name}: conflicting archive for version {version}")
110 if not output.exists():
111 os.replace(archive, output)
112 receipt = artifacts / (name + ".sha256")
113 receipt.with_suffix(".new").write_text(f"{checksum} {output.name}\n")
114 receipt.with_suffix(".new").replace(receipt)
115
116
117def run_queue(args):
118 graph = read_graph(args.order)
119 artifacts, logs = args.work / "artifacts", args.work / "logs"
120 for directory in (artifacts, logs, args.work / "scratch"):
121 directory.mkdir(exist_ok=True, parents=True)
122 # The workspace lock excludes another active queue. A killed build can
123 # leave its private SDK behind; retain unrelated directories in scratch.
124 for old in (args.work / "scratch").iterdir():
125 if not old.is_symlink() and old.is_dir() and (old / SCRATCH_MARKER).is_file():
126 shutil.rmtree(old)
127 pending = list(dict.fromkeys(args.packages))
128 dependencies = {name: prerequisites(name, graph) for name in pending}
129 failed = []
130 while pending:
131 progress = False
132 for name in pending.copy():
133 receipt = artifacts / (name + ".sha256")
134 if receipt.exists():
135 archive, expected = archive_from_receipt(artifacts, name, graph[name]["version"], args.arch)
136 if digest(archive) != expected:
137 raise ValueError(f"{name}: archive checksum mismatch")
138 else:
139 receipts = [artifacts / (dep + ".sha256") for dep in dependencies[name]]
140 if not all(path.exists() for path in receipts):
141 continue
142 if not receipts:
143 raise ValueError(f"{name}: requires a bootstrap SDK")
144 for dep in dependencies[name]:
145 # combined-feed verifies the bytes before installing the SDK.
146 archive_from_receipt(artifacts, dep, graph[dep]["version"], args.arch)
147 if shutil.disk_usage(args.work).free < args.reserve_mib * 1024**2:
148 raise RuntimeError("build volume reached its configured free-space reserve")
149 print(f"Building {name} {graph[name]['version']}", flush=True)
150 record_limits(logs / (name + "-cgroup-before"))
151 try:
152 build(args, name, graph[name]["version"], receipts, logs, artifacts)
153 except (subprocess.CalledProcessError, ValueError, OSError) as error:
154 failed.append(name)
155 print(f"Failed {name}: {error}. See {logs / (name + '-build.log')}", file=sys.stderr, flush=True)
156 finally:
157 record_limits(logs / (name + "-cgroup-after"))
158 pending.remove(name)
159 progress = True
160 if not progress:
161 break
162 for name in pending:
163 missing = [dep for dep in dependencies[name] if not (artifacts / (dep + ".sha256")).exists()]
164 print(f"{name} awaits {', '.join(missing)}", flush=True)
165 return 1 if failed else 2 if pending else 0
166
167
168if __name__ == "__main__":
169 parser = argparse.ArgumentParser(description=__doc__)
170 parser.add_argument("arch", choices=("aarch64", "x86_64"))
171 for name in ("order", "recipes", "work", "keys", "auditor", "vpac", "lock"):
172 parser.add_argument(name, type=lambda p: Path(p).resolve())
173 parser.add_argument("--reserve-mib", type=int, default=0)
174 parser.add_argument("packages", nargs="+")
175 args = parser.parse_args()
176 args.work.mkdir(exist_ok=True, parents=True)
177 with (args.work / "queue.lock").open("a") as lock:
178 fcntl.flock(lock, fcntl.LOCK_EX)
179 sys.exit(run_queue(args))
180