"""Run a heavy command once it holds one of the machine's heavy slots, so sessions running at once cannot starve the machine. usage: run-heavy [...] A heavy command is one that loads the machine for minutes: a full gate, mutation tests, an e2e run, a docker build. The machine has one heavy slot per 4 CPUs, and at least one, shared by every session that runs run-heavy. Each slot is a file locked with flock, under $XDG_STATE_HOME/run-heavy (default ~/.local/state/run-heavy). While every slot is held, run-heavy says so once on stderr and waits. It then runs the command in its place, which holds the slot until it and every process that inherited the lock exit. Its exit code is the command's. A command it runs carries the slot's number in RUN_HEAVY_SLOT, and run-heavy called with that set runs its command at once, so a gate that wraps its own steps cannot wait on itself. As GNU env, nice and timeout do, it exits 125, saying why, when no command is given or the slot folder cannot be made; 126 when the command is found but cannot run; and 127 when it is not found. """ import os import sys import time import typing from machine_load.slots import slot_count, slot_folder, taken_slot # Exit codes for a command run-heavy never ran, apart from any the command exits with, as GNU env, nice and timeout use them. OWN_FAILURE = 125 CANNOT_RUN = 126 NOT_FOUND = 127 # Names the slot a command runs in, so a heavy command it runs does not wait for a second slot. HELD = "RUN_HEAVY_SLOT" # Seconds between tries while every slot is held; a slot frees as its command exits. POLL_SECONDS = 1 USAGE = "usage: run-heavy [...]" def main(argv: list[str], env: typing.Mapping[str, str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 if not argv: print(f"run-heavy: no command given; {USAGE}", file=sys.stderr) return OWN_FAILURE if HELD not in env: folder = slot_folder(env) try: folder.mkdir(parents=True, exist_ok=True) except OSError as failure: print(f"run-heavy: cannot make the slot folder {folder}: {failure.strerror}", file=sys.stderr) return OWN_FAILURE slots = slot_count(os.cpu_count()) said = False while (taken := taken_slot(folder, slots)) is None: if not said: print(f"run-heavy: waiting for one of the machine's {slots} heavy slots", file=sys.stderr, flush=True) said = True time.sleep(POLL_SECONDS) slot, fd = taken # The command inherits the locked file, so the slot stays held until it exits. os.set_inheritable(fd, True) env = {**env, HELD: str(slot)} try: os.execvpe(argv[0], argv, env) except FileNotFoundError: print(f"run-heavy: {argv[0]}: command not found", file=sys.stderr) return NOT_FOUND except OSError as failure: print(f"run-heavy: cannot run {argv[0]}: {failure.strerror}", file=sys.stderr) return CANNOT_RUN