From 6debde95b463543cfb23501827107aff9e96c15d Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:04:11 +0100 Subject: [PATCH] refactor: split the pack probe into probes --- scripts/pack_probe.py | 640 +---------------------------------- scripts/probes/packlayout.py | 142 ++++++++ scripts/probes/packprobe.py | 530 +++++++++++++++++++++++++++++ tests/test_layers.py | 1 + tests/test_pack_probe.py | 84 ++--- 5 files changed, 719 insertions(+), 678 deletions(-) create mode 100644 scripts/probes/packlayout.py create mode 100644 scripts/probes/packprobe.py diff --git a/scripts/pack_probe.py b/scripts/pack_probe.py index edde2aeb0..9f099c6b2 100644 --- a/scripts/pack_probe.py +++ b/scripts/pack_probe.py @@ -40,654 +40,20 @@ Usage: from __future__ import annotations import argparse -import contextlib -import fcntl -import hashlib -import json -import os -import re -import shutil -import subprocess import sys -import time -import urllib.request -import zipfile -from collections.abc import Iterable, Iterator, Sequence -from dataclasses import dataclass, field +from collections.abc import Sequence from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -import autorun -from probes import content as probes_content -from probes import cores as probes_cores -from probes import entries as probes_entries -from probes import host -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 -from model.targets import load_target_config from model.cliargs import platform_arg, require_platform -from resolve.cores import resolve_platform_cores from core.cli import run_cli -from resolve.layout import runs_standalone -from resolve.validation import filter_files_by_mode -from core.ziptools import safe_extract_zip from core.paths import REPO_ROOT +from probes.packlayout import ProbeFailure +from probes.packprobe import EXIT_BUSY, TARGETS, run -MAIN = autorun.main_checkout() -PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml" -CONTENT_DIR = MAIN / ".cache" / "test-content" -CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores" WORK_DIR = REPO_ROOT / "tmp" / "pack_probe" -BUILDBOT = probes_cores.BUILDBOT -PACK_PROBES = mr.PACK_PROBES INSTALLS = ("pack", "installer") -VERDICTS = ("boots", "bios_error", "crash", "hang", "unknown") -MAX_ROUNDS = 6 -PROBE_TIMEOUT = 900 -IDLE_WAIT = 1800 -PROBE_LOCK_ENV = "RETROBIOS_PROBE_LOCK" -PROBE_LOCK_HELD_ENV = "RETROBIOS_PROBE_LOCK_HELD" -PROBE_LOCK = Path(os.environ.get(PROBE_LOCK_ENV) - or Path.home() / ".local" / "state" / "retrobios" / "probe.lock") -EXIT_BUSY = 3 - -# The hardware target each platform is probed for: the one whose libretro -# cores are the buildbot's x86_64 Linux builds, or the platform's only one. -TARGETS = {"retroarch": "linux-x86_64", "batocera": "x86_64", "retrobat": "windows"} - - -class ProbeFailure(RuntimeError): - """The probe cannot go on: no pack, no installer layout, a busy host.""" - - -# -------------------------------------------------------------------------- -# Layouts: the platform's BIOS folder as a user ends up with it -# -------------------------------------------------------------------------- - -@dataclass -class Layout: - """A BIOS folder: every file by its path under the folder, and the pack - or manifest entry that put it there (None for a file nothing declares).""" - - install: str - root: Path - files: dict[str, str | None] - source: dict - sizes: dict[str, int] = field(default_factory=dict) - - def size(self, rel: str) -> int: - if rel not in self.sizes: - self.sizes[rel] = (self.root / rel).stat().st_size - return self.sizes[rel] - - -def walk(root: Path) -> list[str]: - return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()) - - -def file_sha(path: Path, algorithm: str = "sha1") -> str: - digest = hashlib.new(algorithm) - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def pack_layout(pack: Path, root: Path, identity: dict) -> Layout: - """The pack extracted as a user does, at the root of the BIOS folder. - Each file's entry is the archive member it came from.""" - if root.exists(): - shutil.rmtree(root) - safe_extract_zip(str(pack), str(root)) - with zipfile.ZipFile(pack) as handle: - members = {info.filename for info in handle.infolist() if not info.is_dir()} - files = {rel: rel if rel in members else None for rel in walk(root)} - return Layout("pack", root, files, {"pack": identity, "manifest": None}) - - -def pack_identity(pack: Path) -> dict: - with zipfile.ZipFile(pack) as handle: - members = sum(1 for info in handle.infolist() if not info.is_dir()) - return {"file": pack.name, "sha256": file_sha(pack, "sha256"), "size": pack.stat().st_size, - "members": members} - - -def manifest_entries(manifest: dict) -> dict[str, str]: - """Destination -> the manifest entry that names it, as the installer - places it under --dest: a file by its dest, a data directory member - under its directory's dest.""" - out: dict[str, str] = {} - for item in manifest.get("files") or (): - out[item["dest"]] = f"files:{item['dest']}" - for item in manifest.get("case_variants") or (): - out.setdefault(item["dest"], f"case_variants:{item['dest']}") - for directory in manifest.get("data_directories") or (): - base = str(directory.get("dest") or "").strip("/") - for member in directory.get("files") or {}: - dest = f"{base}/{member}" if base else member - out.setdefault(dest, f"data_directories:{directory['ref']}:{member}") - return out - - -def installer_summary(stdout: str, system_dir: Path, save_dir: Path) -> str: - """The end of the installer's output, as a record keeps it. The scratch - folders are written as the options that named them: a record read - elsewhere has no use for the path of the machine that ran the probe.""" - text = stdout.replace(str(system_dir), "").replace(str(save_dir), "") - return " ".join(text.split())[-400:] - - -def installer_layout(platform: str, pack: Path, identity: dict, manifest_path: Path, - root: Path, narrow: Sequence[str] = ()) -> Layout: - """install.py --dest on a scratch root, from the pack, offline. The - manifest is the published one, the file a user's installer reads. - ``narrow`` passes install.py options such as --system, for the tests.""" - system_dir, save_dir = root / "system", root / "saves" - if root.exists(): - shutil.rmtree(root) - argv = [sys.executable, str(REPO_ROOT / "install.py"), "--platform", platform, "--dest", str(system_dir), - "--save-dir", str(save_dir), "--from-pack", str(pack), "--manifest", str(manifest_path), - "--offline", "--yes", "--quiet", *narrow] - proc = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=REPO_ROOT) - if proc.returncode != 0 or not system_dir.is_dir(): - raise ProbeFailure(f"install.py exited {proc.returncode}: {(proc.stderr or proc.stdout)[-1500:]}") - manifest = json.loads(manifest_path.read_text(encoding="utf-8")) - entries = manifest_entries(manifest) - files = {rel: entries.get(rel) for rel in walk(system_dir)} - source = { - "pack": identity, - "manifest": {"path": manifest_path.relative_to(REPO_ROOT).as_posix() if manifest_path.is_relative_to(REPO_ROOT) - else manifest_path.name, - "sha256": file_sha(manifest_path, "sha256"), - "generated": manifest.get("generated"), "pack_files": manifest.get("pack_files")}, - "save_dir_files": len(walk(save_dir)) if save_dir.is_dir() else 0, - "installer_summary": installer_summary(proc.stdout, system_dir, save_dir), - } - return Layout("installer", system_dir, files, source) - - -def build_pack(platform: str, out_dir: Path, narrow: Sequence[str] = ()) -> Path: - """The platform's pack, built from this checkout as a release builds it. - ``narrow`` passes generate_pack.py options such as --system, for the tests.""" - out_dir.mkdir(parents=True, exist_ok=True) - for old in out_dir.glob("*_BIOS_Pack*.zip"): - old.unlink() - argv = [sys.executable, str(REPO_ROOT / "scripts" / "generate_pack.py"), "--platform", platform, - "--offline", "--output-dir", str(out_dir), *narrow] - proc = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=REPO_ROOT) - packs = sorted(p for p in out_dir.glob("*_BIOS_Pack*.zip") if ".part" not in p.name) - if proc.returncode != 0 or len(packs) != 1: - raise ProbeFailure(f"generate_pack.py exited {proc.returncode} with {len(packs)} packs: " - f"{proc.stderr[-1500:]}") - return packs[0] - - -# -------------------------------------------------------------------------- -# Which cores a platform runs for a system -# -------------------------------------------------------------------------- - -@dataclass(frozen=True) -class CoreChoice: - emulator: str - so_name: str - - -def platform_system(config: dict, system: str) -> str | None: - """The platform's own id of a system, compared on the normalised id.""" - wanted = _norm_system_id(system) - matches = sorted(s for s in config.get("systems") or {} if _norm_system_id(s) == wanted) - return matches[0] if matches else None - - -def libretro_build_runs(name: str, profile: dict, config: dict) -> bool: - """The platform launches this profile's libretro build: it has one, and - the platform does not run the emulator standalone only.""" - if "libretro" not in str(profile.get("type", "")) or profile.get("type") == "alias": - return False - standalone = {str(c) for c in config.get("standalone_cores") or ()} - if not runs_standalone(name, profile, standalone): - return True - dual = {str(c) for c in config.get("dual_mode_cores") or ()} - return bool(dual & ({name} | {str(c) for c in profile.get("cores") or ()})) - - -def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | None) -> list[str]: - """The buildbot builds of a profile the platform runs. Every one the - target names, else the build that carries the profile's key, else the - first of its cores: that is on the buildbot.""" - names = [str(c) for c in profile.get("cores") or () if str(c) in buildbot] - if target is not None: - named = [n for n in names if n in target] - if named: - return sorted(named) - if name in buildbot: - return [name] - return names[:1] - - -def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str], - target: set[str] | None) -> list[CoreChoice]: - wanted = _norm_system_id(system) - out: list[CoreChoice] = [] - for name in sorted(resolve_platform_cores(config, profiles, target)): - profile = profiles[name] - if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}: - continue - if not libretro_build_runs(name, profile, config): - continue - out.extend(CoreChoice(name, so) for so in so_names(name, profile, buildbot, target)) - return out - - -# -------------------------------------------------------------------------- -# Staging: what the core can reach, grown to a fixed point -# -------------------------------------------------------------------------- - -def entry_paths(entry: dict) -> list[str]: - """The paths a profile entry names under the system directory: its - path or name, and its aliases beside it.""" - main = probes_entries.entry_dest(entry) - folder = main.rsplit("/", 1)[0] + "/" if "/" in main else "" - return [main] + [f"{folder}{alias}" for alias in entry.get("aliases") or ()] - - -def libretro_entries(profile: dict) -> list[dict]: - return filter_files_by_mode(profile.get("files") or [], standalone=False) - - -def declared_sizes(profile: dict) -> set[int]: - sizes: set[int] = set() - for entry in libretro_entries(profile): - value = entry.get("size") - sizes.update(v for v in (value if isinstance(value, list) else [value]) if isinstance(v, int)) - return sizes - - -def with_folders(files: Iterable[str], staged: set[str]) -> set[str]: - """Every file of every folder a staged file sits in, below the root: a - core that lists its folder sees what the platform's folder holds.""" - folders = {rel.rsplit("/", 1)[0] + "/" for rel in staged if "/" in rel} - return set(staged) | {rel for rel in files if any(rel.startswith(f) for f in folders)} - - -def initial_stage(layout: Layout, profile: dict, platform_dests: Iterable[str]) -> set[str]: - files = set(layout.files) - staged = {p for entry in libretro_entries(profile) for p in entry_paths(entry) if p in files} - staged |= {d for d in platform_dests if d in files} - if profile.get("found_by") == "content": - sizes = declared_sizes(profile) - staged |= {rel for rel in files if "/" not in rel and layout.size(rel) in sizes} - return with_folders(files, staged) - - -def grow_stage(files: Iterable[str], staged: set[str], probed: Iterable[str]) -> set[str]: - """The files the layout holds that the core looked for, as a file or as - a folder, and their folders: empty once the staging is closed.""" - files = set(files) - wanted = set() - for path in probed: - if path in files: - wanted.add(path) - else: - wanted |= {rel for rel in files if rel.startswith(path.rstrip("/") + "/")} - return with_folders(files, staged | wanted) - staged - - -# -------------------------------------------------------------------------- -# Reading a run -# -------------------------------------------------------------------------- - -def run_verdict(record: dict | None) -> tuple[str, dict | None]: - """The verdict of a run record: variants[0] from record version 4, - unknown before the oracle or without a record.""" - if not record or not record.get("variants"): - return "unknown", None - variant = record["variants"][0] - verdict = variant.get("verdict") - if verdict not in VERDICTS: - return "unknown", None - return verdict, variant.get("verdict_evidence") - - -def first_repetition(record: dict) -> dict: - return record["variants"][0]["repetitions"][0] - - -def declaring(profile: dict, path: str) -> list[str]: - return sorted({entry["name"] for entry in libretro_entries(profile) if path in entry_paths(entry)}) - - -def map_run(layout: Layout, staged: set[str], rep: dict, profile: dict) -> tuple[list[dict], list[dict]]: - """The files the core opened, each with its pack entry, and the findings.""" - opened = [] - for item in rep.get("files_opened") or (): - path = item["path"] - opened.append({"path": path, "entry": layout.files.get(path) if path in staged else None, - "sha1": item.get("sha1_after"), "created": path not in staged}) - by_name: dict[str, list[str]] = {} - for rel in layout.files: - by_name.setdefault(rel.rsplit("/", 1)[-1].casefold(), []).append(rel) - # An entry the core found under one of its names asks for nothing more: - # BlastEm tries tmss.md, then reads bios_MD.bin, both names of one entry. - read = {item["path"] for item in opened if not item["created"]} - satisfied = {entry["name"] for entry in libretro_entries(profile) if read & set(entry_paths(entry))} - findings = [] - for path in rep.get("files_probed_absent") or (): - names = declaring(profile, path) - if path in layout.files: - findings.append({"kind": "not_staged", "path": path, "declared_by": names, "paths": [path]}) - continue - if names and set(names) <= satisfied: - continue - elsewhere = sorted(p for p in by_name.get(path.rsplit("/", 1)[-1].casefold(), ()) if p != path) - if elsewhere: - kind = "elsewhere" - else: - kind = "missing_declared" if names else "missing_undeclared" - findings.append({"kind": kind, "path": path, "declared_by": names, "paths": elsewhere}) - findings.extend({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []} - for item in opened if item["path"] in staged and item["entry"] is None) - return opened, findings - - -# -------------------------------------------------------------------------- -# Cores and content -# -------------------------------------------------------------------------- - -def buildbot_listing() -> set[str]: - with urllib.request.urlopen(BUILDBOT, timeout=120) as response: - page = response.read().decode("utf-8", "replace") - return set(re.findall(r"([A-Za-z0-9_]+)_libretro\.so\.zip", page)) - - -def fetch_core(name: str, refresh: bool = False) -> dict: - """The buildbot nightly of a core, kept with where and when it came from.""" - folder = CORE_CACHE / name - so, meta_path = folder / f"{name}_libretro.so", folder / "build.json" - if so.is_file() and meta_path.is_file() and not refresh: - meta = json.loads(meta_path.read_text(encoding="utf-8")) - if meta.get("sha256") == file_sha(so, "sha256"): - return {**meta, "path": str(so)} - url = f"{BUILDBOT}{name}_libretro.so.zip" - folder.mkdir(parents=True, exist_ok=True) - archive = folder / f"{name}.zip.part" - with urllib.request.urlopen(url, timeout=600) as response, archive.open("wb") as out: - shutil.copyfileobj(response, out) - modified = response.headers.get("Last-Modified") - probes_cores.safe_extract_so(archive, f"{name}_libretro.so", so) - archive.unlink() - meta = {"name": name, "url": url, "last_modified": modified, "sha256": file_sha(so, "sha256"), - "fetched_at": now_iso()} - meta_path.write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") - return {**meta, "path": str(so)} - - -def load_contents(files: Sequence[Path]) -> dict[str, list[probes_content.Content]]: - out: dict[str, list[probes_content.Content]] = {} - for path in files: - if path.is_file(): - for system, items in probes_content.load_content(path).items(): - out.setdefault(system, []).extend(items) - return out - - -def content_folder(content: probes_content.Content, fetch: bool) -> Path: - """The game's folder, fetched through romfetch when absent and asked to.""" - folder = CONTENT_DIR / content.romfetch_system / content.name - if not (folder / "identity.json").is_file() and fetch: - romfetch = shutil.which("romfetch") - if not romfetch: - raise host.Unavailable("romfetch not found") - proc = subprocess.run([romfetch, "get", content.romfetch_system, content.name, "--json", "-q", - "--content-dir", str(CONTENT_DIR)], capture_output=True, text=True, - check=False, env=host.child_env(romfetch=True)) - if proc.returncode != 0: - raise host.Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}") - probes_content.verify_identity(folder) - return folder - - -# -------------------------------------------------------------------------- -# One probe: a core, a game, a layout -# -------------------------------------------------------------------------- - -def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None: - """Wait for the load core_probe records under, a quarter of the CPUs. - Extracting a pack loads the host itself for a minute or two.""" - threshold = (os.cpu_count() or 1) / 4 - waited = 0.0 - while os.getloadavg()[0] > threshold: - if waited >= limit: - raise ProbeFailure(f"busy host: load {os.getloadavg()[0]:.2f} above {threshold} " - f"for {int(waited)} s") - time.sleep(poll) - waited += poll - - -@contextlib.contextmanager -def probe_lock(path: Path | None = None) -> Iterator[None]: - """The host's probe lock, for one run: one probe at a time on the host, - released between runs so a pass never holds it for its whole length.""" - path = path or PROBE_LOCK - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a") as handle: - fcntl.flock(handle, fcntl.LOCK_EX) - try: - yield - finally: - fcntl.flock(handle, fcntl.LOCK_UN) - - -def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) -> tuple[int, dict | None, str]: - """core_probe.py run under the probe lock, the system files passed in an - argument file.""" - work.mkdir(parents=True, exist_ok=True) - argfile = work / "system-files.args" - argfile.write_text("".join(f"--system-file\n{rel}={layout.root / rel}\n" for rel in sorted(staged)), - encoding="utf-8") - command = [sys.executable, str(REPO_ROOT / "scripts" / "core_probe.py"), *argv, f"@{argfile}"] - with probe_lock(): - if "--record" in argv: - wait_idle() - # core_probe takes the same lock unless told its caller holds it. - proc = subprocess.run(command, capture_output=True, text=True, check=False, cwd=REPO_ROOT, - timeout=PROBE_TIMEOUT * 2 + 120, - env={**os.environ, PROBE_LOCK_HELD_ENV: "1", PROBE_LOCK_ENV: str(PROBE_LOCK)}) - record = None - if proc.returncode == 0: - try: - record = json.loads(proc.stdout) - except ValueError: - record = None - # A traceback spells the checkout and the scratch folders: a record read - # on another machine names them by role. - places = [(str(work), ""), (str(layout.root), ""), (str(REPO_ROOT), "")] - error = proc.stderr.strip() - for prefix, name in sorted(places, key=lambda place: -len(place[0])): - error = error.replace(prefix, name) - return proc.returncode, record, error[-1500:] - - -def probe_argv(core: dict, choice: CoreChoice, content: probes_content.Content, load: Path, - subject: str, record: bool, supersedes: str | None = None) -> list[str]: - argv = ["run", "--core", core["path"], "--content", str(load), "--content-label", content.name, - "--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every), - "--require-sandbox", "--timeout", str(PROBE_TIMEOUT), - "--work-dir", str(REPO_ROOT / "tmp" / "core_probe"), "--core-artifact", core["url"]] - if record: - argv += ["--record", str(REPO_ROOT), "--emulator", choice.emulator, "--subject", subject] - if supersedes: - argv += ["--supersedes", supersedes] - return argv - - -def subject_for(platform: str, install: str, system: str, so: str, content: str) -> str: - subject = mr.slugify(f"{platform} {install} {system} {so} {content}", 85) - return f"{mr.PACK_SUBJECT_PREFIX}{subject}" - - -@dataclass(frozen=True) -class ProbeTarget: - """One core of one system, on the game loaded for it.""" - - choice: CoreChoice - core: dict - system: str - content: probes_content.Content - load: Path - - -def probe_one(layout: Layout, platform: str, config: dict, profile: dict, target: ProbeTarget, - work: Path) -> dict: - """Run until the staging is closed. The first run is recorded, and when - the staging grew, the closed one is recorded too and supersedes it.""" - choice, core, system, content, load = target.choice, target.core, target.system, target.content, target.load - native = platform_system(config, system) - dests = [f.get("destination") or f.get("name") - for f in ((config.get("systems") or {}).get(native) or {}).get("files") or ()] - staged = initial_stage(layout, profile, dests) - subject = subject_for(platform, layout.install, system, choice.so_name, content.name) - code, record, error = core_probe(probe_argv(core, choice, content, load, subject, True), - staged, layout, work) - if code == EXIT_BUSY: - raise ProbeFailure(f"core_probe refused on a busy host: {error}") - rounds, first_id, records = 1, None, [] - if record: - first_id = record["id"] - records.append(first_id) - added = grow_stage(layout.files, staged, first_repetition(record).get("files_probed_absent") or ()) - while added and rounds < MAX_ROUNDS: - staged |= added - rounds += 1 - code, record, error = core_probe(probe_argv(core, choice, content, load, subject, False), - staged, layout, work) - if not record: - break - added = grow_stage(layout.files, staged, first_repetition(record).get("files_probed_absent") or ()) - if rounds > 1 and record: - code, record, error = core_probe(probe_argv(core, choice, content, load, subject, True, first_id), - staged, layout, work) - if code == EXIT_BUSY: - raise ProbeFailure(f"core_probe refused on a busy host: {error}") - if record: - records.append(record["id"]) - verdict, evidence = run_verdict(record) - opened, findings = map_run(layout, staged, first_repetition(record), profile) if record else ([], []) - return { - "schema_version": 1, - "probed_at": now_iso(), - "platform": platform, - "platform_version": str(config.get("version") or ""), - "target": TARGETS.get(platform), - "install": layout.install, - "source": {**layout.source, "repo_commit": git_head()}, - "system": system, - "platform_system": native, - "emulator": choice.emulator, - "core": {"file": f"{choice.so_name}_libretro.so", "sha256": core["sha256"], "artifact": core["url"], - "last_modified": core.get("last_modified")}, - "content": {"label": content.name, "catalog": content.catalog, "region": content.region}, - "records": records, - "rounds": rounds, - "staged": len(staged), - "verdict": verdict, - "verdict_evidence": evidence, - "files_opened": opened, - "findings": findings, - "error": None if record else (error or f"core_probe exited {code}"), - } - - -def git_head() -> str | None: - proc = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=False, - cwd=REPO_ROOT) - return proc.stdout.strip() or None - - -def append_line(line: dict, root: Path = REPO_ROOT) -> dict: - sealed = mr.seal_line(line, mr.CAMPAIGN_FILES[PACK_PROBES][0]) - path = root / mr.records_path(PACK_PROBES) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(mr.line_text(sealed) + "\n") - return sealed - - -# -------------------------------------------------------------------------- -# Plans and the command line -# -------------------------------------------------------------------------- - -@dataclass -class Unit: - system: str - content: probes_content.Content - cores: list[CoreChoice] - - -def plan(platform: str, systems: set[str] | None, cores: set[str] | None, - buildbot: set[str]) -> tuple[dict, dict, list[Unit]]: - config = load_platform_config(platform, str(REPO_ROOT / "platforms")) - profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) - target = load_target_config(platform, TARGETS[platform], str(REPO_ROOT / "platforms")) - units: list[Unit] = [] - for system, contents in sorted(load_contents([host.CONTENT_FILE, PACK_CONTENT_FILE]).items()): - if systems and system not in systems: - continue - if not platform_system(config, system): - continue - choices = [c for c in choose_cores(config, profiles, system, buildbot, target) - if not cores or c.so_name in cores or c.emulator in cores] - units.extend(Unit(system, content, choices) for content in contents) - return config, profiles, units - - -def run(args: argparse.Namespace) -> int: - buildbot = buildbot_listing() - config, profiles, units = plan(args.platform, args.systems, args.cores, buildbot) - if args.mode == "plan": - for unit in units: - print(f"{unit.system}: {unit.content.name}: " - f"{', '.join(f'{c.so_name} ({c.emulator})' for c in unit.cores) or 'no core'}") - return 0 - if not units: - print(f"ERROR: no test game for any system of {args.platform}", file=sys.stderr) - return 2 - work = Path(args.work_dir) / args.platform - pack = Path(args.pack) if args.pack else build_pack(args.platform, work / "dist") - identity = pack_identity(pack) - status = 0 - for install in args.install: - if install == "pack": - layout = pack_layout(pack, work / "pack", identity) - else: - layout = installer_layout(args.platform, pack, identity, - REPO_ROOT / "install" / f"{args.platform}.json", work / "installer") - try: - for unit in units: - try: - load = probes_content.load_file(content_folder(unit.content, args.fetch), unit.content.load) - except host.Unavailable as exc: - print(f"SKIP {unit.system}: {exc}", file=sys.stderr) - continue - for choice in unit.cores: - core = fetch_core(choice.so_name, args.refresh_cores) - target = ProbeTarget(choice, core, unit.system, unit.content, load) - line = probe_one(layout, args.platform, config, profiles[choice.emulator], target, - work / "runs") - sealed = append_line(line) - print(f"{args.platform} {install} {unit.system} {choice.so_name}: {line['verdict']}, " - f"{len(line['files_opened'])} opened, {len(line['findings'])} findings, " - f"line {sealed['id']}") - if line["error"]: - status = 1 - finally: - if not args.keep: - shutil.rmtree(layout.root if install == "pack" else layout.root.parent, ignore_errors=True) - return status def build_parser() -> argparse.ArgumentParser: diff --git a/scripts/probes/packlayout.py b/scripts/probes/packlayout.py new file mode 100644 index 000000000..90c9b9299 --- /dev/null +++ b/scripts/probes/packlayout.py @@ -0,0 +1,142 @@ +"""A pack as a user installs it: extracted, or written by the installer, and its files.""" + +from __future__ import annotations + +import hashlib +import json +import shutil +import subprocess +import sys +import zipfile +from collections.abc import Sequence +from dataclasses import dataclass, field +from pathlib import Path + +from core.paths import REPO_ROOT +from core.ziptools import safe_extract_zip + + +class ProbeFailure(RuntimeError): + """The probe cannot go on: no pack, no installer layout, a busy host.""" + + +# -------------------------------------------------------------------------- +# Layouts: the platform's BIOS folder as a user ends up with it +# -------------------------------------------------------------------------- + +@dataclass +class Layout: + """A BIOS folder: every file by its path under the folder, and the pack + or manifest entry that put it there (None for a file nothing declares).""" + + install: str + root: Path + files: dict[str, str | None] + source: dict + sizes: dict[str, int] = field(default_factory=dict) + + def size(self, rel: str) -> int: + if rel not in self.sizes: + self.sizes[rel] = (self.root / rel).stat().st_size + return self.sizes[rel] + + +def walk(root: Path) -> list[str]: + return sorted(p.relative_to(root).as_posix() for p in root.rglob("*") if p.is_file()) + + +def file_sha(path: Path, algorithm: str = "sha1") -> str: + digest = hashlib.new(algorithm) + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def pack_layout(pack: Path, root: Path, identity: dict) -> Layout: + """The pack extracted as a user does, at the root of the BIOS folder. + Each file's entry is the archive member it came from.""" + if root.exists(): + shutil.rmtree(root) + safe_extract_zip(str(pack), str(root)) + with zipfile.ZipFile(pack) as handle: + members = {info.filename for info in handle.infolist() if not info.is_dir()} + files = {rel: rel if rel in members else None for rel in walk(root)} + return Layout("pack", root, files, {"pack": identity, "manifest": None}) + + +def pack_identity(pack: Path) -> dict: + with zipfile.ZipFile(pack) as handle: + members = sum(1 for info in handle.infolist() if not info.is_dir()) + return {"file": pack.name, "sha256": file_sha(pack, "sha256"), "size": pack.stat().st_size, + "members": members} + + +def manifest_entries(manifest: dict) -> dict[str, str]: + """Destination -> the manifest entry that names it, as the installer + places it under --dest: a file by its dest, a data directory member + under its directory's dest.""" + out: dict[str, str] = {} + for item in manifest.get("files") or (): + out[item["dest"]] = f"files:{item['dest']}" + for item in manifest.get("case_variants") or (): + out.setdefault(item["dest"], f"case_variants:{item['dest']}") + for directory in manifest.get("data_directories") or (): + base = str(directory.get("dest") or "").strip("/") + for member in directory.get("files") or {}: + dest = f"{base}/{member}" if base else member + out.setdefault(dest, f"data_directories:{directory['ref']}:{member}") + return out + + +def installer_summary(stdout: str, system_dir: Path, save_dir: Path) -> str: + """The end of the installer's output, as a record keeps it. The scratch + folders are written as the options that named them: a record read + elsewhere has no use for the path of the machine that ran the probe.""" + text = stdout.replace(str(system_dir), "").replace(str(save_dir), "") + return " ".join(text.split())[-400:] + + +def installer_layout(platform: str, pack: Path, identity: dict, manifest_path: Path, + root: Path, narrow: Sequence[str] = ()) -> Layout: + """install.py --dest on a scratch root, from the pack, offline. The + manifest is the published one, the file a user's installer reads. + ``narrow`` passes install.py options such as --system, for the tests.""" + system_dir, save_dir = root / "system", root / "saves" + if root.exists(): + shutil.rmtree(root) + argv = [sys.executable, str(REPO_ROOT / "install.py"), "--platform", platform, "--dest", str(system_dir), + "--save-dir", str(save_dir), "--from-pack", str(pack), "--manifest", str(manifest_path), + "--offline", "--yes", "--quiet", *narrow] + proc = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=REPO_ROOT) + if proc.returncode != 0 or not system_dir.is_dir(): + raise ProbeFailure(f"install.py exited {proc.returncode}: {(proc.stderr or proc.stdout)[-1500:]}") + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + entries = manifest_entries(manifest) + files = {rel: entries.get(rel) for rel in walk(system_dir)} + source = { + "pack": identity, + "manifest": {"path": manifest_path.relative_to(REPO_ROOT).as_posix() if manifest_path.is_relative_to(REPO_ROOT) + else manifest_path.name, + "sha256": file_sha(manifest_path, "sha256"), + "generated": manifest.get("generated"), "pack_files": manifest.get("pack_files")}, + "save_dir_files": len(walk(save_dir)) if save_dir.is_dir() else 0, + "installer_summary": installer_summary(proc.stdout, system_dir, save_dir), + } + return Layout("installer", system_dir, files, source) + + +def build_pack(platform: str, out_dir: Path, narrow: Sequence[str] = ()) -> Path: + """The platform's pack, built from this checkout as a release builds it. + ``narrow`` passes generate_pack.py options such as --system, for the tests.""" + out_dir.mkdir(parents=True, exist_ok=True) + for old in out_dir.glob("*_BIOS_Pack*.zip"): + old.unlink() + argv = [sys.executable, str(REPO_ROOT / "scripts" / "generate_pack.py"), "--platform", platform, + "--offline", "--output-dir", str(out_dir), *narrow] + proc = subprocess.run(argv, capture_output=True, text=True, check=False, cwd=REPO_ROOT) + packs = sorted(p for p in out_dir.glob("*_BIOS_Pack*.zip") if ".part" not in p.name) + if proc.returncode != 0 or len(packs) != 1: + raise ProbeFailure(f"generate_pack.py exited {proc.returncode} with {len(packs)} packs: " + f"{proc.stderr[-1500:]}") + return packs[0] diff --git a/scripts/probes/packprobe.py b/scripts/probes/packprobe.py new file mode 100644 index 000000000..421eb89ad --- /dev/null +++ b/scripts/probes/packprobe.py @@ -0,0 +1,530 @@ +"""A pack probed the way a user runs it: cores chosen per system, files staged until the run settles, one line per probe.""" + +from __future__ import annotations + +import argparse +import contextlib +import fcntl +import json +import os +import re +import shutil +import subprocess +import sys +import time +import urllib.request +from collections.abc import Iterable, Iterator, Sequence +from dataclasses import dataclass +from pathlib import Path + +import autorun +from core.paths import REPO_ROOT +from core.statefile import now_iso +from model import measurements as mr +from model.platforms import load_platform_config +from model.profiles import load_emulator_profiles +from model.systems import _norm_system_id +from model.targets import load_target_config +from probes.content import Content, load_content, load_file, verify_identity +from probes.cores import BUILDBOT, safe_extract_so +from probes.entries import entry_dest +from probes.host import CONTENT_FILE, Unavailable, child_env +from probes.packlayout import ( + Layout, + ProbeFailure, + build_pack, + file_sha, + installer_layout, + pack_identity, + pack_layout, +) +from resolve.cores import resolve_platform_cores +from resolve.layout import runs_standalone +from resolve.validation import filter_files_by_mode + + +MAIN = autorun.main_checkout() +PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml" +CONTENT_DIR = MAIN / ".cache" / "test-content" +CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores" + +PACK_PROBES = mr.PACK_PROBES + + +VERDICTS = ("boots", "bios_error", "crash", "hang", "unknown") +MAX_ROUNDS = 6 +PROBE_TIMEOUT = 900 +IDLE_WAIT = 1800 +PROBE_LOCK_ENV = "RETROBIOS_PROBE_LOCK" +PROBE_LOCK_HELD_ENV = "RETROBIOS_PROBE_LOCK_HELD" +PROBE_LOCK = Path(os.environ.get(PROBE_LOCK_ENV) + or Path.home() / ".local" / "state" / "retrobios" / "probe.lock") +EXIT_BUSY = 3 + +# The hardware target each platform is probed for: the one whose libretro +# cores are the buildbot's x86_64 Linux builds, or the platform's only one. +TARGETS = {"retroarch": "linux-x86_64", "batocera": "x86_64", "retrobat": "windows"} + + +# -------------------------------------------------------------------------- +# Which cores a platform runs for a system +# -------------------------------------------------------------------------- + +@dataclass(frozen=True) +class CoreChoice: + emulator: str + so_name: str + + +def platform_system(config: dict, system: str) -> str | None: + """The platform's own id of a system, compared on the normalised id.""" + wanted = _norm_system_id(system) + matches = sorted(s for s in config.get("systems") or {} if _norm_system_id(s) == wanted) + return matches[0] if matches else None + + +def libretro_build_runs(name: str, profile: dict, config: dict) -> bool: + """The platform launches this profile's libretro build: it has one, and + the platform does not run the emulator standalone only.""" + if "libretro" not in str(profile.get("type", "")) or profile.get("type") == "alias": + return False + standalone = {str(c) for c in config.get("standalone_cores") or ()} + if not runs_standalone(name, profile, standalone): + return True + dual = {str(c) for c in config.get("dual_mode_cores") or ()} + return bool(dual & ({name} | {str(c) for c in profile.get("cores") or ()})) + + +def so_names(name: str, profile: dict, buildbot: set[str], target: set[str] | None) -> list[str]: + """The buildbot builds of a profile the platform runs. Every one the + target names, else the build that carries the profile's key, else the + first of its cores: that is on the buildbot.""" + names = [str(c) for c in profile.get("cores") or () if str(c) in buildbot] + if target is not None: + named = [n for n in names if n in target] + if named: + return sorted(named) + if name in buildbot: + return [name] + return names[:1] + + +def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: set[str], + target: set[str] | None) -> list[CoreChoice]: + wanted = _norm_system_id(system) + out: list[CoreChoice] = [] + for name in sorted(resolve_platform_cores(config, profiles, target)): + profile = profiles[name] + if wanted not in {_norm_system_id(s) for s in profile.get("systems") or ()}: + continue + if not libretro_build_runs(name, profile, config): + continue + out.extend(CoreChoice(name, so) for so in so_names(name, profile, buildbot, target)) + return out + + +# -------------------------------------------------------------------------- +# Staging: what the core can reach, grown to a fixed point +# -------------------------------------------------------------------------- + +def entry_paths(entry: dict) -> list[str]: + """The paths a profile entry names under the system directory: its + path or name, and its aliases beside it.""" + main = entry_dest(entry) + folder = main.rsplit("/", 1)[0] + "/" if "/" in main else "" + return [main] + [f"{folder}{alias}" for alias in entry.get("aliases") or ()] + + +def libretro_entries(profile: dict) -> list[dict]: + return filter_files_by_mode(profile.get("files") or [], standalone=False) + + +def declared_sizes(profile: dict) -> set[int]: + sizes: set[int] = set() + for entry in libretro_entries(profile): + value = entry.get("size") + sizes.update(v for v in (value if isinstance(value, list) else [value]) if isinstance(v, int)) + return sizes + + +def with_folders(files: Iterable[str], staged: set[str]) -> set[str]: + """Every file of every folder a staged file sits in, below the root: a + core that lists its folder sees what the platform's folder holds.""" + folders = {rel.rsplit("/", 1)[0] + "/" for rel in staged if "/" in rel} + return set(staged) | {rel for rel in files if any(rel.startswith(f) for f in folders)} + + +def initial_stage(layout: Layout, profile: dict, platform_dests: Iterable[str]) -> set[str]: + files = set(layout.files) + staged = {p for entry in libretro_entries(profile) for p in entry_paths(entry) if p in files} + staged |= {d for d in platform_dests if d in files} + if profile.get("found_by") == "content": + sizes = declared_sizes(profile) + staged |= {rel for rel in files if "/" not in rel and layout.size(rel) in sizes} + return with_folders(files, staged) + + +def grow_stage(files: Iterable[str], staged: set[str], probed: Iterable[str]) -> set[str]: + """The files the layout holds that the core looked for, as a file or as + a folder, and their folders: empty once the staging is closed.""" + files = set(files) + wanted = set() + for path in probed: + if path in files: + wanted.add(path) + else: + wanted |= {rel for rel in files if rel.startswith(path.rstrip("/") + "/")} + return with_folders(files, staged | wanted) - staged + + +# -------------------------------------------------------------------------- +# Reading a run +# -------------------------------------------------------------------------- + +def run_verdict(record: dict | None) -> tuple[str, dict | None]: + """The verdict of a run record: variants[0] from record version 4, + unknown before the oracle or without a record.""" + if not record or not record.get("variants"): + return "unknown", None + variant = record["variants"][0] + verdict = variant.get("verdict") + if verdict not in VERDICTS: + return "unknown", None + return verdict, variant.get("verdict_evidence") + + +def first_repetition(record: dict) -> dict: + return record["variants"][0]["repetitions"][0] + + +def declaring(profile: dict, path: str) -> list[str]: + return sorted({entry["name"] for entry in libretro_entries(profile) if path in entry_paths(entry)}) + + +def map_run(layout: Layout, staged: set[str], rep: dict, profile: dict) -> tuple[list[dict], list[dict]]: + """The files the core opened, each with its pack entry, and the findings.""" + opened = [] + for item in rep.get("files_opened") or (): + path = item["path"] + opened.append({"path": path, "entry": layout.files.get(path) if path in staged else None, + "sha1": item.get("sha1_after"), "created": path not in staged}) + by_name: dict[str, list[str]] = {} + for rel in layout.files: + by_name.setdefault(rel.rsplit("/", 1)[-1].casefold(), []).append(rel) + # An entry the core found under one of its names asks for nothing more: + # BlastEm tries tmss.md, then reads bios_MD.bin, both names of one entry. + read = {item["path"] for item in opened if not item["created"]} + satisfied = {entry["name"] for entry in libretro_entries(profile) if read & set(entry_paths(entry))} + findings = [] + for path in rep.get("files_probed_absent") or (): + names = declaring(profile, path) + if path in layout.files: + findings.append({"kind": "not_staged", "path": path, "declared_by": names, "paths": [path]}) + continue + if names and set(names) <= satisfied: + continue + elsewhere = sorted(p for p in by_name.get(path.rsplit("/", 1)[-1].casefold(), ()) if p != path) + if elsewhere: + kind = "elsewhere" + else: + kind = "missing_declared" if names else "missing_undeclared" + findings.append({"kind": kind, "path": path, "declared_by": names, "paths": elsewhere}) + findings.extend({"kind": "unlisted", "path": item["path"], "declared_by": [], "paths": []} + for item in opened if item["path"] in staged and item["entry"] is None) + return opened, findings + + +# -------------------------------------------------------------------------- +# Cores and content +# -------------------------------------------------------------------------- + +def buildbot_listing() -> set[str]: + with urllib.request.urlopen(BUILDBOT, timeout=120) as response: + page = response.read().decode("utf-8", "replace") + return set(re.findall(r"([A-Za-z0-9_]+)_libretro\.so\.zip", page)) + + +def fetch_core(name: str, refresh: bool = False) -> dict: + """The buildbot nightly of a core, kept with where and when it came from.""" + folder = CORE_CACHE / name + so, meta_path = folder / f"{name}_libretro.so", folder / "build.json" + if so.is_file() and meta_path.is_file() and not refresh: + meta = json.loads(meta_path.read_text(encoding="utf-8")) + if meta.get("sha256") == file_sha(so, "sha256"): + return {**meta, "path": str(so)} + url = f"{BUILDBOT}{name}_libretro.so.zip" + folder.mkdir(parents=True, exist_ok=True) + archive = folder / f"{name}.zip.part" + with urllib.request.urlopen(url, timeout=600) as response, archive.open("wb") as out: + shutil.copyfileobj(response, out) + modified = response.headers.get("Last-Modified") + safe_extract_so(archive, f"{name}_libretro.so", so) + archive.unlink() + meta = {"name": name, "url": url, "last_modified": modified, "sha256": file_sha(so, "sha256"), + "fetched_at": now_iso()} + meta_path.write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") + return {**meta, "path": str(so)} + + +def load_contents(files: Sequence[Path]) -> dict[str, list[Content]]: + out: dict[str, list[Content]] = {} + for path in files: + if path.is_file(): + for system, items in load_content(path).items(): + out.setdefault(system, []).extend(items) + return out + + +def content_folder(content: Content, fetch: bool) -> Path: + """The game's folder, fetched through romfetch when absent and asked to.""" + folder = CONTENT_DIR / content.romfetch_system / content.name + if not (folder / "identity.json").is_file() and fetch: + romfetch = shutil.which("romfetch") + if not romfetch: + raise Unavailable("romfetch not found") + proc = subprocess.run([romfetch, "get", content.romfetch_system, content.name, "--json", "-q", + "--content-dir", str(CONTENT_DIR)], capture_output=True, text=True, + check=False, env=child_env(romfetch=True)) + if proc.returncode != 0: + raise Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}") + verify_identity(folder) + return folder + + +# -------------------------------------------------------------------------- +# One probe: a core, a game, a layout +# -------------------------------------------------------------------------- + +def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None: + """Wait for the load core_probe records under, a quarter of the CPUs. + Extracting a pack loads the host itself for a minute or two.""" + threshold = (os.cpu_count() or 1) / 4 + waited = 0.0 + while os.getloadavg()[0] > threshold: + if waited >= limit: + raise ProbeFailure(f"busy host: load {os.getloadavg()[0]:.2f} above {threshold} " + f"for {int(waited)} s") + time.sleep(poll) + waited += poll + + +@contextlib.contextmanager +def probe_lock(path: Path | None = None) -> Iterator[None]: + """The host's probe lock, for one run: one probe at a time on the host, + released between runs so a pass never holds it for its whole length.""" + path = path or PROBE_LOCK + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a") as handle: + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + +def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) -> tuple[int, dict | None, str]: + """core_probe.py run under the probe lock, the system files passed in an + argument file.""" + work.mkdir(parents=True, exist_ok=True) + argfile = work / "system-files.args" + argfile.write_text("".join(f"--system-file\n{rel}={layout.root / rel}\n" for rel in sorted(staged)), + encoding="utf-8") + command = [sys.executable, str(REPO_ROOT / "scripts" / "core_probe.py"), *argv, f"@{argfile}"] + with probe_lock(): + if "--record" in argv: + wait_idle() + # core_probe takes the same lock unless told its caller holds it. + proc = subprocess.run(command, capture_output=True, text=True, check=False, cwd=REPO_ROOT, + timeout=PROBE_TIMEOUT * 2 + 120, + env={**os.environ, PROBE_LOCK_HELD_ENV: "1", PROBE_LOCK_ENV: str(PROBE_LOCK)}) + record = None + if proc.returncode == 0: + try: + record = json.loads(proc.stdout) + except ValueError: + record = None + # A traceback spells the checkout and the scratch folders: a record read + # on another machine names them by role. + places = [(str(work), ""), (str(layout.root), ""), (str(REPO_ROOT), "")] + error = proc.stderr.strip() + for prefix, name in sorted(places, key=lambda place: -len(place[0])): + error = error.replace(prefix, name) + return proc.returncode, record, error[-1500:] + + +def probe_argv(core: dict, choice: CoreChoice, content: Content, load: Path, + subject: str, record: bool, supersedes: str | None = None) -> list[str]: + argv = ["run", "--core", core["path"], "--content", str(load), "--content-label", content.name, + "--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every), + "--require-sandbox", "--timeout", str(PROBE_TIMEOUT), + "--work-dir", str(REPO_ROOT / "tmp" / "core_probe"), "--core-artifact", core["url"]] + if record: + argv += ["--record", str(REPO_ROOT), "--emulator", choice.emulator, "--subject", subject] + if supersedes: + argv += ["--supersedes", supersedes] + return argv + + +def subject_for(platform: str, install: str, system: str, so: str, content: str) -> str: + subject = mr.slugify(f"{platform} {install} {system} {so} {content}", 85) + return f"{mr.PACK_SUBJECT_PREFIX}{subject}" + + +@dataclass(frozen=True) +class ProbeTarget: + """One core of one system, on the game loaded for it.""" + + choice: CoreChoice + core: dict + system: str + content: Content + load: Path + + +def probe_one(layout: Layout, platform: str, config: dict, profile: dict, target: ProbeTarget, + work: Path) -> dict: + """Run until the staging is closed. The first run is recorded, and when + the staging grew, the closed one is recorded too and supersedes it.""" + choice, core, system, content, load = target.choice, target.core, target.system, target.content, target.load + native = platform_system(config, system) + dests = [f.get("destination") or f.get("name") + for f in ((config.get("systems") or {}).get(native) or {}).get("files") or ()] + staged = initial_stage(layout, profile, dests) + subject = subject_for(platform, layout.install, system, choice.so_name, content.name) + code, record, error = core_probe(probe_argv(core, choice, content, load, subject, True), + staged, layout, work) + if code == EXIT_BUSY: + raise ProbeFailure(f"core_probe refused on a busy host: {error}") + rounds, first_id, records = 1, None, [] + if record: + first_id = record["id"] + records.append(first_id) + added = grow_stage(layout.files, staged, first_repetition(record).get("files_probed_absent") or ()) + while added and rounds < MAX_ROUNDS: + staged |= added + rounds += 1 + code, record, error = core_probe(probe_argv(core, choice, content, load, subject, False), + staged, layout, work) + if not record: + break + added = grow_stage(layout.files, staged, first_repetition(record).get("files_probed_absent") or ()) + if rounds > 1 and record: + code, record, error = core_probe(probe_argv(core, choice, content, load, subject, True, first_id), + staged, layout, work) + if code == EXIT_BUSY: + raise ProbeFailure(f"core_probe refused on a busy host: {error}") + if record: + records.append(record["id"]) + verdict, evidence = run_verdict(record) + opened, findings = map_run(layout, staged, first_repetition(record), profile) if record else ([], []) + return { + "schema_version": 1, + "probed_at": now_iso(), + "platform": platform, + "platform_version": str(config.get("version") or ""), + "target": TARGETS.get(platform), + "install": layout.install, + "source": {**layout.source, "repo_commit": git_head()}, + "system": system, + "platform_system": native, + "emulator": choice.emulator, + "core": {"file": f"{choice.so_name}_libretro.so", "sha256": core["sha256"], "artifact": core["url"], + "last_modified": core.get("last_modified")}, + "content": {"label": content.name, "catalog": content.catalog, "region": content.region}, + "records": records, + "rounds": rounds, + "staged": len(staged), + "verdict": verdict, + "verdict_evidence": evidence, + "files_opened": opened, + "findings": findings, + "error": None if record else (error or f"core_probe exited {code}"), + } + + +def git_head() -> str | None: + proc = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=False, + cwd=REPO_ROOT) + return proc.stdout.strip() or None + + +def append_line(line: dict, root: Path = REPO_ROOT) -> dict: + sealed = mr.seal_line(line, mr.CAMPAIGN_FILES[PACK_PROBES][0]) + path = root / mr.records_path(PACK_PROBES) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(mr.line_text(sealed) + "\n") + return sealed + + +# -------------------------------------------------------------------------- +# Plans and the command line +# -------------------------------------------------------------------------- + +@dataclass +class Unit: + system: str + content: Content + cores: list[CoreChoice] + + +def plan(platform: str, systems: set[str] | None, cores: set[str] | None, + buildbot: set[str]) -> tuple[dict, dict, list[Unit]]: + config = load_platform_config(platform, str(REPO_ROOT / "platforms")) + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) + target = load_target_config(platform, TARGETS[platform], str(REPO_ROOT / "platforms")) + units: list[Unit] = [] + for system, contents in sorted(load_contents([CONTENT_FILE, PACK_CONTENT_FILE]).items()): + if systems and system not in systems: + continue + if not platform_system(config, system): + continue + choices = [c for c in choose_cores(config, profiles, system, buildbot, target) + if not cores or c.so_name in cores or c.emulator in cores] + units.extend(Unit(system, content, choices) for content in contents) + return config, profiles, units + + +def run(args: argparse.Namespace) -> int: + buildbot = buildbot_listing() + config, profiles, units = plan(args.platform, args.systems, args.cores, buildbot) + if args.mode == "plan": + for unit in units: + print(f"{unit.system}: {unit.content.name}: " + f"{', '.join(f'{c.so_name} ({c.emulator})' for c in unit.cores) or 'no core'}") + return 0 + if not units: + print(f"ERROR: no test game for any system of {args.platform}", file=sys.stderr) + return 2 + work = Path(args.work_dir) / args.platform + pack = Path(args.pack) if args.pack else build_pack(args.platform, work / "dist") + identity = pack_identity(pack) + status = 0 + for install in args.install: + if install == "pack": + layout = pack_layout(pack, work / "pack", identity) + else: + layout = installer_layout(args.platform, pack, identity, + REPO_ROOT / "install" / f"{args.platform}.json", work / "installer") + try: + for unit in units: + try: + load = load_file(content_folder(unit.content, args.fetch), unit.content.load) + except Unavailable as exc: + print(f"SKIP {unit.system}: {exc}", file=sys.stderr) + continue + for choice in unit.cores: + core = fetch_core(choice.so_name, args.refresh_cores) + target = ProbeTarget(choice, core, unit.system, unit.content, load) + line = probe_one(layout, args.platform, config, profiles[choice.emulator], target, + work / "runs") + sealed = append_line(line) + print(f"{args.platform} {install} {unit.system} {choice.so_name}: {line['verdict']}, " + f"{len(line['files_opened'])} opened, {len(line['findings'])} findings, " + f"line {sealed['id']}") + if line["error"]: + status = 1 + finally: + if not args.keep: + shutil.rmtree(layout.root if install == "pack" else layout.root.parent, ignore_errors=True) + return status diff --git a/tests/test_layers.py b/tests/test_layers.py index be401b224..ff86fe7f6 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -59,6 +59,7 @@ PENDING_TOP_LEVEL_IMPORTS = frozenset({ ("probes.campaign", "autorun"), ("probes.gate", "autorun"), ("probes.host", "autorun"), + ("probes.packprobe", "autorun"), ("sitegen.build", "release_record"), ("sitegen.config", "release_record"), ("sitegen.decorate", "release_record"), diff --git a/tests/test_pack_probe.py b/tests/test_pack_probe.py index 096308e4c..25a0e2b9f 100644 --- a/tests/test_pack_probe.py +++ b/tests/test_pack_probe.py @@ -25,6 +25,8 @@ from pathlib import Path from model import measurements as mr import pack_probe as pp +from probes import packlayout +from probes import packprobe from model import profiles as model_profiles REPO_ROOT = Path(__file__).resolve().parent.parent @@ -57,37 +59,37 @@ KRONOS = { } -def layout(files: dict[str, int], entries: dict[str, str | None] | None = None) -> pp.Layout: +def layout(files: dict[str, int], entries: dict[str, str | None] | None = None) -> packlayout.Layout: """A layout whose sizes are given, nothing on disk.""" - return pp.Layout("pack", Path("/nonexistent"), entries or {rel: rel for rel in files}, {}, + return packlayout.Layout("pack", Path("/nonexistent"), entries or {rel: rel for rel in files}, {}, sizes=dict(files)) class CoreChoice(unittest.TestCase): def test_system_ids_compare_normalised(self) -> None: config = {"systems": {"megacd": {}, "psx": {}}} - self.assertEqual(pp.platform_system(config, "sega-mega-cd"), "megacd") - self.assertIsNone(pp.platform_system(config, "sega-saturn")) + self.assertEqual(packprobe.platform_system(config, "sega-mega-cd"), "megacd") + self.assertIsNone(packprobe.platform_system(config, "sega-saturn")) def test_standalone_only_is_not_run_as_a_core(self) -> None: both = {"type": "standalone + libretro", "cores": ["duckstation", "duckstation-sa"]} - self.assertTrue(pp.libretro_build_runs("duckstation", both, {})) - self.assertFalse(pp.libretro_build_runs("duckstation", both, {"standalone_cores": ["duckstation"]})) - self.assertTrue(pp.libretro_build_runs("duckstation", both, { + self.assertTrue(packprobe.libretro_build_runs("duckstation", both, {})) + self.assertFalse(packprobe.libretro_build_runs("duckstation", both, {"standalone_cores": ["duckstation"]})) + self.assertTrue(packprobe.libretro_build_runs("duckstation", both, { "standalone_cores": ["duckstation"], "dual_mode_cores": ["duckstation-sa"]})) - self.assertFalse(pp.libretro_build_runs("x", {"type": "standalone"}, {})) - self.assertFalse(pp.libretro_build_runs("x", {"type": "alias"}, {})) + self.assertFalse(packprobe.libretro_build_runs("x", {"type": "standalone"}, {})) + self.assertFalse(packprobe.libretro_build_runs("x", {"type": "alias"}, {})) def test_buildbot_name(self) -> None: buildbot = {"mednafen_psx", "mednafen_psx_hw", "kronos"} beetle = {"cores": ["beetle_psx", "mednafen_psx", "mednafen_psx_hw"]} # The target names both builds: both run. - self.assertEqual(pp.so_names("beetle_psx", beetle, buildbot, {"mednafen_psx", "mednafen_psx_hw"}), + self.assertEqual(packprobe.so_names("beetle_psx", beetle, buildbot, {"mednafen_psx", "mednafen_psx_hw"}), ["mednafen_psx", "mednafen_psx_hw"]) # A target in the platform's own names: the first buildbot name. - self.assertEqual(pp.so_names("beetle_psx", beetle, buildbot, {"beetle-psx"}), ["mednafen_psx"]) - self.assertEqual(pp.so_names("kronos", {"cores": ["kronos"]}, buildbot, None), ["kronos"]) - self.assertEqual(pp.so_names("gone", {"cores": ["gone"]}, buildbot, None), []) + self.assertEqual(packprobe.so_names("beetle_psx", beetle, buildbot, {"beetle-psx"}), ["mednafen_psx"]) + self.assertEqual(packprobe.so_names("kronos", {"cores": ["kronos"]}, buildbot, None), ["kronos"]) + self.assertEqual(packprobe.so_names("gone", {"cores": ["gone"]}, buildbot, None), []) def test_choose_cores(self) -> None: profiles = {"beetle_saturn": SATURN, "kronos": KRONOS, "swanstation": SCANNER, @@ -95,8 +97,8 @@ class CoreChoice(unittest.TestCase): config = {"_key": "p", "cores": ["beetle-saturn", "kronos", "ssf", "swanstation"], "systems": {"saturn": {}}} buildbot = {"mednafen_saturn", "kronos", "swanstation"} - self.assertEqual(pp.choose_cores(config, profiles, "sega-saturn", buildbot, None), - [pp.CoreChoice("beetle_saturn", "mednafen_saturn"), pp.CoreChoice("kronos", "kronos")]) + self.assertEqual(packprobe.choose_cores(config, profiles, "sega-saturn", buildbot, None), + [packprobe.CoreChoice("beetle_saturn", "mednafen_saturn"), packprobe.CoreChoice("kronos", "kronos")]) class Staging(unittest.TestCase): @@ -105,23 +107,23 @@ class Staging(unittest.TestCase): "kronos/stvbios.zip": 10, "mame/hash/saturn.xml": 5, "standalone.bin": 1} def test_declared_names_aliases_and_platform_list(self) -> None: - staged = pp.initial_stage(layout(self.FILES), SATURN, ["other.rom", "absent.bin"]) + staged = packprobe.initial_stage(layout(self.FILES), SATURN, ["other.rom", "absent.bin"]) self.assertEqual(staged, {"sega_101.bin", "saturn_bios.bin", "other.rom"}) def test_a_folder_comes_whole(self) -> None: - staged = pp.initial_stage(layout(self.FILES), KRONOS, []) + staged = packprobe.initial_stage(layout(self.FILES), KRONOS, []) self.assertEqual(staged, {"kronos/saturn_bios.bin", "kronos/stvbios.zip"}) def test_a_core_that_scans_gets_every_root_file_of_its_sizes(self) -> None: - staged = pp.initial_stage(layout(self.FILES), SCANNER, []) + staged = packprobe.initial_stage(layout(self.FILES), SCANNER, []) self.assertEqual(staged, {"sega_101.bin", "saturn_bios.bin", "scph5501.bin", "big.bin"}) def test_grow_to_a_fixed_point(self) -> None: staged = {"sega_101.bin"} - added = pp.grow_stage(self.FILES, staged, ["other.rom", "absent.bin", "mame/hash", "kronos"]) + added = packprobe.grow_stage(self.FILES, staged, ["other.rom", "absent.bin", "mame/hash", "kronos"]) self.assertEqual(added, {"other.rom", "mame/hash/saturn.xml", "kronos/saturn_bios.bin", "kronos/stvbios.zip"}) - self.assertEqual(pp.grow_stage(self.FILES, staged | added, ["absent.bin"]), set()) + self.assertEqual(packprobe.grow_stage(self.FILES, staged | added, ["absent.bin"]), set()) class Mapping(unittest.TestCase): @@ -133,7 +135,7 @@ class Mapping(unittest.TestCase): {"path": "extra.bin", "sha1_after": "b" * 40}, {"path": "bkram.bin", "sha1_after": "c" * 40}], "files_probed_absent": ["saturn_bios.bin", "mpr-17933.bin", "cfg.ini"]} - opened, findings = pp.map_run(lay, {"sega_101.bin", "extra.bin"}, rep, SATURN) + opened, findings = packprobe.map_run(lay, {"sega_101.bin", "extra.bin"}, rep, SATURN) self.assertEqual(opened, [ {"path": "sega_101.bin", "entry": "sega_101.bin", "sha1": "a" * 40, "created": False}, {"path": "extra.bin", "entry": None, "sha1": "b" * 40, "created": False}, @@ -150,7 +152,7 @@ class Mapping(unittest.TestCase): lay = layout({"bios_MD.bin": 1}) rep = {"files_opened": [{"path": "bios_MD.bin", "sha1_after": "a" * 40}], "files_probed_absent": ["tmss.md", "bios_CD_U.bin"]} - _, findings = pp.map_run(lay, {"bios_MD.bin"}, rep, profile) + _, findings = packprobe.map_run(lay, {"bios_MD.bin"}, rep, profile) self.assertEqual(findings, [{"kind": "missing_declared", "path": "bios_CD_U.bin", "declared_by": ["bios_CD_U.bin"], "paths": []}]) @@ -159,7 +161,7 @@ class Mapping(unittest.TestCase): "case_variants": [{"dest": "A.BIN"}, {"dest": "a.bin"}], "data_directories": [{"ref": "bluemsx", "dest": "", "files": {"Machines/x.ini": {}}}, {"ref": "dolphin", "dest": "dolphin-emu/Sys/", "files": {"y": {}}}]} - self.assertEqual(pp.manifest_entries(manifest), { + self.assertEqual(packlayout.manifest_entries(manifest), { "a.bin": "files:a.bin", "A.BIN": "case_variants:A.BIN", "Machines/x.ini": "data_directories:bluemsx:Machines/x.ini", "dolphin-emu/Sys/y": "data_directories:dolphin:y"}) @@ -167,14 +169,14 @@ class Mapping(unittest.TestCase): class Verdict(unittest.TestCase): def test_a_record_before_the_oracle_is_unknown(self) -> None: - self.assertEqual(pp.run_verdict(None), ("unknown", None)) - self.assertEqual(pp.run_verdict({"variants": [{"repetitions": [{}]}]}), ("unknown", None)) + self.assertEqual(packprobe.run_verdict(None), ("unknown", None)) + self.assertEqual(packprobe.run_verdict({"variants": [{"repetitions": [{}]}]}), ("unknown", None)) def test_the_first_variant_decides(self) -> None: evidence = {"rule": "reference_frame", "detail": "frame 120"} record = {"variants": [{"verdict": "boots", "verdict_evidence": evidence, "repetitions": [{}]}]} - self.assertEqual(pp.run_verdict(record), ("boots", evidence)) - self.assertEqual(pp.run_verdict({"variants": [{"verdict": "maybe"}]}), ("unknown", None)) + self.assertEqual(packprobe.run_verdict(record), ("boots", evidence)) + self.assertEqual(packprobe.run_verdict({"variants": [{"verdict": "maybe"}]}), ("unknown", None)) class Line(unittest.TestCase): @@ -202,7 +204,7 @@ class Line(unittest.TestCase): } def test_the_line_is_sealed_valid_and_read_back(self) -> None: - sealed = pp.append_line(self.line(), self.root) + sealed = packprobe.append_line(self.line(), self.root) self.assertEqual(mr.read_campaign(self.root, mr.PACK_PROBES), [sealed]) try: from jsonschema import Draft202012Validator @@ -231,7 +233,7 @@ class SitePages(unittest.TestCase): def test_pack_runs_stay_off_the_emulator_page(self) -> None: from sitegen import measurements as sm - subject = pp.subject_for("retroarch", "pack", "sega-saturn", "mednafen_saturn", "Game (Japan)") + subject = packprobe.subject_for("retroarch", "pack", "sega-saturn", "mednafen_saturn", "Game (Japan)") self.assertEqual(subject, "pack-retroarch-pack-sega-saturn-mednafen-saturn-game-japan") index = {"items": [{"emulator": "beetle_saturn", "subject": subject}, {"emulator": "beetle_saturn", "subject": "boot-sega-101-bin"}]} @@ -277,10 +279,10 @@ class Lock(unittest.TestCase): return subprocess.CompletedProcess(command, 2, "", "refused") lay = layout({"a.bin": 1}) - with unittest.mock.patch.object(pp, "PROBE_LOCK", lock), \ - unittest.mock.patch.object(pp.subprocess, "run", fake_run): + with unittest.mock.patch.object(packprobe, "PROBE_LOCK", lock), \ + unittest.mock.patch.object(packprobe.subprocess, "run", fake_run): for _ in range(2): - self.assertEqual(pp.core_probe(["run"], {"a.bin"}, lay, work), (2, None, "refused")) + self.assertEqual(packprobe.core_probe(["run"], {"a.bin"}, lay, work), (2, None, "refused")) self.assertEqual(held, [True, True]) self.assertFalse(try_lock()) @@ -293,7 +295,7 @@ class RecordsNameNoLocalPath(unittest.TestCase): root = Path("/srv/run/tmp/pack_probe/retroarch/installer") out = (f"Copy it from an owned copy of the game into {root / 'system'}/jazz2/Source/.\n" f"Saves go to {root / 'saves'}.\n") - summary = pp.installer_summary(out, root / "system", root / "saves") + summary = packlayout.installer_summary(out, root / "system", root / "saves") self.assertEqual(summary, "Copy it from an owned copy of the game into /jazz2/Source/. " "Saves go to .") @@ -308,9 +310,9 @@ class RecordsNameNoLocalPath(unittest.TestCase): def fake_run(command, **kwargs): return subprocess.CompletedProcess(command, 1, "", f' File "{script}", line 9\n') - with unittest.mock.patch.object(pp, "PROBE_LOCK", work / "probe.lock"), \ - unittest.mock.patch.object(pp.subprocess, "run", fake_run): - code, record, error = pp.core_probe(["run"], set(), layout({}), work) + with unittest.mock.patch.object(packprobe, "PROBE_LOCK", work / "probe.lock"), \ + unittest.mock.patch.object(packprobe.subprocess, "run", fake_run): + code, record, error = packprobe.core_probe(["run"], set(), layout({}), work) self.assertEqual((code, record), (1, None)) self.assertEqual(error, 'File "/scripts/core_probe.py", line 9') @@ -342,25 +344,25 @@ class RealLayouts(unittest.TestCase): def setUpClass(cls) -> None: cls.work = TMP / "real" shutil.rmtree(cls.work, ignore_errors=True) - cls.pack = pp.build_pack("retroarch", cls.work / "dist", ["--system", "sony-playstation"]) - cls.identity = pp.pack_identity(cls.pack) + cls.pack = packlayout.build_pack("retroarch", cls.work / "dist", ["--system", "sony-playstation"]) + cls.identity = packlayout.pack_identity(cls.pack) @classmethod def tearDownClass(cls) -> None: shutil.rmtree(cls.work, ignore_errors=True) def test_pack_path(self) -> None: - lay = pp.pack_layout(self.pack, self.work / "pack", self.identity) + lay = packlayout.pack_layout(self.pack, self.work / "pack", self.identity) with zipfile.ZipFile(self.pack) as handle: members = {i.filename for i in handle.infolist() if not i.is_dir()} self.assertEqual(set(lay.files), members) self.assertEqual(lay.files["scph5501.bin"], "scph5501.bin") self.assertEqual(lay.source["pack"]["members"], len(members)) swan = model_profiles.load_emulator_profiles(str(REPO_ROOT / "emulators"))["swanstation"] - self.assertIn("scph5501.bin", pp.initial_stage(lay, swan, [])) + self.assertIn("scph5501.bin", packprobe.initial_stage(lay, swan, [])) def test_installer_path(self) -> None: - lay = pp.installer_layout("retroarch", self.pack, self.identity, + lay = packlayout.installer_layout("retroarch", self.pack, self.identity, REPO_ROOT / "install" / "retroarch.json", self.work / "installer", ["--system", "sony-playstation"]) self.assertEqual(lay.root, self.work / "installer" / "system")