Skip to content
94 changes: 93 additions & 1 deletion app/nullius/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@
from datetime import datetime, timezone
from typing import Callable, Dict, List, Optional

from nullius import hosts, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, workspace
from nullius import hosts, identity, ondisk, paths, prices as price_list, progress, providers, redact, secrets, settings, trash, workspace
from nullius.judge import store as judgements
from nullius.runs import parse, uid as job_uid
from nullius.harbor import source as harbor_source
Expand Down Expand Up @@ -2746,3 +2746,95 @@ def _delete(names: List[str], home: str, root: Optional[str], copies, run: Optio
judgements.remove(d)
gone["kept"] += [f"Judgements kept because {why}" for why in dict.fromkeys(whys) if why]
return gone


# --- cleaning a deleted run ----------------------------------------------------
# Not called yet: Delete does not rename a run into the trash.

def _run_payload(data: dict) -> bool:
"""A run intent's payload. ``jobs``: per job folder, where it was in the run's own
folder, its ``uid`` and ``source``, or "" and ``pending``. ``workspaces``: per workspace
that held the run its ``identity`` and the ``roots`` and parsed ``jobs`` to forget, each
in the run's folder. ``host``: the label of the host that has a copy, or None.
``kept``: what the steps report."""
import uuid
payload, was = data["payload"], os.path.join(data["origin"]["runs_root"], data["name"])

def texts(value):
return isinstance(value, list) and all(isinstance(v, str) and v for v in value)

def own(path):
return isinstance(path, str) and os.path.normpath(path) == path and path.startswith(was + os.sep)

def identified(job):
if not isinstance(job, dict) or set(job) != {"uid", "source"} or job["uid"] == "":
return job == {"uid": "", "source": "pending"}
return job["source"] in ("declared", "derived") and isinstance(job["uid"], str) and str(uuid.UUID(job["uid"])) == job["uid"]
try:
return (set(payload) - {"kept"} == {"jobs", "workspaces", "host"} and isinstance(payload["jobs"], dict)
and all(own(d) and identified(j) for d, j in payload["jobs"].items())
and isinstance(payload["workspaces"], list)
and all(set(w) == {"identity", "roots", "jobs"} and identity.valid_workspace(w["identity"])
and texts(w["roots"]) and texts(w["jobs"]) and all(map(own, w["roots"])) and set(w["jobs"]) <= set(payload["jobs"])
for w in payload["workspaces"])
and (payload["host"] is None or isinstance(payload["host"], str) and bool(payload["host"]))
and texts(payload.get("kept", [])))
except (AttributeError, TypeError, ValueError):
return False


def _held_workspace(folder: str):
"""The workspace in *folder*, read whole or not at all: Pending for one damaged in any
part, which is never written again from what could be read of it."""
try:
ws = workspace.load(os.path.dirname(folder), os.path.basename(folder), strict=True)
except (TypeError, ValueError):
ws = None
if ws is None:
raise trash.Pending(f"workspace {os.path.basename(folder)} cannot be read")
return ws


def _detach(path: str, data: dict, env) -> None:
"""Every workspace that held the run, found by its identity, without the run's roots
and parsed jobs, under the profile lock, then read back. One deleted since held them
no more. First, with nothing held, each job in the entry is a folder and the one the
intent names, by identity and source read once. Pending while that, a workspace or its index cannot be told
or read, or while a root is there again or cannot be told gone: a run made under the
name since is not this one."""
was = os.path.join(data["origin"]["runs_root"], data["name"])
for folder, job in data["payload"]["jobs"].items():
there = os.path.join(path, os.path.relpath(folder, was))
try:
found = stat.S_ISDIR(os.lstat(there).st_mode) and job_uid.strict_of(there)
except (AttributeError, TypeError, FileNotFoundError, NotADirectoryError):
found = None # not there, or of a shape nothing is told from
if found != (job["uid"], job["source"]):
raise trash.Pending(f"{there} is not the job its intent names")
with ondisk.locked(paths.profile_lock(env), ondisk.deadline()):
for held in data["payload"]["workspaces"]:
for folder in workspace.located(held["identity"], env):
ws, back = _held_workspace(folder), [r for r in held["roots"] if trash.there(r)]
if back:
raise trash.Pending(f"{back[0]} is there again: workspace {ws.name} keeps its roots")
workspace.forget(ws, held["roots"], held["jobs"], held=True)
now = _held_workspace(folder)
if set(held["roots"]) & {*now.roots, *now.job_roots} or set(held["jobs"]) & set(workspace.job_index(now, strict=True)):
raise trash.Pending(f"workspace {ws.name} still holds it")


def _judgements(path: str, data: dict, env) -> list:
"""The judgements of the run's jobs, in the user's store and in the workspaces that kept
some before, stay where they are, and that is reported: nothing here proves yet that
no copy of a job is left."""
return [workspace.UNSUPPORTED]


def _host_copy(path: str, data: dict, env) -> None:
"""A copy on a host is never removed from here: the entry keeps its intent until the user says it is handled."""
if data["payload"]["host"]:
raise trash.Pending(f"The copy of {data['name']} on {data['payload']['host']} stays: remove it there.")


TRASHED = trash.Handler("run", RECORD, identity.run, identity.same_run, _run_payload,
(("detach", _detach), ("judgements", _judgements)), (("host", _host_copy),))
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
Loading