From 0ec442cded7b7a6a6e7a29b26ea19591e20c53c6 Mon Sep 17 00:00:00 2001 From: Harenome Ranaivoarivony-Razanajato Date: Thu, 3 Dec 2026 21:59:45 +0100 Subject: [PATCH] fix(execution): start every run of a launch or none after a restart --- app/nullius/execution.py | 118 ++++++++++++++++++---- app/tests/test_execution.py | 170 ++++++++++++++++++++++++++++++++ app/ui_tests/test_run_routes.py | 4 +- 3 files changed, 273 insertions(+), 19 deletions(-) diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 8cea92ce0..6619f0fec 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -1989,10 +1989,45 @@ class NameTaken(ValueError): """A run's name another launch took after it was checked (``reserve``).""" -RESERVED = ".reserved" # in a run's folder from its reservation until its first record (``reserve``) +RESERVED = ".launching" # in a run's folder from its reservation until it starts; names its launch's decision (``start_all``) +LEGACY = ".reserved" # an older Nullius's mark, until its first record; one left beside a record is ignored, as it did # What a launch writes in its folder before its first record (``_save``): the # plan, its scripts (``_base``), an atomic write's own file (``ondisk.write_whole``). -_BEFORE_RECORD = re.compile(r"plan\.json|run\.sh|run-[A-Za-z0-9_.-]*\.sh|\.[0-9a-f]{32}\.part|" + re.escape(RESERVED)) +_BEFORE_RECORD = re.compile(r"plan\.json|run\.sh|run-[A-Za-z0-9_.-]*\.sh|\.[0-9a-f]{32}\.part|" + re.escape(RESERVED) + "|" + re.escape(LEGACY)) + + +_DECISION = re.compile(r"\.launch-[0-9a-f]{32}") + + +def _regular(path: str) -> str: + """The text of the regular file *path*, never through a link nor waiting + on a pipe; OSError for anything else.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, encoding="utf-8") as fh: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError(errno.EINVAL, f"{path} is not a file") + return fh.read() + + +def _decided(folder: str) -> Optional[bool]: + """Whether the launch of the run folder *folder*, marked ``RESERVED``, + decided to start, as its decision file says under the mark's token: True + ``committed``, False ``preparing`` or an empty mark before any record; + None when unknown: the file or the mark missing, unreadable, of another + shape or another token. Unknown never starts a run nor frees its name.""" + try: + text = _regular(os.path.join(folder, RESERVED)) + if not text: + return None if os.path.lexists(os.path.join(folder, RECORD)) else False + mark = json.loads(text) + decision, token = mark["decision"], mark["token"] + if not (set(mark) == {"decision", "token"} and isinstance(decision, str) and isinstance(token, str) + and os.path.isabs(decision) and os.path.basename(decision) == f".launch-{token}" and _DECISION.fullmatch(os.path.basename(decision))): + return None + said = json.loads(_regular(decision)) + return {"preparing": False, "committed": True}.get(said["state"]) if said == {"token": token, "state": said["state"]} else None + except (OSError, ValueError, KeyError, TypeError, AttributeError): + return None def _lock(path: str) -> Optional[int]: @@ -2041,11 +2076,13 @@ def _make(ex: Execution) -> Optional[int]: def _orphan(ex: Execution) -> Optional[int]: - """The run's folder taken over, locked and emptied but for its mark, from - a launch that reserved it and ended before its first record; None when - it is not one: a folder no live launch holds, with ``RESERVED``, no + """The run's folder taken over, locked and emptied but for its mark, made fresh, + from a launch that reserved it and ended before it started; None when it + is not one: a folder no live launch holds, with ``RESERVED`` whose launch + did not decide to start (``_decided``), and nothing but what a launch + writes before it starts, its record included; or with ``LEGACY``, no ``run.json`` and nothing but what a launch writes before its record. Any - other entry, an older Nullius's folder included, is left as it is. + other entry is left as it is. OSError when the folder cannot be locked.""" try: if not stat.S_ISDIR(os.lstat(ex.dir).st_mode): # a file or a link holds the name @@ -2057,13 +2094,18 @@ def _orphan(ex: Execution) -> Optional[int]: return None try: names = os.listdir(fd) - if RESERVED not in names or not all( - _BEFORE_RECORD.fullmatch(n) and stat.S_ISREG(os.stat(n, dir_fd=fd, follow_symlinks=False).st_mode) for n in names): + undecided = RESERVED in names and _decided(ex.dir) is False + if not (undecided or LEGACY in names and RESERVED not in names) or not all( + (_BEFORE_RECORD.fullmatch(n) or undecided and n == RECORD) + and stat.S_ISREG(os.stat(n, dir_fd=fd, follow_symlinks=False).st_mode) for n in names): os.close(fd) return None - for n in names: + if RESERVED not in names: # a mark at every instant: the new one first + os.close(os.open(RESERVED, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644, dir_fd=fd)) + for n in sorted(names, key=lambda n: n != RECORD): # the record first if n != RESERVED: os.unlink(n, dir_fd=fd) + ondisk.write_whole(os.path.join(ex.dir, RESERVED), "") return fd except OSError: os.close(fd) @@ -2098,14 +2140,28 @@ def reserve(runs: List[Execution]) -> None: raise -def release(runs: List[Execution]) -> None: +def release(runs: List[Execution]) -> bool: """The folders of *runs*, reserved and not started, removed with what was written there: their names are free again, and a later save writes the - plan anew.""" + plan anew. Each record goes first, then its folder is moved aside whole, + so no instant leaves a record without its mark; a record that cannot go + keeps its folder as it is (``_orphan`` takes it over). True when every + folder went.""" + every = True for ex in runs: - shutil.rmtree(ex.dir, ignore_errors=True) + try: + with contextlib.suppress(FileNotFoundError): + os.unlink(os.path.join(ex.dir, RECORD)) + aside = os.path.join(ex.root, f".released-{os.urandom(16).hex()}") + os.rename(ex.dir, aside) + shutil.rmtree(aside, ignore_errors=True) + except FileNotFoundError: + pass + except OSError: + every = False _unhold(ex) ex._planned = False + return every def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: @@ -2115,7 +2171,15 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: when one cannot be saved: none is registered or started, and their folders are released, since a restart would start them and their names would stay taken. ValueError, before anything is written, for a plan whose - parts would run one script file (``Plan.colliding``).""" + parts would run one script file (``Plan.colliding``). + + The launch starts by one decision: a file of this call's own token in the + first run's root, ``preparing`` before any mark names it, ``committed`` + once every record is saved. A restart starts every run or none + (``restore``); a launch still preparing is taken over (``_orphan``). The + file goes once this call removes every mark; otherwise it stays.""" + if not runs: + return runs for ex in runs: if ex.plan.colliding(): if reserved: @@ -2123,15 +2187,32 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]: raise ValueError(ex.plan.colliding()) if not reserved: reserve(runs) + decision = "" try: + token = os.urandom(16).hex() + decision = os.path.join(os.path.realpath(runs[0].root), f".launch-{token}") + ondisk.write_whole(decision, json.dumps({"token": token, "state": "preparing"})) + for ex in runs: + ondisk.write_whole(os.path.join(ex.dir, RESERVED), json.dumps({"decision": decision, "token": token})) for ex in runs: ex._save(strict=True) + ondisk.write_whole(decision, json.dumps({"token": token, "state": "committed"})) except OSError: - release(runs) + if release(runs) and decision: # else kept: a mark left may name it + with contextlib.suppress(OSError): + os.unlink(decision) raise + unmarked = 0 for ex in runs: + try: + os.unlink(os.path.join(ex.dir, RESERVED)) + unmarked += 1 + except OSError: + pass + if unmarked == len(runs): with contextlib.suppress(OSError): - os.unlink(os.path.join(ex.dir, RESERVED)) # its record is there: nothing to take over + os.unlink(decision) + for ex in runs: _unhold(ex) with _CLAIMS: # never between a delete's look at an id and its removal EXECUTIONS[ex.id] = ex @@ -2253,8 +2334,9 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: """At start-up: every recorded run under the root. The ones still alive are reattached (their thread follows the part that was running, or waits at the pause it was at); the finished ones are listed as they - ended. Returns the ones reattached. ``Followed`` when another process - holds the root (``_follow``).""" + ended. A run still marked ``RESERVED`` is left out unless its launch + decided to start (``_decided``). Returns the ones + reattached. ``Followed`` when another process holds the root (``_follow``).""" root = root or runs_root(kw.get("env", os.environ)) _follow(root) back = [] @@ -2263,6 +2345,8 @@ def restore(root: Optional[str] = None, **kw) -> List[Execution]: except OSError: return back for name in names: + if os.path.lexists(os.path.join(root, name, RESERVED)) and not _decided(os.path.join(root, name)): + continue try: rec, plan = recorded(os.path.join(root, name)) plan = Plan.from_dict(plan) diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index 44cbd2637..ca3193641 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -5,6 +5,8 @@ import shlex import os import shutil +import subprocess +import sys import tempfile import threading import time @@ -242,6 +244,174 @@ def full(path, data, mode=None): self.wait(ex) self.assertEqual([execution.recorded(ex.dir)[1]["name"] for ex in runs], ["s1", "s2"]) + def test_a_launch_killed_before_or_after_its_decision_starts_none_or_all_of_its_runs_after_a_restart(self): + for kill, at, resumed in (("s2/run.json", "write_whole", []), ("s2/.launching", "unlink", ["s1", "s2"])): + with self.subTest(kill=kill): + root = self.tmp / kill.replace("/", "-") + runs = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + write, unlink = execution.ondisk.write_whole, os.unlink + def killed(real, name): + def call(path, *a, **k): + if path == str(root / kill) and name == at: + raise SystemExit("killed") # nothing after it runs, as with a kill + return real(path, *a, **k) + return call + with patch.object(execution.ondisk, "write_whole", killed(write, "write_whole")), patch.object(execution.os, "unlink", killed(unlink, "unlink")), \ + self.assertRaises(SystemExit): + execution.start_all(runs) + for ex in runs: + execution._unhold(ex) # the dead process's locks go with it + self.assertEqual(sorted(self.wait(ex).plan.name for ex in execution.restore(str(root))), resumed) # never one shard alone + again = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + if resumed: + self.assertRaises(execution.NameTaken, execution.start_all, again) + else: + self.assertEqual([self.wait(ex).state for ex in execution.start_all(again)], ["done", "done"]) # both names free again + + def test_an_older_nullius_mark_beside_a_record_is_restored_and_kept_as_it_was(self): + root = self.tmp / "runs" + ex = self.wait(execution.start(execution.Plan(name="old", script="true"), root=str(root))) + (root / "old" / ".reserved").write_text("") # its unlink failed, and its run went on + execution.EXECUTIONS.clear() + execution.restore(str(root)) + self.assertEqual([e.state for e in execution.EXECUTIONS.values()], ["done"]) + self.assertRaises(execution.NameTaken, execution.start, execution.Plan(name="old", script="true"), root=str(root)) + + KILLED = ("import json, os, signal, sys\n" + "sys.path.insert(0, sys.argv[1]); from nullius import execution\n" + "runs, op, attr, end, nth = json.loads(sys.argv[2])\n" + "module = execution.ondisk if attr == 'write_whole' else os\n" + "real, seen = getattr(module, attr), []\n" + "def call(path, *a, **k):\n" + " out = real(path, *a, **k)\n" + " if str(path).endswith(end):\n" + " seen.append(path)\n" + " if len(seen) > nth: os.kill(os.getpid(), signal.SIGKILL)\n" + " return out\n" + "setattr(module, attr, call)\n" + "exs = [execution.Execution(execution.Plan(name=n, script='true'), root=r) for n, r in runs]\n" + "execution.start_all(exs) if op == 'start' else execution.reserve(exs)\n") + + def killed(self, runs, op, attr, end, nth=0): + """*op* of *runs* ([name, root]) in a process of its own, killed just after its call to *attr* past *nth* on a path ending *end*.""" + app = str(Path(execution.__file__).resolve().parents[1]) + return subprocess.run([sys.executable, "-c", self.KILLED, app, json.dumps([[[n, str(r)] for n, r in runs], op, attr, end, nth])], + timeout=60).returncode + + def test_a_takeover_killed_at_any_point_leaves_its_folder_marked(self): + for nth in range(4): + with self.subTest(nth=nth): + root = self.tmp / f"take{nth}" + self.assertEqual(self.killed([("s1", root), ("s2", root)], "start", "write_whole", "s2/run.json"), -9) # before its decision + self.killed([("s1", root)], "reserve", "unlink", "", nth) # the takeover of s1, killed after its nth removal + self.assertEqual(execution.restore(str(root)), []) + again = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + self.assertEqual([self.wait(ex).state for ex in execution.start_all(again)], ["done", "done"]) + + def test_a_decided_launch_whose_decision_is_gone_or_replaced_starts_and_frees_nothing(self): + for case in ("root moved", "root made again", "decision gone", "decision replaced"): # made again: its inode may be the old one's + with self.subTest(case=case): + first, second = self.tmp / case / "a", self.tmp / case / "b" + self.assertEqual(self.killed([("s1", first), ("s2", second)], "start", "unlink", "s1/.launching"), -9) # decided, s2 still marked + decision, = first.glob(".launch-*") + if case == "root moved": + first.rename(first.with_name("moved")) + elif case == "root made again": + shutil.rmtree(first); first.mkdir() + elif case == "decision gone": + decision.unlink() + else: + decision.unlink(); decision.mkdir() + self.assertEqual(execution.restore(str(second)), []) + with self.assertRaises(execution.NameTaken): # its record kept + execution.reserve([execution.Execution(execution.Plan(name="s2", script="true"), root=str(second))]) + self.assertTrue((second / "s2" / "run.json").is_file()) + + def test_a_decided_launch_whose_root_was_copied_back_starts_every_run(self): + first, second = self.tmp / "a", self.tmp / "b" + self.assertEqual(self.killed([("s1", first), ("s2", second)], "start", "unlink", "s1/.launching"), -9) + shutil.copytree(first, self.tmp / "copy"); shutil.rmtree(first); (self.tmp / "copy").rename(first) # another inode, its decision intact + back = execution.restore(str(first)) + execution.restore(str(second)) + self.assertEqual(sorted(self.wait(ex).plan.name for ex in back), ["s1", "s2"]) + + def test_a_recorded_run_whose_mark_is_of_another_shape_starts_and_frees_nothing(self): + for n, mark in enumerate(("", "null", "{}", "[]", '{"decision": false, "root": [1, 2]}', '{"decision": "/x/.launch-0", "token": "0"}')): + with self.subTest(mark=mark): + root = self.tmp / f"shape{n}" + self.assertEqual(self.killed([("s1", root), ("s2", root)], "start", "write_whole", "s2/run.json"), -9) # before its decision + (root / "s1" / ".launching").write_text(mark) + self.assertEqual(execution.restore(str(root)), []) + with self.assertRaises(execution.NameTaken): + execution.reserve([execution.Execution(execution.Plan(name="s1", script="true"), root=str(root))]) + self.assertTrue((root / "s1" / "run.json").is_file()) + + def test_a_link_or_a_legacy_mark_beside_a_new_one_frees_nothing(self): + for case in ("decision a link", "legacy beside a malformed mark"): + with self.subTest(case=case): + root = self.tmp / case + self.assertEqual(self.killed([("s1", root), ("s2", root)], "start", "write_whole", "s2/run.json"), -9) # preparing + if case == "decision a link": + decision, = root.glob(".launch-*") + decision.rename(root / "copy"); decision.symlink_to(root / "copy") # what it says, through a link + kept = root / "s1" / "run.json" + else: + (root / "s1" / "run.json").unlink(); (root / "s1" / ".launching").write_text("null"); (root / "s1" / ".reserved").write_text("") + kept = root / "s1" / ".launching" + with self.assertRaises(execution.NameTaken): + execution.reserve([execution.Execution(execution.Plan(name="s1", script="true"), root=str(root))]) + self.assertTrue(kept.is_file()) + + ROLLBACK = ("import errno, os, signal, sys\n" + "sys.path.insert(0, sys.argv[1]); from nullius import execution\n" + "write = execution.ondisk.write_whole\n" + "def full(path, *a, **k):\n" + " if path.endswith('s2/run.json'): raise OSError(errno.ENOSPC, 'No space left on device')\n" + " return write(path, *a, **k)\n" + "execution.ondisk.write_whole = full\n" + "scandir, unlink = os.scandir, os.unlink\n" + "class MarkFirst(list):\n" + " def __enter__(self): return self\n" + " def __exit__(self, *a): pass\n" + "def ordered(*a):\n" + " with scandir(*a) as it: return MarkFirst(sorted(it, key=lambda e: e.name != '.launching'))\n" + "def killed(*a, **k):\n" + " unlink(*a, **k); os.kill(os.getpid(), signal.SIGKILL)\n" + "os.scandir, os.unlink = ordered, killed\n" + "execution.start_all([execution.Execution(execution.Plan(name=n, script='true'), root=sys.argv[2]) for n in ('s1', 's2')])\n") + + def test_a_rollback_killed_after_its_first_removal_starts_nothing(self): + root = self.tmp / "runs" + app = str(Path(execution.__file__).resolve().parents[1]) + self.assertEqual(subprocess.run([sys.executable, "-c", self.ROLLBACK, app, str(root)], timeout=60).returncode, -9) + self.assertEqual(execution.restore(str(root)), []) + again = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + self.assertEqual([self.wait(ex).state for ex in execution.start_all(again)], ["done", "done"]) + + def test_a_rollback_that_cannot_remove_a_record_keeps_the_launch_preparing(self): + root = self.tmp / "runs" + runs = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + write, unlink = execution.ondisk.write_whole, os.unlink + def full(path, data, mode=None): + if path == str(root / "s2" / "run.json"): + raise OSError(28, "No space left on device") + return write(path, data, mode) + def refused(path, *a, **k): + if os.path.basename(path) == "run.json": # s1's record cannot go, however it is named + raise PermissionError(13, "Permission denied") + return unlink(path, *a, **k) + with patch.object(execution.ondisk, "write_whole", full), patch.object(execution.os, "unlink", refused), self.assertRaises(OSError): + execution.start_all(runs) + self.assertEqual(execution.restore(str(root)), []) + again = [execution.Execution(execution.Plan(name=n, script="true"), root=str(root)) for n in ("s1", "s2")] + self.assertEqual([self.wait(ex).state for ex in execution.start_all(again)], ["done", "done"]) # its decision kept: s1 is free + + def test_a_root_through_a_link_and_dotdot_and_an_empty_launch(self): + (self.tmp / "a" / "b").mkdir(parents=True); (self.tmp / "link").symlink_to(self.tmp / "a" / "b") + root = str(self.tmp / "link" / ".." / "runs") + runs = [execution.Execution(execution.Plan(name=n, script="true"), root=root) for n in ("s1", "s2")] + self.assertEqual([self.wait(ex).state for ex in execution.start_all(runs)], ["done", "done"]) + self.assertEqual(execution.start_all([]), []) + class DockerHere(Base): """A Harbor run here asks docker first, as a run on a host does - and diff --git a/app/ui_tests/test_run_routes.py b/app/ui_tests/test_run_routes.py index f81b3a4ab..617e141d7 100644 --- a/app/ui_tests/test_run_routes.py +++ b/app/ui_tests/test_run_routes.py @@ -186,7 +186,7 @@ def another(runs): # the othe with patch.object(execution, "reserve", another): self.assertEqual(web.execute.begin(plans), ([], execution.name_taken("late"), 409)) self.assertEqual((dict(execution.EXECUTIONS), self.adopted), ({}, [])) # no workspace was given the other launch's jobs - self.assertEqual(sorted(p.name for p in late.iterdir()), [".reserved", "plan.json"]); self.assertEqual((late / "plan.json").read_text(), "theirs") + self.assertEqual(sorted(p.name for p in late.iterdir()), [".launching", "plan.json"]); self.assertEqual((late / "plan.json").read_text(), "theirs") self.assertFalse((self.tmp / "runs" / "fresh").exists()) # this launch's own folder, plan and script included, gone def test_a_folder_a_killed_launch_left_without_its_record_frees_its_name_and_no_other_is_touched(self): @@ -195,7 +195,7 @@ def test_a_folder_a_killed_launch_left_without_its_record_frees_its_name_and_no_ "ex = execution.Execution(execution.Plan(name='crashed', script='true'), root=sys.argv[2])\n" "execution.reserve([ex]); ex._save_plan(); os.kill(os.getpid(), signal.SIGKILL)") self.assertEqual(subprocess.run([shutil.which("python3"), "-c", crash, str(APP), str(runs)]).returncode, -9) - self.assertEqual(sorted(p.name for p in (runs / "crashed").iterdir()), [".reserved", "plan.json", "run.sh"]) + self.assertEqual(sorted(p.name for p in (runs / "crashed").iterdir()), [".launching", "plan.json", "run.sh"]) started, problem, status = web.execute.begin([execution.Plan(name="crashed", script="true")]) self.assertEqual((problem, status), ("", 200)); self.wait() self.assertEqual(execution.recorded(str(runs / "crashed"))[0]["id"], started[0].id)