oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Run Equipo's CI in its box: one container that looks like a runner host.
3
4 scripts/ci-box.py prepare fetch the pinned tools and the image; on CI
5 also deepen the clone and set file times
6 scripts/ci-box.py run CMD... run CMD in the box, from the repository root
7 scripts/ci-box.py cache report the Go caches and trim them to fit
8 scripts/ci-box.py facts print what this machine is
9
10amadan's hosted CI gives each job a fresh arm64 machine with Docker and no
11bubblewrap. Equipo's tests start real containment: they need bubblewrap
120.11.0 exactly, the pinned Codex and Claude programs, user namespaces and
13a delegated cgroup. The box supplies those. It is the official Go image
14on Debian 13 (the runner host's own system), run privileged, with the
15pinned programs mounted where a runner host has them:
16
17 /usr/bin/bwrap Debian's 0.11.0-2+deb13u1 build
18 /usr/local/bin/codex codex 0.165.0
19 ~/.local/share/equipo/try/bin codex, its code mode host, claude
20 /usr/bin/socat Claude's own sandbox needs it
21 /opt/chromium-<version>/chrome the browser tests' Chromium
22 /opt/equipo-pi the pinned Pi and its Node
23 /opt/equipo-opencode the pinned OpenCode
24
25The Pi install is what a runner's is: Node from the official archive by
26its digest, and the npm tree `npm ci --ignore-scripts` makes from the
27committed lockfile, made read-only and checked against the committed
28tree digest (scripts/ci-box.json "pi", the same as the code's pins). The
29OpenCode install is a runner's too: the two npm packages the committed
30lockfile names (@opencode/cli and this machine's binary package), each
31checked against its integrity before it is unpacked, no script run, the
32tree sealed and checked against its digest and the binary against its own
33(scripts/ci-box.json "opencode", the code's pins).
34
35Every pinned program is fetched by URL and checked against the SHA-256 in
36scripts/ci-box.json, for this machine's architecture. Chromium is Debian's
37headless shell and the libraries it needs, some seventy packages pinned in
38scripts/ci-chromium.json (scripts/ci-chromium-pin.py writes it), unpacked
39into one tree; RASTRILLO_CHROME names its launcher, which is where the
40browser tests (harness.ChromePath) look first. The job's checkout
41and Go caches are mounted at fixed paths, so Go's build and test caches
42hold from one fresh machine to the next. Inside, the command runs as an
43ordinary user (scripts/ci-box-enter.sh), never as root.
44
45This file also runs on the CI machine itself, outside the box, where
46python3 is 3.9: keep it to that.
47"""
48import hashlib
49import io
50import json
51import lzma
52import os
53import platform
54import re
55import shutil
56import subprocess
57import sys
58import tarfile
59import tempfile
60import time
61import urllib.request
62from concurrent.futures import ThreadPoolExecutor
63
64ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
65PINS = os.path.join(ROOT, "scripts", "ci-box.json")
66CHROMIUM_PINS = os.path.join(ROOT, "scripts", "ci-chromium.json")
67COLD = os.path.join(ROOT, ".amadan", "cold")
68
69# Where things sit inside the box. Fixed, whatever the job's own paths
70# are: Go keys a compiled package on its source directory, so a checkout
71# that moved would recompile everything.
72WORK = "/work/equipo"
73GOCACHE = "/cache/go-build"
74GOMODCACHE = "/cache/go-mod"
75HOME = "/home/ci"
76TRY_BIN = HOME + "/.local/share/equipo/try/bin"
77
78# Fetched programs get this modification time (2026-01-01), and tracked
79# files get one made from their content: make test fingerprints programs
80# by size and time, and go test keys a cached result on the size and time
81# of each file the test opened. A fresh clone would stamp everything
82# "now" and no result would ever be reused.
83TOOL_TIME = 1767225600
84FILE_TIME_BASE = 1577836800 # 2020-01-01
85FILE_TIME_SPAN = 5 * 365 * 86400
86
87# The hosted cache holds 6 GiB unpacked and 2 GiB compressed, and a save
88# over either is dropped whole. Trim well under it.
89CACHE_LIMIT = 4 * 1024 ** 3
90
91# Environment a step may see inside the box, besides what run() sets.
92# Not GOPRIVATE or GOAUTH: the job's git credential stays outside the
93# box, and every module Equipo uses is on the public proxy.
94PASS_PREFIXES = ("AMADAN_", "EQUIPO_")
95PASS_NAMES = ("CI", "GOFLAGS", "GOPROXY", "TERM")
96
97
98def say(text):
99 print("ci-box: " + text, flush=True)
100
101
102def arch():
103 machine = platform.machine().lower()
104 name = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(machine)
105 if name is None:
106 sys.exit("ci-box: no pinned tools for a %s machine" % machine)
107 return name
108
109
110def pins():
111 with open(PINS) as f:
112 return json.load(f)
113
114
115def box_dir():
116 path = os.environ.get("EQUIPO_CI_BOX_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "equipo-ci-box")
117 os.makedirs(path, exist_ok=True)
118 return path
119
120
121def tools_dir():
122 return os.path.join(box_dir(), "tools", arch())
123
124
125def tool_path(name, tool):
126 """Where a fetched program is kept: the ones tests find in the try
127 directory together in bin, mounted as that directory; the rest in sys."""
128 return os.path.join(tools_dir(), "bin" if tool.get("try_bin") else "sys", name)
129
130
131def boxed():
132 """Whether commands go in the box. EQUIPO_CI_BOX=on or off decides;
133 unset, a machine that already has what the box supplies (the pinned
134 bubblewrap and a codex) is a runner host, and commands run directly."""
135 mode = os.environ.get("EQUIPO_CI_BOX", "")
136 if mode in ("on", "off"):
137 return mode == "on"
138 if mode:
139 sys.exit("ci-box: EQUIPO_CI_BOX is %r; use on or off" % mode)
140 try:
141 version = subprocess.check_output(["/usr/bin/bwrap", "--version"], stderr=subprocess.DEVNULL, text=True).strip()
142 except (OSError, subprocess.CalledProcessError):
143 version = ""
144 return version != pins()["tools"]["bwrap"]["version"] or shutil.which("codex") is None
145
146
147# Pinned tools.
148
149def sha256_file(path):
150 h = hashlib.sha256()
151 with open(path, "rb") as f:
152 for block in iter(lambda: f.read(1 << 20), b""):
153 h.update(block)
154 return h.hexdigest()
155
156
157def download(url, dest):
158 """Fetch url into dest and return its SHA-256; three attempts."""
159 last = None
160 for attempt in range(3):
161 try:
162 h = hashlib.sha256()
163 request = urllib.request.Request(url, headers={"User-Agent": "equipo-ci-box"})
164 with urllib.request.urlopen(request, timeout=120) as response, open(dest, "wb") as out:
165 for block in iter(lambda: response.read(1 << 20), b""):
166 h.update(block)
167 out.write(block)
168 return h.hexdigest()
169 except Exception as e: # a CDN's bad minute is not this change's failure
170 last = e
171 time.sleep(2 * (attempt + 1))
172 raise RuntimeError("fetch %s: %s" % (url, last))
173
174
175def deb_data(path):
176 """The data archive of a .deb: an ar file whose data.tar.* member holds the files."""
177 with open(path, "rb") as f:
178 if f.read(8) != b"!<arch>\n":
179 raise RuntimeError("not a .deb: " + path)
180 while True:
181 header = f.read(60)
182 if len(header) < 60:
183 raise RuntimeError("no data archive in " + path)
184 name = header[:16].decode().strip().rstrip("/")
185 size = int(header[48:58].decode().strip())
186 body = f.read(size + (size & 1))[:size]
187 if name.startswith("data.tar"):
188 if name.endswith(".xz"):
189 body = lzma.decompress(body)
190 elif name != "data.tar":
191 raise RuntimeError("unsupported .deb compression: " + name)
192 return body
193
194
195def extract(archive, fmt, member, dest):
196 if fmt == "raw":
197 shutil.copyfile(archive, dest)
198 return
199 if fmt == "deb":
200 tar = tarfile.open(fileobj=io.BytesIO(deb_data(archive)))
201 elif fmt == "tar.gz":
202 tar = tarfile.open(archive, "r:gz")
203 else:
204 raise RuntimeError("unknown archive format " + fmt)
205 with tar:
206 source = tar.extractfile(member)
207 if source is None:
208 raise RuntimeError("%s is not a file in the archive" % member)
209 with source, open(dest, "wb") as out:
210 shutil.copyfileobj(source, out)
211
212
213def fetch_tool(name, pin, target):
214 if os.path.isfile(target) and sha256_file(target) == pin["sha256"]:
215 return "%s: present" % name
216 started = time.time()
217 os.makedirs(os.path.dirname(target), exist_ok=True)
218 with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch:
219 archive = os.path.join(scratch, "archive")
220 got = download(pin["url"], archive)
221 want = pin.get("archive_sha256", pin["sha256"])
222 if got != want:
223 raise RuntimeError("%s: %s has SHA-256 %s, pinned %s" % (name, pin["url"], got, want))
224 out = os.path.join(scratch, name)
225 extract(archive, pin["format"], pin.get("member"), out)
226 if sha256_file(out) != pin["sha256"]:
227 raise RuntimeError("%s: the program in %s is not the pinned one" % (name, pin["url"]))
228 os.chmod(out, 0o755)
229 os.utime(out, (TOOL_TIME, TOOL_TIME))
230 os.replace(out, target)
231 return "%s: fetched and verified in %.1fs" % (name, time.time() - started)
232
233
234def fetch_tools():
235 os.makedirs(os.path.join(tools_dir(), "bin"), exist_ok=True)
236 machine = arch()
237 jobs = []
238 for name, tool in sorted(pins()["tools"].items()):
239 if machine not in tool:
240 sys.exit("ci-box: %s has no pin for %s" % (name, machine))
241 jobs.append((name, tool[machine], tool_path(name, tool)))
242 with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
243 for line in pool.map(lambda job: fetch_tool(*job), jobs):
244 say(line)
245 return tools_dir()
246
247
248# Pi: Node and an npm tree, not one program.
249
250def pi_root():
251 return os.path.join(tools_dir(), "pi-" + pins()["pi"]["tree_sha256"][:16])
252
253
254def seal(top):
255 """The tree read-only, as provider.SealTree makes it: directories
256 0555, files 0555 when npm made them executable for their owner,
257 else 0444."""
258 dirs = []
259 for root, _, files in os.walk(top):
260 dirs.append(root)
261 for f in files:
262 path = os.path.join(root, f)
263 if not os.path.islink(path):
264 os.chmod(path, 0o555 if os.stat(path).st_mode & 0o100 else 0o444)
265 for d in reversed(dirs):
266 os.chmod(d, 0o555)
267
268
269def tree_sha256(top):
270 """provider.TreeSHA256: every entry in Go's WalkDir order (lexical,
271 each directory's entries right after it), refusing anything writable
272 and any link that is absolute or leaves the tree."""
273 h = hashlib.sha256()
274
275 def mode(st):
276 return format(st.st_mode & 0o777, "o")
277
278 def resolve_inside(rel):
279 """provider.resolveInside: follow the entry link by link, each
280 target from where its link is; never above the tree, never to
281 nothing, at most 40 links."""
282 cur, queue, hops = [], rel.split("/"), 0
283 while queue:
284 c = queue.pop(0)
285 if c in ("", "."):
286 continue
287 if c == "..":
288 if not cur:
289 raise RuntimeError("pi tree: link %s leaves the tree" % rel)
290 cur.pop()
291 continue
292 nxt = cur + [c]
293 p = os.path.join(top, *nxt)
294 if not os.path.lexists(p):
295 raise RuntimeError("pi tree: link %s leads to nothing" % rel)
296 if not os.path.islink(p):
297 cur = nxt
298 continue
299 hops += 1
300 target = os.readlink(p)
301 if hops > 40 or os.path.isabs(target):
302 raise RuntimeError("pi tree: link %s loops or is absolute" % rel)
303 queue = target.split("/") + queue
304
305 def visit(path, rel):
306 st = os.lstat(path)
307 if os.path.islink(path):
308 target = os.readlink(path)
309 if os.path.isabs(target):
310 raise RuntimeError("pi tree: link %s is absolute" % rel)
311 resolve_inside(rel)
312 h.update(("l\0%s\0%s\n" % (rel, target)).encode())
313 return
314 if st.st_mode & 0o222:
315 raise RuntimeError("pi tree: %s is writable" % rel)
316 if os.path.isdir(path):
317 h.update(("d\0%s\0%s\n" % (rel, mode(st))).encode())
318 for name in sorted(os.listdir(path)):
319 visit(os.path.join(path, name), name if rel == "." else rel + "/" + name)
320 return
321 if not os.path.isfile(path) or st.st_nlink != 1:
322 raise RuntimeError("pi tree: %s is not a file with one name" % rel)
323 h.update(("f\0%s\0%s\0%s\n" % (rel, mode(st), sha256_file(path))).encode())
324
325 visit(top, ".")
326 return h.hexdigest()
327
328
329def install_pi():
330 """Install the pinned Pi once per tree digest: Node's archive checked
331 by its digest and unpacked, `npm ci --ignore-scripts` from the
332 committed lockfile, the tree sealed and checked against its pin, the
333 node program checked against its own."""
334 pin = pins()["pi"]
335 node_pin = pin["node"][arch()]
336 root = pi_root()
337 stamp = os.path.join(root, "pinned-" + pin["tree_sha256"])
338 if os.path.isfile(stamp):
339 return "pi: present"
340 started = time.time()
341 if os.path.isdir(root):
342 for d, _, _ in os.walk(root):
343 os.chmod(d, 0o755)
344 shutil.rmtree(root)
345 with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch:
346 archive = os.path.join(scratch, "node.tar.gz")
347 got = download(node_pin["url"], archive)
348 if got != node_pin["archive_sha256"]:
349 raise RuntimeError("pi: %s has SHA-256 %s, pinned %s" % (node_pin["url"], got, node_pin["archive_sha256"]))
350 with tarfile.open(archive, "r:gz") as tar:
351 for member in tar.getmembers():
352 if not (member.name == node_pin["root"] or member.name.startswith(node_pin["root"] + "/")) or ".." in member.name.split("/"):
353 raise RuntimeError("pi: %s is outside the archive's root" % member.name)
354 tar.extractall(scratch)
355 node_dir = os.path.join(scratch, node_pin["root"])
356 node = os.path.join(node_dir, "bin", "node")
357 if sha256_file(node) != node_pin["sha256"]:
358 raise RuntimeError("pi: the node program is not the pinned one")
359 prefix = os.path.join(scratch, "pi")
360 os.makedirs(prefix)
361 for name in ("package.json", "package-lock.json"):
362 shutil.copyfile(os.path.join(ROOT, pin["lockfile"], name), os.path.join(prefix, name))
363 env = dict(os.environ, PATH=os.path.join(node_dir, "bin") + ":/usr/bin:/bin", npm_config_cache=os.path.join(scratch, "npm-cache"), npm_config_update_notifier="false")
364 subprocess.run([node, os.path.join(node_dir, "lib", "node_modules", "npm", "bin", "npm-cli.js"), "ci", "--ignore-scripts", "--no-audit", "--no-fund"], cwd=prefix, env=env, check=True, stdout=subprocess.DEVNULL)
365 tree = os.path.join(prefix, "node_modules")
366 seal(tree)
367 got = tree_sha256(tree)
368 if got != pin["tree_sha256"]:
369 raise RuntimeError("pi: the installed tree has digest %s, pinned %s" % (got, pin["tree_sha256"]))
370 os.makedirs(os.path.join(root, "node", "bin"))
371 shutil.copyfile(node, os.path.join(root, "node", "bin", "node"))
372 os.chmod(os.path.join(root, "node", "bin", "node"), 0o555)
373 # A directory moves to another parent only while it is writable.
374 os.makedirs(os.path.join(root, "pi"))
375 os.chmod(tree, 0o755)
376 os.rename(tree, os.path.join(root, "pi", "node_modules"))
377 os.chmod(os.path.join(root, "pi", "node_modules"), 0o555)
378 with open(stamp, "w") as f:
379 f.write(pin["tree_sha256"] + "\n")
380 os.utime(stamp, (TOOL_TIME, TOOL_TIME))
381 return "pi: installed and verified in %.1fs" % (time.time() - started)
382
383
384# OpenCode: two npm packages, unpacked as the runner's installer does.
385
386def opencode_root():
387 return os.path.join(tools_dir(), "opencode-" + opencode_pin()["tree_sha256"][:16])
388
389
390def opencode_pin():
391 return pins()["opencode"]["platforms"][arch()]
392
393
394def sha512_integrity(path):
395 import base64
396 h = hashlib.sha512()
397 with open(path, "rb") as f:
398 for block in iter(lambda: f.read(1 << 20), b""):
399 h.update(block)
400 return "sha512-" + base64.b64encode(h.digest()).decode()
401
402
403def unpack_npm(archive, dest):
404 """opencode.unpack: a package tarball's package/ files into dest,
405 regular files and directories only, nothing outside dest; a file is
406 0755 when the archive marks it executable, else 0644."""
407 with tarfile.open(archive, "r:gz") as tar:
408 for member in tar:
409 name = os.path.normpath(member.name)
410 if not name.startswith("package/") or name == "package" or ".." in name.split("/") or os.path.isabs(name):
411 raise RuntimeError("opencode: %s is outside the package" % member.name)
412 target = os.path.join(dest, name[len("package/"):])
413 if member.isdir():
414 os.makedirs(target, mode=0o755, exist_ok=True)
415 elif member.isreg():
416 os.makedirs(os.path.dirname(target), mode=0o755, exist_ok=True)
417 with tar.extractfile(member) as src, open(target, "xb") as out:
418 shutil.copyfileobj(src, out)
419 os.chmod(target, 0o755 if member.mode & 0o111 else 0o644)
420 else:
421 raise RuntimeError("opencode: %s is not a file or a directory" % member.name)
422
423
424def install_opencode():
425 """Install the pinned OpenCode once per tree digest: @opencode/cli and
426 this machine's binary package, each checked against the lockfile's
427 integrity, unpacked, the tree sealed and checked against its pin, the
428 binary against its own."""
429 pin = pins()["opencode"]
430 plat = opencode_pin()
431 root = opencode_root()
432 stamp = os.path.join(root, "pinned-" + plat["tree_sha256"])
433 if os.path.isfile(stamp):
434 return "opencode: present"
435 started = time.time()
436 if os.path.isdir(root):
437 for d, _, _ in os.walk(root):
438 os.chmod(d, 0o755)
439 shutil.rmtree(root)
440 with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch:
441 tree = os.path.join(scratch, "node_modules")
442 for name, entry in (("@opencode/cli", pin["cli"]), (plat["package"], plat)):
443 archive = os.path.join(scratch, "package.tgz")
444 download(entry["url"], archive)
445 if sha512_integrity(archive) != entry["integrity"]:
446 raise RuntimeError("opencode: %s is not the pinned package" % entry["url"])
447 unpack_npm(archive, os.path.join(tree, *name.split("/")))
448 os.remove(archive)
449 seal(tree)
450 got = tree_sha256(tree)
451 if got != plat["tree_sha256"]:
452 raise RuntimeError("opencode: the installed tree has digest %s, pinned %s" % (got, plat["tree_sha256"]))
453 binary = os.path.join(tree, *plat["package"].split("/"), "bin", "opencode")
454 if sha256_file(binary) != plat["binary_sha256"]:
455 raise RuntimeError("opencode: the binary is not the pinned one")
456 os.makedirs(os.path.join(root, "opencode"))
457 os.chmod(tree, 0o755)
458 os.rename(tree, os.path.join(root, "opencode", "node_modules"))
459 os.chmod(os.path.join(root, "opencode", "node_modules"), 0o555)
460 with open(stamp, "w") as f:
461 f.write(plat["tree_sha256"] + "\n")
462 os.utime(stamp, (TOOL_TIME, TOOL_TIME))
463 return "opencode: installed and verified in %.1fs" % (time.time() - started)
464
465
466# Chromium: a tree of Debian packages, not one program.
467
468def chromium_pins():
469 with open(CHROMIUM_PINS) as f:
470 return json.load(f)
471
472
473def chromium_name():
474 """The tree's directory name, here and in the box: it carries the
475 version, so RASTRILLO_CHROME, which go test keys cached results on,
476 changes when the pin does."""
477 return "chromium-" + re.sub(r"[^A-Za-z0-9.+-]", "_", chromium_pins()["version"])
478
479
480def chromium_dir():
481 return os.path.join(tools_dir(), chromium_name())
482
483
484def chromium_box():
485 return "/opt/" + chromium_name()
486
487
488def unpack_deb(path, root):
489 """Unpack a .deb's files under root. Nothing may land outside it: an
490 absolute link is made relative to root, and a name that climbs out
491 is refused."""
492 def inside(name):
493 name = os.path.normpath(name[2:] if name.startswith("./") else name)
494 if name == ".." or name.startswith("../") or os.path.isabs(name):
495 raise RuntimeError("%s: %s is outside the package" % (path, name))
496 return name
497
498 with tarfile.open(fileobj=io.BytesIO(deb_data(path))) as tar:
499 for member in tar:
500 name = inside(member.name)
501 if name == ".":
502 continue
503 dest = os.path.join(root, name)
504 if member.isdir():
505 os.makedirs(dest, exist_ok=True)
506 continue
507 os.makedirs(os.path.dirname(dest), exist_ok=True)
508 if os.path.lexists(dest):
509 os.unlink(dest)
510 if member.issym():
511 target = member.linkname
512 if os.path.isabs(target):
513 target = os.path.relpath(os.path.join(root, target.lstrip("/")), os.path.dirname(dest))
514 os.symlink(target, dest)
515 elif member.islnk():
516 shutil.copy2(os.path.join(root, inside(member.linkname)), dest)
517 elif member.isfile():
518 with tar.extractfile(member) as source, open(dest, "wb") as out:
519 shutil.copyfileobj(source, out)
520 os.chmod(dest, member.mode & 0o755)
521
522
523def library_dirs(root):
524 """Every directory of the tree that holds a shared library, the
525 browser's own aside: the launcher's LD_LIBRARY_PATH."""
526 found = []
527 for directory, _, names in os.walk(root):
528 if directory.startswith(os.path.join(root, "usr", "lib", "chromium")):
529 continue
530 if any(".so" in n for n in names):
531 found.append(os.path.relpath(directory, root))
532 return sorted(found)
533
534
535FONTS_CONF = """<?xml version="1.0"?>
536<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">
537<fontconfig>
538 <dir prefix="relative">root/usr/share/fonts</dir>
539 <cachedir prefix="xdg">fontconfig</cachedir>
540</fontconfig>
541"""
542
543LAUNCHER = """#!/bin/sh
544# Chromium %(version)s, Debian's headless shell, from scripts/ci-chromium.json
545# (scripts/ci-box.py unpacked it). Its libraries are in this tree, not on
546# the system, and so is its font configuration.
547here=$(dirname "$(readlink -f "$0")")
548LD_LIBRARY_PATH=%(libs)s${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
549FONTCONFIG_FILE=$here/fonts.conf
550export LD_LIBRARY_PATH FONTCONFIG_FILE
551exec "$here/root/%(program)s" "$@"
552"""
553
554
555def fetch_chromium():
556 pinned = chromium_pins()
557 machine = arch()
558 if machine not in pinned:
559 sys.exit("ci-box: scripts/ci-chromium.json has no pin for " + machine)
560 packages = pinned[machine]
561 stamp = json.dumps(packages, sort_keys=True)
562 final = chromium_dir()
563 marker = os.path.join(final, "pinned.json")
564 if os.path.isfile(marker):
565 with open(marker) as f:
566 if f.read() == stamp:
567 return "chromium %s: present" % pinned["version"]
568 started = time.time()
569 os.makedirs(tools_dir(), exist_ok=True)
570 with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch:
571 def get(index_package):
572 index, package = index_package
573 path = os.path.join(scratch, "%03d.deb" % index)
574 got = download(package["url"], path)
575 if got != package["sha256"]:
576 raise RuntimeError("chromium: %s has SHA-256 %s, pinned %s" % (package["url"], got, package["sha256"]))
577 return path
578 with ThreadPoolExecutor(max_workers=8) as pool:
579 debs = list(pool.map(get, enumerate(packages)))
580 tree = os.path.join(scratch, "tree")
581 root = os.path.join(tree, "root")
582 os.makedirs(root)
583 for deb in debs:
584 unpack_deb(deb, root)
585 os.unlink(deb)
586 program = os.path.join(root, pinned["program"])
587 if not os.path.isfile(program):
588 raise RuntimeError("chromium: the packages hold no " + pinned["program"])
589 libs = ":".join('"$here/root/%s"' % d for d in library_dirs(root))
590 with open(os.path.join(tree, "fonts.conf"), "w") as f:
591 f.write(FONTS_CONF)
592 launcher = os.path.join(tree, "chrome")
593 with open(launcher, "w") as f:
594 f.write(LAUNCHER % {"version": pinned["version"], "libs": libs, "program": pinned["program"]})
595 os.chmod(launcher, 0o755)
596 with open(os.path.join(tree, "pinned.json"), "w") as f:
597 f.write(stamp)
598 if os.path.isdir(final):
599 shutil.rmtree(final)
600 os.replace(tree, final)
601 return "chromium %s: %d packages fetched, verified and unpacked in %.1fs" % (
602 pinned["version"], len(packages), time.time() - started)
603
604
605# The container engine and the image.
606
607def engine():
608 name = os.environ.get("EQUIPO_CI_ENGINE")
609 if name:
610 return name
611 for name in ("docker", "podman"):
612 if shutil.which(name):
613 return name
614 sys.exit("ci-box: neither docker nor podman is installed")
615
616
617def pull_image():
618 image = pins()["image"]
619 if subprocess.call([engine(), "image", "inspect", image], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0:
620 say("image present")
621 return
622 started = time.time()
623 for attempt in range(3):
624 if subprocess.call([engine(), "pull", "-q", image], stdout=subprocess.DEVNULL) == 0:
625 say("image pulled in %.1fs" % (time.time() - started))
626 return
627 time.sleep(3 * (attempt + 1))
628 sys.exit("ci-box: could not pull " + image)
629
630
631# The checkout.
632
633def git(*args):
634 return subprocess.run(["git", "-C", ROOT] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
635
636
637def deepen():
638 """A hosted job clones one commit. gitleaks reads history, and the
639 mixed-version test builds an older release, so fetch the rest."""
640 if git("rev-parse", "--is-shallow-repository").stdout.strip() != b"true":
641 return
642 started = time.time()
643 result = git("fetch", "--quiet", "--unshallow", "origin")
644 if result.returncode != 0:
645 say("WARNING: the clone is one commit deep and could not be deepened: " +
646 result.stderr.decode(errors="replace").strip()[-400:])
647 # Names only, never values: what git has to authenticate with.
648 names = sorted(n for n in os.environ if n.startswith(("GIT_", "GOAUTH", "GOPRIVATE", "NETRC")))
649 keys = sorted(set(line.split("=", 1)[0] for line in git("config", "--list").stdout.decode().splitlines()
650 if "credential" in line or "url." in line or "extraheader" in line.lower()))
651 say("git settings present (names only): env %s; config %s; origin %s" %
652 (names or "none", keys or "none", git("remote", "get-url", "origin").stdout.decode().strip()))
653 return
654 say("clone deepened in %.1fs" % (time.time() - started))
655
656
657def set_file_times():
658 """Give every tracked file a modification time made from its content,
659 and every directory one fixed time. See TOOL_TIME."""
660 listed = git("ls-files", "-s", "-z")
661 if listed.returncode != 0:
662 sys.exit("ci-box: git ls-files: " + listed.stderr.decode(errors="replace"))
663 directories = {ROOT}
664 count = 0
665 for entry in listed.stdout.split(b"\0"):
666 if not entry:
667 continue
668 meta, name = entry.split(b"\t", 1)
669 mode, blob = meta.split()[:2]
670 if mode == b"160000":
671 continue
672 path = os.path.join(ROOT, os.fsdecode(name))
673 stamp = FILE_TIME_BASE + int(blob[:8], 16) % FILE_TIME_SPAN
674 try:
675 os.utime(path, (stamp, stamp), follow_symlinks=False)
676 except FileNotFoundError:
677 continue
678 count += 1
679 parent = os.path.dirname(path)
680 while parent not in directories:
681 directories.add(parent)
682 parent = os.path.dirname(parent)
683 for directory in directories:
684 os.utime(directory, (FILE_TIME_BASE, FILE_TIME_BASE))
685 git("update-index", "-q", "--refresh")
686 say("file times set from content: %d files, %d directories" % (count, len(directories)))
687
688
689# Running a command in the box.
690
691def go_env(name):
692 value = os.environ.get(name)
693 if value:
694 return value
695 return subprocess.check_output(["go", "env", name], text=True).strip()
696
697
698def run(command):
699 if not command:
700 sys.exit("ci-box: run what?")
701 if not boxed():
702 os.chdir(ROOT)
703 os.execvp(command[0], command)
704 machine = arch()
705 tools = pins()["tools"]
706 missing = [name for name, tool in tools.items() if not os.path.isfile(tool_path(name, tool))]
707 if not os.path.isfile(os.path.join(chromium_dir(), "chrome")):
708 missing.append("chromium")
709 if not os.path.isfile(os.path.join(pi_root(), "pinned-" + pins()["pi"]["tree_sha256"])):
710 missing.append("pi")
711 if not os.path.isfile(os.path.join(opencode_root(), "pinned-" + opencode_pin()["tree_sha256"])):
712 missing.append("opencode")
713 if missing:
714 sys.exit("ci-box: %s not fetched; run scripts/ci-box.py prepare first" % ", ".join(sorted(missing)))
715 gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
716 for path in (gocache, gomodcache):
717 os.makedirs(path, exist_ok=True)
718 tool = engine()
719 # /tmp in memory. The tests sync small files and databases thousands
720 # of times; on the machine's disk that doubled every lane's time.
721 args = [tool, "run", "--rm", "--privileged", "--cgroupns=private",
722 "--tmpfs", "/tmp:exec,mode=1777",
723 "-v", ROOT + ":" + WORK, "-w", WORK,
724 "-v", gocache + ":" + GOCACHE, "-v", gomodcache + ":" + GOMODCACHE,
725 "-v", os.path.join(tools_dir(), "bin") + ":" + TRY_BIN + ":ro"]
726 for name, entry in sorted(tools.items()):
727 inside = entry[machine].get("box") or entry.get("box")
728 if inside:
729 args += ["-v", tool_path(name, entry) + ":" + inside + ":ro"]
730 args += ["-v", chromium_dir() + ":" + chromium_box() + ":ro"]
731 args += ["-v", pi_root() + ":" + pins()["pi"]["box"] + ":ro"]
732 args += ["-v", opencode_root() + ":" + pins()["opencode"]["box"] + ":ro"]
733 if tool == "docker":
734 args.append("--init") # reaps the orphans the containment tests leave on purpose
735 # A CI runner checks a branch out as a git worktree: .git is a file
736 # that names a directory in the shared clone. Mount that clone where
737 # the file says it is, or git has no repository inside the box.
738 if os.path.isfile(os.path.join(ROOT, ".git")):
739 common = git("rev-parse", "--path-format=absolute", "--git-common-dir").stdout.decode().strip()
740 if common:
741 args += ["-v", common + ":" + common]
742 for mount in filter(None, os.environ.get("EQUIPO_CI_BOX_MOUNTS", "").split(",")):
743 args += ["-v", mount]
744 env = {
745 "GOCACHE": GOCACHE, "GOMODCACHE": GOMODCACHE,
746 "EQUIPO_TEST_TOOLS_REQUIRED": "1",
747 "RASTRILLO_CHROME": chromium_box() + "/chrome",
748 "EQUIPO_PI_ROOT": pins()["pi"]["box"],
749 "EQUIPO_OPENCODE_ROOT": pins()["opencode"]["box"],
750 "EQUIPO_BOX_UID": str(os.getuid()), "EQUIPO_BOX_GID": str(os.getgid()),
751 }
752 if tool == "podman" and os.getuid() != 0:
753 # Rootless podman, a developer's machine: its root is the caller, and
754 # any other user inside could not write the checkout. Tests then run
755 # as that root, which is good for a first look and not for a verdict.
756 env["EQUIPO_BOX_UID"] = env["EQUIPO_BOX_GID"] = "0"
757 for name, value in os.environ.items():
758 if name in PASS_NAMES or name.startswith(PASS_PREFIXES):
759 env.setdefault(name, value)
760 for name in sorted(env):
761 args += ["-e", name + "=" + env[name]]
762 args += [pins()["image"], WORK + "/scripts/ci-box-enter.sh"] + command
763 os.execvp(args[0], args)
764
765
766# The Go caches.
767
768def tree_size(path):
769 total = files = 0
770 for directory, _, names in os.walk(path):
771 for name in names:
772 try:
773 total += os.lstat(os.path.join(directory, name)).st_size
774 files += 1
775 except OSError:
776 pass
777 return total, files
778
779
780def cache():
781 """Report the caches and, past CACHE_LIMIT, drop what this job did not
782 read. A restore stamps every entry "now", so Go's own five-day trim
783 never fires on a hosted machine and the cache would grow until its
784 save is refused."""
785 if not boxed():
786 return # a runner host's cache is its own to trim
787 gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE")
788 for name, path in (("build cache", gocache), ("module cache", gomodcache)):
789 size, files = tree_size(path)
790 say("%s %s: %.2f GiB in %d files" % (name, path, size / 1024 ** 3, files))
791 size, _ = tree_size(gocache)
792 marker = os.path.join(box_dir(), "prepared")
793 if size <= CACHE_LIMIT or not os.path.exists(marker):
794 return
795 since = os.stat(marker).st_mtime
796 dropped = kept = 0
797 for directory, _, names in os.walk(gocache):
798 for name in names:
799 path = os.path.join(directory, name)
800 try:
801 st = os.lstat(path)
802 if max(st.st_atime, st.st_mtime) < since:
803 os.unlink(path)
804 dropped += st.st_size
805 else:
806 kept += st.st_size
807 except OSError:
808 pass
809 say("build cache over %.1f GiB: dropped %.2f GiB this job did not read, kept %.2f GiB" %
810 (CACHE_LIMIT / 1024 ** 3, dropped / 1024 ** 3, kept / 1024 ** 3))
811
812
813def cold_start():
814 """Empty the restored build cache when the commit carries .amadan/cold:
815 a scratch branch's way to measure a cold run, where every shard
816 compiles and no test result replays. Only on a hosted CI machine, whose
817 cache is a copy; never commit the file to main."""
818 if not os.path.exists(COLD):
819 return
820 gocache = go_env("GOCACHE")
821 size, files = tree_size(gocache)
822 for name in os.listdir(gocache) if os.path.isdir(gocache) else []:
823 path = os.path.join(gocache, name)
824 if os.path.isdir(path) and not os.path.islink(path):
825 shutil.rmtree(path, ignore_errors=True)
826 else:
827 os.unlink(path)
828 say("cold run (.amadan/cold): emptied the build cache, %.2f GiB in %d files" % (size / 1024 ** 3, files))
829
830
831def facts():
832 def out(*command):
833 try:
834 return subprocess.check_output(list(command), stderr=subprocess.STDOUT, text=True).strip()
835 except Exception as e:
836 return "unavailable (%s)" % e
837
838 memory = "unknown"
839 try:
840 with open("/proc/meminfo") as f:
841 memory = "%.0f GiB" % (int(f.readline().split()[1]) / 1024 ** 2)
842 except OSError:
843 pass
844 say("machine: %s, %s CPUs, %s memory, kernel %s" % (platform.machine(), os.cpu_count(), memory, platform.release()))
845 say("python %s; %s" % (platform.python_version(), out(engine(), "--version")))
846 say("user namespaces allowed: " + out("cat", "/proc/sys/user/max_user_namespaces"))
847 say("cgroup: " + out("stat", "-fc", "%T", "/sys/fs/cgroup"))
848 for path in (ROOT, box_dir()):
849 say("disk %s: %s" % (path, out("df", "-h", "--output=fstype,size,avail", path).replace("\n", " | ")))
850
851
852def prepare():
853 if not boxed():
854 return # a runner host: nothing to fetch
855 started = time.time()
856 facts()
857 with ThreadPoolExecutor(max_workers=3) as pool:
858 image = pool.submit(pull_image)
859 chromium = pool.submit(fetch_chromium)
860 fetch_tools()
861 say(install_pi())
862 say(install_opencode())
863 say(chromium.result())
864 image.result()
865 if os.environ.get("AMADAN_CI") == "1":
866 deepen()
867 set_file_times()
868 cold_start()
869 with open(os.path.join(box_dir(), "prepared"), "w") as f:
870 f.write("%d\n" % time.time())
871 say("ready in %.1fs" % (time.time() - started))
872
873
874def main(argv):
875 if argv == ["prepare"]:
876 return prepare()
877 if argv[:1] == ["run"]:
878 return run(argv[1:])
879 if argv == ["cache"]:
880 return cache()
881 if argv == ["facts"]:
882 return facts()
883 print(__doc__, file=sys.stderr)
884 return 2
885
886
887if __name__ == "__main__":
888 sys.exit(main(sys.argv[1:]))
889