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
37 changes: 36 additions & 1 deletion 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 errno
import fcntl
import hashlib
import json
Expand Down Expand Up @@ -2214,6 +2215,40 @@ def deletion(names: List[str], home: str, root: Optional[str] = None, holding: O
"workspaces": list(dict.fromkeys(w["ws"].label for r in runs for w in r["workspaces"])), "hosts": copies}


def _remove_run(path: str) -> None:
"""Remove the run folder *path*: refused before anything goes when it, or
the runs root, does not let its entries go; else its subfolders, its other
files, ``plan.json`` and ``run.json`` last, and its scripts written again,
byte for byte, when one of its files cannot go, so a removal stopped part way leaves a run
still listed and deletable again. An entry gone since the listing (a save
completed) counts as removed."""
for folder in (path, os.path.dirname(path)):
if not os.access(folder, os.W_OK | os.X_OK):
raise PermissionError(errno.EACCES, os.strerror(errno.EACCES), folder)
last = {PLAN: 1, RECORD: 2}
with os.scandir(path) as listed:
entries = sorted(((e.path, e.is_dir(follow_symlinks=False), last.get(e.name, 0)) for e in listed),
key=lambda e: (not e[1], e[2]))
scripts = {}
for entry, folder, _ in entries:
try:
if folder:
shutil.rmtree(entry)
continue
if entry.endswith(".sh"):
with open(entry, "rb") as fh:
scripts[os.path.basename(entry)] = fh.read()
os.remove(entry)
except FileNotFoundError:
continue
except OSError:
for name, data in scripts.items():
if not os.path.exists(os.path.join(path, name)):
ondisk.write_whole(os.path.join(path, name), data)
raise
os.rmdir(path)


def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), run: Optional[Callable] = None) -> dict:
"""Delete the runs *names* of one launch (``deletion`` says what goes):
per run its folder, its entry here, its roots, parsed jobs and judgements
Expand All @@ -2227,7 +2262,7 @@ def delete(names: List[str], home: str, root: Optional[str] = None, copies=(), r
went = []
for r in gone["runs"]:
try:
shutil.rmtree(r["dir"])
_remove_run(r["dir"])
except OSError as e:
gone["stays"].append(r["name"])
gone["kept"].append(f"{r['name']} stays in {r['dir']}: {e.strerror or e}")
Expand Down
76 changes: 69 additions & 7 deletions app/tests/test_run_delete.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
that is not a run's."""
from __future__ import annotations

import contextlib
import json
import os
import shutil
Expand Down Expand Up @@ -154,13 +155,13 @@ def test_a_run_that_stays_keeps_the_judgements_of_its_jobs(self):
real = shutil.rmtree

def fails(path, *a, **k):
if os.path.realpath(path) == os.path.realpath(r2):
os.remove(os.path.join(r2, "jobs", "job-a", "config.json")) # in part: its identity read now is another
if os.path.realpath(path) == os.path.realpath(os.path.join(r2, "jobs")):
os.remove(os.path.join(r2, "jobs", "job-a", "config.json")) # its jobs in part: its identity read now is another
raise PermissionError(13, "Permission denied", path)
return real(path, *a, **k)
with patch.object(execution.shutil, "rmtree", fails):
got = execution.delete(["r1", "r2"], self.home, self.root)
self.assertEqual(got["stays"], ["r2"])
self.assertEqual((got["stays"], got["kept"]), (["r2"], [f"r2 stays in {os.path.realpath(r2)}: Permission denied"]))
self.assertTrue(store.job_dirs(self.data, [uid]))
with self.subTest("a root that cannot be listed when they are decided"), \
patch.object(execution, "_copies", side_effect=PermissionError(13, "Permission denied")):
Expand Down Expand Up @@ -312,20 +313,81 @@ def test_a_sharded_launch_goes_whole_each_copy_from_its_own_host(self):

