diff --git a/scripts/core/hashing.py b/scripts/core/hashing.py index ab722c3eb..b636b13aa 100644 --- a/scripts/core/hashing.py +++ b/scripts/core/hashing.py @@ -85,6 +85,15 @@ def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, st result["adler32"] = format(adler & 0xFFFFFFFF, "08x") return result +def file_digest(path: Path, algorithm: str = "sha1") -> str: + """The hex digest of a file by any hashlib algorithm, read again each call.""" + 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 md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str: """Compute MD5 of a file path or file-like object - matches Batocera's md5sum().""" h = hashlib.md5() diff --git a/scripts/probes/campaign.py b/scripts/probes/campaign.py index ddaba783a..051ba82d2 100644 --- a/scripts/probes/campaign.py +++ b/scripts/probes/campaign.py @@ -18,8 +18,9 @@ import yaml import autorun import core_probe from core import hostguard +from core.hashing import file_digest from core.paths import REPO_ROOT -from core.statefile import now_iso +from core.statefile import now_iso, save_state from model import measurements as mr from probes import rules from probes.profileedit import ProfileEditError, write_fields @@ -40,12 +41,10 @@ from probes.host import ( Settings, Unavailable, child_env, - file_sha1, - file_sha256, slug, working_directory, ) -from probes.state import DONE, FAILED, PENDING, load_state, save_state, should_run +from probes.state import DONE, FAILED, PENDING, load_state, should_run CRASH_ATTEMPTS = 3 @@ -131,7 +130,7 @@ class Campaign: self.cores = Cores(self) self.store = ContentStore(self) self.content = load_content(paths.content_file) - self.oracle_sha = file_sha256(paths.oracle) if paths.oracle.is_file() else "" + self.oracle_sha = file_digest(paths.oracle, "sha256") if paths.oracle.is_file() else "" self.oracle_data = core_probe.load_oracle(paths.oracle)[0] self.deadline = 0.0 self.current: Pass | None = None @@ -369,7 +368,7 @@ class Campaign: for _, other, path in staged.values(): theirs = set(regions_of(other)) if theirs and "world" not in theirs and not theirs & mine and path.resolve() != local.resolve(): - out.setdefault(file_sha1(path), path) + out.setdefault(file_digest(path), path) return sorted(out.values(), key=lambda p: p.name)[:MAX_REGION_DUMPS] def run_unit_content(self, unit: Unit, core: Core, content: Content, digest: str) -> None: diff --git a/scripts/probes/content.py b/scripts/probes/content.py index cfe04d2e3..f8eb40554 100644 --- a/scripts/probes/content.py +++ b/scripts/probes/content.py @@ -12,8 +12,9 @@ from typing import TYPE_CHECKING import yaml +from core.hashing import file_digest from core.statefile import now_iso -from probes.host import Unavailable, child_env, file_sha1 +from probes.host import Unavailable, child_env if TYPE_CHECKING: from probes.campaign import Campaign @@ -89,7 +90,7 @@ def verify_identity(folder: Path) -> dict: 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"]: + if not path.is_file() or path.stat().st_size != item["size"] or file_digest(path) != item["sha1"]: raise Unavailable(f"{folder.name}: {item['name']} does not match its identity") return identity diff --git a/scripts/probes/cores.py b/scripts/probes/cores.py index dd0c6eebd..f355526b3 100644 --- a/scripts/probes/cores.py +++ b/scripts/probes/cores.py @@ -18,8 +18,9 @@ from pathlib import Path from typing import TYPE_CHECKING, TypeVar import core_probe +from core.hashing import file_digest from core.statefile import now_iso -from probes.host import Unavailable, child_env, file_sha256, run_group, slug +from probes.host import Unavailable, child_env, run_group, slug if TYPE_CHECKING: from probes.campaign import Campaign @@ -255,7 +256,7 @@ class Cores: 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"): + or not target.is_file() or file_digest(target, "sha256") != cached.get("sha256"): archive = target.parent / f"{name}_libretro.so.zip" archive.parent.mkdir(parents=True, exist_ok=True) @@ -265,7 +266,7 @@ class Cores: 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()} + cached = {**stamp, "url": url, "sha256": file_digest(target, "sha256"), "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 @@ -295,7 +296,7 @@ class Cores: 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]), + return Core(built[0].name.removesuffix("_libretro.so"), built[0], file_digest(built[0], "sha256"), repo=source, commit=commit, build_command=command) def mirror(self, url: str) -> Path: diff --git a/scripts/probes/host.py b/scripts/probes/host.py index ed2a138a0..dfa2d9f8e 100644 --- a/scripts/probes/host.py +++ b/scripts/probes/host.py @@ -3,7 +3,6 @@ from __future__ import annotations import contextlib -import hashlib import http.client import os import re @@ -29,8 +28,6 @@ if TYPE_CHECKING: CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" -LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV - NETWORK_DELAYS = (10, 60, 300) @@ -54,20 +51,6 @@ 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() # -------------------------------------------------------------------------- @@ -210,7 +193,7 @@ def working_directory(path: Path) -> Iterator[None]: @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): + if os.environ.get(hostguard.LOCK_HELD_ENV): yield return with hostguard.global_lock(lock_path): diff --git a/scripts/probes/packlayout.py b/scripts/probes/packlayout.py index 90c9b9299..53a1fa8f1 100644 --- a/scripts/probes/packlayout.py +++ b/scripts/probes/packlayout.py @@ -2,7 +2,6 @@ from __future__ import annotations -import hashlib import json import shutil import subprocess @@ -12,6 +11,7 @@ from collections.abc import Sequence from dataclasses import dataclass, field from pathlib import Path +from core.hashing import file_digest from core.paths import REPO_ROOT from core.ziptools import safe_extract_zip @@ -45,13 +45,6 @@ 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. @@ -68,7 +61,7 @@ def pack_layout(pack: Path, root: Path, identity: dict) -> Layout: 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, + return {"file": pack.name, "sha256": file_digest(pack, "sha256"), "size": pack.stat().st_size, "members": members} @@ -118,7 +111,7 @@ def installer_layout(platform: str, pack: Path, identity: dict, manifest_path: P "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"), + "sha256": file_digest(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), diff --git a/scripts/probes/packprobe.py b/scripts/probes/packprobe.py index 421eb89ad..22da8bb93 100644 --- a/scripts/probes/packprobe.py +++ b/scripts/probes/packprobe.py @@ -18,6 +18,8 @@ from dataclasses import dataclass from pathlib import Path import autorun +from core_probe import PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, probe_lock_path +from core.hashing import file_digest from core.paths import REPO_ROOT from core.statefile import now_iso from model import measurements as mr @@ -28,12 +30,11 @@ 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.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, child_env from probes.packlayout import ( Layout, ProbeFailure, build_pack, - file_sha, installer_layout, pack_identity, pack_layout, @@ -48,17 +49,10 @@ 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") +PROBE_LOCK = probe_lock_path() EXIT_BUSY = 3 # The hardware target each platform is probed for: the one whose libretro @@ -250,7 +244,7 @@ def fetch_core(name: str, refresh: bool = False) -> dict: 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"): + if meta.get("sha256") == file_digest(so, "sha256"): return {**meta, "path": str(so)} url = f"{BUILDBOT}{name}_libretro.so.zip" folder.mkdir(parents=True, exist_ok=True) @@ -260,7 +254,7 @@ def fetch_core(name: str, refresh: bool = False) -> dict: 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"), + meta = {"name": name, "url": url, "last_modified": modified, "sha256": file_digest(so, "sha256"), "fetched_at": now_iso()} meta_path.write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") return {**meta, "path": str(so)} @@ -449,8 +443,8 @@ def git_head() -> str | 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) + sealed = mr.seal_line(line, mr.CAMPAIGN_FILES[mr.PACK_PROBES][0]) + path = root / mr.records_path(mr.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") diff --git a/scripts/probes/regioncheck.py b/scripts/probes/regioncheck.py index 80426f91b..6c8fe6a8a 100644 --- a/scripts/probes/regioncheck.py +++ b/scripts/probes/regioncheck.py @@ -16,9 +16,11 @@ from pathlib import Path import yaml from core.paths import REPO_ROOT +from core_probe import BUILTIN +from probes.entries import entry_dest, regions_of +from probes.host import CONTENT_FILE -CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" CORES = REPO_ROOT / ".cache" / "region" / "cores" NIGHTLY = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/{core}_libretro.so.zip" VARIANTS = ("full", "own", "others", "pack") @@ -32,16 +34,6 @@ REGION_WORDS = {"japan": "Japanese", "north-america": "US", "europe": "European" # Pure rules # -------------------------------------------------------------------------- -def regions_of(entry: dict) -> list[str]: - regions = entry.get("region") or [] - return [regions] if isinstance(regions, str) else list(regions) - - -def entry_dest(entry: dict) -> str: - path = entry.get("path") - if isinstance(path, str) and path and not path.endswith("/"): - return path - return entry["name"] def region_entries(profile: dict, system: str) -> list[dict]: @@ -158,8 +150,6 @@ def outcome(records: dict[str, dict], entries: list[dict], region: str) -> dict: } -BUILTIN = "builtin" - def staged_name(used: str | None) -> str | None: """The file a bios_used names, or None.""" diff --git a/scripts/probes/state.py b/scripts/probes/state.py index 324d4dedd..5190976c7 100644 --- a/scripts/probes/state.py +++ b/scripts/probes/state.py @@ -5,7 +5,6 @@ from __future__ import annotations import json from pathlib import Path -from core import statefile from model import measurements as mr @@ -31,9 +30,6 @@ def load_state(path: Path) -> dict: 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 diff --git a/tests/test_campaign.py b/tests/test_campaign.py index e71156e52..6f317d202 100644 --- a/tests/test_campaign.py +++ b/tests/test_campaign.py @@ -32,6 +32,7 @@ import autorun import campaign import core_probe from core import hostguard +from core.hashing import file_digest from probes import campaign as probes_campaign from probes import content as probes_content from probes import cores @@ -487,7 +488,7 @@ class StateAndResume(Workspace): def test_state_survives_a_reload(self) -> None: c = self.make() c.pending("fake", "fake/fake-system/x/files", "content: romfetch not found") - state.save_state(self.paths.state, c.state) + statefile.save_state(self.paths.state, c.state) again = self.make() self.assertEqual(again.state["checks"]["fake"]["fake/fake-system/x/files"]["status"], "pending") @@ -529,12 +530,12 @@ class Guards(Workspace): with hostguard.global_lock(lock): with self.assertRaises(hostguard.LockBusy), probes_host.host_lock(lock): pass - os.environ[probes_host.LOCK_HELD_ENV] = "1" + os.environ[hostguard.LOCK_HELD_ENV] = "1" try: with probes_host.host_lock(lock): pass finally: - del os.environ[probes_host.LOCK_HELD_ENV] + del os.environ[hostguard.LOCK_HELD_ENV] class ChildEnvironment(unittest.TestCase): @@ -1093,7 +1094,7 @@ class FakeCorePasses(Workspace): c = probes_campaign.Campaign(self.paths, probes_host.Settings(**values), host, lock_path=self.tmp / "auto.lock") so = core or self.cores[kind] - c.unit_cores = lambda *a, **k: [cores.Core("fake", so, probes_host.file_sha256(so))] + c.unit_cores = lambda *a, **k: [cores.Core("fake", so, file_digest(so, "sha256"))] return c def test_a_stand_in_is_proven_and_written(self) -> None: @@ -1224,7 +1225,7 @@ class FakeCorePasses(Workspace): check_repeat=2, probe_timeout=30, delays=(1,), echo=False), host, lock_path=workspace.tmp / "auto.lock") so = self.cores["hle"] - c.unit_cores = lambda *a, **k: [cores.Core("fake", so, probes_host.file_sha256(so))] + c.unit_cores = lambda *a, **k: [cores.Core("fake", so, file_digest(so, "sha256"))] return c def test_missing_content_leaves_the_checks_pending(self) -> None: