#!/usr/bin/env python3 """Run Equipo's CI in its box: one container that looks like a runner host. scripts/ci-box.py prepare fetch the pinned tools and the image; on CI also deepen the clone and set file times scripts/ci-box.py run CMD... run CMD in the box, from the repository root scripts/ci-box.py cache report the Go caches and trim them to fit scripts/ci-box.py facts print what this machine is amadan's hosted CI gives each job a fresh arm64 machine with Docker and no bubblewrap. Equipo's tests start real containment: they need bubblewrap 0.11.0 exactly, the pinned Codex and Claude programs, user namespaces and a delegated cgroup. The box supplies those. It is the official Go image on Debian 13 (the runner host's own system), run privileged, with the pinned programs mounted where a runner host has them: /usr/bin/bwrap Debian's 0.11.0-2+deb13u1 build /usr/local/bin/codex codex 0.165.0 ~/.local/share/equipo/try/bin codex, its code mode host, claude /usr/bin/socat Claude's own sandbox needs it /opt/chromium-/chrome the browser tests' Chromium /opt/equipo-pi the pinned Pi and its Node /opt/equipo-opencode the pinned OpenCode The Pi install is what a runner's is: Node from the official archive by its digest, and the npm tree `npm ci --ignore-scripts` makes from the committed lockfile, made read-only and checked against the committed tree digest (scripts/ci-box.json "pi", the same as the code's pins). The OpenCode install is a runner's too: the two npm packages the committed lockfile names (@opencode/cli and this machine's binary package), each checked against its integrity before it is unpacked, no script run, the tree sealed and checked against its digest and the binary against its own (scripts/ci-box.json "opencode", the code's pins). Every pinned program is fetched by URL and checked against the SHA-256 in scripts/ci-box.json, for this machine's architecture. Chromium is Debian's headless shell and the libraries it needs, some seventy packages pinned in scripts/ci-chromium.json (scripts/ci-chromium-pin.py writes it), unpacked into one tree; RASTRILLO_CHROME names its launcher, which is where the browser tests (harness.ChromePath) look first. The job's checkout and Go caches are mounted at fixed paths, so Go's build and test caches hold from one fresh machine to the next. Inside, the command runs as an ordinary user (scripts/ci-box-enter.sh), never as root. This file also runs on the CI machine itself, outside the box, where python3 is 3.9: keep it to that. """ import hashlib import io import json import lzma import os import platform import re import shutil import subprocess import sys import tarfile import tempfile import time import urllib.request from concurrent.futures import ThreadPoolExecutor ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PINS = os.path.join(ROOT, "scripts", "ci-box.json") CHROMIUM_PINS = os.path.join(ROOT, "scripts", "ci-chromium.json") COLD = os.path.join(ROOT, ".amadan", "cold") # Where things sit inside the box. Fixed, whatever the job's own paths # are: Go keys a compiled package on its source directory, so a checkout # that moved would recompile everything. WORK = "/work/equipo" GOCACHE = "/cache/go-build" GOMODCACHE = "/cache/go-mod" HOME = "/home/ci" TRY_BIN = HOME + "/.local/share/equipo/try/bin" # Fetched programs get this modification time (2026-01-01), and tracked # files get one made from their content: make test fingerprints programs # by size and time, and go test keys a cached result on the size and time # of each file the test opened. A fresh clone would stamp everything # "now" and no result would ever be reused. TOOL_TIME = 1767225600 FILE_TIME_BASE = 1577836800 # 2020-01-01 FILE_TIME_SPAN = 5 * 365 * 86400 # The hosted cache holds 6 GiB unpacked and 2 GiB compressed, and a save # over either is dropped whole. Trim well under it. CACHE_LIMIT = 4 * 1024 ** 3 # Environment a step may see inside the box, besides what run() sets. # Not GOPRIVATE or GOAUTH: the job's git credential stays outside the # box, and every module Equipo uses is on the public proxy. PASS_PREFIXES = ("AMADAN_", "EQUIPO_") PASS_NAMES = ("CI", "GOFLAGS", "GOPROXY", "TERM") def say(text): print("ci-box: " + text, flush=True) def arch(): machine = platform.machine().lower() name = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(machine) if name is None: sys.exit("ci-box: no pinned tools for a %s machine" % machine) return name def pins(): with open(PINS) as f: return json.load(f) def box_dir(): path = os.environ.get("EQUIPO_CI_BOX_DIR") or os.path.join(os.path.expanduser("~"), ".cache", "equipo-ci-box") os.makedirs(path, exist_ok=True) return path def tools_dir(): return os.path.join(box_dir(), "tools", arch()) def tool_path(name, tool): """Where a fetched program is kept: the ones tests find in the try directory together in bin, mounted as that directory; the rest in sys.""" return os.path.join(tools_dir(), "bin" if tool.get("try_bin") else "sys", name) def boxed(): """Whether commands go in the box. EQUIPO_CI_BOX=on or off decides; unset, a machine that already has what the box supplies (the pinned bubblewrap and a codex) is a runner host, and commands run directly.""" mode = os.environ.get("EQUIPO_CI_BOX", "") if mode in ("on", "off"): return mode == "on" if mode: sys.exit("ci-box: EQUIPO_CI_BOX is %r; use on or off" % mode) try: version = subprocess.check_output(["/usr/bin/bwrap", "--version"], stderr=subprocess.DEVNULL, text=True).strip() except (OSError, subprocess.CalledProcessError): version = "" return version != pins()["tools"]["bwrap"]["version"] or shutil.which("codex") is None # Pinned tools. def sha256_file(path): h = hashlib.sha256() with open(path, "rb") as f: for block in iter(lambda: f.read(1 << 20), b""): h.update(block) return h.hexdigest() def download(url, dest): """Fetch url into dest and return its SHA-256; three attempts.""" last = None for attempt in range(3): try: h = hashlib.sha256() request = urllib.request.Request(url, headers={"User-Agent": "equipo-ci-box"}) with urllib.request.urlopen(request, timeout=120) as response, open(dest, "wb") as out: for block in iter(lambda: response.read(1 << 20), b""): h.update(block) out.write(block) return h.hexdigest() except Exception as e: # a CDN's bad minute is not this change's failure last = e time.sleep(2 * (attempt + 1)) raise RuntimeError("fetch %s: %s" % (url, last)) def deb_data(path): """The data archive of a .deb: an ar file whose data.tar.* member holds the files.""" with open(path, "rb") as f: if f.read(8) != b"!\n": raise RuntimeError("not a .deb: " + path) while True: header = f.read(60) if len(header) < 60: raise RuntimeError("no data archive in " + path) name = header[:16].decode().strip().rstrip("/") size = int(header[48:58].decode().strip()) body = f.read(size + (size & 1))[:size] if name.startswith("data.tar"): if name.endswith(".xz"): body = lzma.decompress(body) elif name != "data.tar": raise RuntimeError("unsupported .deb compression: " + name) return body def extract(archive, fmt, member, dest): if fmt == "raw": shutil.copyfile(archive, dest) return if fmt == "deb": tar = tarfile.open(fileobj=io.BytesIO(deb_data(archive))) elif fmt == "tar.gz": tar = tarfile.open(archive, "r:gz") else: raise RuntimeError("unknown archive format " + fmt) with tar: source = tar.extractfile(member) if source is None: raise RuntimeError("%s is not a file in the archive" % member) with source, open(dest, "wb") as out: shutil.copyfileobj(source, out) def fetch_tool(name, pin, target): if os.path.isfile(target) and sha256_file(target) == pin["sha256"]: return "%s: present" % name started = time.time() os.makedirs(os.path.dirname(target), exist_ok=True) with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch: archive = os.path.join(scratch, "archive") got = download(pin["url"], archive) want = pin.get("archive_sha256", pin["sha256"]) if got != want: raise RuntimeError("%s: %s has SHA-256 %s, pinned %s" % (name, pin["url"], got, want)) out = os.path.join(scratch, name) extract(archive, pin["format"], pin.get("member"), out) if sha256_file(out) != pin["sha256"]: raise RuntimeError("%s: the program in %s is not the pinned one" % (name, pin["url"])) os.chmod(out, 0o755) os.utime(out, (TOOL_TIME, TOOL_TIME)) os.replace(out, target) return "%s: fetched and verified in %.1fs" % (name, time.time() - started) def fetch_tools(): os.makedirs(os.path.join(tools_dir(), "bin"), exist_ok=True) machine = arch() jobs = [] for name, tool in sorted(pins()["tools"].items()): if machine not in tool: sys.exit("ci-box: %s has no pin for %s" % (name, machine)) jobs.append((name, tool[machine], tool_path(name, tool))) with ThreadPoolExecutor(max_workers=len(jobs)) as pool: for line in pool.map(lambda job: fetch_tool(*job), jobs): say(line) return tools_dir() # Pi: Node and an npm tree, not one program. def pi_root(): return os.path.join(tools_dir(), "pi-" + pins()["pi"]["tree_sha256"][:16]) def seal(top): """The tree read-only, as provider.SealTree makes it: directories 0555, files 0555 when npm made them executable for their owner, else 0444.""" dirs = [] for root, _, files in os.walk(top): dirs.append(root) for f in files: path = os.path.join(root, f) if not os.path.islink(path): os.chmod(path, 0o555 if os.stat(path).st_mode & 0o100 else 0o444) for d in reversed(dirs): os.chmod(d, 0o555) def tree_sha256(top): """provider.TreeSHA256: every entry in Go's WalkDir order (lexical, each directory's entries right after it), refusing anything writable and any link that is absolute or leaves the tree.""" h = hashlib.sha256() def mode(st): return format(st.st_mode & 0o777, "o") def resolve_inside(rel): """provider.resolveInside: follow the entry link by link, each target from where its link is; never above the tree, never to nothing, at most 40 links.""" cur, queue, hops = [], rel.split("/"), 0 while queue: c = queue.pop(0) if c in ("", "."): continue if c == "..": if not cur: raise RuntimeError("pi tree: link %s leaves the tree" % rel) cur.pop() continue nxt = cur + [c] p = os.path.join(top, *nxt) if not os.path.lexists(p): raise RuntimeError("pi tree: link %s leads to nothing" % rel) if not os.path.islink(p): cur = nxt continue hops += 1 target = os.readlink(p) if hops > 40 or os.path.isabs(target): raise RuntimeError("pi tree: link %s loops or is absolute" % rel) queue = target.split("/") + queue def visit(path, rel): st = os.lstat(path) if os.path.islink(path): target = os.readlink(path) if os.path.isabs(target): raise RuntimeError("pi tree: link %s is absolute" % rel) resolve_inside(rel) h.update(("l\0%s\0%s\n" % (rel, target)).encode()) return if st.st_mode & 0o222: raise RuntimeError("pi tree: %s is writable" % rel) if os.path.isdir(path): h.update(("d\0%s\0%s\n" % (rel, mode(st))).encode()) for name in sorted(os.listdir(path)): visit(os.path.join(path, name), name if rel == "." else rel + "/" + name) return if not os.path.isfile(path) or st.st_nlink != 1: raise RuntimeError("pi tree: %s is not a file with one name" % rel) h.update(("f\0%s\0%s\0%s\n" % (rel, mode(st), sha256_file(path))).encode()) visit(top, ".") return h.hexdigest() def install_pi(): """Install the pinned Pi once per tree digest: Node's archive checked by its digest and unpacked, `npm ci --ignore-scripts` from the committed lockfile, the tree sealed and checked against its pin, the node program checked against its own.""" pin = pins()["pi"] node_pin = pin["node"][arch()] root = pi_root() stamp = os.path.join(root, "pinned-" + pin["tree_sha256"]) if os.path.isfile(stamp): return "pi: present" started = time.time() if os.path.isdir(root): for d, _, _ in os.walk(root): os.chmod(d, 0o755) shutil.rmtree(root) with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch: archive = os.path.join(scratch, "node.tar.gz") got = download(node_pin["url"], archive) if got != node_pin["archive_sha256"]: raise RuntimeError("pi: %s has SHA-256 %s, pinned %s" % (node_pin["url"], got, node_pin["archive_sha256"])) with tarfile.open(archive, "r:gz") as tar: for member in tar.getmembers(): if not (member.name == node_pin["root"] or member.name.startswith(node_pin["root"] + "/")) or ".." in member.name.split("/"): raise RuntimeError("pi: %s is outside the archive's root" % member.name) tar.extractall(scratch) node_dir = os.path.join(scratch, node_pin["root"]) node = os.path.join(node_dir, "bin", "node") if sha256_file(node) != node_pin["sha256"]: raise RuntimeError("pi: the node program is not the pinned one") prefix = os.path.join(scratch, "pi") os.makedirs(prefix) for name in ("package.json", "package-lock.json"): shutil.copyfile(os.path.join(ROOT, pin["lockfile"], name), os.path.join(prefix, name)) 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") 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) tree = os.path.join(prefix, "node_modules") seal(tree) got = tree_sha256(tree) if got != pin["tree_sha256"]: raise RuntimeError("pi: the installed tree has digest %s, pinned %s" % (got, pin["tree_sha256"])) os.makedirs(os.path.join(root, "node", "bin")) shutil.copyfile(node, os.path.join(root, "node", "bin", "node")) os.chmod(os.path.join(root, "node", "bin", "node"), 0o555) # A directory moves to another parent only while it is writable. os.makedirs(os.path.join(root, "pi")) os.chmod(tree, 0o755) os.rename(tree, os.path.join(root, "pi", "node_modules")) os.chmod(os.path.join(root, "pi", "node_modules"), 0o555) with open(stamp, "w") as f: f.write(pin["tree_sha256"] + "\n") os.utime(stamp, (TOOL_TIME, TOOL_TIME)) return "pi: installed and verified in %.1fs" % (time.time() - started) # OpenCode: two npm packages, unpacked as the runner's installer does. def opencode_root(): return os.path.join(tools_dir(), "opencode-" + opencode_pin()["tree_sha256"][:16]) def opencode_pin(): return pins()["opencode"]["platforms"][arch()] def sha512_integrity(path): import base64 h = hashlib.sha512() with open(path, "rb") as f: for block in iter(lambda: f.read(1 << 20), b""): h.update(block) return "sha512-" + base64.b64encode(h.digest()).decode() def unpack_npm(archive, dest): """opencode.unpack: a package tarball's package/ files into dest, regular files and directories only, nothing outside dest; a file is 0755 when the archive marks it executable, else 0644.""" with tarfile.open(archive, "r:gz") as tar: for member in tar: name = os.path.normpath(member.name) if not name.startswith("package/") or name == "package" or ".." in name.split("/") or os.path.isabs(name): raise RuntimeError("opencode: %s is outside the package" % member.name) target = os.path.join(dest, name[len("package/"):]) if member.isdir(): os.makedirs(target, mode=0o755, exist_ok=True) elif member.isreg(): os.makedirs(os.path.dirname(target), mode=0o755, exist_ok=True) with tar.extractfile(member) as src, open(target, "xb") as out: shutil.copyfileobj(src, out) os.chmod(target, 0o755 if member.mode & 0o111 else 0o644) else: raise RuntimeError("opencode: %s is not a file or a directory" % member.name) def install_opencode(): """Install the pinned OpenCode once per tree digest: @opencode/cli and this machine's binary package, each checked against the lockfile's integrity, unpacked, the tree sealed and checked against its pin, the binary against its own.""" pin = pins()["opencode"] plat = opencode_pin() root = opencode_root() stamp = os.path.join(root, "pinned-" + plat["tree_sha256"]) if os.path.isfile(stamp): return "opencode: present" started = time.time() if os.path.isdir(root): for d, _, _ in os.walk(root): os.chmod(d, 0o755) shutil.rmtree(root) with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch: tree = os.path.join(scratch, "node_modules") for name, entry in (("@opencode/cli", pin["cli"]), (plat["package"], plat)): archive = os.path.join(scratch, "package.tgz") download(entry["url"], archive) if sha512_integrity(archive) != entry["integrity"]: raise RuntimeError("opencode: %s is not the pinned package" % entry["url"]) unpack_npm(archive, os.path.join(tree, *name.split("/"))) os.remove(archive) seal(tree) got = tree_sha256(tree) if got != plat["tree_sha256"]: raise RuntimeError("opencode: the installed tree has digest %s, pinned %s" % (got, plat["tree_sha256"])) binary = os.path.join(tree, *plat["package"].split("/"), "bin", "opencode") if sha256_file(binary) != plat["binary_sha256"]: raise RuntimeError("opencode: the binary is not the pinned one") os.makedirs(os.path.join(root, "opencode")) os.chmod(tree, 0o755) os.rename(tree, os.path.join(root, "opencode", "node_modules")) os.chmod(os.path.join(root, "opencode", "node_modules"), 0o555) with open(stamp, "w") as f: f.write(plat["tree_sha256"] + "\n") os.utime(stamp, (TOOL_TIME, TOOL_TIME)) return "opencode: installed and verified in %.1fs" % (time.time() - started) # Chromium: a tree of Debian packages, not one program. def chromium_pins(): with open(CHROMIUM_PINS) as f: return json.load(f) def chromium_name(): """The tree's directory name, here and in the box: it carries the version, so RASTRILLO_CHROME, which go test keys cached results on, changes when the pin does.""" return "chromium-" + re.sub(r"[^A-Za-z0-9.+-]", "_", chromium_pins()["version"]) def chromium_dir(): return os.path.join(tools_dir(), chromium_name()) def chromium_box(): return "/opt/" + chromium_name() def unpack_deb(path, root): """Unpack a .deb's files under root. Nothing may land outside it: an absolute link is made relative to root, and a name that climbs out is refused.""" def inside(name): name = os.path.normpath(name[2:] if name.startswith("./") else name) if name == ".." or name.startswith("../") or os.path.isabs(name): raise RuntimeError("%s: %s is outside the package" % (path, name)) return name with tarfile.open(fileobj=io.BytesIO(deb_data(path))) as tar: for member in tar: name = inside(member.name) if name == ".": continue dest = os.path.join(root, name) if member.isdir(): os.makedirs(dest, exist_ok=True) continue os.makedirs(os.path.dirname(dest), exist_ok=True) if os.path.lexists(dest): os.unlink(dest) if member.issym(): target = member.linkname if os.path.isabs(target): target = os.path.relpath(os.path.join(root, target.lstrip("/")), os.path.dirname(dest)) os.symlink(target, dest) elif member.islnk(): shutil.copy2(os.path.join(root, inside(member.linkname)), dest) elif member.isfile(): with tar.extractfile(member) as source, open(dest, "wb") as out: shutil.copyfileobj(source, out) os.chmod(dest, member.mode & 0o755) def library_dirs(root): """Every directory of the tree that holds a shared library, the browser's own aside: the launcher's LD_LIBRARY_PATH.""" found = [] for directory, _, names in os.walk(root): if directory.startswith(os.path.join(root, "usr", "lib", "chromium")): continue if any(".so" in n for n in names): found.append(os.path.relpath(directory, root)) return sorted(found) FONTS_CONF = """ root/usr/share/fonts fontconfig """ LAUNCHER = """#!/bin/sh # Chromium %(version)s, Debian's headless shell, from scripts/ci-chromium.json # (scripts/ci-box.py unpacked it). Its libraries are in this tree, not on # the system, and so is its font configuration. here=$(dirname "$(readlink -f "$0")") LD_LIBRARY_PATH=%(libs)s${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} FONTCONFIG_FILE=$here/fonts.conf export LD_LIBRARY_PATH FONTCONFIG_FILE exec "$here/root/%(program)s" "$@" """ def fetch_chromium(): pinned = chromium_pins() machine = arch() if machine not in pinned: sys.exit("ci-box: scripts/ci-chromium.json has no pin for " + machine) packages = pinned[machine] stamp = json.dumps(packages, sort_keys=True) final = chromium_dir() marker = os.path.join(final, "pinned.json") if os.path.isfile(marker): with open(marker) as f: if f.read() == stamp: return "chromium %s: present" % pinned["version"] started = time.time() os.makedirs(tools_dir(), exist_ok=True) with tempfile.TemporaryDirectory(dir=tools_dir()) as scratch: def get(index_package): index, package = index_package path = os.path.join(scratch, "%03d.deb" % index) got = download(package["url"], path) if got != package["sha256"]: raise RuntimeError("chromium: %s has SHA-256 %s, pinned %s" % (package["url"], got, package["sha256"])) return path with ThreadPoolExecutor(max_workers=8) as pool: debs = list(pool.map(get, enumerate(packages))) tree = os.path.join(scratch, "tree") root = os.path.join(tree, "root") os.makedirs(root) for deb in debs: unpack_deb(deb, root) os.unlink(deb) program = os.path.join(root, pinned["program"]) if not os.path.isfile(program): raise RuntimeError("chromium: the packages hold no " + pinned["program"]) libs = ":".join('"$here/root/%s"' % d for d in library_dirs(root)) with open(os.path.join(tree, "fonts.conf"), "w") as f: f.write(FONTS_CONF) launcher = os.path.join(tree, "chrome") with open(launcher, "w") as f: f.write(LAUNCHER % {"version": pinned["version"], "libs": libs, "program": pinned["program"]}) os.chmod(launcher, 0o755) with open(os.path.join(tree, "pinned.json"), "w") as f: f.write(stamp) if os.path.isdir(final): shutil.rmtree(final) os.replace(tree, final) return "chromium %s: %d packages fetched, verified and unpacked in %.1fs" % ( pinned["version"], len(packages), time.time() - started) # The container engine and the image. def engine(): name = os.environ.get("EQUIPO_CI_ENGINE") if name: return name for name in ("docker", "podman"): if shutil.which(name): return name sys.exit("ci-box: neither docker nor podman is installed") def pull_image(): image = pins()["image"] if subprocess.call([engine(), "image", "inspect", image], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) == 0: say("image present") return started = time.time() for attempt in range(3): if subprocess.call([engine(), "pull", "-q", image], stdout=subprocess.DEVNULL) == 0: say("image pulled in %.1fs" % (time.time() - started)) return time.sleep(3 * (attempt + 1)) sys.exit("ci-box: could not pull " + image) # The checkout. def git(*args): return subprocess.run(["git", "-C", ROOT] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE) def deepen(): """A hosted job clones one commit. gitleaks reads history, and the mixed-version test builds an older release, so fetch the rest.""" if git("rev-parse", "--is-shallow-repository").stdout.strip() != b"true": return started = time.time() result = git("fetch", "--quiet", "--unshallow", "origin") if result.returncode != 0: say("WARNING: the clone is one commit deep and could not be deepened: " + result.stderr.decode(errors="replace").strip()[-400:]) # Names only, never values: what git has to authenticate with. names = sorted(n for n in os.environ if n.startswith(("GIT_", "GOAUTH", "GOPRIVATE", "NETRC"))) keys = sorted(set(line.split("=", 1)[0] for line in git("config", "--list").stdout.decode().splitlines() if "credential" in line or "url." in line or "extraheader" in line.lower())) say("git settings present (names only): env %s; config %s; origin %s" % (names or "none", keys or "none", git("remote", "get-url", "origin").stdout.decode().strip())) return say("clone deepened in %.1fs" % (time.time() - started)) def set_file_times(): """Give every tracked file a modification time made from its content, and every directory one fixed time. See TOOL_TIME.""" listed = git("ls-files", "-s", "-z") if listed.returncode != 0: sys.exit("ci-box: git ls-files: " + listed.stderr.decode(errors="replace")) directories = {ROOT} count = 0 for entry in listed.stdout.split(b"\0"): if not entry: continue meta, name = entry.split(b"\t", 1) mode, blob = meta.split()[:2] if mode == b"160000": continue path = os.path.join(ROOT, os.fsdecode(name)) stamp = FILE_TIME_BASE + int(blob[:8], 16) % FILE_TIME_SPAN try: os.utime(path, (stamp, stamp), follow_symlinks=False) except FileNotFoundError: continue count += 1 parent = os.path.dirname(path) while parent not in directories: directories.add(parent) parent = os.path.dirname(parent) for directory in directories: os.utime(directory, (FILE_TIME_BASE, FILE_TIME_BASE)) git("update-index", "-q", "--refresh") say("file times set from content: %d files, %d directories" % (count, len(directories))) # Running a command in the box. def go_env(name): value = os.environ.get(name) if value: return value return subprocess.check_output(["go", "env", name], text=True).strip() def run(command): if not command: sys.exit("ci-box: run what?") if not boxed(): os.chdir(ROOT) os.execvp(command[0], command) machine = arch() tools = pins()["tools"] missing = [name for name, tool in tools.items() if not os.path.isfile(tool_path(name, tool))] if not os.path.isfile(os.path.join(chromium_dir(), "chrome")): missing.append("chromium") if not os.path.isfile(os.path.join(pi_root(), "pinned-" + pins()["pi"]["tree_sha256"])): missing.append("pi") if not os.path.isfile(os.path.join(opencode_root(), "pinned-" + opencode_pin()["tree_sha256"])): missing.append("opencode") if missing: sys.exit("ci-box: %s not fetched; run scripts/ci-box.py prepare first" % ", ".join(sorted(missing))) gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE") for path in (gocache, gomodcache): os.makedirs(path, exist_ok=True) tool = engine() # /tmp in memory. The tests sync small files and databases thousands # of times; on the machine's disk that doubled every lane's time. args = [tool, "run", "--rm", "--privileged", "--cgroupns=private", "--tmpfs", "/tmp:exec,mode=1777", "-v", ROOT + ":" + WORK, "-w", WORK, "-v", gocache + ":" + GOCACHE, "-v", gomodcache + ":" + GOMODCACHE, "-v", os.path.join(tools_dir(), "bin") + ":" + TRY_BIN + ":ro"] for name, entry in sorted(tools.items()): inside = entry[machine].get("box") or entry.get("box") if inside: args += ["-v", tool_path(name, entry) + ":" + inside + ":ro"] args += ["-v", chromium_dir() + ":" + chromium_box() + ":ro"] args += ["-v", pi_root() + ":" + pins()["pi"]["box"] + ":ro"] args += ["-v", opencode_root() + ":" + pins()["opencode"]["box"] + ":ro"] if tool == "docker": args.append("--init") # reaps the orphans the containment tests leave on purpose # A CI runner checks a branch out as a git worktree: .git is a file # that names a directory in the shared clone. Mount that clone where # the file says it is, or git has no repository inside the box. if os.path.isfile(os.path.join(ROOT, ".git")): common = git("rev-parse", "--path-format=absolute", "--git-common-dir").stdout.decode().strip() if common: args += ["-v", common + ":" + common] for mount in filter(None, os.environ.get("EQUIPO_CI_BOX_MOUNTS", "").split(",")): args += ["-v", mount] env = { "GOCACHE": GOCACHE, "GOMODCACHE": GOMODCACHE, "EQUIPO_TEST_TOOLS_REQUIRED": "1", "RASTRILLO_CHROME": chromium_box() + "/chrome", "EQUIPO_PI_ROOT": pins()["pi"]["box"], "EQUIPO_OPENCODE_ROOT": pins()["opencode"]["box"], "EQUIPO_BOX_UID": str(os.getuid()), "EQUIPO_BOX_GID": str(os.getgid()), } if tool == "podman" and os.getuid() != 0: # Rootless podman, a developer's machine: its root is the caller, and # any other user inside could not write the checkout. Tests then run # as that root, which is good for a first look and not for a verdict. env["EQUIPO_BOX_UID"] = env["EQUIPO_BOX_GID"] = "0" for name, value in os.environ.items(): if name in PASS_NAMES or name.startswith(PASS_PREFIXES): env.setdefault(name, value) for name in sorted(env): args += ["-e", name + "=" + env[name]] args += [pins()["image"], WORK + "/scripts/ci-box-enter.sh"] + command os.execvp(args[0], args) # The Go caches. def tree_size(path): total = files = 0 for directory, _, names in os.walk(path): for name in names: try: total += os.lstat(os.path.join(directory, name)).st_size files += 1 except OSError: pass return total, files def cache(): """Report the caches and, past CACHE_LIMIT, drop what this job did not read. A restore stamps every entry "now", so Go's own five-day trim never fires on a hosted machine and the cache would grow until its save is refused.""" if not boxed(): return # a runner host's cache is its own to trim gocache, gomodcache = go_env("GOCACHE"), go_env("GOMODCACHE") for name, path in (("build cache", gocache), ("module cache", gomodcache)): size, files = tree_size(path) say("%s %s: %.2f GiB in %d files" % (name, path, size / 1024 ** 3, files)) size, _ = tree_size(gocache) marker = os.path.join(box_dir(), "prepared") if size <= CACHE_LIMIT or not os.path.exists(marker): return since = os.stat(marker).st_mtime dropped = kept = 0 for directory, _, names in os.walk(gocache): for name in names: path = os.path.join(directory, name) try: st = os.lstat(path) if max(st.st_atime, st.st_mtime) < since: os.unlink(path) dropped += st.st_size else: kept += st.st_size except OSError: pass say("build cache over %.1f GiB: dropped %.2f GiB this job did not read, kept %.2f GiB" % (CACHE_LIMIT / 1024 ** 3, dropped / 1024 ** 3, kept / 1024 ** 3)) def cold_start(): """Empty the restored build cache when the commit carries .amadan/cold: a scratch branch's way to measure a cold run, where every shard compiles and no test result replays. Only on a hosted CI machine, whose cache is a copy; never commit the file to main.""" if not os.path.exists(COLD): return gocache = go_env("GOCACHE") size, files = tree_size(gocache) for name in os.listdir(gocache) if os.path.isdir(gocache) else []: path = os.path.join(gocache, name) if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path, ignore_errors=True) else: os.unlink(path) say("cold run (.amadan/cold): emptied the build cache, %.2f GiB in %d files" % (size / 1024 ** 3, files)) def facts(): def out(*command): try: return subprocess.check_output(list(command), stderr=subprocess.STDOUT, text=True).strip() except Exception as e: return "unavailable (%s)" % e memory = "unknown" try: with open("/proc/meminfo") as f: memory = "%.0f GiB" % (int(f.readline().split()[1]) / 1024 ** 2) except OSError: pass say("machine: %s, %s CPUs, %s memory, kernel %s" % (platform.machine(), os.cpu_count(), memory, platform.release())) say("python %s; %s" % (platform.python_version(), out(engine(), "--version"))) say("user namespaces allowed: " + out("cat", "/proc/sys/user/max_user_namespaces")) say("cgroup: " + out("stat", "-fc", "%T", "/sys/fs/cgroup")) for path in (ROOT, box_dir()): say("disk %s: %s" % (path, out("df", "-h", "--output=fstype,size,avail", path).replace("\n", " | "))) def prepare(): if not boxed(): return # a runner host: nothing to fetch started = time.time() facts() with ThreadPoolExecutor(max_workers=3) as pool: image = pool.submit(pull_image) chromium = pool.submit(fetch_chromium) fetch_tools() say(install_pi()) say(install_opencode()) say(chromium.result()) image.result() if os.environ.get("AMADAN_CI") == "1": deepen() set_file_times() cold_start() with open(os.path.join(box_dir(), "prepared"), "w") as f: f.write("%d\n" % time.time()) say("ready in %.1fs" % (time.time() - started)) def main(argv): if argv == ["prepare"]: return prepare() if argv[:1] == ["run"]: return run(argv[1:]) if argv == ["cache"]: return cache() if argv == ["facts"]: return facts() print(__doc__, file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))