refactor: host lock and measurement records go low

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 20:37:33 +01:00
1 parent a40c75e689
commit fdb7b6f912
21 files changed
+160 -118

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
"""The environment a child process inherits: an allowlist, never a token or a password."""
from __future__ import annotations
import os
from collections.abc import Sequence
# What a job step inherits. A step can run third-party code (a buildbot
# core, a scraped page, a downloaded tool), so it gets the variables a
# program needs to run and nothing it could leak: no token, no password.
SAFE_ENV = frozenset({"PATH", "HOME", "LANG", "TZ", "TMPDIR"})
SECRET_NAMES = frozenset({"GITHUB_TOKEN", "GH_TOKEN", "ROMSTATION_USER", "ROMSTATION_PASS"})
SECRET_MARKERS = ("TOKEN", "SECRET", "PASS")
def is_secret(name: str) -> bool:
upper = name.upper()
return name in SECRET_NAMES or any(marker in upper for marker in SECRET_MARKERS)
def safe_env(names: Sequence[str] = (), add: dict[str, str] | None = None,
source: dict[str, str] | None = None) -> dict[str, str]:
"""The allowlisted environment, plus the variables a step names
explicitly. A secret is dropped even when named."""
source = dict(os.environ) if source is None else source
wanted = set(names)
env = {key: value for key, value in source.items()
if (key in SAFE_ENV or key.startswith("LC_") or key in wanted) and not is_secret(key)}
env.update({key: value for key, value in (add or {}).items() if not is_secret(key)})
return env
+51
View File
@@ -0,0 +1,51 @@
"""Host-wide guards every heavy job shares: the automation lock and free disk space."""
from __future__ import annotations
import contextlib
import os
import shutil
from collections.abc import Iterator
from pathlib import Path
DEFAULT_LOCK = Path.home() / ".local" / "state" / "retrobios" / "auto.lock"
LOCK_ENV = "RETROBIOS_AUTO_LOCK"
LOCK_HELD_ENV = "RETROBIOS_AUTO_LOCK_HELD"
class LockBusy(RuntimeError):
"""Another job holds the host-wide lock."""
@contextlib.contextmanager
def global_lock(path: Path) -> Iterator[None]:
"""Hold the host-wide automation lock, or raise LockBusy at once."""
import fcntl
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a+", encoding="utf-8") as handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
raise LockBusy(f"{path} is held by another job") from exc
handle.seek(0)
handle.truncate()
handle.write(f"{os.getpid()}\n")
handle.flush()
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def lock_busy(path: Path) -> bool:
try:
with global_lock(path):
return False
except LockBusy:
return True
def free_gb(path: Path) -> float:
return shutil.disk_usage(path).free / 1024 ** 3
+19
View File
@@ -0,0 +1,19 @@
"""State files of unattended jobs: UTC timestamps and atomic JSON writes."""
from __future__ import annotations
import datetime as dt
import json
import os
from pathlib import Path
def now_iso() -> str:
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
def save_state(path: Path, state: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
scratch = path.with_suffix(".tmp")
scratch.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")
os.replace(scratch, path)