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
56 changes: 48 additions & 8 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -2040,6 +2040,11 @@ class NameTaken(ValueError):
"""A run's name another launch took after it was checked (``reserve``)."""


class Undecided(OSError):
"""A launch whose decision could not be read back after it was written
(``start_all``): a restart starts it or not, as the file says then."""


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
Expand Down Expand Up @@ -2191,13 +2196,13 @@ def reserve(runs: List[Execution]) -> None:
raise


def release(runs: List[Execution]) -> bool:
def release(runs: List[Execution], kept: Optional[list] = None) -> 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. 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."""
folder went; *kept* given the folders that stay."""
every = True
for ex in runs:
try:
Expand All @@ -2210,12 +2215,27 @@ def release(runs: List[Execution]) -> bool:
pass
except OSError:
every = False
if kept is not None:
kept.append(ex.dir)
_unhold(ex)
ex._planned = False
return every


def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]:
def _refuse(runs: List[Execution], decision: str, undo: Optional[Callable], kept: Optional[list]) -> None:
"""A launch refused before its decision: ``undo``, then its folders
released and its decision removed once no mark is left to name it."""
try:
if undo is not None:
undo()
finally:
if release(runs, kept) and decision: # else kept: a mark left may name it
with contextlib.suppress(OSError):
os.unlink(decision)


def start_all(runs: List[Execution], reserved: bool = False, then: Optional[Callable] = None,
undo: Optional[Callable] = None, kept: Optional[list] = None) -> List[Execution]:
"""Start *runs*, those of one launch, once each has its first record: a
run without one could not be picked up after a restart (``restore``).
Their folders are reserved first unless ``reserved`` says they are. OSError
Expand All @@ -2224,6 +2244,14 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]:
would stay taken. ValueError, before anything is written, for a plan whose
parts would run one script file (``Plan.colliding``).

``then``: called once every record is saved, the records saved again
after it; ``undo``: called on a refusal before the folders go, while the
names and the decision are held, to take back what ``then`` did; *kept*:
as ``release``'s. What ``then`` raises refuses the launch as a failed
save does. A failed decision write is read back: written, the launch
starts (an interrupt leaves it to the restart); still ``preparing``, it
is refused; unknown, everything stays and ``Undecided`` says so.

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
Expand All @@ -2247,12 +2275,24 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]:
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:
if release(runs) and decision: # else kept: a mark left may name it
with contextlib.suppress(OSError):
os.unlink(decision)
if then is not None:
then()
for ex in runs:
ex._save(strict=True)
except BaseException:
_refuse(runs, decision, undo, kept)
raise
try:
ondisk.write_whole(decision, json.dumps({"token": token, "state": "committed"}))
except BaseException as error:
said = _decided(runs[0].dir) # read back while the names are held
if said is False:
_refuse(runs, decision, undo, kept)
raise
if said is None and isinstance(error, Exception):
raise Undecided(f"the launch's decision, {decision}, could not be read back") from error
if said is None or not isinstance(error, Exception):
raise # left as it is: a restart reads the decision
unmarked = 0
for ex in runs:
try:
Expand Down
56 changes: 53 additions & 3 deletions app/nullius/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,61 @@ def _set_state(ws: Workspace, **state) -> None:
ws.opened, ws.closed = now.opened, now.closed


def add_roots(ws: Workspace, roots) -> None:
"""*ws* with *roots* it does not hold yet."""
def add_roots(ws: Workspace, roots) -> list:
"""*ws* with *roots* it does not hold yet: those it took, as its record was saved."""
added = []

def add(now):
now.roots = list(now.roots) + [r for r in roots if r not in now.roots]
added[:] = [r for r in dict.fromkeys(roots) if r not in now.roots]
now.roots = list(now.roots) + added
_change(ws, add)
return added


def take_back(home_dir: str, ws: Workspace, roots) -> tuple:
"""*ws* without *roots* in its record, the rest of it - parsed jobs, index, state - as it
is: (the workspace as found, "taken"), (it, "kept") when its record could not be saved
and it still lists some, or (*ws*, "unknown") when it cannot be found or read, so what
it lists is not known.
Found by its uid, or for one saved without, by its folder and created time; looked up
again when it moves meanwhile."""
for _ in range(3):
where = _found(home_dir, ws)
if where is None:
break
taken = []

def drop(now):
now.roots = [r for r in now.roots if r not in roots]
taken.append(now)
try:
_change(where, drop)
except OSError:
again = _found(home_dir, ws) # where it is now: moved meanwhile, looked up again
if again is not None and again.dir == where.dir:
return again, "kept" if any(r in again.roots for r in roots) else "taken"
continue
except (TypeError, ValueError):
break
if taken:
return where, "taken"
return ws, "unknown"


def _found(home_dir: str, ws: Workspace) -> Workspace | None:
"""*ws* where it is now (``_still``): under its name, else under any other."""
try:
names = sorted(os.listdir(home_dir)) if ws.uid or ws.folder else []
except OSError:
names = []
for name in dict.fromkeys([ws.name] + names):
try:
there = _still(ws, load(home_dir, name))
except (TypeError, ValueError):
continue
if there is not None:
return there
return None


def _state(ws_dir: str) -> dict | None:
Expand Down
Loading
Loading