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
118 changes: 101 additions & 17 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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]:
Expand All @@ -2115,23 +2171,48 @@ 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:
release(runs)
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
Expand Down Expand Up @@ -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 = []
Expand All @@ -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)
Expand Down
Loading
Loading