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
35 changes: 27 additions & 8 deletions app/nullius/migrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class CopyPlan:
directories: set[Path] = field(default_factory=set)
catalogue_entries: dict[Path, dict | None] = field(default_factory=dict)
catalogue_snapshot: bool = False
settings: Path | None = None # settings.json, when it is written: under its lock


def _no_symlinks(path: Path):
Expand Down Expand Up @@ -122,7 +123,8 @@ def prepare(checkout: Path, licence_source: Path | None = None):
workspaces_target = Path(paths.workspaces_dir()).expanduser().resolve()
secrets_target = Path(paths.secrets_dir()).expanduser().resolve()
_no_symlinks(target)
held = settings.in_file(str(target))
previous = target.read_bytes() if target.is_file() else None # one snapshot: the merge and apply's check
held = settings.values_of(previous) if previous is not None else {}
for name, value in values.items():
if name in held and held[name] != value:
raise ValueError(f"Existing setting differs: {name}. Choose a separate NULLIUS_HOME or resolve it first.")
Expand All @@ -144,11 +146,12 @@ def add(dest, data, mode=0o600):
else:
pending.files.append((dest, data, mode, None))

if merged != held or (merged and not target.exists()):
if merged != held or (merged and previous is None):
# Merging non-conflicting settings is the one allowed replacement.
data = (json.dumps(merged, indent=2, ensure_ascii=False) + "\n").encode()
destination(target)
pending.files.append((target, data, 0o600, target.read_bytes() if target.exists() else None))
pending.files.append((target, data, 0o600, previous))
pending.settings = target

bundled = Path(__file__).resolve().parent / "catalogue"
source_catalogue = checkout / "app" / "nullius" / "catalogue"
Expand Down Expand Up @@ -212,7 +215,8 @@ def add(dest, data, mode=0o600):


def apply(pending):
"""Write the prepared copy using private files. Original data is untouched."""
"""Write the prepared copy using private files. Original data is untouched. Everything is checked before
anything is written; settings.json is checked again and written under its lock, so a save in between waits."""
for dest, inventory in pending.catalogue_entries.items():
if _inventory(dest) != inventory:
raise ValueError(f"Destination changed since preview: {dest}")
Expand All @@ -229,11 +233,23 @@ def mkdir(parent):
for directory in reversed(missing):
directory.mkdir(mode=0o700, exist_ok=True)

def write(dest, data, mode, previous):
mkdir(dest.parent)
if dest != pending.settings:
ondisk.write_whole(dest, data, mode=mode)
return
with settings.changing(dest):
if (dest.read_bytes() if dest.exists() else None) != previous:
raise ValueError(f"Destination changed since preview: {dest}")
ondisk.write_whole(dest, data, mode=mode)

files = sorted(pending.files, key=lambda f: f[0] != pending.settings) # settings first: refused, nothing written
if pending.settings:
write(*files.pop(0))
for directory in sorted(pending.directories):
mkdir(directory)
for dest, data, mode, _ in pending.files:
mkdir(dest.parent)
ondisk.write_whole(dest, data, mode=mode)
for dest, data, mode, previous in files:
write(dest, data, mode, previous)


def provider_records(values: dict) -> dict:
Expand All @@ -245,6 +261,9 @@ def provider_records(values: dict) -> dict:
old = {f: values.get(f"MODEL_{i}_{part}") for f, part in (("name", "NAME"), ("base", "API_URL"))}
if not any(v is not None for v in old.values()):
continue
if not settings.is_record(f"MODEL_{i}"):
raise ValueError(f"MODEL_{i} is a setting of its own, not a provider record: "
f"remove {' and '.join(f'MODEL_{i}_{p}' for p in ('NAME', 'API_URL') if f'MODEL_{i}_{p}' in values)} first.")
rec = settings.json_object(values.get(f"MODEL_{i}")) or {}
rec = {**{f: v for f, v in old.items() if v}, **rec}
changes[f"MODEL_{i}"] = json.dumps(rec, ensure_ascii=False)
Expand All @@ -262,7 +281,7 @@ def migrate_providers(apply_it: bool) -> int:
if bad:
raise ValueError(" ".join(bad))
if apply_it and changes:
settings.save_many(target, changes)
changes = settings.save_many(target, provider_records) # again, from what the file holds now
except (OSError, ValueError) as error:
print(f"Migration stopped: {error}", file=sys.stderr)
return 1
Expand Down
53 changes: 49 additions & 4 deletions app/nullius/ondisk.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import hashlib
import os
import stat
import time
import uuid

