diff --git a/app/nullius/execution.py b/app/nullius/execution.py index 5f2284f3..6de8c856 100644 --- a/app/nullius/execution.py +++ b/app/nullius/execution.py @@ -61,7 +61,8 @@ and each part's ``run-.sh``, nowhere else; a run of one part runs ``run.sh`` itself. ``restore`` reads those records when Nullius starts and reattaches to what -is still running, waits again where it was paused, and settles what ended +is still running, waits again where it was paused, checks a run that had +not begun as a fresh launch is (``_main``), and settles what ended while nobody was looking, once it holds the runs root's lock (``_follow``): one web UI per runs folder. What is supported: ``docs/concepts.md``. A record is checked against the part's files and processes on the target @@ -452,6 +453,8 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl # the last part whose launch began, saved before its script is sent, so a restart tells a Stop that cut its # launch short from one before it (_kill_part) self.launched: str = rec.get("launched") or "" + # the fresh checks passed, the run's name on a host its own (``_checked``): None for a record from before the field + self.checked: Optional[bool] = rec.get("checked") if record else False if self.state == "stopping": # a Stop that a restart interrupted: finish it, do not run on self._stop.set() self.log_offset = int(rec.get("log_offset", 0)) @@ -561,7 +564,7 @@ def _save(self, strict: bool = False, inline: bool = False) -> bool: "log_offset": self.log_offset, "exit_code": self.exit_code, "error": self.error, "question": self.question, "ends": self.ends, "started": self.started, "finished": self.finished, "harbor": self.harbor, "tasks_on_target": self.tasks_on_target, "app_on_target": self.app_on_target, "catalogue_on_target": self.catalogue_on_target, "workspace": self.workspace, - "launched": self.launched, "feeds": self._feeds, "caps": self.caps, + "launched": self.launched, "checked": self.checked, "feeds": self._feeds, "caps": self.caps, "again": [{k: v for k, v in p.items() if k != "script"} for p in self.plan.parts if p.get("again")]} if self._pending: data["pending"] = self._pending @@ -926,12 +929,60 @@ def _main(self) -> None: missing = self._missing() if missing: return self._fail("credentials", missing) - if not self._prepare(fresh=True): + if not (self._prepare(fresh=False, again=True) if self.checked else self._prepare(fresh=True)): return self._parts() except Exception as e: # a step that raised is a failed run, not a dead thread self._fail(self.step or "run", f"{type(e).__name__}: {e}") + def _unbegun(self) -> Optional[bool]: + """Whether a restored run is checked as a fresh launch is (``_main``): + no part of it ended, and none reached the target - none was sent + (``launched``, saved before one is), or, sent or from a record before + ``checked``, none left a claim, pid, log or exit code there. False + when one did: it resumes. On a host, a run folder that is not there + takes the fresh path, name check included; one there that holds no + part of this run cannot be told from another run's, and None: the run + failed, as it does when the host does not say - unless a part was + launched, which is followed as before.""" + if self.state not in ("preparing", "running") or self.ends: + return False + sent = bool(self.launched) or self.checked is None # a part of its own may be on the target + names = [f"{_base(p)}.{ext}" for p in self.plan.steps() for ext in ("launch", "pid", "log", "exit")] + if not self.on_host: + return not (sent and any(os.path.lexists(os.path.join(self.dir, n)) for n in names)) + rc, out = self._sh(f"cd {self._q(self._run_dir())} 2>/dev/null || {{ echo @absent; exit 0; }}; for f in " + + " ".join(shlex.quote(n) for n in names) + '; do [ -e "$f" ] && echo @part; done; echo @looked', 30) + words = out.split() + if rc != 0 or not {"@absent", "@looked"} & set(words): + if self.state == "running": # a part may be running: followed as before (``_settle``) + self.log(f" {self.plan.host.label} did not say whether the run's folder is there; following the run as recorded") + return False + self._fail("connect", f"{self.plan.host.label} did not say whether the run's folder is there: " + out.strip()[-400:]) + return None + if sent and "@part" in words: + return False + self.checked = False # not its own as far as anyone can tell: never removed with it (``deletion``) + if "@absent" in words: + return True + self._fail("name", "cannot confirm the host folder belongs to this run; delete it and launch again") + return None + + def _checked(self) -> bool: + """The fresh checks passed, saved before the target is changed: a + restart then knows the run's folder there is its own. False, the run + failed, when it cannot be saved.""" + self.checked = True + try: + if self._save(strict=True): + return True + why = "the run was deleted" + except OSError as e: + why = f"the run's record could not be saved ({e.strerror or e})" + self.checked = False + self._fail(self.step or "run", why + "; nothing was changed on the target") + return False + def _missing(self) -> Optional[str]: """Why the run's key or endpoint cannot be sent, or None: not set, or holding a line break.""" harbor_model = "NULLIUS_HARBOR" in (self.plan.script + "".join(p.get("script", "") for p in self.plan.parts)) and self.plan.model @@ -1060,6 +1111,12 @@ def holds(self, job_id: str) -> Optional[str]: def _main_resumed(self) -> None: try: self.log(f"— Nullius is back; picking the run up at {self.plan.steps()[min(self.part, len(self.plan.steps()) - 1)]['label']}") + unbegun = self._unbegun() + if unbegun is None: + return + if unbegun: # checked as a fresh launch is, its key read at restore + self.state, self.pid, self.log_offset = "preparing", None, 0 + return self._main() if self.state == "preparing": if not self._prepare(fresh=False): return @@ -1387,6 +1444,8 @@ def _prepare(self, fresh: bool = True, again: bool = False) -> bool: if why: self._fail("docker", why) return False + if fresh and not self.on_host and not self._checked(): + return False pin = self.plan.harbor_pin if self.plan.runner == "harbor" else {} if (fresh or again) and (self.on_host or pin): self.log(progress.line("plan", stages=",".join( @@ -1433,6 +1492,8 @@ def _prepare(self, fresh: bool = True, again: bool = False) -> bool: if "@taken" in out.split(): self._fail("name", name_taken(self.plan.name, host.label)) return False + if not self._checked(): + return False # what this run needs of the host, and nothing it does not if self.plan.runner == "harbor": self.log(f" {probe['hostname'] or host.label}: docker {'yes' if probe['docker'] else 'no'}" @@ -1851,7 +1912,16 @@ def _launch(self, part: dict) -> Optional[bool]: with self._turn: # the Stop takes this lock too: said before this, nothing is launched if self._stop.is_set(): return None + was = self.state, self.launched self.state, self._live, self.launched = "running", part, part["id"] + try: # saved before anything is sent: a restart follows the part, never checks it as unbegun + why = None if self._save(strict=True) else "the run was deleted" + except OSError as e: + why = f"the run's record could not be saved ({e.strerror or e})" + if why: + (self.state, self.launched), self._live = was, None + self._fail("run", f"{why}; {part['label']} was not started") + return False where = self.plan.host.label if self.on_host else "this machine" self._begin("run", f"running {part['label']} on {where}") run_dir = self._run_dir() @@ -2553,8 +2623,10 @@ def _run_deletion(name: str, home: str, root: Optional[str], holding: Callable, plan = recorded(path, scripts=False)[1] or {} except (OSError, ValueError): # a run whose plan cannot be read goes from this machine alone plan = {} - # a run refused at the name check never made the host folder: one of that name there is not its own - host = hosts.parse(plan["host"]) if plan.get("host") and (rec.get("launched") or rec.get("step") not in ("connect", "name")) else None + # the host folder is its own once its name was checked there (``checked``); a record from before that field, + # once it launched or got past the name check. Any other folder of that name there is not its own + owned = rec["checked"] if rec.get("checked") is not None else rec.get("launched") or rec.get("step") in ("uv", "tasks", "app", "run") + host = hosts.parse(plan["host"]) if plan.get("host") and owned else None held, olds = [], [] for ws, roots in holding(path): dirs = parse.find_job_dirs(roots) diff --git a/app/tests/test_execution.py b/app/tests/test_execution.py index ca319364..02be7ffa 100644 --- a/app/tests/test_execution.py +++ b/app/tests/test_execution.py @@ -279,7 +279,7 @@ def test_an_older_nullius_mark_beside_a_record_is_restored_and_kept_as_it_was(se 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" + "runs, op, attr, end, nth, plan = 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" @@ -289,13 +289,14 @@ def test_an_older_nullius_mark_beside_a_record_is_restored_and_kept_as_it_was(se " 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" + "exs = [execution.Execution(execution.Plan(name=n, script='true', **plan), 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*.""" + def killed(self, runs, op, attr, end, nth=0, plan=None): + """*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*; + *plan*: more of each run's ``Plan`` fields.""" 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])], + return subprocess.run([sys.executable, "-c", self.KILLED, app, json.dumps([[[n, str(r)] for n, r in runs], op, attr, end, nth, plan or {}])], timeout=60).returncode def test_a_takeover_killed_at_any_point_leaves_its_folder_marked(self): @@ -308,6 +309,57 @@ def test_a_takeover_killed_at_any_point_leaves_its_folder_marked(self): 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_killed_before_it_started_is_checked_as_a_fresh_one_after_a_restart(self): + plan = {"runner": "standard", "key_var": "TEST_RUN_KEY", "url_var": "", "base_url": "https://example.invalid"} + key = "TEST_RUN_KEY is not set in Settings; the producers and the judge would have no model key" + for case, docker, step, why in (("key removed", None, "credentials", key), ("docker quit", "docker is gone", "docker", "docker is gone")): + with self.subTest(case=case): + root = self.tmp / case.replace(" ", "-") + with patch.dict(os.environ, {"TEST_RUN_KEY": "k" * 20}): + self.assertEqual(self.killed([("s1", root)], "start", "unlink", "s1/.launching", plan=dict(plan, docker=True)), -9) + if case == "key removed": + del os.environ["TEST_RUN_KEY"] # removed from Settings while Nullius was gone + with patch.object(execution, "docker_here", return_value=docker): + ex, = execution.restore(str(root)) + self.wait(ex) + self.assertEqual((ex.state, ex.step, ex.error), ("failed", step, why), ex.lines) + rec, _ = execution.recorded(ex.dir) + self.assertEqual((rec["state"], rec["error"]), ("failed", why)) + self.assertIn(f"✕ {step}: {why}", (root / "s1" / "nullius.log").read_text()) + self.assertFalse(list((root / "s1").glob("run*.log"))) # nothing launched + + def test_a_part_that_ran_keeps_its_result_after_a_restart_whatever_progress_was_saved(self): + real = execution.Execution._save + for case in ("progress saves refused", "record from before the launch checkpoint"): + with self.subTest(case=case): + root, ran = self.tmp / case.replace(" ", "-"), self.tmp / f"{case}.ran" + plan = execution.Plan(name="r", script=f"echo x >> '{ran}'", runner="standard", key_var="TEST_RUN_KEY", url_var="", base_url="https://example.invalid") + with patch.dict(os.environ, {"TEST_RUN_KEY": "k" * 20}): + if case == "progress saves refused": + with patch.object(execution.Execution, "_save", lambda ex, strict=False, inline=False: real(ex, strict, inline) if strict else False): + self.wait(execution.start(plan, root=str(root))) + else: + self.wait(execution.start(plan, root=str(root))) + rec = json.loads((root / "r" / "run.json").read_text()) + rec.update(state="preparing", step="", launched="", pid=None, exit_code=None, finished=None, ends={}, part=0) + rec.pop("checked", None) + (root / "r" / "run.json").write_text(json.dumps(rec)) + execution.EXECUTIONS.clear() # its key removed meanwhile + ex, = execution.restore(str(root)) + self.assertEqual((self.wait(ex).state, ex.exit_code), ("done", 0), ex.lines) + self.assertEqual(ran.read_text(), "x\n") # once + + def test_a_launch_saved_before_its_part_reached_this_machine_is_checked_as_a_fresh_one(self): + root, ran = self.tmp / "runs", self.tmp / "ran" + plan = execution.Plan(name="r", script=f"echo x >> '{ran}'", runner="standard", key_var="TEST_RUN_KEY", url_var="", base_url="https://example.invalid") + ex = execution.Execution(plan, root=str(root), key="k" * 20) + ex.state, ex.launched = "running", "run" # saved, and Nullius gone before the launcher ran + ex._save() + execution.EXECUTIONS.clear() + back, = execution.restore(str(root)) # its key removed meanwhile + self.assertEqual((self.wait(back).state, back.step), ("failed", "credentials"), back.lines) + self.assertFalse(ran.exists()) + 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): @@ -909,17 +961,60 @@ def test_a_new_run_whose_directory_is_on_the_host_already_is_refused_before_anyt self.assertFalse((self.tmp / "ran").exists()) self.assertEqual(execution.name_taken("r"), "a run named r exists already; press Run again for a new name") # the route's words - def test_a_restored_run_is_not_refused_its_own_directory(self): - """Nullius gone while a run on a host was being prepared: its - directory there is its own, and the run goes on.""" - ex = execution.Execution(self.plan([{"id": "a", "label": "a", "script": "echo a-out"}]), root=str(self.tmp / "runs"), key="k" * 20) + def restored(self, ran, folder, state="preparing", checked=True, **env): + """A run of one part recorded as Nullius left it before sending the part, restored: its record + ``checked`` (None: from before the field), its host folder made or not, the key ``env`` holds.""" + plan = self.plan([{"id": "a", "label": "a", "script": f': "$NULLIUS_HARBOR"; echo a-out; echo ran >> {ran}'}]) + plan.key_var, plan.url_var, plan.model = "TEST_RUN_KEY", "", "m" + ex = execution.Execution(plan, root=str(self.tmp / "runs"), key="k" * 20) + ex.state, ex.checked, ex.launched = state, checked, "a" if state == "running" else "" ex._save() - self.on_host().mkdir(parents=True) # the run's own, made before Nullius went + if checked is None: + rec = json.loads((Path(ex.dir) / "run.json").read_text()); del rec["checked"] + (Path(ex.dir) / "run.json").write_text(json.dumps(rec)) + if folder: + self.on_host().mkdir(parents=True) + (self.on_host() / "run.sh").write_text("echo other\n"); (self.on_host() / "run-other.log").write_text("other\n") execution.EXECUTIONS.clear() - back = execution.restore(str(self.tmp / "runs"), key="k" * 20) - self.assertEqual(len(back), 1); self.wait(back[0]) - self.assertEqual((back[0].state, back[0].error), ("done", None), back[0].lines) - self.assertIn("a-out", back[0].lines) + with patch.dict(os.environ, env): + back, = execution.restore(str(self.tmp / "runs")) + return self.wait(back) + + def test_a_restored_run_never_writes_into_a_host_folder_it_cannot_prove_its_own(self): + for state, checked in (("preparing", True), ("preparing", None), ("preparing", False), ("running", True)): + with self.subTest(state=state, checked=checked): + self.setUp() + ran = self.tmp / "ran" + back = self.restored(ran, True, state, checked, TEST_RUN_KEY="k" * 20) + self.assertEqual((back.state, back.step, back.error), + ("failed", "name", "cannot confirm the host folder belongs to this run; delete it and launch again"), back.lines) + self.assertEqual(sorted(p.name for p in self.on_host().iterdir()), ["run-other.log", "run.sh"]) + self.assertEqual((self.on_host() / "run.sh").read_text(), "echo other\n") + self.assertFalse(ran.exists()) + self.assertEqual(execution.deletion(["r"], str(self.tmp / "ws"), str(self.tmp / "runs"))["hosts"], {}) # nor removes it + + def test_a_restored_run_that_sent_no_part_is_checked_as_a_fresh_one(self): + for state, checked in (("preparing", True), ("preparing", None), ("running", True)): + with self.subTest(state=state, checked=checked): + self.setUp() + ran = self.tmp / "ran" + back = self.restored(ran, False, state, checked) # its key removed meanwhile + self.assertEqual((back.state, back.step), ("failed", "credentials"), back.lines) + self.assertFalse(ran.exists()) + back = self.restored(ran, False, state, checked, TEST_RUN_KEY="k" * 20) + self.assertEqual((back.state, back.error), ("done", None), back.lines) + self.assertEqual(ran.read_text(), "ran\n") + + def test_a_run_gone_before_its_name_was_checked_is_refused_a_leftover_directory(self): + d, was = self.leftover() + ex = execution.Execution(self.plan([{"id": "a", "label": "a", "script": f"echo new > {self.tmp / 'ran'}"}]), root=str(self.tmp / "runs"), key="k" * 20) + ex.step = "connect" # saved, and Nullius gone before the host was asked + ex._save() + execution.EXECUTIONS.clear() + back, = execution.restore(str(self.tmp / "runs"), key="k" * 20) + self.assertEqual((self.wait(back).state, back.step), ("failed", "name"), back.lines) + self.assertEqual(sorted(p.name for p in d.iterdir()), was) # the leftover's part neither adopted nor overwritten + self.assertFalse((self.tmp / "ran").exists()) class Recipe(Base): diff --git a/app/tests/test_execution_recovery.py b/app/tests/test_execution_recovery.py index 79381ee5..66e9f5db 100644 --- a/app/tests/test_execution_recovery.py +++ b/app/tests/test_execution_recovery.py @@ -467,11 +467,12 @@ def live(self, parts): snaps = self.tmp / "snaps" ex = execution.Execution(execution.Plan(name="r", script="", parts=parts), root=str(self.tmp / "live")) records, pids, real_save, real_launch = [], {}, ex._save, ex._launch - def save(): - real_save() + def save(*a, **k): + saved = real_save(*a, **k) dest = snaps / str(len(records)) / "r" shutil.copytree(ex.dir, dest) records.append(json.loads((dest / "run.json").read_text())) + return saved def launch(part): ok = real_launch(part); pids[part["id"]] = ex.pid return ok diff --git a/app/tests/test_execution_stop.py b/app/tests/test_execution_stop.py index 38a85062..d68621de 100644 --- a/app/tests/test_execution_stop.py +++ b/app/tests/test_execution_stop.py @@ -33,9 +33,10 @@ class StopBetweenParts(Base): def recorded_states(self, ex): """Every state the record took, in order.""" states, real = [], ex._save - def save(): - real() + def save(*a, **k): + saved = real(*a, **k) states.append(json.loads((Path(ex.dir) / "run.json").read_text())["state"]) + return saved ex._save = save return states diff --git a/app/tests/test_run_delete.py b/app/tests/test_run_delete.py index a77a2b09..aaea50fe 100644 --- a/app/tests/test_run_delete.py +++ b/app/tests/test_run_delete.py @@ -406,6 +406,15 @@ def test_a_run_refused_at_the_name_check_leaves_the_host_s_folder(self): self.run_("far", state="failed", host="ubuntu@10.0.0.4", step="name") # that folder on the host is another run's self.assertEqual(execution.deletion(["far"], self.home, self.root)["hosts"], {}) + def test_a_run_that_never_had_the_host_s_folder_leaves_it(self): + for name, fields in (("new", {"checked": False}), ("old", {})): # failed before its name was checked there + self.run_(name, state="failed", host="ubuntu@10.0.0.4", step="credentials") + path = os.path.join(self.root, name, execution.RECORD) + with open(path) as fh: + rec = json.load(fh) + _write_json(path, {**rec, **fields}) + self.assertEqual(execution.deletion(["new", "old"], self.home, self.root)["hosts"], {}) + def test_a_sharded_launch_goes_whole_each_copy_from_its_own_host(self): roots = [self.run_(f"s{i}", host=f"ubuntu@10.0.0.{3 + i}", job=f"L-shard-{i}of2") for i in (1, 2)] ws = workspace.create(self.home, roots, label="d"); workspace.load_jobs(ws, ws.roots)