def test_a_folder_that_cannot_go_is_said_and_its_run_kept_whole(self):
self.run_("s1", host="ubuntu@10.0.0.4"); self.run_("s2", host="ubuntu@10.0.0.5")
real = shutil.rmtree
def rmtree(path, *a, **kw):
real = execution._remove_run
def remove(path):
if os.path.basename(path) == "s2":
raise PermissionError(13, "Permission denied", path)
return real(path, *a, **kw)
return real(path)
calls = []
with patch.object(execution.shutil, "rmtree", rmtree):
with patch.object(execution, "_remove_run", remove):
gone = execution.delete(["s1", "s2"], self.home, self.root, copies={"ubuntu@10.0.0.4", "ubuntu@10.0.0.5"},
run=lambda argv, timeout: calls.append(argv[-2]) or (0, ""))
s2 = os.path.realpath(os.path.join(self.root, "s2"))
self.assertEqual((gone["stays"], gone["kept"]), (["s2"], [f"s2 stays in {s2}: Permission denied"]))
self.assertEqual(calls, ["ubuntu@10.0.0.4"]) # s2's host copy stays with it
self.assertFalse(os.path.exists(os.path.join(self.root, "s1"))); self.assertTrue(os.path.isdir(s2))

def stays_listed_and_deletes_again(self, name, allow, kept):
folder = os.path.join(self.root, name)
self.assertEqual(execution.delete([name], self.home, self.root)["stays"], [name])
self.assertEqual([k for k in kept if not os.path.exists(os.path.join(folder, k))], [])
execution.EXECUTIONS.clear(); execution.restore(self.root)
self.assertIn(name, [e.plan.name for e in execution.EXECUTIONS.values()])
allow()
self.assertEqual(execution.delete([name], self.home, self.root)["stays"], [])
self.assertFalse(os.path.exists(folder))

@unittest.skipIf(os.geteuid() == 0, "root removes a read-only folder's files")
def test_a_removal_stopped_part_way_keeps_the_record_and_deletes_again(self):
job = os.path.join("jobs", "job-a", "config.json")
for i, locked in enumerate(("jobs", "", os.pardir)): # a file in its jobs, its folder, the runs root
with self.subTest(locked=locked):
name = f"p{i}"; self.run_(name)
folder = os.path.realpath(os.path.join(self.root, name, locked))
os.chmod(folder, 0o555) # as a root-owned container's output
self.addCleanup(lambda f=folder: os.path.isdir(f) and os.chmod(f, 0o755))
kept = [execution.RECORD] + ([] if locked == "jobs" else [job]) # a folder whose entries cannot go: nothing goes
self.stays_listed_and_deletes_again(name, lambda: os.chmod(folder, 0o755), kept)

def test_a_file_that_cannot_go_after_a_script_went_keeps_the_record_whole(self):
parts = [{"id": i, "label": i, "script": f"printf '{i}\r{i}'"} for i in "abcdefgh"] # a carriage return, kept as it is
ex = execution.Execution(execution.Plan(name="p", script="printf 'p\rp'", parts=parts), root=self.root)
ex.state = "done"; ex._save()
folder = os.path.join(self.root, "p")
with open(os.path.join(folder, "aux.sh"), "wb") as fh:
fh.write("printf 'café\r'\n".encode("latin-1")) # not UTF-8
scripts = {n: open(os.path.join(folder, n), "rb").read() for n in os.listdir(folder) if n.endswith(".sh")}
real, gone, refusing = os.unlink, [], [True]
def unlink(path, *a, **k):
if refusing and any(n.endswith(".sh") for n in gone):
raise PermissionError(13, "Permission denied", path) # the next file once a script went
real(path, *a, **k); gone.append(os.path.basename(path))
def allow():
self.assertEqual({n: open(os.path.join(folder, n), "rb").read() for n in scripts}, scripts) # as they were written
refusing.clear()
with patch.object(execution.os, "unlink", unlink), patch.object(execution.os, "remove", unlink):
self.stays_listed_and_deletes_again("p", allow, [execution.PLAN, execution.RECORD, *scripts])

def test_a_file_gone_since_the_listing_counts_as_removed(self):
folder = os.path.dirname(self.jobs)
saving = os.path.join(folder, ".0.part"); _write_json(saving, {}) # a save of the record, under way
real = os.scandir
def scandir(path=".", *a):
listed = real(path, *a)
if path != folder:
return listed
with listed:
entries = list(listed)
os.replace(saving, os.path.join(folder, execution.RECORD)) # the save completes once the folder is listed
return contextlib.nullcontext(entries)
remove = execution._remove_run
def removing(path): # the folder listed by the removal itself
with patch.object(execution.os, "scandir", scandir):
return remove(path)
with patch.object(execution, "_remove_run", removing):
self.assertEqual(execution.delete(["r1"], self.home, self.root)["stays"], [])
self.assertFalse(os.path.exists(folder))


class RunSize(unittest.TestCase):
setUp, run_ = RunDelete.setUp, RunDelete.run_
Expand Down
Loading