# a handle that searches a folder without reading it: a folder its writer cannot list (0300) is written all the same
Expand Down Expand Up @@ -57,16 +58,60 @@ def write_whole(path, data, mode=None) -> None:
os.close(folder)


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:
"""*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."""
until = time.monotonic() + FIRST_WAIT
while True:
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_NONBLOCK, 0o600)
made = True
except FileExistsError:
try:
fd = os.open(path, os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
except FileNotFoundError:
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:
os.chmod(path, stat.S_IMODE(st.st_mode) | 0o200, follow_symlinks=False)
continue
if time.monotonic() >= until:
raise
time.sleep(0.005)
continue
made = False
try:
st = os.fstat(fd)
if not stat.S_ISREG(st.st_mode):
raise OSError(errno.EINVAL, "not a regular file", os.fspath(path))
if made and stat.S_IMODE(st.st_mode) != 0o600:
os.fchmod(fd, 0o600) # published already: on failure it stays, for the next to repair
except BaseException:
os.close(fd)
raise
return fd


@contextlib.contextmanager
def locked(path):
"""One holder of ``path`` at a time, across processes. The file holds nothing."""
"""One holder of ``path`` at a time, across processes and threads. The file holds
nothing and is never a link or a special file."""
import fcntl # POSIX only: imported where the lock is taken
with open(path, "a") as f:
fcntl.flock(f, fcntl.LOCK_EX)
fd = _lock_file(os.fspath(path))
try:
fcntl.flock(fd, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(f, fcntl.LOCK_UN)
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)


def sha256_of(path) -> str:
Expand Down
168 changes: 111 additions & 57 deletions app/nullius/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"""
from __future__ import annotations

import io
import os
import json
import re
Expand Down Expand Up @@ -268,11 +269,17 @@ def validate(self, value: str) -> Optional[str]:
def parse(path: str) -> List[Tuple[str, Optional[str], Optional[str]]]:
"""The file as a list of (line, key, value): key and value are None for
a comment or blank line. Quotes around a value are dropped."""
out = []
if not os.path.isfile(path):
return out
with open(path, encoding="utf-8") as fh:
if str(path).endswith(".json"):
return []
with open(path, "rb") as fh:
return _entries(fh.read(), str(path).endswith(".json"))


def _entries(data: bytes, as_json: bool) -> List[Tuple[str, Optional[str], Optional[str]]]:
"""``parse`` of a file's bytes."""
out = []
with io.TextIOWrapper(io.BytesIO(data), encoding="utf-8") as fh:
if as_json:
try:
values = json.load(fh)
except (ValueError, UnicodeError) as e:
Expand Down Expand Up @@ -457,6 +464,11 @@ def in_file(path: str) -> Dict[str, str]:
return {k: v or "" for _, k, v in parse(path) if k}


def values_of(data: bytes) -> Dict[str, str]:
"""``in_file`` of settings.json's bytes, read once by the caller."""
return {k: v or "" for _, k, v in _entries(data, True) if k}


def agent_key_names(env=None) -> List[str]:
"""The agent keys' names, as AGENT_KEYS lists them, each once: a name that
is not one, or is already something else's (``reserved_agent_keys``), is
Expand Down Expand Up @@ -531,6 +543,13 @@ def agent_variable(name: str) -> Variable:
return Variable(name, GROUPS[2], f"An agent key, {name}: sent to Harbor runs, to the agent that reads it.", "secret")


def changing(path: str):
"""One change of the file at a time, the page's and the command's: a lock beside it, owner-only like the file."""
path = os.fspath(path)
os.makedirs(os.path.dirname(os.path.abspath(path)), mode=0o700, exist_ok=True)
return ondisk.locked(path + ".lock")


def _write_lines(path: str, lines: List[str]) -> None:
"""Atomically replace one owner-only settings file; never print values."""
os.makedirs(os.path.dirname(os.path.abspath(path)), mode=0o700, exist_ok=True)
Expand All @@ -550,16 +569,20 @@ def take(path: str, name: str) -> Optional[str]:
setting reads (``unread``)."""
if name in BY_NAME or name in STARTUP or name in set(agent_key_names()):
raise ValueError(f"{name} is a setting of its own; it is not moved")
value = in_file(path).get(name)
if value is None:
return None
lines = [line for line, key, _ in parse(path) if key != name]
while lines and not lines[-1].strip():
lines.pop()
_write_lines(path, lines)
if name in LOADED_KEYS:
os.environ.pop(name, None)
LOADED_KEYS.discard(name)
path = os.fspath(path)
if name not in in_file(path):
return None # nothing to take: no lock, nothing created
with changing(path):
value = in_file(path).get(name)
if value is None:
return None
lines = [line for line, key, _ in parse(path) if key != name]
while lines and not lines[-1].strip():
lines.pop()
_write_lines(path, lines)
if name in LOADED_KEYS:
os.environ.pop(name, None)
LOADED_KEYS.discard(name)
return value


Expand Down Expand Up @@ -619,13 +642,8 @@ def save(path: str, name: str, value: Optional[str]) -> None:
save_many(path, {name: value})


def save_many(path: str, changes: Dict[str, Optional[str]]) -> None:
"""Set (or, with None, remove) variables in the file, keeping every
other line as it was, and apply each change to the process environment
unless the environment already held that variable. Every value is
validated before any is written - one bad value and nothing changes;
the file is written whole to a temporary name beside the target, then
renamed."""
def _valid(changes: Dict[str, Optional[str]]) -> None:
"""Every value valid, or ValueError naming each that is not."""
problems = []
listed = changes.get("AGENT_KEYS") if "AGENT_KEYS" in changes else os.environ.get("AGENT_KEYS", "")
agents = set() if listed is None or _agent_key_names(listed) else {n.strip() for n in listed.split(",") if n.strip()}
Expand All @@ -640,42 +658,78 @@ def save_many(path: str, changes: Dict[str, Optional[str]]) -> None:
problems.append(f"{name} must be {why}.")
if problems:
raise ValueError(" ".join(problems))
# a setting saved under its new name takes its old one out of the file
old = {o for o, n in RENAMED.items() if n in changes and o not in changes}
lines, done = [], set()
for line, key, _ in parse(path):
if key in old:
if key in LOADED_KEYS:
os.environ.pop(key, None)
LOADED_KEYS.discard(key)
continue
if key in changes:
value = changes[key]
if value is not None and key not in done:
lines.append(f"{key}={value}")
done.add(key) # a duplicate line is dropped rather than kept
continue
lines.append(line)
for name, value in changes.items():
if value is not None and name not in done:
lines.append(f"{name}={value}")
while lines and not lines[-1].strip():
lines.pop()
_write_lines(path, lines)
for name, value in changes.items():
if is_record(name) and name in os.environ and name not in LOADED_KEYS:
_merge_env(name, value or "") # a record: the environment's fields stay over the file's
_FROM[name] = os.path.abspath(path)
continue
if name in os.environ and name not in LOADED_KEYS:
continue # the process environment holds it; the file is for the next start
if value is None:
os.environ.pop(name, None)
LOADED_KEYS.discard(name)
else:
os.environ[name] = value
LOADED_KEYS.add(name)
_FROM[name] = os.path.abspath(path)


def _not_shadowed(path: str, changes: Dict[str, Optional[str]]) -> None:
"""ValueError when a custom provider's old name or URL is set while the file's record of it now holds
that field: the edit would be saved and never read (``providers.record``)."""
old = [(n, m.group(1), "name" if m.group(2) == "NAME" else "base") for n, v in changes.items()
if v is not None and (m := _ENDPOINT_VAR.match(n)) and m.group(2) != "API_KEY" and f"MODEL_{m.group(1)}" not in changes]
if not old:
return
held = in_file(path)
for name, i, field in old:
if field in (json_object(held.get(f"MODEL_{i}")) or {}):
raise ValueError(f"{name} is now part of the provider record MODEL_{i}. Reload, then save again.")


def save_many(path: str, changes) -> Dict[str, Optional[str]]:
"""Set (or, with None, remove) variables in the file, keeping every
other line as it was, and apply each change to the process environment
unless the environment already held that variable. Every value is
validated before any is written - one bad value and nothing changes;
the file is read, changed and written whole under ``changing``'s lock,
to a temporary name beside the target, then renamed, and the environment
changed before the lock is let go. ``changes`` may be a function of the
file's values, called under the lock, so it changes what is there now.
Returns the changes made."""
path = os.fspath(path)
if not callable(changes):
_valid(changes)
with changing(path):
if callable(changes):
changes = changes(in_file(path))
if not changes:
return changes
_valid(changes)
_not_shadowed(path, changes)
# a setting saved under its new name takes its old one out of the file
old = {o for o, n in RENAMED.items() if n in changes and o not in changes}
lines, done = [], set()
for line, key, _ in parse(path):
if key in old:
if key in LOADED_KEYS:
os.environ.pop(key, None)
LOADED_KEYS.discard(key)
continue
if key in changes:
value = changes[key]
if value is not None and key not in done:
lines.append(f"{key}={value}")
done.add(key) # a duplicate line is dropped rather than kept
continue
lines.append(line)
for name, value in changes.items():
if value is not None and name not in done:
lines.append(f"{name}={value}")
while lines and not lines[-1].strip():
lines.pop()
_write_lines(path, lines)
for name, value in changes.items():
if is_record(name) and name in os.environ and name not in LOADED_KEYS:
_merge_env(name, value or "") # a record: the environment's fields stay over the file's
_FROM[name] = os.path.abspath(path)
continue
if name in os.environ and name not in LOADED_KEYS:
continue # the process environment holds it; the file is for the next start
if value is None:
os.environ.pop(name, None)
LOADED_KEYS.discard(name)
else:
os.environ[name] = value
LOADED_KEYS.add(name)
_FROM[name] = os.path.abspath(path)
return changes


def example() -> str:
Expand Down
Loading
Loading