diff --git a/.github/scripts/fork-contracts.test.py b/.github/scripts/fork-contracts.test.py index 004b97d8ae225..1c6f618ff26d4 100644 --- a/.github/scripts/fork-contracts.test.py +++ b/.github/scripts/fork-contracts.test.py @@ -4175,6 +4175,9 @@ def result_step(jobs, name): "fork-ci/actions/head-check/review_guide.test.py": ["ReleaseTags." + t for t in ( "test_override_authors_is_first_in_the_release_after_the_one_the_notes_name", "test_the_path_rules_are_first_in_the_release_the_guide_names")], + # Runs an older release's installer, found by its ci/vN tag; CI's checkout fetches none. + "fork-kit/heavy/tests/install.test.py": [ + "Install.test_older_installers_install_and_uninstall_keep_the_hosts_t3_capacity"], } check("records: the tests a part run may skip are exactly the pinned ones, each by name (MAY_SKIP)", {f: sorted(n) if isinstance(n, list) else n for f, n in DECLARED_SKIPS.items()} == MAY_SKIP, diff --git a/fork-kit/heavy/README.md b/fork-kit/heavy/README.md index aacbf83ad0c9e..4d177b59484ab 100644 --- a/fork-kit/heavy/README.md +++ b/fork-kit/heavy/README.md @@ -19,7 +19,7 @@ Linux with systemd (user manager) and cgroup v2 only. Python 3 standard library | ---------------------------- | -------------------------------------------------------------------------------------------- | | `heavy [args...]` | runs the command in `heavy--.scope` in the slice; stops leftovers when it ends | | `HEAVY_KEEP=1 heavy ` | the same in `heavy-keep--.scope`, but leftovers keep running (a daemon) | -| `heavy --self-check` | checks the config, that the slice has a unit with a memory limit, and the installed files | +| `heavy --self-check` | checks the config, the slice's limit and the installed files; warns on another `t3-capacity` | | `systemctl --user stop UNIT` | stops what `HEAVY_KEEP=1` kept (the name is in heavy's message) | | `heavy sweep [--dry-run]` | one leftover sweep (below); the user timer runs it every 5 minutes | | `heavy sweep --json` | looks only: what a sweep would stop or report, as JSON | @@ -569,13 +569,17 @@ after another, up to the group's ceiling), the memory budget, the queue and note cache folder nothing carries, so every call starts "elevated" (only the rule's floors admit; never straight to "ok"). -Two thin callers come with it (not linked onto PATH: a host wires them in itself): +Two thin callers come with it: - `bin/t3-capacity [--kind KIND] [MB]`: the older host check's output (first line `available=..MB swapfree=..MB load=..`, available less the rule's whole reservation hold, last line `OK` or `NOT OK: why`, exit 0 or 1), now - from `heavy facts`. MB defaults to 3072. -- `bin/agent-slots`: a Claude Code hook (UserPromptSubmit, Stop) for orchestrator sessions: free agent slots are - the smaller of the process limit and the machine's `fits` for its kind. + from `heavy facts`. MB defaults to 3072. The installer links `/usr/local/bin/t3-capacity` to it, so the command + has one source, the release in use (a host's own plain copy there only with `--replace-t3-capacity`: Install, + below); `heavy --self-check` warns when the `t3-capacity` found on PATH is another copy (its readings can differ: + an older copy, for one, counts no reservations). +- `bin/agent-slots` (not linked onto PATH: a host wires it in itself): a Claude Code hook (UserPromptSubmit, Stop) + for orchestrator sessions: free agent slots are the smaller of the process limit and the machine's `fits` for + its kind. A `heavy facts` that does not answer within 5 s (it is killed), fails or prints something else is never free for either caller. @@ -645,9 +649,11 @@ limit options. A user's own unit in `~/.config/systemd/user/` wins over the one | ----------------------------------------------- | ------------------------------------------------------------------------- | | `/usr/local/bin/heavy` | link to `current/bin/heavy` | | `/usr/local/sbin/heavy-install` | link to `current/sbin/heavy-install` | +| `/usr/local/bin/t3-capacity` | link to `current/bin/t3-capacity` | | `/usr/local/libexec/heavy/versions//` | the code of one release, with `MANIFEST.sha256` (root 755) | | `/usr/local/libexec/heavy/current` | link to the release in use (switched in one step) | | `/usr/local/libexec/heavy/replaced/` | a plain `/usr/local/bin/heavy` from before the kit, put back on uninstall | +| `/usr/local/libexec/heavy-kept/` | a plain `/usr/local/bin/t3-capacity` (a host's copy), put back likewise | | `/etc/heavy/config.json` | slice name and grace time | | `/etc/heavy/installed.tsv` | every installed path with its link target or hash (`--self-check`) | | `/etc/systemd/user/` | only with limit options: the slice unit | @@ -674,17 +680,30 @@ It prints the sha, the hash of the download and every installed path. Add `--sli runs `systemctl --user daemon-reload`). Add `--sweep-timer` to install the leftover sweep's user units (each user then runs `systemctl --user daemon-reload && systemctl --user enable --now heavy-sweep.timer`; `--no-sweep-timer` removes them again). Upgrade: the same line again. Remove: -`/usr/local/sbin/heavy-install uninstall` (puts an old plain `/usr/local/bin/heavy` back). Check: -`heavy --self-check` (as the user: config, slice and files) or `heavy-install self-check` (files only). +`/usr/local/sbin/heavy-install uninstall` (puts an old plain `/usr/local/bin/heavy` and `/usr/local/bin/t3-capacity` +back). Check: `heavy --self-check` (as the user: config, slice and files, and a warning when `t3-capacity` on the +user's PATH is not the kit's) or `heavy-install self-check` (files only). + +`/usr/local/bin/t3-capacity`: with nothing there, or the kit's link, the installer links it. A plain file there is a +host's own copy, which the host's scripts may read or compare: the installer leaves it as it is and says so (in a +note and again in its closing `installed release` line), until it is run once with `--replace-t3-capacity` (it +keeps the copy in `/usr/local/libexec/heavy-kept/`, links the kit's, and later runs keep the link without the +option). A link there that the kit did not make is left alone the same way; with `--replace-t3-capacity` it is +refused (remove it by hand first: there is no file to keep). A host whose own installer wrote that copy first changes it to stop writing +that path and to run `heavy-install` (or check that the path is the link to +`/usr/local/libexec/heavy/current/bin/t3-capacity`): a copy over the link would land in the release's own folder +(`heavy-install self-check` then says `changed since install`), and one written beside it and renamed over it puts +a plain copy back (`heavy --self-check` says the link differs and warns about the copy). ## Runs again, stops half-way, old or empty state - **Runs again:** every step checks what is there and only fixes what differs; a second run changes nothing. - **Stops half-way:** the steps run in this order: check, folders, copy, self-test, config, slice unit, switch, links, sweep units, record. A version folder is copied to a temporary name and renamed; a half-copied or changed - one is made again. The old `/usr/local/bin/heavy` keeps working until the links step, which copies it to - `replaced/` before the link replaces it. The sweep's units are written only after that, so a timer never runs - before the release it needs is in use. Running the same line again finishes the job. + one is made again. The old `/usr/local/bin/heavy` and `/usr/local/bin/t3-capacity` keep working until the links + step, which copies each to its kept folder before its link replaces it in one rename. The sweep's units are + written only after that, so a timer never runs before the release it needs is in use. Running the same line again + finishes the job. - **Rollback:** the timer's service runs `/usr/local/libexec/heavy/current/lib/heavy_sweep.py` (the sweep of the release in use, never an older `heavy` without the `sweep` verb), and only when that file exists. Before going back to a release without the sweep, run the newer installer with `--no-sweep-timer`; if you did not, the @@ -697,10 +716,21 @@ removes them again). Upgrade: the same line again. Remove: - **Rollback past the memory queue:** remove the `queue` key from the machine file's `heavy` section first. A release from before the queue does not know it: its sweep refuses the whole machine file and says which key. That release cannot be changed from here, so the order is the guard: key out, then the older release. +- **Rollback past the `t3-capacity` link:** an older installer leaves `/usr/local/bin/t3-capacity` as it is, a link + to `current/bin/t3-capacity`; every release since `heavy facts` has that file. Before going back further, run + `heavy-install uninstall` (it puts the old copy back). The old copy is kept in `/usr/local/libexec/heavy-kept/`, + outside `/usr/local/libexec/heavy` and `/etc/heavy`, because an older installer's uninstall deletes those two + folders whole (and puts the newest file of `replaced/` back as `heavy`). That older uninstall does not know the + `t3-capacity` link, so it leaves it broken (every `t3-capacity N && …` gate then fails): run this release's + `sbin/heavy-install uninstall` from its source folder, as root, which removes the broken link and puts the kept + copy back, or install again. - **Old state:** a plain-file `/usr/local/bin/heavy` (the one-line wrapper from before) is kept and put back by - uninstall. A link there that points elsewhere, a folder where the kit expects its own, or a slice unit in - `/etc/systemd/user/` the kit did not write is refused with a message, never overwritten. Config values stay - unless an option names a new one. + uninstall; a plain `/usr/local/bin/t3-capacity` (a host's own copy) is left alone, or with `--replace-t3-capacity` + kept and put back by uninstall. A link at `t3-capacity` that points elsewhere is left alone (refused with + `--replace-t3-capacity`). A link at `heavy` or `heavy-install` that points elsewhere, a folder where the kit + expects its own, or a slice unit in `/etc/systemd/user/` the kit did not write is refused with a message, never + overwritten. Config + values stay unless an option names a new one. - **Empty state:** a fresh machine installs with the defaults. heavy then refuses to run commands until the slice has a unit with a memory limit (install with limit options, or add the unit). diff --git a/fork-kit/heavy/bin/heavy b/fork-kit/heavy/bin/heavy index 7c1484b88b1ff..f3028010313ec 100755 --- a/fork-kit/heavy/bin/heavy +++ b/fork-kit/heavy/bin/heavy @@ -3,7 +3,8 @@ heavy [args...] run in its own scope in the slice, wait for it, stop the scope HEAVY_KEEP=1 heavy the same, but processes the command leaves running are kept (a daemon) - heavy --self-check check the config, the slice and the installed files; exit 1 on a problem + heavy --self-check check the config, the slice and the installed files (exit 1 on a problem), and + warn when the t3-capacity on PATH is not this kit's heavy sweep [--dry-run|--json] stop or report what commands left behind outside heavy (lib/heavy_sweep.py) heavy leftovers [--older-than AGE] [--json] look only: what is left behind (processes, heavy scopes, containers) older @@ -1059,6 +1060,20 @@ def sha256_file(path): return h.hexdigest() +def capacity_on_path(): + """None when the `t3-capacity` found on PATH is this kit's bin/t3-capacity (links resolved), else why not. Only a + warning: a host may wire the command in itself, but another copy's readings can differ from the kit's.""" + import shutil + kit = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'bin', 't3-capacity') + found = shutil.which('t3-capacity') + if found is None: + return f't3-capacity is not on PATH (this kit\'s is {kit}; heavy-install links /usr/local/bin/t3-capacity)' + if os.path.realpath(found) != os.path.realpath(kit): + return (f't3-capacity on PATH is {found}, not this kit\'s {kit}: its readings can differ from the kit\'s ' + f'(heavy-install links /usr/local/bin/t3-capacity; remove the other copy or put that folder first)') + return None + + def self_check(): problems = [] try: @@ -1095,6 +1110,8 @@ def self_check(): problems.append(f'{path}: differs from what was installed ({kind})') if rows is not None: print(f'installed files: {len(rows)} checked') + warning = capacity_on_path() + print(f'WARNING: {warning}' if warning else 't3-capacity on PATH: this kit\'s') for p in problems: print(f'PROBLEM: {p}') print('self-check: ' + ('OK' if not problems else f'{len(problems)} problems')) diff --git a/fork-kit/heavy/sbin/heavy-install b/fork-kit/heavy/sbin/heavy-install index c8929bf23dbf3..90c74b84f88fe 100755 --- a/fork-kit/heavy/sbin/heavy-install +++ b/fork-kit/heavy/sbin/heavy-install @@ -3,19 +3,22 @@ heavy-install install --source KIT_FOLDER --sha RELEASE_SHA [--slice NAME] [--grace SECONDS] [--memory-high SIZE] [--memory-max SIZE] [--swap-max SIZE] [--cpu-weight N] - [--sweep-timer | --no-sweep-timer] + [--sweep-timer | --no-sweep-timer] [--replace-t3-capacity] heavy-install uninstall heavy-install self-check install copies bin/heavy, sbin/heavy-install, lib/, systemd/, README.md and fork-kit/common/machine_file.py of one release into /usr/local/libexec/heavy/versions// (with MANIFEST.sha256), checks the copy, switches the link `current` to it, -writes /etc/heavy/config.json and links /usr/local/bin/heavy and /usr/local/sbin/heavy-install to it. An old -/usr/local/bin/heavy that is a plain file (a copy from before this kit) is kept in /usr/local/libexec/heavy/replaced/ -and put back by uninstall. With a --memory-*, --swap-max or --cpu-weight option it also writes the slice unit -/etc/systemd/user/ (every user's manager reads it after `systemctl --user daemon-reload`; a user's own -~/.config/systemd/user/ wins over it). With --sweep-timer it also writes the user units heavy-sweep.service -and heavy-sweep.timer to /etc/systemd/user/ (each user enables the timer); --no-sweep-timer removes them. Safe to -run again, and to stop at any step. +writes /etc/heavy/config.json and links /usr/local/bin/heavy, /usr/local/bin/t3-capacity and +/usr/local/sbin/heavy-install to it. An old /usr/local/bin/heavy that is a plain file (a copy from before this kit) is +kept in /usr/local/libexec/heavy/replaced/ and put back by uninstall. A plain /usr/local/bin/t3-capacity (a host's +own copy, which its own scripts may read) or a link someone else made there is left alone, with a note, unless +--replace-t3-capacity is given: then a plain copy is kept in /usr/local/libexec/heavy-kept/ (outside the folders +every uninstall deletes, an older installer's too), linked, and put back by uninstall. With a --memory-*, +--swap-max or --cpu-weight option it also writes the slice unit /etc/systemd/user/ (every user's manager reads +it after `systemctl --user daemon-reload`; a user's own ~/.config/systemd/user/ wins over it). With +--sweep-timer it also writes the user units heavy-sweep.service and heavy-sweep.timer to /etc/systemd/user/ (each +user enables the timer); --no-sweep-timer removes them. Safe to run again, and to stop at any step. """ import argparse, contextlib, hashlib, json, os, re, shutil, stat, subprocess, sys, tempfile @@ -31,8 +34,15 @@ CURRENT = LIBEXEC + '/current' REPLACED = LIBEXEC + '/replaced' WRAPPER = '/usr/local/bin/heavy' INSTALLER = '/usr/local/sbin/heavy-install' +CAPACITY = '/usr/local/bin/t3-capacity' +# a plain old copy of t3-capacity has its own folder, outside LIBEXEC and ETC: an installer from before it restores +# the newest file of REPLACED as /usr/local/bin/heavy on uninstall (so a t3-capacity there could come back as heavy), +# and its uninstall deletes LIBEXEC and ETC whole (so a copy kept anywhere in them would be lost) +KEPT_CAPACITY = '/usr/local/libexec/heavy-kept' UNIT_DIR = '/etc/systemd/user' -LINKS = {WRAPPER: CURRENT + '/bin/heavy', INSTALLER: CURRENT + '/sbin/heavy-install'} +LINKS = {WRAPPER: CURRENT + '/bin/heavy', INSTALLER: CURRENT + '/sbin/heavy-install', + CAPACITY: CURRENT + '/bin/t3-capacity'} +KEPT = {WRAPPER: (REPLACED, 'heavy'), CAPACITY: (KEPT_CAPACITY, 't3-capacity')} # where a plain old file goes SOURCE_FILES = ('bin/heavy', 'sbin/heavy-install', 'README.md', 'lib/heavy_sweep.py', 'lib/heavy_queue.py', 'lib/heavy_measure.py', 'common/machine_file.py', 'systemd/heavy-sweep.service', @@ -249,17 +259,19 @@ def check_options(a): return limits -def check_old_state(): +def check_old_state(replace_capacity=False): """Refuse, before writing anything, what the installer must not overwrite.""" for path, target in LINKS.items(): real = p(path) if not os.path.lexists(real) or ours(path, target): continue - if path == WRAPPER and os.path.isfile(real) and not os.path.islink(real): - continue # a plain old copy: kept in REPLACED, put back by uninstall + if path in KEPT and os.path.isfile(real) and not os.path.islink(real): + continue # a plain old copy: kept in its KEPT folder, put back by uninstall + if path == CAPACITY and os.path.islink(real) and not replace_capacity: + continue # a host's own link: left alone, with a note (there is no file of ours to keep for it) raise Refused(f'{path} exists and is not the kit\'s link (a link elsewhere, or a folder): ' f'remove it by hand and run again') - for path in (ETC, LIBEXEC, VERSIONS, REPLACED): + for path in (ETC, LIBEXEC, VERSIONS, REPLACED, KEPT_CAPACITY): real = p(path) if os.path.lexists(real) and (os.path.islink(real) or not os.path.isdir(real)): raise Refused(f'{path} exists and is not a folder: remove it by hand and run again') @@ -267,19 +279,21 @@ def check_old_state(): raise Refused(f'{CURRENT} exists and is not a link: remove it by hand and run again') -def keep_old_wrapper(): - """A plain old /usr/local/bin/heavy goes to REPLACED (by its hash, so a second run copies nothing).""" - real = p(WRAPPER) - if not os.path.isfile(real) or os.path.islink(real): +def keep_old(path): + """A plain old file at a linked path (/usr/local/bin/heavy, /usr/local/bin/t3-capacity) goes to its KEPT folder + (by its hash, so a second run copies nothing). The file itself stays until its link replaces it in one step.""" + real = p(path) + if path not in KEPT or not os.path.isfile(real) or os.path.islink(real): return None - ensure_dir(REPLACED) + folder, name = KEPT[path] + ensure_dir(folder) digest = sha256_file(real) - dest = p(f'{REPLACED}/heavy.{digest[:16]}') + dest = p(f'{folder}/{name}.{digest[:16]}') if not os.path.exists(dest): tmp = dest + '.tmp' shutil.copy2(real, tmp) os.replace(tmp, dest) - say(f'the old {WRAPPER} (sha256 {digest[:16]}) is kept as {REPLACED}/heavy.{digest[:16]}') + say(f'the old {path} (sha256 {digest[:16]}) is kept as {folder}/{name}.{digest[:16]}') return dest @@ -297,7 +311,8 @@ def ours_unit(path): def record_rows(sha, unit_path, sweep_timer=False): - rows = [(path, 'link', target) for path, target in sorted(LINKS.items())] + rows = [(path, 'link', target) for path, target in sorted(LINKS.items()) + if path != CAPACITY or ours(path, target)] # a host's own t3-capacity left in place is not recorded rows.append((CURRENT, 'link', f'{VERSIONS}/{sha}')) folder = p(f'{VERSIONS}/{sha}') for rel, digest in sorted(read_manifest(folder).items()): @@ -318,7 +333,7 @@ def install(a, stop_after=None): if os.geteuid() != ROOT_UID: raise Refused('run this as root') limits = check_options(a) - check_old_state() + check_old_state(a.replace_t3_capacity) old = read_config() units_left = any(ours_unit(u) for u in sweep_unit_paths()) if a.sweep_timer is not None: @@ -376,8 +391,17 @@ def install(a, stop_after=None): done('slice-unit') switch_link(CURRENT, f'{VERSIONS}/{a.sha}') done('switch') - keep_old_wrapper() for path, target in LINKS.items(): + if path == CAPACITY and os.path.lexists(p(path)) and not ours(path, target) and not a.replace_t3_capacity: + if os.path.islink(p(path)): + say(f'note: {path} is a link this kit did not make (to {os.readlink(p(path))}): left as it is (its ' + f'readings can differ from the kit\'s; remove it and run again with --replace-t3-capacity to ' + f'link the kit\'s)') + else: + say(f'note: {path} is a plain file this kit did not write: left as it is (its readings can differ ' + f'from the kit\'s; --replace-t3-capacity keeps it in {KEPT_CAPACITY}/ and links the kit\'s)') + continue + keep_old(path) switch_link(path, target) done('links') # after the links: the timer is only written once the release it runs is the one in use @@ -400,7 +424,9 @@ def install(a, stop_after=None): + ''.join('\t'.join(r) + '\n' for r in rows)) done('record') say(f'installed release {a.sha}: slice {cfg["slice"]}, grace {cfg["grace_seconds"]:g}s' - + (', sweep timer units written' if sweep_timer else '')) + + (', sweep timer units written' if sweep_timer else '') + + ('' if ours(CAPACITY, LINKS[CAPACITY]) else + f'; WARNING: {CAPACITY} is still the host\'s own, not the kit\'s (--replace-t3-capacity switches it)')) for path, kind, want in rows: say(f' {path} {kind} {want}') return 0 @@ -415,15 +441,22 @@ def uninstall(): for path, target in LINKS.items(): if ours(path, target): os.unlink(p(path)) - backups = [] - if os.path.isdir(p(REPLACED)): - backups = sorted((os.path.join(p(REPLACED), n) for n in os.listdir(p(REPLACED)) if not n.endswith('.tmp')), - key=os.path.getmtime) - if backups and not os.path.lexists(p(WRAPPER)): - tmp = p(WRAPPER) + '.restore' - shutil.copy2(backups[-1], tmp) - os.replace(tmp, p(WRAPPER)) - say(f'put the old {WRAPPER} back') + for path, (folder, name) in KEPT.items(): + backups = [] + if os.path.isdir(p(folder)): + backups = sorted((os.path.join(p(folder), n) for n in os.listdir(p(folder)) + if n.startswith(name + '.') and not n.endswith('.tmp')), key=os.path.getmtime) + if backups and not os.path.lexists(p(path)): + tmp = p(path) + '.restore' + shutil.copy2(backups[-1], tmp) + os.replace(tmp, p(path)) + say(f'put the old {path} back') + if folder == KEPT_CAPACITY and backups: # outside LIBEXEC: removed only once its copy is back in place + if os.path.isfile(p(path)) and not os.path.islink(p(path)) \ + and sha256_file(p(path)) == sha256_file(backups[-1]): + shutil.rmtree(p(folder), ignore_errors=True) + else: + say(f'note: {path} is not the kept copy, so {folder}/ is left in place') for path in sweep_unit_paths(): if ours_unit(path): os.unlink(p(path)) @@ -479,6 +512,7 @@ def main(argv, stop_after=None): i.add_argument('--' + key.replace('_', '-'), dest=key) i.add_argument('--sweep-timer', dest='sweep_timer', action='store_true', default=None) i.add_argument('--no-sweep-timer', dest='sweep_timer', action='store_false') + i.add_argument('--replace-t3-capacity', action='store_true') sub.add_parser('uninstall') sub.add_parser('self-check') a = ap.parse_args(argv) diff --git a/fork-kit/heavy/tests/install.test.py b/fork-kit/heavy/tests/install.test.py index 1561000f4cf54..d89d6a718ed83 100644 --- a/fork-kit/heavy/tests/install.test.py +++ b/fork-kit/heavy/tests/install.test.py @@ -3,16 +3,21 @@ python3 -I -B fork-kit/heavy/tests/install.test.py """ +# CI's checkout is shallow without tags, so the test that runs an older release's installer skips there (it runs locally): +# fork-ci: may skip Install.test_older_installers_install_and_uninstall_keep_the_hosts_t3_capacity import contextlib, importlib.machinery, importlib.util, io, json, os, shutil, subprocess, sys, tempfile, unittest +OLDER_RELEASE = 'ci/v22' # a released installer from before the t3-capacity link (its uninstall is run below) + KIT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CAPACITY = os.path.join(os.path.dirname(os.path.dirname(KIT)), 'packages', 'shared', 'src', 'capacity') SHA1, SHA2 = 'a' * 40, 'b' * 40 OLD_WRAPPER = b'#!/bin/sh\nexec systemd-run --user --scope --quiet --slice=heavy.slice --collect -- "$@"\n' +OLD_CAPACITY = b'#!/bin/sh\necho "available=9999MB swapfree=9999MB load=0/4cores"; echo OK\n' # a host's own copy +CAPACITY_LINK = '/usr/local/libexec/heavy/current/bin/t3-capacity' -def load(): - path = os.path.join(KIT, 'sbin', 'heavy-install') +def load(path=os.path.join(KIT, 'sbin', 'heavy-install')): loader = importlib.machinery.SourceFileLoader('heavy_install', path) spec = importlib.util.spec_from_loader('heavy_install', loader) mod = importlib.util.module_from_spec(spec) @@ -36,11 +41,11 @@ def close(self): def path(self, p): return self.root + p - def run_main(self, *argv, stop_after=None): + def run_main(self, *argv, stop_after=None, m=None): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): try: - code = self.m.main(list(argv), stop_after=stop_after) + code = (m or self.m).main(list(argv), **({} if m else {'stop_after': stop_after})) except SystemExit as e: code = str(e) return code, out.getvalue(), err.getvalue() @@ -52,6 +57,35 @@ def config(self): with open(self.path('/etc/heavy/config.json')) as f: return json.load(f) + def write_old(self, path, data): + with open(self.path(path), 'wb') as f: + f.write(data) + os.chmod(self.path(path), 0o755) + + def resolve(self, path): + """Follow the installed (absolute, unprefixed) links in every part of path inside the fake root.""" + parts, done = path.strip('/').split('/'), '' + for _ in range(40): + if not parts: + return self.path(done) + here = f'{done}/{parts.pop(0)}' + if os.path.islink(self.path(here)): + target = os.readlink(self.path(here)) + self.assertTrue(target.startswith('/'), here) + parts, done = target.strip('/').split('/') + parts, '' + else: + done = here + raise AssertionError(f'{path}: too many links') + + def run_old_capacity(self): + """The command at /usr/local/bin/t3-capacity runs and is still the host's old copy.""" + real = self.path('/usr/local/bin/t3-capacity') + self.assertFalse(os.path.islink(real)) + with open(real, 'rb') as f: + self.assertEqual(f.read(), OLD_CAPACITY) + r = subprocess.run([real], capture_output=True, text=True, timeout=60) + self.assertEqual((r.returncode, r.stdout.splitlines()[-1]), (0, 'OK')) + def snapshot(self): """Every path under the fake root with its kind, mode, mtime and link target.""" out = {} @@ -106,6 +140,225 @@ def test_old_plain_wrapper_is_kept_and_put_back_by_uninstall(self): self.assertFalse(os.path.exists(self.path('/etc/heavy'))) self.assertEqual(self.run_main('uninstall')[0], 0) # again: nothing left, still fine + def test_fresh_install_links_t3_capacity_to_the_release(self): + code, out, err = self.install() + self.assertEqual(code, 0, err) + link = self.path('/usr/local/bin/t3-capacity') + self.assertEqual(os.readlink(link), CAPACITY_LINK) + self.assertEqual(self.resolve('/usr/local/bin/t3-capacity'), + self.path(f'/usr/local/libexec/heavy/versions/{SHA1}/bin/t3-capacity')) + with open(self.resolve('/usr/local/bin/t3-capacity'), 'rb') as f, \ + open(os.path.join(KIT, 'bin', 't3-capacity'), 'rb') as g: + self.assertEqual(f.read(), g.read()) + r = subprocess.run([sys.executable, '-I', '-B', self.resolve('/usr/local/bin/t3-capacity'), '--help'], + capture_output=True, text=True, timeout=60) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('t3-capacity [--kind KIND] [MB]', r.stdout) + with open(self.path('/etc/heavy/installed.tsv')) as f: + self.assertIn(f'/usr/local/bin/t3-capacity\tlink\t{CAPACITY_LINK}\n', f.read()) + self.assertEqual(self.run_main('self-check')[0], 0) + self.assertEqual(self.install(sha=SHA2)[0], 0) # an upgrade: the same link, the new release + self.assertEqual(self.resolve('/usr/local/bin/t3-capacity'), + self.path(f'/usr/local/libexec/heavy/versions/{SHA2}/bin/t3-capacity')) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy-kept'))) + self.assertEqual(self.run_main('uninstall')[0], 0) + self.assertFalse(os.path.lexists(link)) + + def test_old_plain_t3_capacity_is_left_alone_without_the_option(self): + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + code, out, err = self.install() + self.assertEqual(code, 0, err) + self.assertIn('note: /usr/local/bin/t3-capacity is a plain file this kit did not write: left as it is', out) + self.assertIn('--replace-t3-capacity', out) + closing = [line for line in out.splitlines() if line.startswith('heavy-install: installed release ')] + self.assertEqual(len(closing), 1, out) + self.assertIn("WARNING: /usr/local/bin/t3-capacity is still the host's own, not the kit's " + '(--replace-t3-capacity switches it)', closing[0]) + self.run_old_capacity() + self.assertTrue(os.path.islink(self.path('/usr/local/bin/heavy'))) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy-kept'))) + with open(self.path('/etc/heavy/installed.tsv')) as f: + self.assertNotIn('/usr/local/bin/t3-capacity', f.read()) + self.assertEqual(self.run_main('self-check')[0], 0) + before = self.snapshot() + self.assertEqual(self.install()[0], 0) # again: still left alone, nothing changes + self.assertEqual(self.snapshot(), before) + self.assertEqual(self.run_main('uninstall')[0], 0) + self.run_old_capacity() + + def test_old_plain_t3_capacity_is_kept_linked_and_put_back_by_uninstall(self): + self.write_old('/usr/local/bin/heavy', OLD_WRAPPER) + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + code, out, err = self.install('--replace-t3-capacity') + self.assertEqual(code, 0, err) + self.assertIn('the old /usr/local/bin/t3-capacity (sha256 ', out) + self.assertIn('is kept as /usr/local/libexec/heavy-kept/t3-capacity.', out) + self.assertNotIn('WARNING', out) # the closing line: the kit's now + self.assertEqual(os.readlink(self.path('/usr/local/bin/t3-capacity')), CAPACITY_LINK) + kept = self.path('/usr/local/libexec/heavy-kept') + self.assertEqual(len(os.listdir(kept)), 1) + with open(os.path.join(kept, os.listdir(kept)[0]), 'rb') as f: + self.assertEqual(f.read(), OLD_CAPACITY) + # heavy's own backup folder holds only heavy (an older installer's uninstall restores its newest file) + self.assertEqual([n[:6] for n in os.listdir(self.path('/usr/local/libexec/heavy/replaced'))], ['heavy.']) + self.assertEqual(self.run_main('self-check')[0], 0) + before = self.snapshot() + code, out, err = self.install() # again, the usual line: nothing changes + self.assertEqual(code, 0, err) + self.assertNotIn('is kept as', out) + self.assertEqual(self.snapshot(), before) + code, out, _ = self.run_main('uninstall') + self.assertEqual(code, 0) + self.run_old_capacity() + self.assertEqual(os.stat(self.path('/usr/local/bin/t3-capacity')).st_mode & 0o777, 0o755) + with open(self.path('/usr/local/bin/heavy'), 'rb') as f: + self.assertEqual(f.read(), OLD_WRAPPER) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy-kept'))) # its copy is back + self.assertEqual(self.run_main('uninstall')[0], 0) # again: nothing left, still fine + + def test_kept_t3_capacity_is_outside_every_folder_an_uninstall_deletes(self): + # every released uninstall (ci/v6 to ci/v22) deletes LIBEXEC and ETC whole, and unlinks only heavy and + # heavy-install; it does not know the t3-capacity link or the kept copy + for gone in (self.m.LIBEXEC, self.m.ETC): + self.assertFalse((self.m.KEPT_CAPACITY + '/').startswith(gone + '/'), gone) + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + self.assertEqual(self.install('--replace-t3-capacity')[0], 0) + for path in ('/usr/local/bin/heavy', '/usr/local/sbin/heavy-install'): + os.unlink(self.path(path)) + for path in (self.m.LIBEXEC, self.m.ETC): + shutil.rmtree(self.path(path)) + self.assert_older_uninstall_left_the_kept_copy_then_restore() + + def assert_older_uninstall_left_the_kept_copy_then_restore(self): + link = self.path('/usr/local/bin/t3-capacity') + self.assertEqual(os.readlink(link), CAPACITY_LINK) # broken: an older uninstall does not know it + self.assertFalse(os.path.lexists(self.path(CAPACITY_LINK))) # (its target, inside the fake root) + kept = self.path('/usr/local/libexec/heavy-kept') + self.assertEqual(len(os.listdir(kept)), 1) + with open(os.path.join(kept, os.listdir(kept)[0]), 'rb') as f: + self.assertEqual(f.read(), OLD_CAPACITY) + code, out, err = self.run_main('uninstall') # this release's uninstall puts it back + self.assertEqual(code, 0, err) + self.assertIn('put the old /usr/local/bin/t3-capacity back', out) + self.run_old_capacity() + self.assertFalse(os.path.exists(kept)) + self.assertEqual(self.run_main('uninstall')[0], 0) + self.run_old_capacity() + + def test_older_installers_install_and_uninstall_keep_the_hosts_t3_capacity(self): + repo = os.path.dirname(os.path.dirname(KIT)) + r = subprocess.run(['git', '-C', repo, 'rev-parse', '--verify', '-q', OLDER_RELEASE + '^{commit}'], + capture_output=True, text=True, timeout=60) + if r.returncode != 0: + self.skipTest(f'{OLDER_RELEASE} is not in this checkout (a shallow clone without tags); ' + f'test_kept_t3_capacity_is_outside_every_folder_an_uninstall_deletes covers its deletes') + older = os.path.join(self.root, 'older-release') + os.mkdir(older) + tree = subprocess.run(['git', '-C', repo, 'archive', OLDER_RELEASE, 'fork-kit', 'packages/shared/src/capacity'], + capture_output=True, timeout=120, check=True).stdout + subprocess.run(['tar', '-x', '-C', older], input=tree, check=True, timeout=120) + m_old = load(os.path.join(older, 'fork-kit', 'heavy', 'sbin', 'heavy-install')) + m_old.PREFIX, m_old.ROOT_UID = self.root, os.geteuid() + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + self.assertEqual(self.install('--replace-t3-capacity')[0], 0) + # the rollback: the older installer installs its own release over this state, then uninstalls + code, _, err = self.run_main('install', '--source', os.path.join(older, 'fork-kit', 'heavy'), '--sha', SHA2, + m=m_old) + self.assertEqual(code, 0, err) + self.assertEqual(self.resolve('/usr/local/bin/t3-capacity'), + self.path(f'/usr/local/libexec/heavy/versions/{SHA2}/bin/t3-capacity')) + code, _, err = self.run_main('uninstall', m=m_old) + self.assertEqual(code, 0, err) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy'))) + self.assertFalse(os.path.exists(self.path('/etc/heavy'))) + self.assert_older_uninstall_left_the_kept_copy_then_restore() + + def test_t3_capacity_swap_fails_old_command_still_works_then_run_again(self): + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + real_switch = self.m.switch_link + + def broken(path, target): + if path == self.m.CAPACITY: + raise OSError('the swap did not happen (test)') + return real_switch(path, target) + + self.m.switch_link = broken + with self.assertRaises(OSError): + self.install('--replace-t3-capacity') + self.m.switch_link = real_switch + self.run_old_capacity() # the old copy until the swap, whole + self.assertTrue(os.path.islink(self.path('/usr/local/bin/heavy'))) + code, out, err = self.install('--replace-t3-capacity') + self.assertEqual(code, 0, err) + self.assertNotIn('is kept as', out) # kept already by the run that stopped + self.assertEqual(os.readlink(self.path('/usr/local/bin/t3-capacity')), CAPACITY_LINK) + self.assertEqual(len(os.listdir(self.path('/usr/local/libexec/heavy-kept'))), 1) + self.assertEqual(self.run_main('self-check')[0], 0) + + def test_foreign_t3_capacity_link_is_left_alone_without_the_option(self): + link = self.path('/usr/local/bin/t3-capacity') + os.symlink('/opt/other/t3-capacity', link) + code, out, err = self.install() + self.assertEqual(code, 0, err) + self.assertIn('note: /usr/local/bin/t3-capacity is a link this kit did not make (to /opt/other/t3-capacity): ' + 'left as it is', out) + self.assertIn("WARNING: /usr/local/bin/t3-capacity is still the host's own", out) + self.assertEqual(os.readlink(link), '/opt/other/t3-capacity') + self.assertTrue(os.path.islink(self.path('/usr/local/bin/heavy'))) + with open(self.path('/etc/heavy/installed.tsv')) as f: + self.assertNotIn('/usr/local/bin/t3-capacity', f.read()) + self.assertEqual(self.run_main('self-check')[0], 0) + before = self.snapshot() + self.assertEqual(self.install()[0], 0) # again: still left alone, nothing changes + self.assertEqual(self.snapshot(), before) + self.assertEqual(self.run_main('uninstall')[0], 0) + self.assertEqual(os.readlink(link), '/opt/other/t3-capacity') + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy-kept'))) + + def test_foreign_t3_capacity_link_or_folder_is_refused_before_anything_is_written(self): + # with the option a link elsewhere is refused (nothing to keep); a folder is refused with or without it + for make, extra in ((lambda p: os.symlink('/opt/other/t3-capacity', p), ('--replace-t3-capacity',)), + (os.mkdir, ()), (os.mkdir, ('--replace-t3-capacity',))): + with self.subTest(make=make, extra=extra): + shutil.rmtree(self.root) + os.makedirs(self.path('/usr/local/bin')) + make(self.path('/usr/local/bin/t3-capacity')) + code, _, err = self.install(*extra) + self.assertEqual(code, 1) + self.assertIn('/usr/local/bin/t3-capacity exists and is not the kit\'s link', err) + self.assertEqual(sorted(os.listdir(self.path('/usr/local/bin'))), ['t3-capacity']) + self.assertFalse(os.path.exists(self.path('/usr/local/libexec/heavy'))) + self.assertFalse(os.path.exists(self.path('/etc/heavy'))) + + def test_heavy_self_check_warns_when_t3_capacity_on_path_is_not_the_kits(self): + self.assertEqual(self.install()[0], 0) + version = self.path(f'/usr/local/libexec/heavy/versions/{SHA1}') + ours, other, empty = (os.path.join(self.root, n) for n in ('ours', 'other', 'empty')) + for d in (ours, other, empty): + os.mkdir(d) + os.symlink(os.path.join(version, 'bin', 't3-capacity'), os.path.join(ours, 't3-capacity')) + with open(os.path.join(other, 't3-capacity'), 'wb') as f: + f.write(OLD_CAPACITY) + os.chmod(os.path.join(other, 't3-capacity'), 0o755) + config = os.path.join(self.root, 'config.json') + with open(config, 'w') as f: + json.dump({'version': 1, 'slice': 'heavy.slice', 'grace_seconds': 30}, f) + + def self_check(path): + env = dict(os.environ, PATH=path, HEAVY_CONFIG=config, HEAVY_SYSTEMCTL='/bin/false') + r = subprocess.run([sys.executable, '-I', '-B', os.path.join(version, 'bin', 'heavy'), '--self-check'], + capture_output=True, text=True, timeout=60, env=env) + return r.stdout + + out = self_check(f'{ours}:{other}') + self.assertIn("t3-capacity on PATH: this kit's\n", out) + self.assertNotIn('WARNING', out) + out = self_check(f'{other}:{ours}') + self.assertIn(f'WARNING: t3-capacity on PATH is {other}/t3-capacity, not this kit\'s ', out) + self.assertIn('its readings can differ', out) + out = self_check(empty) + self.assertIn('WARNING: t3-capacity is not on PATH', out) + def test_foreign_link_or_folder_is_refused_before_anything_is_written(self): os.symlink('/somewhere/else', self.path('/usr/local/bin/heavy')) code, _, err = self.install() @@ -119,24 +372,27 @@ def test_every_stop_half_way_then_run_again(self): with self.subTest(step=step): shutil.rmtree(self.root) os.makedirs(self.path('/usr/local/bin')) - with open(self.path('/usr/local/bin/heavy'), 'wb') as f: - f.write(OLD_WRAPPER) - os.chmod(self.path('/usr/local/bin/heavy'), 0o755) - code, _, _ = self.install('--memory-high', '5G', '--sweep-timer', stop_after=step) + self.write_old('/usr/local/bin/heavy', OLD_WRAPPER) + self.write_old('/usr/local/bin/t3-capacity', OLD_CAPACITY) + code, _, _ = self.install('--memory-high', '5G', '--sweep-timer', '--replace-t3-capacity', + stop_after=step) self.assertEqual(code, f'stopped after {step} (test)') - # until the links step, the old wrapper is what runs + # until the links step, the old wrapper and the old t3-capacity are what runs if self.m.STEPS.index(step) < self.m.STEPS.index('links'): self.assertFalse(os.path.islink(self.path('/usr/local/bin/heavy'))) + self.run_old_capacity() # a timer only once the release it runs is the one in use (#183 nit d) if os.path.exists(self.path('/etc/systemd/user/heavy-sweep.service')): current = os.readlink(self.path('/usr/local/libexec/heavy/current')) # absolute, as installed self.assertTrue(os.path.isfile(self.path(current + '/lib/heavy_sweep.py'))) self.assertTrue(os.path.islink(self.path('/usr/local/bin/heavy'))) - code, _, err = self.install('--memory-high', '5G', '--sweep-timer') + code, _, err = self.install('--memory-high', '5G', '--sweep-timer', '--replace-t3-capacity') self.assertEqual(code, 0, err) self.assertTrue(os.path.isfile(self.path('/etc/systemd/user/heavy-sweep.timer'))) self.assertEqual(self.run_main('self-check')[0], 0) self.assertEqual(len(os.listdir(self.path('/usr/local/libexec/heavy/replaced'))), 1) + self.assertEqual(len(os.listdir(self.path('/usr/local/libexec/heavy-kept'))), 1) + self.assertEqual(os.readlink(self.path('/usr/local/bin/t3-capacity')), CAPACITY_LINK) def test_half_copied_version_is_made_again(self): self.assertEqual(self.install()[0], 0)