diff --git a/app/nullius/identity.py b/app/nullius/identity.py new file mode 100644 index 00000000..edc7ca7b --- /dev/null +++ b/app/nullius/identity.py @@ -0,0 +1,183 @@ +"""Who is who on disk: the profile an intent was written under, the profile a workspaces +folder belongs to, a workspace, a run. An unprovable match is no match. + +A profile is its data directory's path, device and inode, all three. One whose data +directory changed any of them (moved, copied, restored from a backup elsewhere or into a +folder made again) is another profile: it owns no workspaces folder marked before and +inherits no pending deletion. One restored in place, all three kept, is the same. The data +directory and the workspaces folder are made before the first claim; nothing here makes them. +""" +from __future__ import annotations + +import hashlib +import json +import math +import os +import uuid + +from nullius import ondisk, paths + +OWNER = "._owner.json" +OWNER_VERSION = 1 + + +class NotOwner(ValueError): + """A workspaces folder that another profile owns, or whose owner cannot be read.""" + + +def _int(value) -> bool: + return type(value) is int # never ``true`` for 1 + + +def _text(value) -> bool: + return isinstance(value, str) and bool(value) + + +def _finite(value) -> bool: + """A number a time can be: no infinity, no integer past what a float holds.""" + try: + return type(value) in (int, float) and math.isfinite(value) + except OverflowError: + return False + + +def _profile(value) -> bool: + return (isinstance(value, dict) and set(value) == {"path", "device", "inode"} and _text(value["path"]) + and _int(value["device"]) and _int(value["inode"])) + + +def origin(env=None) -> dict: + """The profile and roots this process writes under, as every intent records them.""" + data = os.path.realpath(paths.data_dir(env)) + found = os.stat(data) + return {"data_dir": {"path": data, "device": found.st_dev, "inode": found.st_ino}, + "workspaces_root": os.path.realpath(paths.workspaces_dir(env)), "runs_root": os.path.realpath(paths.runs_dir(env))} + + +def valid_origin(value) -> bool: + return (isinstance(value, dict) and set(value) == {"data_dir", "workspaces_root", "runs_root"} and _profile(value["data_dir"]) + and _text(value["workspaces_root"]) and _text(value["runs_root"])) + + +def same_origin(recorded, env=None) -> bool: + """*recorded* is this process's own profile and roots: else it was written under another profile.""" + try: + return valid_origin(recorded) and recorded == origin(env) + except OSError: + return False + + +def own(root, env=None) -> None: + """*root* is this profile's workspaces folder: from now on when no profile had it, since + of two taking it at once the link makes one the owner. ``NotOwner`` names another's.""" + mine, record = origin(env)["data_dir"], os.path.join(root, OWNER) + if not os.path.lexists(record): + part = os.path.join(root, f".{uuid.uuid4().hex}.part") + try: + with open(os.open(part, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as f: + os.fchmod(f.fileno(), 0o600) # its owner reads it back whatever the umask + json.dump({"version": OWNER_VERSION, "data_dir": mine}, f) + os.link(part, record) # made whole or not at all; never over another's + except FileExistsError: + pass + finally: + if os.path.lexists(part): + os.unlink(part) + try: + data = ondisk.read_record(record) + if not (set(data) == {"version", "data_dir"} and _int(data["version"]) and data["version"] == OWNER_VERSION and _profile(data["data_dir"])): + raise ValueError("not an owner record this Nullius reads") + except (OSError, ValueError) as error: + raise NotOwner(f"The owner of this workspaces folder cannot be read: {record}") from error + if data["data_dir"] != mine: + raise NotOwner(f"This workspaces folder belongs to the profile at {data['data_dir']['path']}.") + + +def _held(folder, read): + """``read`` of *folder* through one descriptor, a path's opened here, itself no link + (its parents may be: a configured root is): None when it cannot be.""" + if isinstance(folder, int): + return read(folder) + folder = os.fspath(folder) + while folder.rstrip("/").endswith("/.") or len(folder) > 1 and folder.endswith("/"): + folder = folder.rstrip("/").removesuffix("/.") or "/" # the same folder, spelt so that a link is followed: ``..`` stays + try: + fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except OSError: + return None + try: + return read(fd) + finally: + os.close(fd) + + +def _record(fd: int, name: str): + """The folder's own ``fstat`` and the object in its *name*, both through *fd*: a folder + swapped meanwhile cannot lend its record. None when either cannot be read.""" + try: + return os.fstat(fd), ondisk.read_record(name, dir_fd=fd) + except (OSError, ValueError): + return None + + +def workspace(folder) -> dict | None: + """The identity of the workspace in *folder*, a path or a directory descriptor its + caller holds and goes on reading through: ``uid`` (empty in one saved before it had + one), folder ``device`` and ``inode``, ``created``. None when it cannot be proved, or + its record is of a version ``workspace`` does not read.""" + from nullius import workspace as records # where it is imported from, in time + def read(fd): + found = _record(fd, "workspace.json") + if found is None or "version" in found[1] and not (_int(found[1]["version"]) and found[1]["version"] == records.RECORD_VERSION): + return None # one from before versions has none + value = {"uid": found[1].get("uid", ""), "device": found[0].st_dev, "inode": found[0].st_ino, "created": found[1].get("created", "")} + return value if valid_workspace(value) else None + return _held(folder, read) + + +def valid_workspace(value) -> bool: + """With no UID, a created time: one with neither has nothing to be matched by.""" + return (isinstance(value, dict) and set(value) == {"uid", "device", "inode", "created"} and isinstance(value["uid"], str) + and isinstance(value["created"], str) and bool(value["uid"] or value["created"]) and _int(value["device"]) and _int(value["inode"])) + + +def _proof(value: dict) -> list: + """What must match: with a UID, it and the folder; without, the folder and ``created``.""" + return [value["uid"], value["device"], value["inode"]] if value["uid"] else ["", value["device"], value["inode"], value["created"]] + + +def digest(value: dict) -> str: + """One opaque value for a workspace identity, equal exactly when two are the same workspace.""" + return hashlib.sha256(json.dumps(_proof(value)).encode()).hexdigest() + + +def same_workspace(a, b) -> bool: + return valid_workspace(a) and valid_workspace(b) and _proof(a) == _proof(b) + + +def run(folder) -> dict | None: + """What proves the run in *folder*, a path or a held directory descriptor: its + ``generation``; only for one saved without that field, ``id``, ``started`` and the + folder's ``device`` and ``inode`` together. None when it cannot be proved.""" + def read(fd): + found = _record(fd, "run.json") + if found is None: + return None + value = {"generation": found[1]["generation"]} if "generation" in found[1] else { + "id": found[1].get("id"), "started": found[1].get("started"), "device": found[0].st_dev, "inode": found[0].st_ino} + return value if valid_run(value) else None + return _held(folder, read) + + +def valid_run(value) -> bool: + if not isinstance(value, dict): + return False + if "generation" in value: + return set(value) == {"generation"} and _text(value["generation"]) + return (set(value) == {"id", "started", "device", "inode"} and _text(value["id"]) + and _finite(value["started"]) and _int(value["device"]) and _int(value["inode"])) + + +def same_run(a, b) -> bool: + """A run id alone proves nothing.""" + return valid_run(a) and valid_run(b) and a == b diff --git a/app/nullius/ondisk.py b/app/nullius/ondisk.py index 26b15d07..26ed748d 100644 --- a/app/nullius/ondisk.py +++ b/app/nullius/ondisk.py @@ -1,14 +1,17 @@ -"""A file written whole, a lock, a digest.""" +"""A file written whole, a record read, a lock, a digest.""" from __future__ import annotations import contextlib import errno import hashlib +import json import os import stat import time import uuid +WAIT = 1.0 # seconds one foreground sequence of locks waits, all of them together + # a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same _SEARCH = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY @@ -58,16 +61,65 @@ def write_whole(path, data, mode=None) -> None: os.close(folder) +def _regular(path, dir_fd=None) -> int: + """*path* open to read, when it is a regular file: no link followed, and nothing waited + for, so a FIFO put there is refused instead of read.""" + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=dir_fd) + if not stat.S_ISREG(os.fstat(fd).st_mode): + os.close(fd) + raise OSError(errno.EINVAL, "not a regular file", os.fspath(path)) + return fd + + +def _once(pairs) -> dict: + found = dict(pairs) + if len(found) != len(pairs): + raise ValueError("a key given twice") + return found + + +def record(raw) -> dict: + """The JSON object *raw* spells; ``ValueError`` when it is not one object, names a + key twice or nests too deep to read.""" + try: + data = json.loads(raw, object_pairs_hook=_once) + except RecursionError as error: + raise ValueError("nested too deep") from error + if not isinstance(data, dict): + raise ValueError("not an object") + return data + + +def read_record(path, dir_fd=None) -> dict: + """``record`` of the regular file *path*, under *dir_fd* when given; ``OSError`` when + it cannot be opened or is not one.""" + with os.fdopen(_regular(path, dir_fd), "rb") as f: + return record(f.read()) + + +class Busy(TimeoutError): + """A lock still held by another at the deadline.""" + + +def deadline(seconds=WAIT) -> float: + """The monotonic time by which a sequence of locks is had, shared by all of them.""" + return time.monotonic() + seconds + + FIRST_WAIT = 1.0 # seconds an opener waits for a lock file made at this moment by another to get its mode -def _lock_file(path) -> int: +def _lock_file(path, deadline=None) -> int: """*path* open to write, as a lock wants it (NFS locks need a writable descriptor): a regular file, no link followed, never replaced nor removed. Made when missing, owner read and write whatever the umask; one of - this user's left without owner write (its maker stopped before setting its mode) gets it back, in place; - another refusal is tried again for a moment.""" + this user's left without owner write (its maker stopped before setting its mode) gets it back, in place, + once; another refusal is tried again for a moment, no later than *deadline*.""" until = time.monotonic() + FIRST_WAIT + until, repaired, again = until if deadline is None else min(until, deadline), False, False while True: + if again and deadline is not None and time.monotonic() >= deadline: # before each retry: never had late + raise Busy(path) + again = True try: fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600) made = True @@ -78,12 +130,15 @@ def _lock_file(path) -> int: continue # gone since: made again except PermissionError: st = os.lstat(path) - if stat.S_ISREG(st.st_mode) and st.st_uid == os.geteuid() and not st.st_mode & 0o200: + if not repaired and stat.S_ISREG(st.st_mode) and st.st_uid == os.geteuid() and not st.st_mode & 0o200: os.chmod(path, stat.S_IMODE(st.st_mode) | 0o200, follow_symlinks=False) + repaired, again = True, False # no wait in it: a caller with one try has it too continue if time.monotonic() >= until: + if deadline is not None and until == deadline: + raise Busy(path) from None raise - time.sleep(0.005) + time.sleep(max(0, min(0.005, until - time.monotonic()))) continue made = False try: @@ -99,13 +154,29 @@ def _lock_file(path) -> int: @contextlib.contextmanager -def locked(path): +def locked(path, deadline=None): """One holder of ``path`` at a time, across processes and threads. The file holds - nothing and is never a link or a special file.""" + nothing and is never a link or a special file. + + Without ``deadline`` it waits. With one, a monotonic time, it raises ``Busy`` once + that passes; one already past tries once. Locks nested under one deadline share + its wait, and the one that fails releases those taken before it.""" import fcntl # POSIX only: imported where the lock is taken - fd = _lock_file(os.fspath(path)) + path = os.fspath(path) + fd = _lock_file(path, deadline) try: - fcntl.flock(fd, fcntl.LOCK_EX) + if deadline is None: + fcntl.flock(fd, fcntl.LOCK_EX) + else: + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + break + except BlockingIOError: + pass + time.sleep(max(0, min(deadline - time.monotonic(), 0.01))) + if time.monotonic() >= deadline: # checked before each retry: a late waiter never takes it + raise Busy(path) try: yield finally: diff --git a/app/nullius/paths.py b/app/nullius/paths.py index 4cd3d489..a81c7d5a 100644 --- a/app/nullius/paths.py +++ b/app/nullius/paths.py @@ -57,6 +57,11 @@ def own_prices_file(env=None) -> str: return f"{root}-own{ext}" +def profile_lock(env=None) -> str: + """The profile's one lock, whatever ``WORKSPACES_DIR`` and ``RUNS_DIR`` say. Permanent: never removed.""" + return os.path.join(data_dir(env), "._home.lock") + + def catalogue_dir(env=None) -> str: env = os.environ if env is None else env return env.get("NULLIUS_CATALOGUE") or os.path.join(data_dir(env), "catalogue") diff --git a/app/nullius/trash.py b/app/nullius/trash.py new file mode 100644 index 00000000..fbc09e8a --- /dev/null +++ b/app/nullius/trash.py @@ -0,0 +1,189 @@ +"""The trash of the configured runs and workspaces roots, ``/.trash//./``: +where an entry goes, what keeps it out of discovery, the intent it carries, one collector +per kind. Nothing here removes anything. + +An intent is acted on only under the profile and roots it was written under +(``identity``): a profile whose data directory changed path, device or inode, moved, copied +or restored elsewhere, does not inherit pending deletions, which stay, reported as written +under another profile. +""" +from __future__ import annotations + +import json +import os +import re +import stat +import time +import uuid +from datetime import datetime + +from nullius import identity, ondisk, paths + +KINDS = ("run", "workspace") +VERSION = 1 +INTENT = "intent.json" +STAMP = "%Y-%m-%dT%H:%M:%SZ" # UTC +_ENTRY = re.compile(r"(?P.+)\.(?P[0-9a-f]{32})", re.S) # the token follows the last dot: a dotted name parses +_FIELDS = {"version", "kind", "token", "name", "written", "origin", "subject", "steps", "pending", "payload"} + +# what ``read`` finds; only ``VALID`` may be acted on, only ``EMPTY`` removed +VALID, EMPTY, UNRECOGNISED, UNREADABLE, MISSING, DAMAGED, FUTURE, FOREIGN = ( + "valid", "empty", "unrecognised", "unreadable", "no intent", "damaged", "written by a later Nullius", "written under another profile") + + +class Refused(ValueError): + """A kind, name, trash folder or destination that is not safe to use. Nothing was touched.""" + + +class Invalid(ValueError): + """An intent that must not be acted on; its message is one of the states above.""" + + +def token() -> str: + return uuid.uuid4().hex + + +def _component(text) -> bool: + return isinstance(text, str) and text not in ("", ".", "..") and not any(c in text for c in ("/", os.sep, "\0")) + + +def parse(entry): + """``(name, token)`` of an entry's folder name, or None when it is not one: a single + path component, as its name is. The one check of a name and token, whoever asks.""" + found = _ENTRY.fullmatch(entry) if _component(entry) else None + return (found["name"], found["token"]) if found and _component(found["name"]) else None + + +def _named(name, token) -> bool: + return isinstance(name, str) and isinstance(token, str) and parse(f"{name}.{token}") == (name, token) + + +def root(kind: str, env=None) -> str: + """The configured root *kind* is trashed under, resolved: never a caller's own choice.""" + if kind not in KINDS: + raise Refused(f"{kind!r} is not a kind of trash") + return os.path.realpath(paths.runs_dir(env) if kind == "run" else paths.workspaces_dir(env)) + + +def folder(kind: str, make: bool = False, env=None) -> str: + """The folder of *kind*'s entries, once it and ``.trash`` are real directories (no + link) on their root's device, ours, mode 0700. ``FileNotFoundError`` when there is + none and *make* is not asked.""" + path = root(kind, env) + device = os.stat(path).st_dev + for part in (".trash", kind): + path = os.path.join(path, part) + if make: + try: + os.mkdir(path, 0o700) + os.chmod(path, 0o700) # the umask may have taken bits off + except FileExistsError: + pass + found = os.lstat(path) + wrong = ("is not a real folder" if not stat.S_ISDIR(found.st_mode) else "is on another device" if found.st_dev != device + else "belongs to another user" if found.st_uid != os.geteuid() else "is not mode 0700" if stat.S_IMODE(found.st_mode) != 0o700 else "") + if wrong: + raise Refused(f"{path} {wrong}") + return path + + +def destination(kind: str, name: str, token: str, env=None) -> str: + """Where *name* goes when trashed under *token*, its folders made. One that exists refuses.""" + if not _named(name, token): + raise Refused(f"{name!r} with {token!r} names no trash entry") + path = os.path.join(folder(kind, make=True, env=env), f"{name}.{token}") + if os.path.lexists(path): + raise Refused(f"{path} exists") + return path + + +def in_trash(path, env=None) -> bool: + """*path* leads to, or into, the trash of a configured root, however it is spelt: what + discovery leaves out. Links are resolved as they are met, never after ``..`` is + folded away; a linked ``.trash`` is left out with what it leads to. A ``.trash`` + anywhere else is read.""" + reached, trashes = os.path.realpath(path), set() + for kind in KINDS: + trash = os.path.join(root(kind, env), ".trash") + trashes |= {trash, os.path.realpath(trash)} + return any(os.path.commonpath([reached, trash]) == trash for trash in trashes) + + +def collector(kind: str, env=None): + """The one collector of *kind*, never waited for: ``ondisk.Busy`` when cleanup is + running elsewhere.""" + return ondisk.locked(os.path.join(folder(kind, env=env), ".collector.lock"), deadline=time.monotonic()) + + +def intent(kind: str, name: str, token: str, subject: dict, payload: dict | None = None, env=None) -> dict: + """The envelope written as ``intent.json`` in the live folder before its rename; + ``Invalid`` for one that would not be read back.""" + return validate({"version": VERSION, "kind": kind, "token": token, "name": name, "written": time.strftime(STAMP, time.gmtime()), + "origin": identity.origin(env), "subject": subject, "steps": {}, "pending": None, + "payload": {} if payload is None else payload}, kind, name, token, env) + + +def _stamp(value) -> bool: + """*value* is a time exactly as it is written here.""" + try: + return isinstance(value, str) and datetime.strptime(value, STAMP).strftime(STAMP) == value + except ValueError: + return False + + +def _written(data) -> bool: + """*data* is what reading it back from its file gives: no key that becomes another's, nothing JSON does not hold.""" + try: + return ondisk.record(json.dumps(data, allow_nan=False)) == data + except (TypeError, ValueError, RecursionError): + return False + + +def validate(data, kind: str, name: str, token: str, env=None) -> dict: + """*data* when it is the intent of this entry, written under this profile and roots; + else ``Invalid``. The subject is the kind handler's to check against the disk, as + are its own steps and payload.""" + if not isinstance(data, dict) or type(data.get("version")) is not int: + raise Invalid(DAMAGED) + if data["version"] > VERSION: + raise Invalid(FUTURE) + subject = identity.valid_workspace if kind == "workspace" else identity.valid_run + if not (data["version"] == VERSION and set(data) == _FIELDS and kind in KINDS and _named(name, token) + and (data["kind"], data["name"], data["token"]) == (kind, name, token) and _stamp(data["written"]) + and identity.valid_origin(data["origin"]) and subject(data["subject"]) + and isinstance(data["steps"], dict) and all(isinstance(k, str) and _stamp(v) for k, v in data["steps"].items()) + and (data["pending"] is None or isinstance(data["pending"], dict) and set(data["pending"]) == {"step", "reason", "at"} + and isinstance(data["pending"]["step"], str) and isinstance(data["pending"]["reason"], str) and _stamp(data["pending"]["at"])) + and isinstance(data["payload"], dict) and _written(data)): + raise Invalid(DAMAGED) + if not identity.same_origin(data["origin"], env): + raise Invalid(FOREIGN) + return data + + +def read(kind: str, entry: str, env=None) -> tuple: + """``(state, intent)`` of one entry of the configured root, its contents untouched; the + intent only when ``VALID``. ``EMPTY`` is a recognised entry seen to hold nothing; + one that cannot be listed, or whose intent is no regular file, is ``UNREADABLE``.""" + parsed = parse(entry) + if parsed is None: + return UNRECOGNISED, None + try: + fd = os.open(os.path.join(folder(kind, env=env), entry), os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return UNREADABLE, None + try: + names = os.listdir(fd) + if INTENT not in names: + return (MISSING if names else EMPTY), None + data = ondisk.read_record(INTENT, dir_fd=fd) + except OSError: + return UNREADABLE, None + except ValueError: + return DAMAGED, None + finally: + os.close(fd) + try: + return VALID, validate(data, kind, *parsed, env=env) + except Invalid as error: + return str(error), None diff --git a/app/tests/test_identity_on_disk.py b/app/tests/test_identity_on_disk.py new file mode 100644 index 00000000..873bd4fa --- /dev/null +++ b/app/tests/test_identity_on_disk.py @@ -0,0 +1,217 @@ +"""``nullius.identity``: the profile a root belongs to, the same workspace, the same run.""" +import json +import os +import shutil +import tempfile +import threading +import unittest +from unittest import mock + +from nullius import identity, paths + + +def put(folder, name, data): + os.makedirs(folder, exist_ok=True) + with open(os.path.join(folder, name), "w") as f: + json.dump(data, f) + + +class Case(unittest.TestCase): + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def profile(self, name, **roots): + env = {"NULLIUS_HOME": os.path.join(self.tmp, name), **roots} + os.makedirs(paths.data_dir(env)) + return env + + +class Profile(Case): + def test_an_origin_is_its_own_profile_and_roots_and_no_other(self): + a, b = self.profile("a"), self.profile("b") + recorded = json.loads(json.dumps(identity.origin(a))) + self.assertTrue(identity.same_origin(recorded, a)) + self.assertFalse(identity.same_origin(recorded, b)) + for moved in ("WORKSPACES_DIR", "RUNS_DIR"): # the same profile, a root relocated + self.assertFalse(identity.same_origin(recorded, {**a, moved: os.path.join(self.tmp, "elsewhere")})) + self.assertFalse(identity.same_origin({**recorded, "runs_root": 1}, a)) + self.assertFalse(identity.same_origin(recorded, {"NULLIUS_HOME": os.path.join(self.tmp, "none")})) + os.rename(a["NULLIUS_HOME"], a["NULLIUS_HOME"] + "-old") # another profile made at the same path + os.makedirs(paths.data_dir(a)) + self.assertFalse(identity.same_origin(recorded, a)) + + def test_of_two_profiles_taking_an_unmarked_root_at_once_one_owns_it(self): + root = os.path.join(self.tmp, "shared") + os.mkdir(root) + envs = [self.profile("a", WORKSPACES_DIR=root), self.profile("b", WORKSPACES_DIR=root)] + both, link, refused, owned = threading.Barrier(2, timeout=5), os.link, [], [] + def together(src, dst): + both.wait() # each has written its own record, neither has linked + return link(src, dst) + def take(env): + try: + identity.own(root, env) + owned.append(env) + except identity.NotOwner as error: + refused.append(str(error)) + with mock.patch.object(os, "link", together): + threads = [threading.Thread(target=take, args=(env,)) for env in envs] + for t in threads: t.start() + for t in threads: t.join(10) + self.assertEqual((len(owned), len(refused)), (1, 1)) + owner = paths.data_dir(owned[0]) + self.assertEqual(refused, [f"This workspaces folder belongs to the profile at {owner}."]) + self.assertEqual(os.listdir(root), [identity.OWNER]) # nothing left beside it + identity.own(root, owned[0]) # every later use compares + loser = next(env for env in envs if env is not owned[0]) + with self.assertRaisesRegex(identity.NotOwner, owner): + identity.own(root, loser) + record, mine = os.path.join(root, identity.OWNER), identity.origin(owned[0])["data_dir"] + kept = os.path.join(self.tmp, "kept") + os.rename(record, kept) + wrong = ["{", json.dumps({"version": True, "data_dir": mine}), json.dumps({"version": 2, "data_dir": mine}), + json.dumps({"version": 1, "data_dir": {**mine, "device": True}}), json.dumps({"version": 1, "data_dir": {**mine, "inode": str(mine["inode"])}}), + json.dumps({"version": 1, "data_dir": mine})[:-1] + ', "version": 1}', os.mkfifo, lambda path: os.symlink(kept, path)] + for made in wrong: + if callable(made): + made(record) + else: + with open(record, "w") as f: + f.write(made) + with self.assertRaisesRegex(identity.NotOwner, "cannot be read"): + identity.own(root, owned[0]) # never read as ours, never taken over, never waited for + os.unlink(record) + os.rename(kept, record) + identity.own(root, owned[0]) + + + def test_a_first_claim_under_a_closed_umask_is_read_back_by_its_owner(self): + root, env = os.path.join(self.tmp, "w"), self.profile("a") + os.mkdir(root) + old = os.umask(0o477) + try: + identity.own(root, env) + finally: + os.umask(old) + self.assertEqual(os.stat(os.path.join(root, identity.OWNER)).st_mode & 0o777, 0o600) + identity.own(root, env) + + +class Workspace(Case): + def make(self, name, **record): + folder = os.path.join(self.tmp, name) + put(folder, "workspace.json", {"name": name, **record}) + return folder + + def test_a_rename_keeps_it_and_a_copy_under_its_name_is_another(self): + folder = self.make("w", uid="u1", created="2026-01-01T00:00:00Z") + before = identity.workspace(folder) + self.assertEqual((before["uid"], before["created"], before["inode"]), ("u1", "2026-01-01T00:00:00Z", os.stat(folder).st_ino)) + os.rename(folder, folder + "-renamed") + renamed = identity.workspace(folder + "-renamed") + self.assertTrue(identity.same_workspace(before, renamed)) + self.assertEqual(identity.digest(before), identity.digest(renamed)) + shutil.copytree(folder + "-renamed", folder) # a replacement carrying the copied UID + copy = identity.workspace(folder) + self.assertEqual(copy["uid"], "u1") + self.assertFalse(identity.same_workspace(before, copy)) + self.assertNotEqual(identity.digest(before), identity.digest(copy)) + self.assertFalse(identity.same_workspace(before, identity.workspace(os.path.join(self.tmp, "gone")))) + self.assertFalse(identity.same_workspace(None, None)) + + def test_it_is_read_through_a_folder_its_caller_holds(self): + folder = self.make("w", uid="u1", created="2026-01-01T00:00:00Z") + fd = os.open(folder, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, fd) + before = identity.workspace(fd) + self.assertEqual(before, identity.workspace(folder)) + os.rename(folder, folder + "-renamed") + self.make("w", uid="u2", created="2026-02-02T00:00:00Z") # another under its name: the held folder is still the first + self.assertEqual(identity.workspace(fd), before) + self.assertEqual(identity.workspace(folder)["uid"], "u2") + os.fstat(fd) # left open for its caller + run = os.path.join(self.tmp, "run") + put(run, "run.json", {"generation": "g1"}) + held = os.open(run, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, held) + self.assertEqual(identity.run(held), {"generation": "g1"}) + + def test_one_with_nothing_to_match_or_no_regular_record_is_no_one(self): + for record in ({}, {"created": ""}, {"uid": "", "created": ""}, {"uid": None, "created": "2026-01-01T00:00:00Z"}, {"uid": 1}): + folder = self.make("w", **record) + os.unlink(os.path.join(folder, "workspace.json")) + put(folder, "workspace.json", record) # not even a name + self.assertIsNone(identity.workspace(folder), record) + self.assertIsNotNone(identity.workspace(self.make("first", uid="u1"))) # from before versions + self.assertIsNotNone(identity.workspace(self.make("now", uid="u1", version=1))) + for version in (2, "1", True, None): # one ``workspace.load`` does not read + self.assertIsNone(identity.workspace(self.make(f"v{version}", uid="u1", version=version)), version) + parent, link = os.path.join(self.tmp, "parent"), os.path.join(self.tmp, "w-link") + os.symlink(self.tmp, parent) + os.symlink(os.path.join(self.tmp, "now"), link) + self.assertEqual(identity.workspace(os.path.join(parent, "now")), identity.workspace(os.path.join(self.tmp, "now"))) # an aliased root + for spelt in ("", "/", "/.", "/./", "//.//"): + self.assertIsNone(identity.workspace(link + spelt), spelt) # a link in its place lends nothing, however it is spelt + self.assertIsNotNone(identity.workspace(os.path.join(self.tmp, "now") + spelt), spelt) + self.assertIsNotNone(identity.workspace(link + "/../now/")) # ``..`` after a link is the system's to read + empty = {"uid": "", "device": 1, "inode": 2, "created": ""} + self.assertFalse(identity.valid_workspace(empty)) + self.assertFalse(identity.same_workspace(empty, empty)) + real = self.make("real", uid="u1") + for made in (os.mkfifo, lambda path: os.symlink(os.path.join(real, "workspace.json"), path)): + os.unlink(os.path.join(folder, "workspace.json")) + made(os.path.join(folder, "workspace.json")) + self.assertIsNone(identity.workspace(folder)) # a pipe is not waited for, a link not followed + + def test_one_without_a_uid_needs_its_folder_and_created_time_all_three(self): + folder = self.make("old", created="2025-01-01T00:00:00Z") + before = identity.workspace(folder) + self.assertEqual(before["uid"], "") + self.assertTrue(identity.same_workspace(before, identity.workspace(folder))) + self.assertTrue(identity.same_workspace(before, json.loads(json.dumps(before)))) # as an intent carries it + for field, other in (("created", "2025-01-02T00:00:00Z"), ("device", before["device"] + 1), ("inode", before["inode"] + 1), ("uid", "u1")): + self.assertFalse(identity.same_workspace(before, {**before, field: other}), field) + self.assertNotEqual(identity.digest(before), identity.digest({**before, field: other}), field) + self.make("old", created="2025-01-02T00:00:00Z") # rewritten in place: the same folder, another created + self.assertFalse(identity.same_workspace(before, identity.workspace(folder))) + self.assertFalse(identity.same_workspace(before, {k: v for k, v in before.items() if k != "created"})) + + +class Run(Case): + def test_two_runs_with_one_id_and_start_are_two_runs(self): + record = {"id": "bench-1700000000", "started": 1700000000.5} + first, second = os.path.join(self.tmp, "runs", "bench"), os.path.join(self.tmp, "other", "bench") + put(first, "run.json", record) + put(second, "run.json", record) + a, b = identity.run(first), identity.run(second) + self.assertEqual((a["id"], a["started"]), (b["id"], b["started"])) + self.assertTrue(identity.same_run(a, identity.run(first))) + self.assertFalse(identity.same_run(a, b)) + self.assertFalse(identity.same_run({"id": a["id"]}, {"id": a["id"]})) # an id alone proves nothing + self.assertFalse(identity.same_run(a, {**a, "started": a["started"] + 1})) + put(first, "run.json", {**record, "generation": "g1"}) + put(second, "run.json", {**record, "generation": "g2"}) + new = identity.run(first) + self.assertEqual(new, {"generation": "g1"}) + self.assertTrue(identity.same_run(new, {"generation": "g1"})) + self.assertFalse(identity.same_run(new, identity.run(second))) + self.assertFalse(identity.same_run(new, a)) # confirmed before it had one: confirm again + put(first, "run.json", {"id": "bench-1700000000"}) + self.assertIsNone(identity.run(first)) + for generation in (None, "", 1): # there and worthless: never the older proof instead + put(first, "run.json", {**record, "generation": generation}) + self.assertIsNone(identity.run(first), generation) + self.assertFalse(identity.same_run({**a, "generation": None}, {**a, "generation": None})) + self.assertFalse(identity.same_run({**a, "device": True}, {**a, "device": True})) + with open(os.path.join(first, "run.json"), "w") as f: + f.write('{"id": "bench-1700000000", "started": 1e400}') # read as infinity + self.assertIsNone(identity.run(first)) + for never in (float("inf"), float("nan")): + self.assertFalse(identity.valid_run({**a, "started": never})) + os.symlink(second, os.path.join(self.tmp, "linked")) + self.assertEqual(identity.run(second), {"generation": "g2"}) + for spelt in ("", "/", "/.", "/./"): + self.assertIsNone(identity.run(os.path.join(self.tmp, "linked") + spelt), spelt) # as ``execution.run_folder`` refuses it + self.assertEqual(identity.run(second + spelt), {"generation": "g2"}, spelt) + self.assertFalse(identity.valid_run({**a, "started": 10 ** 309})) diff --git a/app/tests/test_ondisk.py b/app/tests/test_ondisk.py index e92f0b8e..5d8b0f32 100644 --- a/app/tests/test_ondisk.py +++ b/app/tests/test_ondisk.py @@ -8,10 +8,11 @@ import tempfile import textwrap import threading +import time import unittest from unittest import mock -from nullius import ondisk +from nullius import ondisk, paths class Whole(unittest.TestCase): @@ -328,6 +329,152 @@ def test_a_linked_lock_is_refused(self): with ondisk.locked(path): pass + +class Deadline(unittest.TestCase): + """The profile lock, waited for until a deadline.""" + def setUp(self): + self.tmp = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.tmp, True) + self.profile = {"NULLIUS_HOME": self.tmp} + os.makedirs(paths.data_dir(self.profile)) + self.lock = paths.profile_lock(self.profile) + + def held(self, path, seconds=None): + """A thread holding *path* now: for *seconds*, or until the test ends or sets what is returned.""" + has, free = threading.Event(), threading.Event() + def hold(): + with ondisk.locked(path): + has.set() + free.wait(seconds) + t = threading.Thread(target=hold) + t.start() + self.addCleanup(t.join, 5) + self.addCleanup(free.set) + self.assertTrue(has.wait(5)) + return free + + def test_a_thread_holding_it_is_waited_for_until_the_deadline_only(self): + with ondisk.locked(self.lock, ondisk.deadline()): # free: had at once + pass + free, start = self.held(self.lock), time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline()): # the one-second default + self.fail("two holders") + took = time.monotonic() - start + self.assertTrue(ondisk.WAIT <= took < ondisk.WAIT + 0.5, took) + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, time.monotonic()): # a deadline already past: one try + self.fail("two holders") + self.assertLess(time.monotonic() - start, 0.2) + threading.Timer(0.2, free.set).start() + start = time.monotonic() + with ondisk.locked(self.lock, ondisk.deadline()): + took = time.monotonic() - start + self.assertTrue(0.15 <= took < ondisk.WAIT, took) + + def test_another_process_with_its_roots_elsewhere_takes_the_same_lock(self): + moved = {**self.profile, "WORKSPACES_DIR": os.path.join(self.tmp, "w"), "RUNS_DIR": os.path.join(self.tmp, "r")} + self.assertEqual(paths.profile_lock(moved), os.path.join(self.tmp, "data", "._home.lock")) + script = textwrap.dedent(""" + import sys + from nullius import ondisk, paths + with ondisk.locked(paths.profile_lock()): + print("held", flush=True) + sys.stdin.read() + """) + app = os.path.dirname(os.path.dirname(os.path.abspath(ondisk.__file__))) + other = subprocess.Popen([sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env={**os.environ, **moved, "PYTHONPATH": app}) + self.addCleanup(other.wait, 5) + self.addCleanup(other.stdin.close) + self.assertEqual(other.stdout.readline(), "held\n") + other.stdout.close() + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.3)): + self.fail("two holders") + took = time.monotonic() - start + self.assertTrue(0.3 <= took < 0.8, took) + other.stdin.close() + with ondisk.locked(self.lock, ondisk.deadline()): + pass + self.assertTrue(os.path.exists(self.lock)) # permanent + + def test_one_deadline_covers_every_lock_and_a_timeout_releases_those_already_had(self): + first, second = self.lock, os.path.join(self.tmp, "second.lock") + self.held(first, 0.25) + self.held(second) + start, until = time.monotonic(), ondisk.deadline(0.5) + with self.assertRaises(ondisk.Busy) as busy: + with ondisk.locked(first, until): + had = time.monotonic() - start + with ondisk.locked(second, until): + self.fail("two holders") + took = time.monotonic() - start + self.assertEqual(busy.exception.args, (second,)) + self.assertTrue(0.2 <= had < 0.5 <= took < 0.9, (had, took)) # not 250 ms and then 500 more + with ondisk.locked(first, time.monotonic()): # the first was given back + pass + + def test_a_waiter_that_wakes_after_its_deadline_does_not_take_a_lock_freed_meanwhile(self): + free, nap = self.held(self.lock), time.sleep + def overslept(seconds): + free.set() # the holder lets go while this waiter is late + nap(0.1) + with mock.patch.object(time, "sleep", overslept), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.025)): + self.fail("had after its deadline") + + def test_the_deadline_covers_a_lock_file_that_stays_refused(self): + with ondisk.locked(self.lock): + pass + real = os.open + def refused(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT: + raise PermissionError("made at this moment, its mode not yet set") + return real(path, flags, *a, **k) + start = time.monotonic() + with mock.patch.object(os, "open", refused), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.2)): + self.fail("held") + self.assertTrue(0.2 <= time.monotonic() - start < 0.7) + with mock.patch.object(os, "open", refused), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, time.monotonic()): # the collector's one try + self.fail("held") + nap, late = time.sleep, [] + def once(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT and not late: + raise PermissionError("refused this once") + return real(path, flags, *a, **k) + def overslept(seconds): + late.append(seconds) # allowed from now on, and this waiter is late + nap(0.1) + with mock.patch.object(os, "open", once), mock.patch.object(time, "sleep", overslept), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.015)): + self.fail("had after its deadline") + self.assertTrue(late and max(late) <= 0.005, late) + def gone(path, flags, *a, **k): + if path == self.lock and not flags & os.O_CREAT: + raise FileNotFoundError("removed at this moment") + return real(path, flags, *a, **k) + start = time.monotonic() + with mock.patch.object(os, "open", gone), self.assertRaises(ondisk.Busy): + with ondisk.locked(self.lock, ondisk.deadline(0.05)): + self.fail("had after its deadline") + self.assertTrue(0.05 <= time.monotonic() - start < 0.5) + os.chmod(self.lock, 0o400) # left by a maker that stopped: put right within one try + with ondisk.locked(self.lock, time.monotonic()): + pass + + def test_a_caller_without_a_deadline_waits_past_the_default(self): + self.held(self.lock, ondisk.WAIT + 0.2) + start = time.monotonic() + with ondisk.locked(self.lock): + took = time.monotonic() - start + self.assertGreaterEqual(took, ondisk.WAIT + 0.1) + + class Digest(unittest.TestCase): def test_it_is_the_sha256_of_the_bytes(self): with tempfile.NamedTemporaryFile(delete=False) as f: diff --git a/app/tests/test_trash.py b/app/tests/test_trash.py new file mode 100644 index 00000000..3d8a1d49 --- /dev/null +++ b/app/tests/test_trash.py @@ -0,0 +1,311 @@ +"""``nullius.trash``: where an entry goes, what discovery leaves out, which intents may be acted on.""" +import json +import os +import shutil +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +from unittest import mock + +from nullius import ondisk, paths, trash + +T1, T2 = "0123456789abcdef" * 2, "f" * 32 + + +class Case(unittest.TestCase): + def setUp(self): + self.tmp = os.path.realpath(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.root = os.path.join(self.tmp, "root") # runs and workspaces in one folder + self.env = {"NULLIUS_HOME": os.path.join(self.tmp, "home"), "WORKSPACES_DIR": self.root, "RUNS_DIR": self.root} + os.makedirs(paths.data_dir(self.env)) + os.mkdir(self.root) + + def entry(self, kind, name, token, intent=None, env=None, **files): + """An entry as a producer leaves it: its intent and files, in place.""" + path = trash.destination(kind, name, token, env or self.env) + os.mkdir(path) + if intent is not None: + files[trash.INTENT] = intent if isinstance(intent, (str, bytes)) else json.dumps(intent) + for file, text in files.items(): + with open(os.path.join(path, file), "wb") as f: + f.write(text if isinstance(text, bytes) else text.encode()) + return path + + def intent(self, kind="run", name="bench", token=T1, env=None): + subject = {"generation": "g1"} if kind == "run" else {"uid": "u1", "device": 1, "inode": 2, "created": ""} + return trash.intent(kind, name, token, subject, env=env or self.env) + + def read(self, kind, entry, env=None): + return trash.read(kind, entry, env or self.env) + + +class Paths(Case): + def test_the_token_follows_the_last_dot_of_one_path_component(self): + self.assertEqual(trash.parse(f"a.{T1}"), ("a", T1)) + self.assertEqual(trash.parse(f"a.b.{T1}"), ("a.b", T1)) # never an entry of ``a`` + self.assertEqual(trash.parse(f"v1.2.{T1}.{T2}"), (f"v1.2.{T1}", T2)) + for other in ("a", T1, f".{T1}", f"a.{T1.upper()}", f"a.{T1[:-1]}", f"a.{T1}0", f"a-{T1}", ".collector.lock", + f"a/b.{T1}", f"../a.{T1}", f"/a.{T1}", f"...{T1}", f"..{T1}", f"a\0b.{T1}", "", None, 1): + self.assertIsNone(trash.parse(other), other) + self.assertRegex(trash.token(), r"\A[0-9a-f]{32}\Z") + path = trash.destination("run", "a.b", T1, self.env) + self.assertEqual(path, os.path.join(self.root, ".trash", "run", f"a.b.{T1}")) + self.assertEqual(os.stat(os.path.dirname(path)).st_mode & 0o777, 0o700) + good = self.intent() + for name, token in (("", T1), ("a/b", T1), ("..", T1), (".", T1), ("a\0", T1), (None, T1), ("a", "nope"), ("a", T1.upper()), ("a", None)): + with self.assertRaises(trash.Refused): # the builder, the reader and the validator, one check + trash.destination("run", name, token, self.env) + with self.assertRaises(trash.Invalid): + trash.validate({**good, "name": name, "token": token}, "run", name, token, self.env) + with self.assertRaises(trash.Invalid): + trash.intent("run", name, token, {"generation": "g1"}, env=self.env) + self.assertEqual(self.read("run", f"../run/a.b.{T1}"), (trash.UNRECOGNISED, None)) + for use in (lambda: trash.destination("job", "a", T1, self.env), lambda: self.read("job", f"a.{T1}"), lambda: trash.collector("job", self.env)): + with self.assertRaises(trash.Refused): + use() + + def test_a_run_and_a_workspace_of_one_name_neither_bar_nor_meet_each_other(self): + run = self.entry("run", "same", T1, self.intent("run", "same")) + workspace = self.entry("workspace", "same", T1, self.intent("workspace", "same")) + self.assertNotEqual(run, workspace) + self.assertEqual([self.read(kind, f"same.{T1}")[0] for kind in trash.KINDS], [trash.VALID] * 2) + os.rename(os.path.join(run, trash.INTENT), os.path.join(run, "moved")) + self.assertEqual(self.read("workspace", f"same.{T1}")[0], trash.VALID) + with trash.collector("run", self.env), trash.collector("workspace", self.env): # one collector per kind + pass + + def test_each_kind_is_read_under_its_own_configured_root_only(self): + runs = os.path.join(self.tmp, "runs") + os.mkdir(runs) + apart = {**self.env, "RUNS_DIR": runs} + self.assertEqual(os.path.dirname(trash.destination("run", "a", T1, apart)), os.path.join(runs, ".trash", "run")) + self.assertEqual(os.path.dirname(trash.destination("workspace", "a", T1, apart)), os.path.join(self.root, ".trash", "workspace")) + link = os.path.join(self.tmp, "link") # a configured root may be an alias + os.symlink(runs, link) + self.assertEqual(trash.destination("run", "a", T1, {**apart, "RUNS_DIR": link}), os.path.join(runs, ".trash", "run", f"a.{T1}")) + self.entry("run", "misplaced", T1, self.intent("run", "misplaced")) # in the workspaces root: no run trash of this configuration + self.entry("run", "hollow", T1) + self.assertEqual(self.read("run", f"misplaced.{T1}", apart), (trash.UNREADABLE, None)) + self.assertEqual(self.read("run", f"hollow.{T1}", apart), (trash.UNREADABLE, None)) # not EMPTY there + self.entry("run", "copied", T1, self.intent("run", "copied"), env=apart) # an intent of the other configuration, copied over + self.assertEqual(self.read("run", f"copied.{T1}", apart), (trash.FOREIGN, None)) + self.entry("run", "ours", T1, self.intent("run", "ours", env=apart), env=apart) + self.assertEqual(self.read("run", f"ours.{T1}", apart)[0], trash.VALID) + + def test_an_existing_destination_refuses(self): + path = self.entry("run", "a", T1, kept="x") + with self.assertRaisesRegex(trash.Refused, "exists"): + trash.destination("run", "a", T1, self.env) + self.assertEqual(os.listdir(path), ["kept"]) + trash.destination("run", "a", T2, self.env) # the same name under another token + os.symlink(os.path.join(self.tmp, "nowhere"), os.path.join(self.root, ".trash", "run", f"b.{T1}")) # a link to nothing counts + with self.assertRaisesRegex(trash.Refused, "exists"): + trash.destination("run", "b", T1, self.env) + + def test_trash_folders_that_are_not_ours_alone_refuse(self): + def refused(reason, kind="run"): + for use in (lambda: trash.destination(kind, "a", T1, self.env), lambda: self.read(kind, f"a.{T1}"), + lambda: trash.collector(kind, self.env)): + with self.assertRaisesRegex(trash.Refused, reason): + use() + trash.destination("run", "a", T1, self.env) + top, kind = os.path.join(self.root, ".trash"), os.path.join(self.root, ".trash", "run") + real = os.lstat + def elsewhere_mounted(path): + found = real(path) + return os.stat_result((*found[:2], found.st_dev + 1, *found[3:])) if path == kind else found + with mock.patch.object(os, "lstat", elsewhere_mounted): + refused("another device") + with mock.patch.object(os, "geteuid", lambda: os.stat(top).st_uid + 1): + refused("another user") + for folder in (kind, top): + os.chmod(folder, 0o750) + refused("not mode 0700") + os.chmod(folder, 0o700) + elsewhere = os.path.join(self.tmp, "elsewhere") + os.mkdir(elsewhere, 0o700) + os.symlink(elsewhere, os.path.join(top, "workspace")) + refused("not a real folder", "workspace") + os.rename(top, top + "-real") + os.symlink(top + "-real", top) + refused("not a real folder") + self.assertEqual(os.listdir(elsewhere), []) # nothing made through a link + + def test_only_the_trash_of_the_configured_roots_is_left_out_of_discovery(self): + runs = os.path.join(self.tmp, "runs") + env = {**self.env, "RUNS_DIR": runs} + entry = self.entry("workspace", "w", T1) + inner = os.path.join(runs, ".trash", "run", f"r.{T1}", "jobs") + os.makedirs(inner) + os.makedirs(os.path.join(self.root, "w", ".trash")) + unrelated = os.path.join(self.tmp, "imports", ".trash", "job") # a folder that merely has the name + os.makedirs(unrelated) + alias, into = os.path.join(self.tmp, "alias"), os.path.join(self.tmp, "into") + os.symlink(self.root, alias) + os.symlink(inner, into) # an alias into real trash + os.symlink(unrelated, os.path.join(entry, "out")) + for inside in (os.path.join(self.root, ".trash"), entry, os.path.join(entry, "jobs", "j"), os.path.join(alias, ".trash", "workspace"), + os.path.join(runs, ".trash"), inner, into, os.path.join(into, "j"), os.path.join(self.root, "w", "..", ".trash", "workspace"), + os.path.join(into, ".."), # the entry itself: ``..`` after the link, not of its name + os.path.join(entry, "out", "..", "..", "..", "root", ".trash")): + self.assertTrue(trash.in_trash(inside, env), inside) + for outside in (self.root, runs, os.path.join(self.root, "w"), os.path.join(self.root, "w", ".trash"), os.path.join(self.root, ".trashed"), + unrelated, os.path.dirname(unrelated), os.path.join(entry, "out"), os.path.join(entry, "out", ".."), + os.path.join(entry, "..", "..", "..", "w")): + self.assertFalse(trash.in_trash(outside, env), outside) + self.assertFalse(trash.in_trash(os.path.join(runs, ".trash"), self.env)) # no root of this configuration + os.symlink(unrelated, os.path.join(runs, "linked")) + self.assertFalse(trash.in_trash(os.path.join(runs, "linked"), env)) + os.rename(os.path.join(runs, ".trash"), os.path.join(runs, "real")) + os.symlink(os.path.join(runs, "real"), os.path.join(runs, ".trash")) + for inside in (os.path.join(runs, ".trash"), os.path.join(runs, ".trash", "run", f"r.{T1}"), into): # a linked one, and under it + self.assertTrue(trash.in_trash(inside, env), inside) + os.unlink(os.path.join(runs, ".trash")) + os.symlink("/", os.path.join(runs, ".trash")) # one that leads to the top: by component, not by prefix + for inside in ("/", os.path.join(runs, ".trash"), os.path.join(runs, ".trash", "usr"), os.path.join(runs, "real")): + self.assertTrue(trash.in_trash(inside, env), inside) + + +class Intents(Case): + def tree(self): + found = [] + for folder, _, files in os.walk(self.root): + for file in sorted(files): + with open(os.path.join(folder, file), "rb") as f: + found.append((folder, file, f.read())) + return sorted(found) + + def test_only_a_whole_intent_of_this_entry_and_profile_is_valid(self): + good = self.intent() + self.assertEqual(set(good), {"version", "kind", "token", "name", "written", "origin", "subject", "steps", "pending", "payload"}) + self.entry("run", "bench", T1, good, kept="x") + self.assertEqual(self.read("run", f"bench.{T1}"), (trash.VALID, good)) + done = {**good, "steps": {"detach": good["written"]}, "pending": {"step": "bytes", "reason": "busy", "at": good["written"]}} + self.assertEqual(trash.validate(done, "run", "bench", T1, self.env), done) + legacy = {"id": "bench-1", "started": 1.5, "device": 1, "inode": 2} + self.assertEqual(trash.intent("run", "bench", T1, legacy, {"host": "h"}, self.env)["payload"], {"host": "h"}) + for subject, payload in (({"id": "bench-1"}, None), ({"generation": ""}, None), (legacy, []), (legacy, ""), (legacy, 0), + (legacy, {1: "a", "1": "b"}), (legacy, {"deep": [{"raw": b"x"}]}), (legacy, {"pair": (1, 2)}), + (legacy, {"n": float("nan")}), ({**legacy, "started": float("inf")}, None)): + with self.assertRaises(trash.Invalid): # built as it is read: nothing put right in silence + trash.intent("run", "bench", T1, subject, payload, self.env) + other = {"NULLIUS_HOME": os.path.join(self.tmp, "other"), "WORKSPACES_DIR": self.root, "RUNS_DIR": self.root} + os.makedirs(paths.data_dir(other)) + def at(name, **changed): + return {**good, "name": name, "token": T2, **changed} + cases = { + "nothing": (None, trash.MISSING), "cut": (json.dumps(at("cut"))[:-9], trash.DAMAGED), "list": ("[]", trash.DAMAGED), + "bytes": (b"\xff", trash.DAMAGED), "deep": ('{"a":' * 100000, trash.DAMAGED), + "twice": (json.dumps(at("twice"))[:-1] + ', "version": 1}', trash.DAMAGED), + "later": ({"version": 2, "what": "unknown here"}, trash.FUTURE), "zero": (at("zero", version=0), trash.DAMAGED), + "true": (at("true", version=True), trash.DAMAGED), + "huge": (at("huge", subject={"id": "b", "started": 10 ** 309, "device": 1, "inode": 2}), trash.DAMAGED), + "kind": (at("kind", kind="workspace"), trash.DAMAGED), "token": (at("token", token=T1), trash.DAMAGED), + "name": (at("other"), trash.DAMAGED), "extra": (at("extra", more=1), trash.DAMAGED), + "short": ({k: v for k, v in at("short").items() if k != "payload"}, trash.DAMAGED), + "when": (at("when", written="yesterday"), trash.DAMAGED), "leap": (at("leap", written="2026-12-04T10:00:61Z"), trash.DAMAGED), + "sixty": (at("sixty", written="2026-12-04T10:00:60Z"), trash.DAMAGED), "loose": (at("loose", written="2026-12-4T10:00:00Z"), trash.DAMAGED), + "never": (json.dumps(at("never", subject={"id": "b", "started": 0, "device": 1, "inode": 2})).replace('"started": 0', '"started": 1e400'), trash.DAMAGED), "steps": (at("steps", steps={"detach": True}), trash.DAMAGED), + "pending": (at("pending", pending={"step": "bytes"}), trash.DAMAGED), "payload": (at("payload", payload=[]), trash.DAMAGED), + "origin": (at("origin", origin={"data_dir": "/x"}), trash.DAMAGED), + "subject": (at("subject", subject={"uid": "u1", "device": 1, "inode": 2, "created": ""}), trash.DAMAGED), + "id": (at("id", subject={"id": "bench-1"}), trash.DAMAGED), + "profile": (self.intent("run", "profile", T2, env=other), trash.FOREIGN), + "roots": (self.intent("run", "roots", T2, env={**self.env, "WORKSPACES_DIR": self.tmp}), trash.FOREIGN), + } + for name, (intent, _) in cases.items(): + self.entry("run", name, T2, intent, kept="x") + before = self.tree() + for name, (_, state) in cases.items(): + self.assertEqual(self.read("run", f"{name}.{T2}"), (state, None), name) + self.assertEqual(self.read("run", "stray"), (trash.UNRECOGNISED, None)) + self.assertEqual(self.read("run", f"bench.{T1}", other), (trash.FOREIGN, None)) # another profile's retry + self.assertEqual(self.tree(), before) # every one kept whole + + def test_an_empty_entry_is_told_from_one_that_cannot_be_read(self): + self.entry("run", "empty", T1) + self.entry("run", "full", T1, kept="x") + self.entry("run", "closed", T1, self.intent(name="closed")) + kind = os.path.join(self.root, ".trash", "run") + os.symlink(self.tmp, os.path.join(kind, f"link.{T1}")) + os.mkfifo(os.path.join(kind, f"pipe.{T1}")) + with open(os.path.join(kind, f"file.{T1}"), "w"): + pass + self.assertEqual(self.read("run", f"empty.{T1}"), (trash.EMPTY, None)) + self.assertEqual(self.read("run", f"full.{T1}"), (trash.MISSING, None)) + for name in ("link", "pipe", "file", "gone"): + self.assertEqual(self.read("run", f"{name}.{T1}"), (trash.UNREADABLE, None), name) + with mock.patch.object(os, "listdir", side_effect=PermissionError("no listing")): + self.assertEqual(self.read("run", f"empty.{T1}"), (trash.UNREADABLE, None)) + real = os.open + def no_intent(path, *a, **k): + if path == trash.INTENT: + raise PermissionError("no read") + return real(path, *a, **k) + with mock.patch.object(os, "open", no_intent): + self.assertEqual(self.read("run", f"closed.{T1}"), (trash.UNREADABLE, None)) + self.assertEqual(self.read("run", f"closed.{T1}")[0], trash.VALID) + + def test_an_intent_that_is_no_regular_file_is_neither_read_nor_waited_for(self): + real = self.entry("run", "real", T1, self.intent(name="real")) + made = {"pipe": lambda path: os.mkfifo(path), "link": lambda path: os.symlink(os.path.join(real, trash.INTENT), path), + "folder": lambda path: os.mkdir(path)} + start = time.monotonic() + for name, make in made.items(): + make(os.path.join(self.entry("run", name, T1), trash.INTENT)) + self.assertEqual(self.read("run", f"{name}.{T1}"), (trash.UNREADABLE, None), name) # a pipe with no writer would wait for ever + self.assertLess(time.monotonic() - start, 2) + + +class Collector(Case): + def test_of_two_processes_one_collects_and_the_other_does_not_wait(self): + with self.assertRaises(FileNotFoundError): # no trash, nothing to collect, nothing made + trash.collector("run", self.env) + self.assertEqual(os.listdir(self.root), []) + self.entry("run", "a", T1) + self.entry("workspace", "a", T1) + script = textwrap.dedent(""" + import sys + from nullius import trash + with trash.collector("run"): + print("collecting", flush=True) + sys.stdin.read() + """) + app = os.path.dirname(os.path.dirname(os.path.abspath(trash.__file__))) + other = subprocess.Popen([sys.executable, "-c", script], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, + env={**os.environ, **self.env, "PYTHONPATH": app}) + self.addCleanup(other.wait, 5) + self.addCleanup(other.stdin.close) + self.assertEqual(other.stdout.readline(), "collecting\n") + other.stdout.close() + start = time.monotonic() + with self.assertRaises(ondisk.Busy): + with trash.collector("run", self.env): + self.fail("two collectors") + self.assertLess(time.monotonic() - start, 0.5) + with trash.collector("workspace", self.env): # the other kind's is its own + pass + other.stdin.close() + other.wait(5) + with trash.collector("run", self.env): + pass + self.assertEqual(sorted(os.listdir(os.path.join(self.root, ".trash", "run"))), [".collector.lock", f"a.{T1}"]) + self.assertEqual(self.read("run", ".collector.lock"), (trash.UNRECOGNISED, None)) + + def test_a_collector_lock_that_is_a_link_or_a_pipe_is_refused_at_once(self): + self.entry("run", "a", T1) + lock, outside = os.path.join(self.root, ".trash", "run", ".collector.lock"), os.path.join(self.tmp, "outside") + start = time.monotonic() + for make in (lambda: os.symlink(outside, lock), lambda: os.symlink(self.tmp, lock), lambda: os.mkfifo(lock)): + make() + with self.assertRaises(OSError) as refused: + with trash.collector("run", self.env): + self.fail("held through it") + self.assertNotIsInstance(refused.exception, ondisk.Busy) + os.unlink(lock) + self.assertLess(time.monotonic() - start, 2) + self.assertFalse(os.path.lexists(outside)) # nothing made where the link led