vinix-ports / tools / build-queue.py
269 lines · 243 sloc · 12.68 KB · 06415977ce658ec19ca78b7154e45c34ecd61b51
Raw
1"""Build selected native Vile ports in dependency order against clean signed SDKs."""
2import argparse
3import csv
4import errno
5import fcntl
6import hashlib
7import os
8from pathlib import Path
9import shutil
10import subprocess
11import sys
12import tempfile
13
14
15SCRATCH_MARKER = ".vinix-build-queue"
16
17
18def digest(path):
19 with path.open("rb") as stream:
20 return hashlib.file_digest(stream, "sha256").hexdigest()
21
22
23def read_graph(path):
24 with path.open() as stream:
25 return {row["package"]: row for row in csv.DictReader(stream, delimiter="\t")}
26
27
28def 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
42def 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
58def 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
65def 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
70def 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
78def 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
84def 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
130def 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 run([sys.executable, scripts / "combined-feed.py", args.arch, args.keys, args.auditor, sdk, *receipts])
154 finally:
155 for filename in ("selection.tsv", "audit.log", "install.log", "publish.log"):
156 if (sdk / filename).is_file():
157 shutil.copyfile(sdk / filename, logs / (recipe_name + "-sdk-" + filename))
158 command = [args.vpac, "--native-build", recipe / "PKGBUILD.vile", manifest]
159 if args.arch != os.uname().machine:
160 command.append("--target=" + args.arch)
161 run(["flock", args.lock, *command], env=env)
162 archives = {}
163 for path in manifest.read_text().splitlines():
164 archive = Path(path)
165 name = archive_fields(archive, ".PKGINFO")["pkgname"]
166 if name not in outputs or name in archives:
167 raise ValueError(f"{recipe_name}: unexpected build output {name}")
168 version = outputs[name]
169 check_archive(archive, name, version, args.arch)
170 with (logs / (name + "-pages.tsv")).open("w") as report:
171 subprocess.run([sys.executable, scripts / "archive-pages.py", args.arch, archive],
172 check=True, stdout=report, stderr=log)
173 checksum = digest(archive)
174 output = artifacts / archive.name
175 if output.exists() and digest(output) != checksum:
176 raise ValueError(f"{name}: conflicting archive for version {version}")
177 archives[name] = (archive, output, checksum)
178 if archives.keys() != outputs.keys():
179 raise ValueError(f"{recipe_name}: missing build outputs {sorted(outputs.keys() - archives.keys())}")
180 for archive, output, _ in archives.values():
181 if not output.exists():
182 os.replace(archive, output)
183 for name, (_, output, checksum) in archives.items():
184 record_archive(artifacts, name, output.name, checksum)
185
186
187def run_queue(args):
188 graph = read_graph(args.order)
189 artifacts, logs = args.work / "artifacts", args.work / "logs"
190 for directory in (artifacts, logs, args.work / "scratch"):
191 directory.mkdir(exist_ok=True, parents=True)
192 # The workspace lock excludes another active queue. A killed build can
193 # leave its private SDK behind; retain unrelated directories in scratch.
194 for old in (args.work / "scratch").iterdir():
195 if not old.is_symlink() and old.is_dir() and (old / SCRATCH_MARKER).is_file():
196 shutil.rmtree(old)
197 pending = list(dict.fromkeys(args.packages))
198 dependencies = {name: prerequisites(name, graph) for name in pending}
199 recipes = {}
200 recipe_names = {}
201 for name, row in graph.items():
202 recipe = row.get("source_recipe") or name
203 if Path(recipe).name != recipe or recipe in ("", ".", ".."):
204 raise ValueError(f"{name}: invalid source recipe directory {recipe!r}")
205 recipe_names[name] = recipe
206 recipes.setdefault(recipe, {})[name] = row["version"]
207 reusable = set(pending)
208 for deps in dependencies.values():
209 reusable.update(deps)
210 for name in sorted(reusable):
211 if args.reuse and not (artifacts / (name + ".sha256")).exists():
212 reuse_archive(args, artifacts, logs, name, graph[name]["version"], recipe_names[name])
213 failed = set()
214 while pending:
215 progress = False
216 for name in pending.copy():
217 if name in failed:
218 pending.remove(name)
219 continue
220 receipt = artifacts / (name + ".sha256")
221 if receipt.exists():
222 archive, expected = archive_from_receipt(artifacts, name, graph[name]["version"], args.arch)
223 if digest(archive) != expected:
224 raise ValueError(f"{name}: archive checksum mismatch")
225 else:
226 receipts = [artifacts / (dep + ".sha256") for dep in dependencies[name]]
227 if not all(path.exists() for path in receipts):
228 continue
229 if not receipts:
230 raise ValueError(f"{name}: requires a bootstrap SDK")
231 for dep in dependencies[name]:
232 # combined-feed verifies the bytes before installing the SDK.
233 archive_from_receipt(artifacts, dep, graph[dep]["version"], args.arch)
234 if shutil.disk_usage(args.work).free < args.reserve_mib * 1024**2:
235 raise RuntimeError("build volume reached its configured free-space reserve")
236 recipe = recipe_names[name]
237 print(f"Building {recipe} {graph[name]['version']}", flush=True)
238 record_limits(logs / (recipe + "-cgroup-before"))
239 try:
240 build(args, recipe, recipes[recipe], receipts, logs, artifacts)
241 except (subprocess.CalledProcessError, ValueError, OSError) as error:
242 failed.update(recipes[recipe])
243 print(f"Failed {recipe}: {error}. See {logs / (recipe + '-build.log')}", file=sys.stderr, flush=True)
244 finally:
245 record_limits(logs / (recipe + "-cgroup-after"))
246 pending.remove(name)
247 progress = True
248 if not progress:
249 break
250 for name in pending:
251 missing = [dep for dep in dependencies[name] if not (artifacts / (dep + ".sha256")).exists()]
252 print(f"{name} awaits {', '.join(missing)}", flush=True)
253 return 1 if failed else 2 if pending else 0
254
255
256if __name__ == "__main__":
257 parser = argparse.ArgumentParser(description=__doc__)
258 parser.add_argument("arch", choices=("aarch64", "x86_64"))
259 for name in ("order", "recipes", "work", "keys", "auditor", "vpac", "lock"):
260 parser.add_argument(name, type=lambda p: Path(p).resolve())
261 parser.add_argument("--reserve-mib", type=int, default=0)
262 parser.add_argument("--reuse", action="append", type=lambda p: Path(p).resolve(), default=[],
263 metavar="ARTIFACT_DIR", help="reuse exact verified build receipts from another queue")
264 parser.add_argument("packages", nargs="+")
265 args = parser.parse_args()
266 args.work.mkdir(exist_ok=True, parents=True)
267 with (args.work / "queue.lock").open("a") as lock:
268 fcntl.flock(lock, fcntl.LOCK_EX)
269 sys.exit(run_queue(args))
270