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
110 changes: 104 additions & 6 deletions app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
from __future__ import annotations

import base64
import contextlib
import errno
import fcntl
import hashlib
Expand All @@ -124,6 +125,7 @@
import re
import shlex
import shutil
import stat
import subprocess
import sys
import threading
Expand Down Expand Up @@ -468,6 +470,7 @@ def __init__(self, plan: Plan, root: Optional[str] = None, run: Optional[Callabl
# a record from before the feeds' positions: the trials it said, (job, trial), until their feed has a position
self._seen_trials: set = {(k[0], k[1]) for k in rec.get("seen_trials") or ()}
self._planned = "version" in rec # the plan is in its own file already
self._held: Optional[int] = None # the folder's lock while it has no record yet (``reserve``)
self.caps: dict = dict(rec.get("caps") or {}) # a job's spending cap set on its page, {job: USD}: it holds from the job's next run
self._settled: set = set() # the kept tries whose trial's copy was settled (settle_retried)
if record:
Expand Down Expand Up @@ -1858,18 +1861,109 @@ 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``)
# 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))


def _lock(path: str) -> Optional[int]:
"""*path*, a run's folder, locked by this process: its descriptor, or
None when another launch holds it; OSError when it cannot be locked.
The lock goes when the process ends, however it ends (a child forked
without exec, which Nullius does not do, would keep it until it ends);
a link is not followed."""
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
os.close(fd)
return None
except OSError:
os.close(fd)
raise
return fd


def _unhold(ex: Execution) -> None:
fd, ex._held = ex._held, None
if fd is not None:
os.close(fd)


def _make(ex: Execution) -> Optional[int]:
"""The run's folder made and locked, with its ``RESERVED`` mark; None
when it is there already. OSError, the folder removed, when it cannot be."""
try:
os.mkdir(ex.dir)
except FileExistsError:
return None
fd = None
try:
fd = _lock(ex.dir)
if fd is None:
raise OSError(f"{ex.dir} could not be locked")
os.close(os.open(RESERVED, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644, dir_fd=fd))
return fd
except OSError:
if fd is not None:
os.close(fd)
shutil.rmtree(ex.dir, ignore_errors=True)
raise


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
``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.
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
return None
except FileNotFoundError:
return None
fd = _lock(ex.dir)
if fd is None:
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):
os.close(fd)
return None
for n in names:
if n != RESERVED:
os.unlink(n, dir_fd=fd)
return fd
except OSError:
os.close(fd)
raise


def reserve(runs: List[Execution]) -> None:
"""Each run's folder made where there is none, so one launch alone holds
each name: NameTaken for a name taken meanwhile, OSError when the runs
root cannot hold it; either way the folders this made are removed."""
"""Each run's folder made, or taken over from a launch that ended before
its first record (``_orphan``), and held until that record (``_lock``),
so one launch alone holds each name; one launch at a time decides, the
runs root itself locked. NameTaken for a name taken, OSError when
the runs root cannot hold or lock it; either way the folders this
reserved are removed."""
made = []
try:
for ex in runs:
os.makedirs(ex.root, exist_ok=True)
root = os.open(ex.root, os.O_RDONLY | os.O_DIRECTORY)
try:
os.mkdir(ex.dir)
except FileExistsError:
raise NameTaken(name_taken(ex.plan.name)) from None
fcntl.flock(root, fcntl.LOCK_EX)
fd = _make(ex)
if fd is None:
fd = _orphan(ex)
finally:
os.close(root)
if fd is None:
raise NameTaken(name_taken(ex.plan.name))
ex._held = fd
made.append(ex)
except (OSError, NameTaken):
release(made)
Expand All @@ -1882,6 +1976,7 @@ def release(runs: List[Execution]) -> None:
plan anew."""
for ex in runs:
shutil.rmtree(ex.dir, ignore_errors=True)
_unhold(ex)
ex._planned = False


Expand All @@ -1907,6 +2002,9 @@ def start_all(runs: List[Execution], reserved: bool = False) -> List[Execution]:
release(runs)
raise
for ex in runs:
with contextlib.suppress(OSError):
os.unlink(os.path.join(ex.dir, RESERVED)) # its record is there: nothing to take over
_unhold(ex)
EXECUTIONS[ex.id] = ex
ex.start()
return runs
Expand Down
106 changes: 102 additions & 4 deletions app/ui_tests/test_run_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
takes. The execution's runners are fakes."""
from __future__ import annotations

