diff --git a/.github/scripts/fork-ci-release.test.py b/.github/scripts/fork-ci-release.test.py index a4a98ca33eb1..8ba5d0e358ef 100644 --- a/.github/scripts/fork-ci-release.test.py +++ b/.github/scripts/fork-ci-release.test.py @@ -8,12 +8,15 @@ exits 1. Each row of the failure table (first release, re-run, half states, main moving, a push refused half-way) is one block below. """ +import atexit import contextlib import importlib.util import io import json import os import pathlib +import re +import shutil import subprocess import sys import tempfile @@ -39,6 +42,7 @@ def check(name, ok, detail=""): work = pathlib.Path(tempfile.mkdtemp(prefix="fork-ci-release-test-")) +atexit.register(shutil.rmtree, work, ignore_errors=True) # its release copies are tens of MB per run gitconfig = work / "gitconfig" gitconfig.write_text("[user]\n\tname = Test\n\temail = test@example.invalid\n[init]\n\tdefaultBranch = main\n" "[protocol \"file\"]\n\tallow = always\n") @@ -406,50 +410,80 @@ def unpacked(name): # passes them and fails every real install (heavy-install refused "capacity/capacity-rule.json is missing" on every # release after the capacity rule moved to packages/shared/src/capacity). Here the release's files are written to a # folder exactly as release_entries picks them, and each kit's installer, loaded from that folder, runs its own -# file check on it: the same list and the same path rules install uses. A new kit with an installer needs a row. +# file check (missing_sources, or kit_install's) on the --source its bootstrap passes; heavy also copies itself and +# runs its self-test, and desk stages the release and runs its self-test (both under a throwaway PREFIX), so a +# copied script that loads a file the release lacks fails here too. Every fork-kit folder needs a row in KITS or +# NO_INSTALLER, and each row must match what the kit's bootstrap runs. KIT_CHECK = r""" -import importlib.machinery, importlib.util, json, os, sys -top, kit, how = sys.argv[1:4] +import importlib.machinery, importlib.util, json, os, sys, tempfile +top, kit, how, installer, source = sys.argv[1:6] src = os.path.join(top, 'fork-kit', kit) +source = top if source == 'top' else src def load(rel, name): loader = importlib.machinery.SourceFileLoader(name, os.path.join(src, rel)) mod = importlib.util.module_from_spec(importlib.util.spec_from_loader(name, loader)) loader.exec_module(mod) return mod -installer = sys.argv[4] if len(sys.argv) > 4 else '' +failed = [] if how == 'kit_install': # agent-guards, cleaner, golive, schedule-kick: check_options' file part m = load(installer, 'kit_installer') inst, missing = m.INSTALLER, [] for rel in inst.source_files(): try: - inst.read_source(os.path.realpath(src), rel) + inst.read_source(os.path.realpath(source), rel) except m.kit_install.Refused as e: missing.append(f'{rel}: {e}') if not missing: - inst.check_same_installer(os.path.realpath(src)) -elif how == 'source_file': # heavy (check_options), model-guard (install): SOURCE_FILES through source_file - m = load(installer, 'kit_installer') - missing = [rel for rel in m.SOURCE_FILES if not os.path.isfile(m.source_file(src, rel))] -elif how == 'gh-apps': # copy_tool: SOURCE_FILES under the kit folder + inst.check_same_installer(os.path.realpath(source)) +elif how == 'gh-apps': # copy_tool's check sys.path.insert(0, os.path.join(src, 'lib')) from ghapps import install - missing = [rel for rel in install.SOURCE_FILES if not os.path.isfile(os.path.join(src, rel))] -elif how == 'desk': # install: missing_sources of the release's top folder - missing = load(installer, 'kit_installer').missing_sources(top) -elif how == 'pc-agents': # setup: CODE sources under the release's top folder - missing = [s for s in load(installer, 'kit_installer').k.CODE if not os.path.isfile(os.path.join(top, s))] -print(json.dumps(missing)) + missing = install.missing_sources(source) +else: # heavy (check_options), model-guard (install), desk (install), pc-agents (setup) + m = load(installer, 'kit_installer') + missing = m.missing_sources(source) +if how in ('heavy', 'desk') and not missing: + m.PREFIX, m.ROOT_UID = tempfile.mkdtemp(prefix=f'prefix-{kit}-', dir=os.getcwd()), os.geteuid() + if how == 'heavy': # install's copy and self-test steps + os.makedirs(m.p(m.VERSIONS)) + failed = m.self_test(m.copy_tool(os.path.realpath(source), '0' * 40)) + else: # install's stage step (its self-test), for the release config's first pool + # The staged scripts run with os.getppid() == 1, so fork-fleet.py's gate (which refuses here) never finds the + # Runner.Worker of the CI job running this test, and never kills it. + shim = os.path.join(m.PREFIX, 'no-parent.py') + with open(shim, 'w') as f: + f.write("import os, runpy, sys\nos.getppid = lambda: 1\nargs = sys.argv[1:]\n" + "while args[0] in ('-I', '-B'):\n args.pop(0)\nsys.argv = args\n" + "runpy.run_path(args[0], run_name='__main__')\n") + m.CMD['python3'] = [sys.executable, '-I', '-B', shim] + os.makedirs(m.p(m.OPT)) + with open(os.path.join(source, '.github/fork-fleet.json')) as f: + pool = ([x.get('name') for x in json.load(f).get('pools') or [] if isinstance(x, dict)] or [''])[0] + try: + m.stage(source, '0' * 40, None, pool) + except m.Refused as e: + failed = [str(e)] +print(json.dumps({'missing': missing, 'failed': failed})) """ -# kit -> (how its installer checks its files, the installer as the bootstrap runs it) -KITS = {"agent-guards": ("kit_install", "sbin/agent-guards-install"), - "cleaner": ("kit_install", "sbin/fork-cleaner-install"), - "golive": ("kit_install", "sbin/t3-golive-install"), - "schedule-kick": ("kit_install", "sbin/schedule-kick-install"), - "heavy": ("source_file", "sbin/heavy-install"), - "model-guard": ("source_file", "sbin/model-guard-install"), - "gh-apps": ("gh-apps", "sbin/gh-apps-install"), - "desk": ("desk", "sbin/desk-install"), - "pc-agents": ("pc-agents", "sbin/pc-agents")} +# kit -> (how its installer checks its files, the installer as the bootstrap runs it, the --source the bootstrap +# passes: the kit's folder or the release's top folder) +KITS = {"agent-guards": ("kit_install", "sbin/agent-guards-install", "kit"), + "cleaner": ("kit_install", "sbin/fork-cleaner-install", "kit"), + "golive": ("kit_install", "sbin/t3-golive-install", "kit"), + "schedule-kick": ("kit_install", "sbin/schedule-kick-install", "kit"), + "heavy": ("heavy", "sbin/heavy-install", "kit"), + "model-guard": ("own", "sbin/model-guard-install", "kit"), + "gh-apps": ("gh-apps", "sbin/gh-apps-install", "kit"), + "desk": ("desk", "sbin/desk-install", "top"), + "pc-agents": ("own", "sbin/pc-agents", "top")} +# fork-kit folders that install nothing on a host +NO_INSTALLER = {"common": "the code and the bootstrap the kits share", "review": "a skill an agent reads"} +# What each kind of failure asks for +CAUSES = {"path": "add the path(s) to .github/fork-ci-release.json paths", + "self-test": "the installer's own self-test failed on the release: a file a copied script loads is not in " + "the release (add it to .github/fork-ci-release.json paths) or the kit is broken", + "row": "add or fix the kit's row in KITS or NO_INSTALLER of .github/scripts/fork-ci-release.test.py", + "ran": "the check did not run: fix the installer, or the kit's row in KITS"} def write_release(repo, entries, dest): @@ -468,36 +502,98 @@ def write_release(repo, entries, dest): os.chmod(p, 0o755 if mode == "100755" else 0o644) +def bootstrap_runs(top, kit): + """(the installer's path in the release, "kit" or "top" for its --source) as the kit's bootstrap runs it: its own + bootstrap.sh, else its arm in the shared fork-kit/common/bootstrap.sh; None when no bootstrap names the kit.""" + own = top / "fork-kit" / kit / "bootstrap.sh" + shared = top / "fork-kit/common/bootstrap.sh" + if not own.is_file() and not shared.is_file(): + return None + text = (own if own.is_file() else shared).read_text() + names = {"top": ""} + if not own.is_file(): + arm = re.search(rf"^\s*{re.escape(kit)}\) installer='([^']+)'", text, re.M) + if not arm: + return None + names.update(kit=kit, installer=arm.group(1)) + + def expand(s): + return re.sub(r"\$\{?(\w+)\}?", lambda m: names.get(m.group(1), m.group(0)), s).strip("/") + + for name, value in re.findall(r'^(\w+)="(\$top[^"]*)"$', text, re.M): + names[name] = "/" + expand(value) + run, source = re.search(r'python3 -I -B "([^"]+)"', text), re.search(r'--source "([^"]+)"', text) + if not run or not source: + return None + where = expand(source.group(1)) + return expand(run.group(1)), {"": "top", f"fork-kit/{kit}": "kit"}.get(where, where) + + def kit_release_problems(top): - """{kit: [what its installer misses in the release at TOP]}, plus kits with an installer and no row.""" + """{kit: [(cause, text)]} for the release at TOP: what each kit's installer misses or fails on, and kit folders + with no row or a row that does not match the bootstrap. cause is a key of CAUSES.""" problems = {} for kit_dir in sorted((top / "fork-kit").iterdir()) if (top / "fork-kit").is_dir() else []: - if (kit_dir / "sbin").is_dir() and kit_dir.name not in KITS: - problems[kit_dir.name] = ["has an installer (sbin/) but no row in KITS of fork-ci-release.test.py"] - for kit, (how, installer) in KITS.items(): + if not kit_dir.is_dir(): + continue + if kit_dir.name not in KITS and kit_dir.name not in NO_INSTALLER: + problems[kit_dir.name] = [("row", "a fork-kit folder with no row in KITS or NO_INSTALLER")] + elif kit_dir.name in NO_INSTALLER and ((kit_dir / "sbin").is_dir() or ( + kit_dir.name != "common" and (kit_dir / "bootstrap.sh").is_file())): + problems[kit_dir.name] = [("row", "listed in NO_INSTALLER but has an installer (sbin/ or bootstrap.sh)")] + for kit, (how, installer, source) in KITS.items(): + found = [] if not (top / "fork-kit" / kit / installer).is_file(): - problems[kit] = [f"fork-kit/{kit}/{installer} is not in the release"] + problems[kit] = [("path", f"fork-kit/{kit}/{installer} is not in the release")] continue - r = subprocess.run([sys.executable, "-I", "-B", "-c", KIT_CHECK, str(top), kit, how, installer], + runs = bootstrap_runs(top, kit) + if runs != (f"fork-kit/{kit}/{installer}", source): + found.append(("row", f"its bootstrap runs {runs[0]} --source {runs[1] or 'top'}, the row says " + f"fork-kit/{kit}/{installer} --source {source}" if runs else + "no bootstrap runs its installer with --source")) + r = subprocess.run([sys.executable, "-I", "-B", "-c", KIT_CHECK, str(top), kit, how, installer, source], capture_output=True, text=True, cwd=work) try: - missing = json.loads(r.stdout) if r.returncode == 0 else None - except ValueError: - missing = None - if missing is None: - problems[kit] = [f"its file check failed to run: {(r.stderr or r.stdout).strip()[-400:]}"] - elif missing: - problems[kit] = missing + got = json.loads(r.stdout.strip().splitlines()[-1]) if r.returncode == 0 else None + except (ValueError, IndexError): + got = None + if got is None: + found.append(("ran", f"its file check failed to run: {(r.stderr or r.stdout).strip()[-400:]}")) + else: + found += [("path", m) for m in got["missing"]] + [("self-test", f) for f in got["failed"]] + if found: + problems[kit] = found return problems +def kit_failure_text(found): + """One kit's problems, each kind of cause followed once by what it asks for.""" + causes = list(dict.fromkeys(c for c, _ in found)) + return " | ".join("; ".join(t for c, t in found if c == cause)[:1500] + f" ({CAUSES[cause]})" for cause in causes) + + +def mutated_release(name, change): + """A copy of the release at rel_top, changed by CHANGE(folder).""" + dest = work / name + shutil.copytree(rel_top, dest, symlinks=True) + change(dest) + return dest + + +def edit(path, old, new): + text = path.read_text() + if old not in text: + raise RuntimeError(f"{path}: {old!r} not found (the mutation needs updating)") + path.write_text(text.replace(old, new, 1)) + + if real_ok: rel_top = work / "release-of-head" write_release(root, entries, rel_top) kit_problems = kit_release_problems(rel_top) for kit in sorted(set(KITS) | set(kit_problems)): check(f"release holds what the {kit} kit's installer reads", kit not in kit_problems, - "; ".join(kit_problems.get(kit, []))[:1500] + " (add the path(s) to .github/fork-ci-release.json paths)") + kit_failure_text(kit_problems.get(kit, []))) else: check("release holds what each kit's installer reads (the release tree above was refused)", False, why) # The check itself: a kit whose file is not in the release fails (heavy without its capacity files, as on ci/v21). @@ -505,8 +601,49 @@ def kit_release_problems(top): mutated = work / "release-without-capacity" write_release(root, [e for e in entries if not e[2].startswith("packages/shared/src/capacity/")], mutated) caught = kit_release_problems(mutated).get("heavy", []) - check("release check: a release without packages/shared/src/capacity fails the heavy kit", - any("capacity/capacity-rule.json" in m for m in caught), str(caught)) + check("release check: a release without packages/shared/src/capacity fails the heavy kit, asking for the path", + ("path", "capacity/capacity-rule.json") in caught and CAUSES["path"] in kit_failure_text(caught), str(caught)) + + # Each installer's own missing_sources is what runs (not a copy of it in this test). + DRIFT = "\n\ndef missing_sources(source):\n return ['drift-sentinel']\n" + OWN = {"heavy": "sbin/heavy-install", "model-guard": "sbin/model-guard-install", "desk": "sbin/desk-install", + "pc-agents": "sbin/pc-agents", "gh-apps": "lib/ghapps/install.py"} + + def drift(top): + for kit, rel_path in OWN.items(): + with open(top / "fork-kit" / kit / rel_path, "a") as f: + f.write(DRIFT) + (top / "fork-kit/newkit").mkdir() + (top / "fork-kit/newkit/bootstrap.sh").write_text("#!/bin/sh\n") + edit(top / "fork-kit/model-guard/bootstrap.sh", '--source "$kit"', '--source "$top"') + + caught = kit_release_problems(mutated_release("release-drift", drift)) + for kit in OWN: + check(f"release check: the {kit} row runs the installer's own missing_sources", + ("path", "drift-sentinel") in caught.get(kit, []), str(caught.get(kit))) + check("release check: a kit folder with only a bootstrap.sh and no row fails, asking for a row (not a path)", + [c for c, _ in caught.get("newkit", [])] == ["row"] and CAUSES["row"] in kit_failure_text(caught["newkit"]) + and CAUSES["path"] not in kit_failure_text(caught["newkit"]), str(caught.get("newkit"))) + check("release check: a bootstrap that passes another --source than its row fails, asking for the row", + any(c == "row" and "--source top" in t for c, t in caught.get("model-guard", [])), + str(caught.get("model-guard"))) + + # The installers' copy, staging and self-test run on the release, and a check that cannot run says so. + def loads_more(top): + extra = "import os\nopen(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'not-in-release.txt'))\n" + edit(top / "fork-kit/heavy/bin/heavy", '"""heavy:', extra + '"""heavy:') + agent = top / ".github/scripts/fork-fleet-desk-agent.py" + agent.write_text(extra + agent.read_text()) + (top / "fork-kit/agent-guards/sbin/agent-guards-install").write_text("this is not python\n") + + caught = kit_release_problems(mutated_release("release-loads-more", loads_more)) + for kit, says in (("heavy", "bin/heavy --help failed"), ("desk", "fork-fleet-desk-agent.py --help fails")): + check(f"release check: a copied {kit} script that loads a file the release lacks fails the {kit} self-test", + any(c == "self-test" and says in t for c, t in caught.get(kit, [])) + and CAUSES["self-test"] in kit_failure_text(caught[kit]), str(caught.get(kit))[:1500]) + check("release check: an installer that cannot run fails as 'did not run', not as a missing path", + [c for c, _ in caught.get("agent-guards", [])] == ["ran"] + and CAUSES["path"] not in kit_failure_text(caught["agent-guards"]), str(caught.get("agent-guards"))) for bad in ("/abs", "a/../b", "dir/", ""): t = work / f"cfg-{abs(hash(bad))}.json" diff --git a/fork-ci/README.md b/fork-ci/README.md index cc6559c1481b..3099828a88ea 100644 --- a/fork-ci/README.md +++ b/fork-ci/README.md @@ -39,8 +39,9 @@ read from outside `fork-kit/` (the desk kit's fleet scripts and units, the heavy `.github/scripts/fork-fleet.py`) and the reusable workflows that start only on `workflow_call` (the list is `paths` in [`.github/fork-ci-release.json`](../.github/fork-ci-release.json)). The paths are the same as on main. Release commits contain no symlinks and no workflow that starts by itself. `fork-ci-release.test.py` writes this -commit's release files to a folder and runs each kit installer's file check on it, so a kit that reads a file outside -the paths fails CI. +commit's release files to a folder and runs each kit installer's own file check on it, with the `--source` the kit's +bootstrap passes (heavy also copies itself and desk stages the release, each with its self-test), so a kit that reads +a file outside the paths fails CI. Every `fork-kit/` folder needs a row in that test (`KITS`, or `NO_INSTALLER`). ## Using the actions diff --git a/fork-kit/gh-apps/lib/ghapps/install.py b/fork-kit/gh-apps/lib/ghapps/install.py index ee94120118be..8aef695db76a 100644 --- a/fork-kit/gh-apps/lib/ghapps/install.py +++ b/fork-kit/gh-apps/lib/ghapps/install.py @@ -248,10 +248,16 @@ def tree_problems(folder): return problems +def missing_sources(source): + """The SOURCE_FILES that SOURCE lacks; [] when it has them all. + .github/scripts/fork-ci-release.test.py runs it on the files a release commit holds.""" + return [rel for rel in SOURCE_FILES if not os.path.isfile(os.path.join(source, rel))] + + def copy_tool(ops, source, sha): - for rel in SOURCE_FILES: - if not os.path.isfile(os.path.join(source, rel)): - raise Refused(f'--source {source}: {rel} is missing (point it at the fork-kit/gh-apps folder)') + missing = missing_sources(source) + if missing: + raise Refused(f'--source {source}: {missing[0]} is missing (point it at the fork-kit/gh-apps folder)') versions = c.p(c.VERSIONS) dest = os.path.join(versions, sha) if os.path.lexists(dest): diff --git a/fork-kit/gh-apps/tests/install.test.py b/fork-kit/gh-apps/tests/install.test.py index 0ca3bcf409a4..69de99eb0239 100644 --- a/fork-kit/gh-apps/tests/install.test.py +++ b/fork-kit/gh-apps/tests/install.test.py @@ -407,6 +407,8 @@ def test_source_missing_a_file_is_refused(self): for rel in install.SOURCE_FILES[:-1]: os.makedirs(os.path.dirname(os.path.join(src, rel)), exist_ok=True) shutil.copyfile(os.path.join(kf.KIT, rel), os.path.join(src, rel)) + self.assertEqual(install.missing_sources(src), ['README.md']) + self.assertEqual(install.missing_sources(kf.KIT), []) with self.assertRaisesRegex(Refused, 'README.md is missing'): self.quiet(install.install, src, SHA_A, 'agent', ops=self.ops) diff --git a/fork-kit/heavy/sbin/heavy-install b/fork-kit/heavy/sbin/heavy-install index 90c74b84f88f..f88bea858581 100755 --- a/fork-kit/heavy/sbin/heavy-install +++ b/fork-kit/heavy/sbin/heavy-install @@ -81,6 +81,12 @@ def source_file(source, rel): return os.path.join(source, rel) +def missing_sources(source): + """The SOURCE_FILES that SOURCE lacks (each looked up as copy_tool reads it); [] when it has them all. + .github/scripts/fork-ci-release.test.py runs it on the files a release commit holds.""" + return [rel for rel in SOURCE_FILES if not os.path.isfile(source_file(source, rel))] + + def say(msg): print(f'heavy-install: {msg}', flush=True) @@ -210,6 +216,18 @@ def copy_tool(source, sha): return dest +def self_test(dest): + """The copied version folder DEST is whole and its commands start from it; [] when they do.""" + problems = tree_problems(dest) + for args in (['--help'], ['sweep', '--help'], ['queue', '--help'], ['capacity', '--help'], + ['facts', '--help']): + r = subprocess.run([sys.executable, '-I', '-B', os.path.join(dest, 'bin', 'heavy'), *args], + capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) + if r.returncode != 0 or 'heavy' not in r.stdout: + problems.append(f'bin/heavy {" ".join(args)} failed: {(r.stderr or r.stdout).strip()[:200]}') + return problems + + def read_config(): try: with open(p(CONFIG), encoding='utf-8') as f: @@ -233,9 +251,9 @@ def slice_unit_text(name, limits): def check_options(a): if not SHA_RE.match(a.sha or ''): raise Refused('--sha must be the full 40-character release commit') - for rel in SOURCE_FILES: - if not os.path.isfile(source_file(a.source or '', rel)): - raise Refused(f'--source {a.source}: {rel} is missing (point it at the fork-kit/heavy folder)') + missing = missing_sources(a.source or '') + if missing: + raise Refused(f'--source {a.source}: {missing[0]} is missing (point it at the fork-kit/heavy folder)') if a.slice is not None and not SLICE_RE.match(a.slice): raise Refused(f'bad --slice {a.slice!r} (a unit name ending in .slice)') if a.grace is not None: @@ -356,13 +374,7 @@ def install(a, stop_after=None): done('folders') dest = copy_tool(os.path.realpath(a.source), a.sha) done('copy') - problems = tree_problems(dest) - for args in (['--help'], ['sweep', '--help'], ['queue', '--help'], ['capacity', '--help'], - ['facts', '--help']): - r = subprocess.run([sys.executable, '-I', '-B', os.path.join(dest, 'bin', 'heavy'), *args], - capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) - if r.returncode != 0 or 'heavy' not in r.stdout: - problems.append(f'bin/heavy {" ".join(args)} failed: {(r.stderr or r.stdout).strip()[:200]}') + problems = self_test(dest) if problems: raise Refused('the new copy failed its self-test (the version in use is unchanged):\n ' + '\n '.join(problems)) done('self-test') diff --git a/fork-kit/heavy/tests/install.test.py b/fork-kit/heavy/tests/install.test.py index d89d6a718ed8..66dc3d597375 100644 --- a/fork-kit/heavy/tests/install.test.py +++ b/fork-kit/heavy/tests/install.test.py @@ -458,6 +458,19 @@ def test_a_slice_unit_someone_else_wrote_is_not_overwritten(self): self.assertEqual(f.read(), '[Slice]\nMemoryMax=1G\n') self.assertEqual(self.install()[0], 0) # without limits: used as it is + def test_a_source_without_a_file_is_refused_before_anything_is_written(self): + self.assertEqual(self.m.missing_sources(KIT), []) + top = tempfile.mkdtemp(prefix='heavy-source-') # the kit alone: no fork-kit/common, no capacity rule + self.addCleanup(shutil.rmtree, top, ignore_errors=True) + src = os.path.join(top, 'fork-kit', 'heavy') + shutil.copytree(KIT, src) + missing = self.m.missing_sources(src) + self.assertEqual(missing, [r for r in self.m.SOURCE_FILES if r.startswith(('common/', 'capacity/'))]) + code, _, err = self.install(source=src) + self.assertEqual(code, 1, err) + self.assertIn(f'{missing[0]} is missing', err) + self.assertEqual(os.listdir(self.root), ['usr']) + def test_bad_options_are_refused(self): for extra in (['--slice', 'heavy'], ['--slice', '../x.slice'], ['--grace', '0'], ['--grace', 'soon'], ['--memory-max', '6 GB'], ['--cpu-weight', '0'], ['--swap-max', '1G']): diff --git a/fork-kit/model-guard/sbin/model-guard-install b/fork-kit/model-guard/sbin/model-guard-install index 98d4590bc078..92f198544d35 100755 --- a/fork-kit/model-guard/sbin/model-guard-install +++ b/fork-kit/model-guard/sbin/model-guard-install @@ -60,6 +60,12 @@ def source_file(source, rel): return os.path.join(source, rel) +def missing_sources(source): + """The SOURCE_FILES that SOURCE lacks (each looked up as copy_tool reads it); [] when it has them all. + .github/scripts/fork-ci-release.test.py runs it on the files a release commit holds.""" + return [rel for rel in SOURCE_FILES if not os.path.isfile(source_file(source, rel))] + + def sha256_file(path): with open(path, 'rb') as f: return hashlib.sha256(f.read()).hexdigest() @@ -306,9 +312,9 @@ def install(a, stop_after=None): raise Refused('run this as root') if not SHA_RE.match(a.sha or ''): raise Refused('--sha must be the full 40-character release commit') - for rel in SOURCE_FILES: - if not os.path.isfile(source_file(a.source or '', rel)): - raise Refused(f'--source {a.source}: {rel} is missing (point it at the fork-kit/model-guard folder)') + missing = missing_sources(a.source or '') + if missing: + raise Refused(f'--source {a.source}: {missing[0]} is missing (point it at the fork-kit/model-guard folder)') own = load_guard(OWN_LIB) check_old_state(own) check_policy(own) diff --git a/fork-kit/model-guard/tests/install.test.py b/fork-kit/model-guard/tests/install.test.py index 30aa17471dde..0605a6af7976 100644 --- a/fork-kit/model-guard/tests/install.test.py +++ b/fork-kit/model-guard/tests/install.test.py @@ -288,6 +288,19 @@ def test_leftovers_of_a_stopped_run_are_cleared(self): self.assertEqual(sorted(os.listdir(versions)), [SHA1, SHA2]) self.assertEqual(sorted(os.listdir(self.path('/usr/local/libexec/model-guard'))), ['current', 'versions']) + def test_a_source_without_a_file_is_refused_before_anything_is_written(self): + self.assertEqual(self.m.missing_sources(KIT), []) + top = tempfile.mkdtemp(prefix='model-guard-source-') # the kit alone: no fork-kit/common next to it + self.addCleanup(shutil.rmtree, top, ignore_errors=True) + src = os.path.join(top, 'fork-kit', 'model-guard') + shutil.copytree(KIT, src) + self.assertEqual(self.m.missing_sources(src), ['common/machine_file.py']) + before = self.snapshot() + code, _, err = self.install(source=src) + self.assertEqual(code, 1, err) + self.assertIn('common/machine_file.py is missing', err) + self.assertEqual(self.snapshot(), before) + def test_foreign_link_is_refused_before_anything_is_written(self): self.turn_on() os.makedirs(self.path('/usr/local/bin')) diff --git a/fork-kit/pc-agents/sbin/pc-agents b/fork-kit/pc-agents/sbin/pc-agents index 518f89ff9b88..f9a42c4fb38e 100755 --- a/fork-kit/pc-agents/sbin/pc-agents +++ b/fork-kit/pc-agents/sbin/pc-agents @@ -442,6 +442,12 @@ def install_packages(): return None +def missing_sources(source): + """The code files of a release that setup copies and SOURCE (the release's top folder) lacks; [] when it has them + all. .github/scripts/fork-ci-release.test.py runs it on the files a release commit holds.""" + return [src for src in k.CODE if not os.path.isfile(os.path.join(source, src))] + + def setup(source, sha): """Make or repair everything from the release sha. source: its files (a checkout), or None for the release folder setup installed before (the automatic update reruns setup from the installed kit, never from new code).""" @@ -451,6 +457,10 @@ def setup(source, sha): if not k.ROOT and os.geteuid() != 0: return say('run this as root') or 2 os.umask(0o022) + missing = [] if source is None else missing_sources(source) + if missing: + return say(f'refused, nothing changed: --source {source}: {missing[0]} is missing (point it at the release\'s ' + 'top folder)') or 1 try: c = k.config() except machine_file.MachineFileError as e: diff --git a/fork-kit/pc-agents/tests/setup.test.py b/fork-kit/pc-agents/tests/setup.test.py index f7a4a9712425..d35e635a747f 100644 --- a/fork-kit/pc-agents/tests/setup.test.py +++ b/fork-kit/pc-agents/tests/setup.test.py @@ -5,7 +5,7 @@ python3 -I -B fork-kit/pc-agents/tests/setup.test.py """ -import json, os, re, shutil, signal, stat, subprocess, sys, time, unittest +import json, os, re, shutil, signal, stat, subprocess, sys, tempfile, time, unittest from unittest import mock sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -863,16 +863,25 @@ def test_pair_runs_the_installed_t3_pair_as_the_agent(self): class Refused(Case): - def refused(self, why): + def refused(self, why, source=REPO): lock = ('/run', os.path.dirname(k.LOCK), k.LOCK) # the lock setup holds: a tmpfs file, gone at boot before = {p: v for p, v in self.snapshot().items() if p not in lock} - code, out = self.setup_run() + code, out = self.call(cli.main, ['setup', '--source', source, '--sha', SHA1]) self.assertEqual(code, 1, out) self.assertIn('refused, nothing changed', out) self.assertIn(why, out) self.assertEqual({p: v for p, v in self.snapshot().items() if p not in lock}, before) self.assertEqual(self.log(), []) + def test_a_source_without_a_code_file(self): # refused before any write, not half-way through the copy + with tempfile.TemporaryDirectory() as top: + for src in list(k.CODE)[:-1]: + os.makedirs(os.path.dirname(os.path.join(top, src)), exist_ok=True) + shutil.copyfile(os.path.join(REPO, src), os.path.join(top, src)) + self.assertEqual(cli.missing_sources(top), [list(k.CODE)[-1]]) + self.refused(f'{list(k.CODE)[-1]} is missing', source=top) + self.assertEqual(cli.missing_sources(REPO), []) + def test_a_distro_with_its_own_user(self): with open(self.path('/etc/passwd'), 'a') as f: f.write('someone:x:1000:1000::/home/someone:/bin/bash\n')