mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-25 02:57:52 -06:00
refactor: host lock and measurement records go low
This commit is contained in:
1 parent
a40c75e689
commit
fdb7b6f912
21 files changed
+160
-118
No files matched your search
+13
-77
@@ -44,16 +44,25 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable, Iterator, Sequence
|
||||
from collections.abc import Callable, Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from core.childenv import is_secret, safe_env
|
||||
from core.hostguard import (
|
||||
DEFAULT_LOCK,
|
||||
LOCK_ENV,
|
||||
LOCK_HELD_ENV,
|
||||
LockBusy,
|
||||
free_gb,
|
||||
global_lock,
|
||||
lock_busy,
|
||||
)
|
||||
from core.statefile import now_iso, save_state
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
JOBS_FILE = REPO_ROOT / "automation" / "jobs.yml"
|
||||
AUTORUN_DIR = Path(".cache") / "autorun"
|
||||
DEFAULT_LOCK = Path.home() / ".local" / "state" / "retrobios" / "auto.lock"
|
||||
LOCK_ENV = "RETROBIOS_AUTO_LOCK"
|
||||
LOCK_HELD_ENV = "RETROBIOS_AUTO_LOCK_HELD"
|
||||
|
||||
BRANCH = "autorun"
|
||||
REMOTE = "origin"
|
||||
@@ -91,10 +100,6 @@ class AutorunError(RuntimeError):
|
||||
self.detail = detail
|
||||
|
||||
|
||||
class LockBusy(RuntimeError):
|
||||
"""Another job holds the host-wide lock."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Step:
|
||||
argv: tuple[str, ...]
|
||||
@@ -312,35 +317,6 @@ def load_jobs(path: Path = JOBS_FILE) -> dict[str, Job]:
|
||||
# Host guards
|
||||
|
||||
|
||||
@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 wait_for_load(host: Host, max_wait: float) -> bool:
|
||||
"""True once the 1-minute load is at most a quarter of the CPUs."""
|
||||
deadline = host.clock() + max_wait
|
||||
@@ -353,10 +329,6 @@ def wait_for_load(host: Host, max_wait: float) -> bool:
|
||||
host.sleep(min(host.poll, left))
|
||||
|
||||
|
||||
def free_gb(path: Path) -> float:
|
||||
return shutil.disk_usage(path).free / 1024 ** 3
|
||||
|
||||
|
||||
def host_misread(returncode: int, text: str) -> bool:
|
||||
"""A failure this host's CPU produces under load, worth one idle retry."""
|
||||
if returncode in SEGFAULT_CODES:
|
||||
@@ -707,10 +679,6 @@ def may_push(state: dict) -> str:
|
||||
# State and logs
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat()
|
||||
|
||||
|
||||
def load_state(path: Path) -> dict:
|
||||
try:
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
@@ -720,13 +688,6 @@ def load_state(path: Path) -> dict:
|
||||
raise AutorunError(FAILED, f"{path} is unreadable: {exc}") from exc
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def prune_logs(logs: Path, days: int = LOG_DAYS, now: float | None = None) -> int:
|
||||
limit = (now if now is not None else time.time()) - days * 86400
|
||||
removed = 0
|
||||
@@ -748,31 +709,6 @@ def set_alert(state: dict, name: str, active: bool, detail: str, now: str) -> No
|
||||
# Running a job
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
def token_env() -> dict[str, str]:
|
||||
"""The environment of the phases that need GitHub: the push and gh."""
|
||||
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
||||
|
||||
+13
-10
@@ -97,17 +97,20 @@ import core_probe
|
||||
import yaml
|
||||
|
||||
import autorun
|
||||
from core import childenv
|
||||
from core import hostguard
|
||||
from core import statefile
|
||||
import campaign_profiles
|
||||
import campaign_rules as rules
|
||||
import measurement_records as mr
|
||||
from autorun import now_iso
|
||||
from model import measurements as mr
|
||||
from core.statefile import now_iso
|
||||
from core.paths import REPO_ROOT
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml"
|
||||
BUILDBOT = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/"
|
||||
LOCK_HELD_ENV = autorun.LOCK_HELD_ENV
|
||||
LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV
|
||||
ROMFETCH_ENV = "RETROBIOS_ROMFETCH"
|
||||
STATE_VERSION = 1
|
||||
|
||||
@@ -256,7 +259,7 @@ class Host:
|
||||
sleep: Callable[[float], None] = time.sleep
|
||||
clock: Callable[[], float] = time.monotonic
|
||||
cpu_count: int = os.cpu_count() or 1
|
||||
free_gb: Callable[[Path], float] = autorun.free_gb
|
||||
free_gb: Callable[[Path], float] = hostguard.free_gb
|
||||
poll: float = 60.0
|
||||
run: Callable[..., subprocess.CompletedProcess] = run_group
|
||||
urlopen: Callable[..., http.client.HTTPResponse] = urllib.request.urlopen
|
||||
@@ -329,7 +332,7 @@ def child_env(romfetch: bool = False) -> dict[str, str]:
|
||||
names: list[str] = [core_probe.PROBE_LOCK_ENV, core_probe.PROBE_LOCK_HELD_ENV]
|
||||
if romfetch:
|
||||
names += [k for k in os.environ if k.startswith("ROMFETCH_")] + list(ROMFETCH_PASSED)
|
||||
return autorun.safe_env(names)
|
||||
return childenv.safe_env(names)
|
||||
|
||||
|
||||
# Host-side git on a third-party project. It only ever touches bare mirrors
|
||||
@@ -501,7 +504,7 @@ def host_lock(lock_path: Path) -> Iterator[None]:
|
||||
if os.environ.get(LOCK_HELD_ENV):
|
||||
yield
|
||||
return
|
||||
with autorun.global_lock(lock_path):
|
||||
with hostguard.global_lock(lock_path):
|
||||
yield
|
||||
|
||||
|
||||
@@ -521,7 +524,7 @@ def load_state(path: Path) -> dict:
|
||||
|
||||
|
||||
def save_state(path: Path, state: dict) -> None:
|
||||
autorun.save_state(path, state)
|
||||
statefile.save_state(path, state)
|
||||
|
||||
|
||||
def should_run(previous: dict | None, core_sha: str, digest: str, oracle_sha: str = "") -> bool:
|
||||
@@ -949,7 +952,7 @@ class Campaign:
|
||||
self.settings = settings or Settings()
|
||||
self.host = host or Host()
|
||||
self.probe_script = probe_script or REPO_ROOT / "scripts" / "core_probe.py"
|
||||
self.lock_path = lock_path or Path(os.environ.get(autorun.LOCK_ENV) or autorun.DEFAULT_LOCK)
|
||||
self.lock_path = lock_path or Path(os.environ.get(hostguard.LOCK_ENV) or hostguard.DEFAULT_LOCK)
|
||||
self.state = load_state(paths.state)
|
||||
self.cores = Cores(self)
|
||||
self.store = ContentStore(self)
|
||||
@@ -2048,7 +2051,7 @@ def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) ->
|
||||
try:
|
||||
with host_lock(campaign.lock_path):
|
||||
listed = campaign.references(only, args.system, Path(args.png_dir))
|
||||
except autorun.LockBusy as exc:
|
||||
except hostguard.LockBusy as exc:
|
||||
print(f"campaign: deferred, {exc}", file=sys.stderr)
|
||||
return 75
|
||||
print(json.dumps(listed, indent=2))
|
||||
@@ -2094,7 +2097,7 @@ def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], path
|
||||
with host_lock(campaign.lock_path):
|
||||
current = campaign.run(only, args.system, commit_every=args.commit_every,
|
||||
commit=args.commit)
|
||||
except autorun.LockBusy as exc:
|
||||
except hostguard.LockBusy as exc:
|
||||
print(f"campaign: deferred, {exc}", file=sys.stderr)
|
||||
return 75
|
||||
counts, _, _ = campaign.counts()
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -1538,7 +1538,7 @@ def default_emulator(core_file: Path, library_name: str | None) -> str:
|
||||
def default_subject(record: dict) -> str:
|
||||
"""A slug shared by the reruns of one test: a check by its claim and
|
||||
method, a run or bench by its inputs."""
|
||||
from measurement_records import canonical, sha256_hex, slugify
|
||||
from model.measurements import canonical, sha256_hex, slugify
|
||||
|
||||
check = record.get("check")
|
||||
if check:
|
||||
@@ -1554,7 +1554,7 @@ def default_subject(record: dict) -> str:
|
||||
def write_record(directory: Path, full: dict) -> tuple[Path, dict]:
|
||||
"""Append the record, with its id, to its emulator's .jsonl. Returns the
|
||||
file and the record as written."""
|
||||
from measurement_records import line_text, parse_lines, records_path, seal
|
||||
from model.measurements import line_text, parse_lines, records_path, seal
|
||||
|
||||
sealed = seal(full)
|
||||
lines = directory / records_path(sealed["emulator"])
|
||||
@@ -1599,7 +1599,7 @@ def _probe(args: argparse.Namespace) -> int:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
load_after = load_average()
|
||||
first = variants[0]["repetitions"][0]
|
||||
from measurement_records import RECORD_VERSION
|
||||
from model.measurements import RECORD_VERSION
|
||||
|
||||
record: dict = {
|
||||
"record_version": RECORD_VERSION,
|
||||
@@ -1710,7 +1710,7 @@ def rejudged(record: dict, data: dict, identity: dict | None, now: str) -> dict
|
||||
|
||||
|
||||
def RECORD_VERSION_NOW() -> int:
|
||||
from measurement_records import RECORD_VERSION
|
||||
from model.measurements import RECORD_VERSION
|
||||
|
||||
return RECORD_VERSION
|
||||
|
||||
@@ -1718,7 +1718,7 @@ def RECORD_VERSION_NOW() -> int:
|
||||
def rejudge_records(args: argparse.Namespace) -> int:
|
||||
"""Append, for each live record whose judgement the oracle now gives
|
||||
otherwise, the record judged again, superseding it."""
|
||||
from measurement_records import line_text, live, read_records, records_path, seal
|
||||
from model.measurements import line_text, live, read_records, records_path, seal
|
||||
|
||||
root = Path(args.record)
|
||||
data, identity = load_oracle(Path(args.oracle) if args.oracle else DEFAULT_ORACLE)
|
||||
|
||||
File renamed without changes.
@@ -60,8 +60,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import autorun
|
||||
import campaign
|
||||
import measurement_records as mr
|
||||
from autorun import now_iso
|
||||
from model import measurements as mr
|
||||
from core.statefile import now_iso
|
||||
from model.systems import _norm_system_id
|
||||
from model.profiles import load_emulator_profiles
|
||||
from model.platforms import load_platform_config
|
||||
|
||||
@@ -374,7 +374,7 @@ def collect(root: Path = REPO_ROOT, stored_records: list | None = None) -> list[
|
||||
listed under several systems (sega-megacd and mega-cd) is judged under
|
||||
the one whose profile ran it."""
|
||||
from model.profiles import load_emulator_profiles
|
||||
from measurement_records import live, read_records
|
||||
from model.measurements import live, read_records
|
||||
|
||||
content: dict[str, list[tuple[str, dict]]] = {}
|
||||
for system, items in load_content(root / "tests" / "campaign" / "content.yml").items():
|
||||
|
||||
@@ -31,7 +31,7 @@ import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import measurement_records as mr
|
||||
from model import measurements as mr
|
||||
from sitegen import markup
|
||||
from core.artifacts import json_text, write_if_changed
|
||||
from sitegen.render import _escape_tags
|
||||
|
||||
@@ -48,7 +48,7 @@ from typing import IO
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import core_probe as cp
|
||||
from autorun import now_iso
|
||||
from core.statefile import now_iso
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CACHE = ROOT / ".cache" / "standalone"
|
||||
@@ -592,7 +592,7 @@ def _probe(args: argparse.Namespace, emu: Emulator) -> int:
|
||||
if args.mode == "check":
|
||||
record["check"] = {"claim": args.claim, "method": args.method, "observable": args.observable,
|
||||
"variable": args.vary[0][0], "result": check_result(variants, args.observable)}
|
||||
from measurement_records import canonical, sha256_hex, slugify
|
||||
from model.measurements import canonical, sha256_hex, slugify
|
||||
|
||||
if args.subject:
|
||||
record["subject"] = args.subject
|
||||
|
||||
@@ -844,7 +844,7 @@ def _format_errors() -> list[str]:
|
||||
def _measurement_errors(root: Path | None = None) -> list[str]:
|
||||
"""Every record line under measurements/, against its schema and the
|
||||
rules measurement_records.read_records applies."""
|
||||
import measurement_records as mr
|
||||
from model import measurements as mr
|
||||
|
||||
root = root or ROOT
|
||||
validator = _validator("core-probe-record.schema.json")
|
||||
|
||||
Reference in new issue
Block a user