import errno
import json
import os
import re
Expand Down Expand Up @@ -166,7 +167,7 @@ def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self)
with patch.dict(execution.EXECUTIONS, {"going": going}):
r = self.post(body)
self.assertEqual((r.status_code, r.json["error"]), (409, "twice is running already"))
(self.tmp / "runs" / "twice").mkdir(parents=True)
(self.tmp / "runs" / "twice").mkdir(parents=True); (self.tmp / "runs" / "twice" / "run.json").write_text("{}")
r = self.post(body)
self.assertEqual((r.status_code, r.json["error"]), (409, execution.name_taken("twice")))
plans = [execution.Plan(name="fresh", script="true"), execution.Plan(name="twice", script="true")]
Expand All @@ -177,16 +178,113 @@ def test_a_name_still_running_or_used_before_is_refused_and_nothing_starts(self)
def test_a_name_another_launch_takes_after_the_check_is_refused_and_its_folder_left_alone(self):
late = self.tmp / "runs" / "late"
real = execution.reserve
def another(runs): # the other launch lands between the check and the start
late.mkdir(parents=True); (late / "plan.json").write_text("theirs")
def another(runs): # the other launch lands between the check and the start, still before its record
other = execution.Execution(execution.Plan(name="late", script="true")); real([other]); self.addCleanup(execution._unhold, other)
(late / "plan.json").write_text("theirs")
return real(runs)
plans = [execution.Plan(name="fresh", script="true"), execution.Plan(name="late", script="true")]
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()), ["plan.json"]); self.assertEqual((late / "plan.json").read_text(), "theirs")
self.assertEqual(sorted(p.name for p in late.iterdir()), [".reserved", "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):
runs = self.tmp / "runs"
crash = ("import os, signal, sys; sys.path.insert(0, sys.argv[1]); from nullius import execution\n"
"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"])
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)
(runs / "kept").mkdir(); (runs / "kept" / ".reserved").write_text(""); (runs / "kept" / "notes.txt").write_text("mine")
self.assertEqual(web.execute.begin([execution.Plan(name="kept", script="true")]), ([], execution.name_taken("kept"), 409))
self.assertEqual(sorted(p.name for p in (runs / "kept").iterdir()), [".reserved", "notes.txt"]) # not only a launch's files: left as it is

def reserving(self, name="taken", **plan):
"""A launch of *name* whose reservation the test keeps, and lets go of after."""
ex = execution.Execution(execution.Plan(name=name, script="true", **plan), root=str(self.tmp / "runs"))
self.addCleanup(execution._unhold, ex)
return ex

def test_a_launch_paused_after_making_its_folder_is_never_taken_over(self):
mine, theirs, made, go, won = self.reserving(), self.reserving(), threading.Event(), threading.Event(), []
real = os.mkdir
def mkdir(path, *a, **k):
real(path, *a, **k)
if threading.current_thread().name == "mine" and os.fspath(path) == mine.dir:
made.set(); go.wait(5) # paused between making the folder and holding it
def launch(ex, publish):
try:
execution.reserve([ex])
if publish:
execution._unhold(ex); ex._save(strict=True) # its first record, published
won.append(ex)
except execution.NameTaken:
pass
with patch.object(execution.os, "mkdir", mkdir):
a = threading.Thread(target=launch, args=(mine, False), name="mine"); a.start(); made.wait(5)
b = threading.Thread(target=launch, args=(theirs, True)); b.start(); b.join(0.5)
go.set(); a.join(5); b.join(5)
self.assertEqual(len(won), 1)

