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
82 changes: 77 additions & 5 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@
and each part's ``run-<part>.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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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'}"
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading