Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
221 changes: 179 additions & 42 deletions .github/scripts/fork-ci-release.test.py

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions fork-ci/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
12 changes: 9 additions & 3 deletions fork-kit/gh-apps/lib/ghapps/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions fork-kit/gh-apps/tests/install.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
32 changes: 22 additions & 10 deletions fork-kit/heavy/sbin/heavy-install
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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')
Expand Down
13 changes: 13 additions & 0 deletions fork-kit/heavy/tests/install.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']):
Expand Down
12 changes: 9 additions & 3 deletions fork-kit/model-guard/sbin/model-guard-install
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
13 changes: 13 additions & 0 deletions fork-kit/model-guard/tests/install.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
10 changes: 10 additions & 0 deletions fork-kit/pc-agents/sbin/pc-agents
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand All @@ -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:
Expand Down
15 changes: 12 additions & 3 deletions fork-kit/pc-agents/tests/setup.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)))
Expand Down Expand Up @@ -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')
Expand Down
Loading