def test_a_folder_that_cannot_be_locked_is_a_storage_error(self):
real, calls = execution.fcntl.flock, []
def flock(fd, op):
calls.append(op)
if len(calls) == 1:
raise OSError(errno.ENOLCK, "No locks available")
return real(fd, op)
with patch.object(execution.fcntl, "flock", flock):
runs, problem, status = web.execute.begin([execution.Plan(name="unlocked", script="true")])
self.assertEqual((runs, status), ([], 503))
self.assertFalse((self.tmp / "runs" / "unlocked").exists())

def test_a_folder_an_older_nullius_is_still_preparing_is_left_alone(self):
older = self.tmp / "runs" / "older"
older.mkdir(parents=True); (older / "plan.json").write_text("theirs"); (older / "run.sh").write_text("true\n") # no lock, no mark
self.assertEqual(web.execute.begin([execution.Plan(name="older", script="true")]), ([], execution.name_taken("older"), 409))
self.assertEqual(sorted(p.name for p in older.iterdir()), ["plan.json", "run.sh"])

def test_a_second_reserve_of_one_launch_keeps_its_first(self):
first = self.reserving()
execution.reserve([first])
with self.assertRaises(execution.NameTaken):
execution.reserve([first])
with self.assertRaises(execution.NameTaken):
execution.reserve([self.reserving()])

def test_a_killed_launch_of_a_part_without_an_id_frees_its_name(self):
dead = self.reserving(parts=[{"id": "", "label": "the part", "script": "true"}])
execution.reserve([dead]); dead._save_plan(); execution._unhold(dead) # what its end lets go of
self.assertIn("run-.sh", os.listdir(dead.dir))
execution.reserve([self.reserving()])

def test_an_unmarked_folder_is_never_taken_held_or_not(self):
runs = self.tmp / "runs"
crash = ("import os, signal, sys; sys.path.insert(0, sys.argv[1]); from nullius import execution\n"
"ex = execution.Execution(execution.Plan(name='bare', script='true'), root=sys.argv[2])\n"
"real = os.mkdir\n"
"def mkdir(path, *a, **k):\n"
" real(path, *a, **k)\n"
" if path == ex.dir: os.kill(os.getpid(), signal.SIGKILL)\n"
"os.mkdir = mkdir; execution.reserve([ex])")
self.assertEqual(subprocess.run([shutil.which("python3"), "-c", crash, str(APP), str(runs)]).returncode, -9) # killed before its mark
(runs / "older").mkdir() # an older Nullius's launch, live: it takes no lock
(runs / "held").mkdir(); fd = execution._lock(str(runs / "held")); self.addCleanup(os.close, fd) # a live launch, before its mark
for name in ("bare", "older", "held"):
self.assertEqual(web.execute.begin([execution.Plan(name=name, script="true")]), ([], execution.name_taken(name), 409))
self.assertEqual(list((runs / name).iterdir()), [])

def test_a_file_or_a_link_at_the_name_takes_it(self):
runs = self.tmp / "runs"; runs.mkdir()
(runs / "file").write_text("mine"); (runs / "link").symlink_to(self.tmp)
for name in ("file", "link"):
self.assertEqual(web.execute.begin([execution.Plan(name=name, script="true")]), ([], execution.name_taken(name), 409))
self.assertEqual(((runs / "file").read_text(), os.readlink(runs / "link")), ("mine", str(self.tmp)))

def test_a_runs_folder_that_cannot_hold_runs_is_a_storage_error_not_a_name(self):
(self.tmp / "runs").write_text("")
runs, problem, status = web.execute.begin([execution.Plan(name="free", script="true")])
Expand Down
2 changes: 0 additions & 2 deletions app/web/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,6 @@ def begin(plans: list, into: str = "") -> tuple:
return [], problem, 400
if any(e.plan.name == plan.name for e in execution.active()):
return [], f"{plan.name} is running already", 409
if os.path.exists(os.path.join(execution.runs_root(), plan.name)):
return [], execution.name_taken(plan.name), 409
prepared = [execution.Execution(plan) for plan in plans]
saving = (lambda error: (f"The run's record could not be saved ({error.strerror or error}). "
f"Check the permissions and free space of {execution.runs_root()}, then retry."))
Expand Down
Loading