Skip to content
Open
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
183 changes: 183 additions & 0 deletions app/nullius/identity.py
Original file line number Diff line number Diff line change
@@ -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
91 changes: 81 additions & 10 deletions app/nullius/ondisk.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions app/nullius/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading