refactor: split the campaign into probes

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 20:38:03 +01:00
1 parent 853a36c79f
commit 0471b80946
13 files changed
+2203 -1992

No files matched your search

+14 -1866
View File
File diff suppressed because it is too large. Load diff
+21 -18
View File
@@ -59,7 +59,10 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import autorun
import campaign
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
@@ -79,7 +82,7 @@ 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 = campaign.BUILDBOT
BUILDBOT = probes_cores.BUILDBOT
PACK_PROBES = mr.PACK_PROBES
INSTALLS = ("pack", "installer")
VERDICTS = ("boots", "bios_error", "crash", "hang", "unknown")
@@ -287,7 +290,7 @@ def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot:
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 = campaign.entry_dest(entry)
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 ()]
@@ -415,7 +418,7 @@ def fetch_core(name: str, refresh: bool = False) -> dict:
with urllib.request.urlopen(url, timeout=600) as response, archive.open("wb") as out:
shutil.copyfileobj(response, out)
modified = response.headers.get("Last-Modified")
campaign.safe_extract_so(archive, f"{name}_libretro.so", so)
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()}
@@ -423,28 +426,28 @@ def fetch_core(name: str, refresh: bool = False) -> dict:
return {**meta, "path": str(so)}
def load_contents(files: Sequence[Path]) -> dict[str, list[campaign.Content]]:
out: dict[str, list[campaign.Content]] = {}
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 campaign.load_content(path).items():
for system, items in probes_content.load_content(path).items():
out.setdefault(system, []).extend(items)
return out
def content_folder(content: campaign.Content, fetch: bool) -> Path:
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 campaign.Unavailable("romfetch not found")
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=campaign.child_env(romfetch=True))
check=False, env=host.child_env(romfetch=True))
if proc.returncode != 0:
raise campaign.Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}")
campaign.verify_identity(folder)
raise host.Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}")
probes_content.verify_identity(folder)
return folder
@@ -509,7 +512,7 @@ def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) ->
return proc.returncode, record, error[-1500:]
def probe_argv(core: dict, choice: CoreChoice, content: campaign.Content, load: Path,
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),
@@ -534,7 +537,7 @@ class ProbeTarget:
choice: CoreChoice
core: dict
system: str
content: campaign.Content
content: probes_content.Content
load: Path
@@ -621,7 +624,7 @@ def append_line(line: dict, root: Path = REPO_ROOT) -> dict:
@dataclass
class Unit:
system: str
content: campaign.Content
content: probes_content.Content
cores: list[CoreChoice]
@@ -631,7 +634,7 @@ def plan(platform: str, systems: set[str] | None, cores: set[str] | None,
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([campaign.CONTENT_FILE, PACK_CONTENT_FILE]).items()):
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):
@@ -666,8 +669,8 @@ def run(args: argparse.Namespace) -> int:
try:
for unit in units:
try:
load = campaign.load_file(content_folder(unit.content, args.fetch), unit.content.load)
except campaign.Unavailable as exc:
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:
File diff suppressed because it is too large. Load diff
+206
View File
@@ -0,0 +1,206 @@
"""The test content of each system, fetched through romfetch and checked by hash."""
from __future__ import annotations
import contextlib
import json
import os
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
import yaml
from core.statefile import now_iso
from probes.host import Unavailable, child_env, file_sha1
if TYPE_CHECKING:
from probes.campaign import Campaign
ROMFETCH_ENV = "RETROBIOS_ROMFETCH"
ROMFETCH_TRANSIENT = 3
# --------------------------------------------------------------------------
# Content: what each system is tested with, and where it comes from
# --------------------------------------------------------------------------
@dataclass(frozen=True)
class Content:
system: str
romfetch_system: str
name: str
catalog: str
reason: str
region: str | None
load: str
frames: int
frame_hash_every: int
pinned: bool
boot_file: str | None
@property
def key(self) -> str:
return f"{self.romfetch_system}/{self.name}"
def load_content(path: Path) -> dict[str, list[Content]]:
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
out: dict[str, list[Content]] = {}
for system, spec in (data.get("systems") or {}).items():
for item in spec.get("content") or ():
out.setdefault(system, []).append(Content(
system=system, romfetch_system=str(spec["romfetch"]), name=str(item["name"]),
catalog=str(item["catalog"]), reason=str(item["reason"]).strip(),
region=item.get("region"), load=str(item.get("load") or ""),
frames=int(item.get("frames", 3600)),
frame_hash_every=int(item.get("frame_hash_every", 10)),
pinned=bool(item.get("pinned", False)), boot_file=spec.get("boot_file"),
))
return out
def load_file(folder: Path, load: str) -> Path:
"""The file handed to the core."""
if load == "cue":
cues = sorted(folder.glob("*.cue"))
if len(cues) != 1:
raise Unavailable(f"{folder.name}: {len(cues)} .cue files, one expected")
return cues[0]
if load:
return folder / load
files = [p for p in sorted(folder.iterdir()) if p.is_file() and p.name != "identity.json"]
if len(files) != 1:
raise Unavailable(f"{folder.name}: {len(files)} files, name one with load:")
return files[0]
def verify_identity(folder: Path) -> dict:
"""The identity.json romfetch wrote, each listed file hashed again."""
try:
identity = json.loads((folder / "identity.json").read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise Unavailable(f"{folder}: no identity.json") from exc
if identity.get("status") != "verified":
raise Unavailable(f"{folder.name}: identity status {identity.get('status')!r}")
for item in identity.get("files") or ():
path = folder / item["name"]
if not path.is_file() or path.stat().st_size != item["size"] or file_sha1(path) != item["sha1"]:
raise Unavailable(f"{folder.name}: {item['name']} does not match its identity")
return identity
def folder_size(folder: Path) -> int:
return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file())
class ContentStore:
"""Content on disk, its users counted, the least recently used evicted
past the cap. Only what the campaign fetched is ever deleted, and never
a pinned entry."""
def __init__(self, campaign: Campaign) -> None:
self.c = campaign
self.state: dict = campaign.state["content"]
self.refs: dict[str, set[str]] = {}
self.verified: set[str] = set()
def folder(self, content: Content) -> Path:
return self.c.paths.content / content.romfetch_system / content.name
def hold(self, content: Content, user: str) -> None:
self.refs.setdefault(content.key, set()).add(user)
def get(self, content: Content) -> Path:
"""The folder of the content, fetched when absent. Unavailable when not."""
folder = self.folder(content)
entry = self.state.setdefault(content.key, {"fetched_by_campaign": False})
entry["pinned"] = content.pinned
if not (folder / "identity.json").is_file():
self.evict(keep={content.key})
self.fetch(content)
entry["fetched_by_campaign"] = True
if content.key not in self.verified:
identity = verify_identity(folder)
entry["identity"] = {"catalog": identity.get("catalog"), "dat": identity.get("dat"),
"entry": identity.get("entry")}
self.verified.add(content.key)
entry["size"] = folder_size(folder)
entry["last_used"] = now_iso()
return folder
def romfetch(self) -> str | None:
configured = self.c.settings.romfetch or os.environ.get(ROMFETCH_ENV, "")
if configured:
return configured if Path(configured).is_file() or shutil.which(configured) else None
return shutil.which("romfetch")
def fetch(self, content: Content) -> None:
command = self.romfetch()
if not command:
raise Unavailable(f"content: romfetch not found, {content.catalog} entry {content.name!r}")
if not self.c.settings.network:
raise Unavailable(f"content: offline, {content.catalog} entry {content.name!r}")
argv = [command, "get", content.romfetch_system, content.name, "--json", "-q",
"--content-dir", str(self.c.paths.content)]
for attempt, delay in enumerate((*self.c.settings.delays, None)):
proc = self.c.host.run(argv, capture_output=True, text=True, check=False,
timeout=6 * 3600, env=child_env(romfetch=True))
if proc.returncode == 0:
self.c.log(f"romfetch {content.name}: {proc.stdout.strip()[:300]}")
return
code = "unknown"
with contextlib.suppress(ValueError, AttributeError):
code = json.loads(proc.stdout)["error"]["code"]
if proc.returncode != ROMFETCH_TRANSIENT or delay is None:
raise Unavailable(f"content: romfetch exit {proc.returncode} ({code}) "
f"for {content.name!r}")
self.c.log(f"romfetch {content.name}: exit {proc.returncode} ({code}), "
f"retry {attempt + 1} in {delay}s")
self.c.host.sleep(delay)
def release(self, content: Content, user: str) -> None:
users = self.refs.get(content.key, set())
users.discard(user)
if not users:
self.drop(content.key)
def deletable(self, key: str) -> bool:
entry = self.state.get(key) or {}
return bool(entry.get("fetched_by_campaign")) and not entry.get("pinned")
def drop(self, key: str) -> bool:
if not self.deletable(key) or self.refs.get(key):
return False
folder = self.c.paths.content / key
if folder.is_dir():
shutil.rmtree(folder)
self.c.log(f"content {key}: deleted, no check left needs it")
self.state.pop(key, None)
self.verified.discard(key)
return True
def evict(self, keep: set[str]) -> list[str]:
"""Least recently used first, until the campaign's content fits the cap."""
cap = self.c.settings.cache_cap_gb * 1024 ** 3
held = sorted((entry.get("last_used", ""), key) for key, entry in self.state.items()
if self.deletable(key) and key not in keep)
total = sum(entry.get("size", 0) for key, entry in self.state.items() if self.deletable(key))
evicted = []
for _, key in held:
if total <= cap:
break
size = self.state[key].get("size", 0)
folder = self.c.paths.content / key
if folder.is_dir():
shutil.rmtree(folder)
self.state.pop(key, None)
self.verified.discard(key)
total -= size
evicted.append(key)
self.c.log(f"content {key}: evicted, the cache is over {self.c.settings.cache_cap_gb} GB")
return evicted
+346
View File
@@ -0,0 +1,346 @@
"""Where a campaign's cores come from: the buildbot nightly, else a sandboxed build of the profile's pinned commit."""
from __future__ import annotations
import io
import os
import re
import shutil
import stat
import subprocess
import tarfile
import urllib.error
import urllib.request
import zipfile
from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, TypeVar
import core_probe
from core.statefile import now_iso
from probes.host import Unavailable, child_env, file_sha256, run_group, slug
if TYPE_CHECKING:
from probes.campaign import Campaign
T = TypeVar("T")
BUILDBOT = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/"
BUILD_TIMEOUT = 3600
# Host-side git on a third-party project. It only ever touches bare mirrors
# this campaign created: no working tree, never bound into a sandbox. No user
# or system config is read, https is the only transport, and the overrides
# blank every hook, filter, proxy and ssh command a config could name.
GIT_SAFE = (
"-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
"-c", "core.sshCommand=", "-c", "core.gitProxy=", "-c", "core.askPass=",
"-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always",
"-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=", "-c", "filter.lfs.process=",
"-c", "filter.lfs.required=false", "-c", "core.attributesFile=/dev/null",
)
MIRROR_URL = re.compile(r"^https://[A-Za-z0-9.-]+(?::\d+)?/[A-Za-z0-9._~/+-]+$")
def host_git(*args: str) -> list[str]:
return ["git", *GIT_SAFE, *args]
def git_env() -> dict[str, str]:
env = child_env()
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0",
GIT_ALLOW_PROTOCOL="https", GIT_ATTR_NOSYSTEM="1")
return env
def blank_filters(repo: Path) -> list[str]:
"""-c overrides emptying every filter driver the repository's config,
includes followed, defines: git archive runs smudge filters."""
config = repo / "config"
if not config.is_file():
return []
listing = run_group(["git", "config", "--file", str(config), "--includes", "--name-only",
"--get-regexp", r"^filter\."], capture_output=True, env=git_env(),
timeout=60).stdout.decode("utf-8", "replace")
drivers = sorted({line.rsplit(".", 1)[0] for line in listing.splitlines() if line.count(".") >= 2})
out = []
for driver in drivers:
for key in ("smudge", "clean", "process"):
out += ["-c", f"{driver}.{key}="]
out += ["-c", f"{driver}.required=false"]
return out
def git_out(*args: str, timeout: int = 1800) -> bytes:
extra = blank_filters(Path(args[1])) if len(args) > 1 and args[0] == "-C" else []
return run_group(["git", *GIT_SAFE, *extra, *args], capture_output=True, check=True,
env=git_env(), timeout=timeout).stdout
def submodule_url(base: str, url: str) -> str:
"""A .gitmodules URL, relative ones read against the parent's URL."""
if url.startswith(("./", "../")):
parts = base.rstrip("/").removesuffix(".git").split("/")
for piece in url.split("/"):
if piece == "..":
parts.pop()
elif piece not in (".", ""):
parts.append(piece)
url = "/".join(parts)
return url
def extract_tar(blob: bytes, target: Path) -> None:
"""A git archive unpacked into target: no absolute path, no .., no link
that leaves target."""
target.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=io.BytesIO(blob)) as handle:
if hasattr(tarfile, "data_filter"):
handle.extractall(target, filter="data")
return
for member in handle.getmembers():
name = Path(member.name)
link = Path(member.linkname)
if name.is_absolute() or ".." in name.parts or member.islnk() or (
member.issym() and (link.is_absolute() or ".." in link.parts)):
raise Unavailable(f"core: unsafe archive member {member.name}")
handle.extractall(target)
def export_commit(mirror: Callable[[str], Path], url: str, commit: str, dest: Path) -> None:
"""The tree of commit, and of each submodule at the commit the tree
records, as plain files in a fresh dest. Every object comes from a bare
mirror (mirror(url) fetches into it), never from a working tree."""
if dest.exists():
shutil.rmtree(dest)
def one(repo_url: str, sha: str, target: Path) -> None:
if not re.fullmatch(r"[0-9a-f]{40}", sha):
raise Unavailable(f"core: {sha!r} is not a commit id")
bare = mirror(repo_url)
try:
git_out("-C", str(bare), "cat-file", "-e", f"{sha}^{{commit}}")
except subprocess.CalledProcessError:
git_out("-C", str(bare), "fetch", "--quiet", repo_url, sha)
extract_tar(git_out("-C", str(bare), "archive", "--format=tar", sha), target)
links: dict[str, str] = {}
for entry in git_out("-C", str(bare), "ls-tree", "-r", "-z", sha).split(b"\0"):
if entry.startswith(b"160000 commit "):
meta, raw_path = entry.split(b"\t", 1)
links[raw_path.decode()] = meta.split()[2].decode()
if not links:
return
try:
config = git_out("-C", str(bare), "config", "--blob", f"{sha}:.gitmodules", "-z",
"--get-regexp", r"^submodule\..*\.(path|url)$").decode()
except subprocess.CalledProcessError as exc:
raise Unavailable(f"core: {repo_url} has submodules and no readable .gitmodules") from exc
paths: dict[str, str] = {}
urls: dict[str, str] = {}
for item in filter(None, config.split("\0")):
key, _, value = item.partition("\n")
name, field_ = key[len("submodule."):].rsplit(".", 1)
(paths if field_ == "path" else urls)[name] = value
for name, path in paths.items():
if path in links and name in urls:
one(submodule_url(repo_url, urls[name]), links[path], target / path)
one(url, commit, dest)
def built_core(tree: Path) -> Path:
"""The newest *_libretro.so a build left: a regular file inside the tree,
never a link a build could point at a host file."""
root = tree.resolve()
found = []
for path in tree.rglob("*_libretro.so"):
info = path.lstat()
if stat.S_ISREG(info.st_mode) and path.resolve().is_relative_to(root):
found.append((info.st_mtime, path))
if not found:
raise Unavailable(f"core: the build left no *_libretro.so regular file in {tree}")
return max(found)[1]
def copy_regular(src: Path, dest: Path) -> None:
"""Copy src only when it is a regular file, never through a link."""
fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW)
with os.fdopen(fd, "rb") as handle:
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
raise Unavailable(f"core: {src} is not a regular file")
dest.parent.mkdir(parents=True, exist_ok=True)
with dest.open("wb") as out:
shutil.copyfileobj(handle, out)
# --------------------------------------------------------------------------
# Cores
# --------------------------------------------------------------------------
@dataclass(frozen=True)
class Core:
name: str
path: Path
sha256: str
artifact: str | None = None
repo: str | None = None
commit: str | None = None
build_command: str | None = None
def safe_extract_so(archive: Path, member: str, target: Path) -> None:
with zipfile.ZipFile(archive) as handle:
names = handle.namelist()
if member not in names:
raise Unavailable(f"{archive.name}: no {member} inside ({', '.join(names[:5])})")
target.parent.mkdir(parents=True, exist_ok=True)
scratch = target.with_suffix(".part")
with handle.open(member) as src, scratch.open("wb") as dst:
shutil.copyfileobj(src, dst)
os.replace(scratch, target)
class Cores:
"""Buildbot nightlies, downloaded once per build, else local builds of
the profile's pinned commit."""
def __init__(self, campaign: Campaign) -> None:
self.c = campaign
self.listing: set[str] | None = None
def retrying(self, what: str, call: Callable[[], T]) -> T:
for attempt, delay in enumerate((*self.c.settings.delays, None)):
try:
return call()
except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc:
if isinstance(exc, urllib.error.HTTPError) and exc.code < 500 and exc.code != 429:
raise Unavailable(f"{what}: HTTP {exc.code}") from exc
if delay is None:
raise Unavailable(f"{what}: {exc}") from exc
self.c.log(f"{what}: {exc}, retry {attempt + 1} in {delay}s")
self.c.host.sleep(delay)
raise AssertionError("unreachable")
def buildbot(self) -> set[str]:
if self.listing is None:
if not self.c.settings.network:
self.listing = set()
else:
def read() -> bytes:
with self.c.host.urlopen(BUILDBOT, timeout=120) as response:
return response.read()
page = self.retrying("buildbot listing", read).decode("utf-8", "replace")
self.listing = set(re.findall(r"([A-Za-z0-9_]+)_libretro\.so\.zip", page))
return self.listing
def names(self, profile: dict) -> list[str]:
listing = self.buildbot()
return sorted({str(c) for c in profile.get("cores") or () if str(c) in listing})
def nightly(self, name: str, profile: dict) -> Core:
url = f"{BUILDBOT}{name}_libretro.so.zip"
cached = self.c.state["cores"].get(name) or {}
def head() -> dict:
request = urllib.request.Request(url, method="HEAD")
with self.c.host.urlopen(request, timeout=120) as response:
return {"etag": response.headers.get("ETag"),
"last_modified": response.headers.get("Last-Modified")}
stamp = self.retrying(f"{name} nightly", head)
target = self.c.paths.home / "cores" / name / f"{name}_libretro.so"
if (cached.get("etag"), cached.get("last_modified")) != (stamp["etag"], stamp["last_modified"]) \
or not target.is_file() or file_sha256(target) != cached.get("sha256"):
archive = target.parent / f"{name}_libretro.so.zip"
archive.parent.mkdir(parents=True, exist_ok=True)
def download() -> None:
with self.c.host.urlopen(url, timeout=600) as response, archive.open("wb") as out:
shutil.copyfileobj(response, out)
self.retrying(f"{name} nightly", download)
safe_extract_so(archive, f"{name}_libretro.so", target)
archive.unlink()
cached = {**stamp, "url": url, "sha256": file_sha256(target), "fetched_at": now_iso()}
self.c.state["cores"][name] = cached
self.c.log(f"core {name}: new nightly {cached['sha256'][:12]} ({stamp['last_modified']})")
repo = profile.get("source") if isinstance(profile.get("source"), str) else None
return Core(name, target, cached["sha256"], artifact=url,
repo=repo if repo and repo.startswith("http") else None)
def build(self, emulator: str, profile: dict) -> Core:
"""The profile's pinned commit, built once and kept."""
source, commit = profile.get("source"), profile.get("source_commit")
if not (isinstance(source, str) and source.startswith("http") and isinstance(commit, str)):
raise Unavailable("core: not on the buildbot, and no source and source_commit to build")
record = self.c.state["builds"].setdefault(emulator, {})
if record.get("commit") == commit and record.get("error"):
raise Unavailable(f"core: build of {commit[:12]} failed before: {record['error']}")
out = self.c.paths.home / "builds" / emulator / commit
built = sorted(out.glob("*_libretro.so"))
if not built:
if not self.c.settings.network:
raise Unavailable("core: not on the buildbot, offline, nothing built yet")
try:
so, command = self.compile(source, commit, out)
except Unavailable as exc:
self.c.state["builds"][emulator] = {"commit": commit, "error": str(exc), "at": now_iso()}
raise
built = [so]
record["command"] = command
command = record.get("command") or "make"
self.c.state["builds"][emulator] = {"commit": commit, "command": command,
"so": built[0].name, "at": now_iso()}
return Core(built[0].name.removesuffix("_libretro.so"), built[0], file_sha256(built[0]),
repo=source, commit=commit, build_command=command)
def mirror(self, url: str) -> Path:
"""The bare mirror of a repository, created on first use. Only host
git with the overrides of GIT_SAFE ever touches it."""
if not MIRROR_URL.match(url):
raise Unavailable(f"core: {url!r} is not an https repository URL")
bare = self.c.paths.home / "mirrors" / f"{slug(url)}.git"
if not (bare / "HEAD").is_file():
bare.parent.mkdir(parents=True, exist_ok=True)
git_out("clone", "--bare", "--quiet", url, str(bare))
return bare
def compile(self, source: str, commit: str, out: Path) -> tuple[Path, str]:
"""Fetch the commit into a bare mirror (host git, networked), export
it and its submodules with git archive into a fresh folder, and run
the project's make there under bubblewrap: no network, that folder
the one writable path. Returns the .so and the command, with how it
was isolated."""
log = self.c.paths.logs / "builds" / f"{slug(source)}-{commit[:12]}.log"
log.parent.mkdir(parents=True, exist_ok=True)
isolation = core_probe.sandbox_argv([])[1]
if isolation != core_probe.SANDBOX and not self.c.settings.allow_unsandboxed:
raise Unavailable(f"refused: no sandbox to build {source} in ({isolation}), "
f"--allow-unsandboxed overrides")
# Working-tree clones of earlier campaign versions are never reused.
shutil.rmtree(self.c.paths.home / "src", ignore_errors=True)
tree = self.c.paths.home / "build-trees" / f"{slug(source)}-{commit[:12]}"
try:
export_commit(self.mirror, source, commit, tree)
except (OSError, subprocess.CalledProcessError, tarfile.TarError) as exc:
raise Unavailable(f"core: exporting {commit[:12]} of {source} failed: {exc}") from exc
makefile = "Makefile.libretro" if (tree / "Makefile.libretro").is_file() else "Makefile"
jobs = str(max(1, (os.cpu_count() or 2) // 2))
command = ["make", "-f", makefile, f"-j{jobs}", "platform=unix"]
prefix, isolation = core_probe.sandbox_argv([tree])
with log.open("a", encoding="utf-8") as handle:
handle.write(f"$ {' '.join(command)} in {tree} ({isolation})\n")
handle.flush()
proc = self.c.host.run(prefix + command, cwd=tree, stdout=handle, stderr=subprocess.STDOUT,
check=False, timeout=BUILD_TIMEOUT, env=child_env())
if proc.returncode != 0:
tail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()[-3:]
raise Unavailable(f"core: make exited {proc.returncode}: {' | '.join(tail)} (log {log})")
built = built_core(tree)
copy_regular(built, out / built.name)
shutil.rmtree(tree, ignore_errors=True)
return out / built.name, f"{' '.join(command)} on git archive (isolation: {isolation})"
+51
View File
@@ -0,0 +1,51 @@
"""Profile entries as the probes read them: systems, destination, regions, category."""
from __future__ import annotations
import hashlib
from model import measurements as mr
def profile_digest(profile: dict) -> str:
"""What a check depends on in a profile: its entries, evidence left out,
so the campaign's own evidence never makes it run again."""
entries = [{k: v for k, v in entry.items() if k != "evidence"}
for entry in profile.get("files") or []]
body = {"files": entries, "cores": profile.get("cores"), "type": profile.get("type"),
"systems": profile.get("systems")}
return hashlib.sha1(mr.canonical(body)).hexdigest()
def entry_systems(entry: dict, profile: dict) -> list[str]:
if entry.get("systems"):
return list(entry["systems"])
if entry.get("system"):
return [entry["system"]]
return list(profile.get("systems") or [])
def entry_dest(entry: dict) -> str:
"""Where the core reads the entry, relative to its system directory."""
path = entry.get("path")
if isinstance(path, str) and path and not path.endswith("/"):
return path
return entry["name"]
def region_matches(entry: dict, region: str | None) -> bool:
regions = entry.get("region")
if not regions or not region:
return True
if isinstance(regions, str):
regions = [regions]
return region in regions or "world" in regions
def regions_of(entry: dict) -> list[str]:
regions = entry.get("region") or []
return [regions] if isinstance(regions, str) else list(regions)
def is_bios(entry: dict) -> bool:
return entry.get("category", "bios") == "bios" and entry.get("type") != "directory"
+42
View File
@@ -0,0 +1,42 @@
"""The gate a campaign commit passes: tests, schemas, verify and pack of the changed profiles."""
from __future__ import annotations
import shutil
import sys
from collections.abc import Sequence
from pathlib import Path
import autorun
from probes.host import Host
# --------------------------------------------------------------------------
# Gate
# --------------------------------------------------------------------------
def gate(root: Path, emulators: Sequence[str], host: Host | None = None) -> int:
"""The measurement tests, the schemas, and verify plus an emulator pack
for each profile the campaign changed."""
host = host or Host()
python = sys.executable
steps = [
[python, "-m", "unittest", "tests.test_measurements", "tests.test_campaign"],
[python, "scripts/validate_schemas.py", "--source-only"],
]
for emulator in sorted(set(emulators)):
steps.append([python, "scripts/verify.py", "--emulator", emulator])
steps.append([python, "scripts/generate_pack.py", "--emulator", emulator, "--offline",
"--output-dir", "tmp/campaign/packs"])
for argv in steps:
proc = host.run(argv, cwd=root, check=False)
if proc.returncode != 0:
print(f"gate: {' '.join(argv)} exited {proc.returncode}", file=sys.stderr)
return 1
shutil.rmtree(root / "tmp" / "campaign" / "packs", ignore_errors=True)
return 0
def changed_profiles(root: Path) -> list[str]:
return [Path(p).stem for p in autorun.changed_files(root)
if p.startswith("emulators/") and p.endswith(".yml")]
+217
View File
@@ -0,0 +1,217 @@
"""What a campaign reads from the machine: processes in their own group, settings, paths, the child environment and the host lock."""
from __future__ import annotations
import contextlib
import hashlib
import http.client
import os
import re
import signal
import subprocess
import threading
import time
import urllib.request
from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import IO, TYPE_CHECKING, TypedDict
import autorun
import core_probe
from core import childenv, hostguard
from core.paths import REPO_ROOT
if TYPE_CHECKING:
from typing_extensions import Unpack
CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml"
LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV
NETWORK_DELAYS = (10, 60, 300)
BENCH_WARMUP = 600
BENCH_FRAMES = 1800
BENCH_REPEAT = 5
CHECK_REPEAT = 2
PROBE_TIMEOUT = 900
class Unavailable(RuntimeError):
"""A core or a piece of content the campaign cannot get."""
# --------------------------------------------------------------------------
# Small helpers
# --------------------------------------------------------------------------
def slug(text: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x"
def file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def file_sha1(path: Path) -> str:
digest = hashlib.sha1()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
# --------------------------------------------------------------------------
# Host
# --------------------------------------------------------------------------
class PopenOptions(TypedDict, total=False):
"""The Popen arguments the campaign passes through run_group."""
cwd: str | Path
env: dict[str, str]
text: bool
stdout: int | IO[str] | IO[bytes]
stderr: int | IO[str] | IO[bytes]
def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool = False,
capture_output: bool = False, **kwargs: Unpack[PopenOptions]) -> subprocess.CompletedProcess:
"""subprocess.run in a process group of its own, the whole group killed
on a timeout or an interruption: a hung core never outlives its run."""
if capture_output:
kwargs.setdefault("stdout", subprocess.PIPE)
kwargs.setdefault("stderr", subprocess.PIPE)
with subprocess.Popen(list(argv), start_new_session=True, **kwargs) as proc:
try:
out, err = proc.communicate(timeout=timeout)
except BaseException:
with contextlib.suppress(ProcessLookupError):
os.killpg(proc.pid, signal.SIGKILL)
proc.communicate()
raise
result = subprocess.CompletedProcess(list(argv), proc.returncode, out, err)
if check:
result.check_returncode()
return result
@dataclass
class Host:
"""What the campaign reads from the machine and the network, replaced in tests."""
loadavg: Callable[[], tuple[float, float, float]] = os.getloadavg
sleep: Callable[[float], None] = time.sleep
clock: Callable[[], float] = time.monotonic
cpu_count: int = os.cpu_count() or 1
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
@property
def max_load(self) -> float:
return self.cpu_count / 4
@dataclass
class Settings:
budget: float = 6 * 3600
max_load_wait: float = 3600
min_free_gb: float = 30
cache_cap_gb: float = 20
probe_timeout: int = PROBE_TIMEOUT
check_repeat: int = CHECK_REPEAT
bench_repeat: int = BENCH_REPEAT
bench_warmup: int = BENCH_WARMUP
bench_frames: int = BENCH_FRAMES
romfetch: str = ""
network: bool = True
# Benchmarks only choose between variants: never part of a default pass.
bench: bool = False
delays: tuple[float, ...] = NETWORK_DELAYS
echo: bool = True
# Third-party code (a nightly core, a project's Makefile) runs only under
# bubblewrap unless this is set.
allow_unsandboxed: bool = False
@dataclass
class Paths:
"""Where the campaign writes: records and profiles in the checkout it
runs from, state, cores, logs and content in the main checkout's .cache."""
root: Path
home: Path
content: Path
db: Path
content_file: Path = CONTENT_FILE
oracle: Path = core_probe.DEFAULT_ORACLE
@property
def state(self) -> Path:
return self.home / "state.json"
@property
def logs(self) -> Path:
return self.home / "logs"
@property
def emulators(self) -> Path:
return self.root / "emulators"
@classmethod
def default(cls) -> Paths:
main = autorun.main_checkout()
return cls(root=REPO_ROOT, home=main / ".cache" / "campaign",
content=main / ".cache" / "test-content", db=REPO_ROOT / "database.json")
ROMFETCH_PASSED = ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME")
def child_env(romfetch: bool = False) -> dict[str, str]:
"""What a program the campaign starts inherits: autorun's allowlist,
never a token or a password. romfetch also gets its own settings
(ROMFETCH_*), its account staying in its config file."""
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 childenv.safe_env(names)
# The working directory belongs to the process. Two passes in threads that
# each saved and restored it could leave the process in the other's root,
# then in a folder deleted with its workspace.
_CWD_LOCK = threading.Lock()
@contextlib.contextmanager
def working_directory(path: Path) -> Iterator[None]:
"""contextlib.chdir, which Python 3.9 lacks, one thread at a time."""
with _CWD_LOCK:
before = Path.cwd()
os.chdir(path)
try:
yield
finally:
os.chdir(before)
@contextlib.contextmanager
def host_lock(lock_path: Path) -> Iterator[None]:
"""The automation lock, unless the autorun job running us holds it."""
if os.environ.get(LOCK_HELD_ENV):
yield
return
with hostguard.global_lock(lock_path):
yield
+111
View File
@@ -0,0 +1,111 @@
"""What the campaign reports: check status, open findings, and their review."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import yaml
from core.statefile import now_iso
from model import measurements as mr
from probes import rules
from probes.profileedit import write_fields
from probes.state import DONE, FAILED, PENDING
if TYPE_CHECKING:
from probes.campaign import Campaign
# --------------------------------------------------------------------------
# Reports
# --------------------------------------------------------------------------
def status_report(campaign: Campaign) -> dict:
counts, reasons, failed = campaign.counts()
runs = mr.read_campaign(campaign.paths.root, mr.CAMPAIGN_RUNS)
per = {}
for emulator, checks in sorted(campaign.state["checks"].items()):
per[emulator] = {key: {k: v for k, v in entry.items() if k in ("status", "reason", "record", "at")}
for key, entry in sorted(checks.items())}
return {"last_run": runs[-1] if runs else None, "counts": counts, "pending_reasons": reasons,
"failed": failed, "emulators": per}
def render_status(report: dict) -> str:
lines = []
last = report["last_run"]
if last:
lines.append(f"last run {last['started_at']} to {last['ended_at']}: {last['result']}"
+ (f" ({last['detail']})" if last["detail"] else ""))
else:
lines.append("no run yet")
counts = report["counts"]
lines.append(f"{counts.get(DONE, 0)} done, {counts.get(FAILED, 0)} failed, "
f"{counts.get(PENDING, 0)} pending")
lines.extend(f" pending {number:5} {reason}"
for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1]))
lines.extend(f" FAILED {item['emulator']} {item['check']}: {item['reason']}" for item in report["failed"])
for emulator, checks in report["emulators"].items():
ran = [k for k, v in checks.items() if v["status"] != PENDING]
if ran:
lines.append(f"{emulator}")
for key in ran:
entry = checks[key]
lines.append(f" {entry['status']:7} {key}" + (f" {entry['record']}" if entry.get("record") else "")
+ (f" ({entry['reason']})" if entry.get("reason") else ""))
return "\n".join(lines)
def open_findings(root: Path, everything: bool = False) -> list[dict]:
latest: dict[str, dict] = {}
for line in mr.read_campaign(root, mr.FINDINGS):
latest[line["key"]] = line
return [line for key, line in sorted(latest.items())
if everything or line["status"] in ("open", "flagged")]
REVIEWED = ("applied", "rejected")
def review_finding(root: Path, key: str, status: str, reason: str,
updates: dict[str, object] | None = None, index: int | None = None) -> dict:
"""Close an open finding after reading the core's code.
`applied` writes `updates` into the entry the finding names, through the
same editor as the rule table, with the finding's record ids added as
`evidence:` under its field. An applied finding with no update records a
profile changed by hand. `rejected` keeps the profile as it is. Either
way a line with the reason is appended to the findings."""
if status not in REVIEWED:
raise ValueError(f"status {status!r}: one of {', '.join(REVIEWED)}")
if not reason.strip():
raise ValueError("a review names its reason")
latest = {line["key"]: line for line in mr.read_campaign(root, mr.FINDINGS)}
finding = latest.get(key)
if finding is None:
raise ValueError(f"no finding {key}")
if finding["status"] not in ("open", "flagged"):
raise ValueError(f"{key} is {finding['status']}, not open")
if updates and status != "applied":
raise ValueError("only an applied review changes the profile")
if updates:
path = root / "emulators" / f"{finding['emulator']}.yml"
entries = yaml.safe_load(path.read_text(encoding="utf-8")).get("files") or []
matches = [i for i, entry in enumerate(entries) if entry.get("name") == finding["file"]]
if index is not None:
matches = [i for i in matches if i == index]
if len(matches) != 1:
raise ValueError(f"{finding['emulator']}: {len(matches)} entries named {finding['file']}"
+ ("" if index is not None else ", pass --index"))
entry = entries[matches[0]]
verdict = rules.Verdict(finding["rule"], finding["field"], finding["run_shows"],
finding["statement"], tuple(finding["evidence"]))
evidence = rules.merge_evidence(entry.get("evidence"), verdict)
write_fields(path, matches[0], {**updates, "evidence": evidence})
body = {key_: value for key_, value in finding.items() if key_ != "id"}
line = mr.seal_line({**body, "found_at": now_iso(), "status": status, "reason": reason},
"found_at")
with (root / mr.records_path(mr.FINDINGS)).open("a", encoding="utf-8") as handle:
handle.write(mr.line_text(line) + "\n")
return line
+48
View File
@@ -0,0 +1,48 @@
"""The campaign's state file: what each check ran against, and whether it runs again."""
from __future__ import annotations
import json
from pathlib import Path
from core import statefile
from model import measurements as mr
STATE_VERSION = 1
DONE = "done"
FAILED = "failed"
PENDING = "pending"
# --------------------------------------------------------------------------
# State
# --------------------------------------------------------------------------
def load_state(path: Path) -> dict:
try:
state = json.loads(path.read_text(encoding="utf-8"))
except FileNotFoundError:
state = {}
state.setdefault("version", STATE_VERSION)
for key in ("checks", "cores", "content", "builds", "emulators"):
state.setdefault(key, {})
return state
def save_state(path: Path, state: dict) -> None:
statefile.save_state(path, state)
def should_run(previous: dict | None, core_sha: str, digest: str, oracle_sha: str = "") -> bool:
"""A check runs again when it never ran, is pending, or ran against
another core build, another version of the profile, another oracle, or
before records carried a verdict."""
if not previous:
return True
if previous.get("status") == PENDING:
return True
return (previous.get("core_sha256") != core_sha or previous.get("profile_digest") != digest
or previous.get("record_version") != mr.RECORD_VERSION
or previous.get("oracle_sha256", "") != oracle_sha)