refactor: one digest and one lock name for probes

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 20:38:29 +01:00
1 parent 4ea44a027e
commit cacd290d2e
10 files changed
+43 -76

No files matched your search

+9
View File
@@ -85,6 +85,15 @@ def _compute_hashes(filepath: str | Path, algos: frozenset[str]) -> dict[str, st
result["adler32"] = format(adler & 0xFFFFFFFF, "08x") result["adler32"] = format(adler & 0xFFFFFFFF, "08x")
return result 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: def md5sum(source: str | os.PathLike[str] | IO[bytes]) -> str:
"""Compute MD5 of a file path or file-like object - matches Batocera's md5sum().""" """Compute MD5 of a file path or file-like object - matches Batocera's md5sum()."""
h = hashlib.md5() h = hashlib.md5()
+5 -6
View File
@@ -18,8 +18,9 @@ import yaml
import autorun import autorun
import core_probe import core_probe
from core import hostguard from core import hostguard
from core.hashing import file_digest
from core.paths import REPO_ROOT 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 model import measurements as mr
from probes import rules from probes import rules
from probes.profileedit import ProfileEditError, write_fields from probes.profileedit import ProfileEditError, write_fields
@@ -40,12 +41,10 @@ from probes.host import (
Settings, Settings,
Unavailable, Unavailable,
child_env, child_env,
file_sha1,
file_sha256,
slug, slug,
working_directory, 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 CRASH_ATTEMPTS = 3
@@ -131,7 +130,7 @@ class Campaign:
self.cores = Cores(self) self.cores = Cores(self)
self.store = ContentStore(self) self.store = ContentStore(self)
self.content = load_content(paths.content_file) 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.oracle_data = core_probe.load_oracle(paths.oracle)[0]
self.deadline = 0.0 self.deadline = 0.0
self.current: Pass | None = None self.current: Pass | None = None
@@ -369,7 +368,7 @@ class Campaign:
for _, other, path in staged.values(): for _, other, path in staged.values():
theirs = set(regions_of(other)) theirs = set(regions_of(other))
if theirs and "world" not in theirs and not theirs & mine and path.resolve() != local.resolve(): 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] 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: def run_unit_content(self, unit: Unit, core: Core, content: Content, digest: str) -> None:
+3 -2
View File
@@ -12,8 +12,9 @@ from typing import TYPE_CHECKING
import yaml import yaml
from core.hashing import file_digest
from core.statefile import now_iso 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: if TYPE_CHECKING:
from probes.campaign import Campaign 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}") raise Unavailable(f"{folder.name}: identity status {identity.get('status')!r}")
for item in identity.get("files") or (): for item in identity.get("files") or ():
path = folder / item["name"] 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") raise Unavailable(f"{folder.name}: {item['name']} does not match its identity")
return identity return identity
+5 -4
View File
@@ -18,8 +18,9 @@ from pathlib import Path
from typing import TYPE_CHECKING, TypeVar from typing import TYPE_CHECKING, TypeVar
import core_probe import core_probe
from core.hashing import file_digest
from core.statefile import now_iso 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: if TYPE_CHECKING:
from probes.campaign import Campaign from probes.campaign import Campaign
@@ -255,7 +256,7 @@ class Cores:
stamp = self.retrying(f"{name} nightly", head) stamp = self.retrying(f"{name} nightly", head)
target = self.c.paths.home / "cores" / name / f"{name}_libretro.so" target = self.c.paths.home / "cores" / name / f"{name}_libretro.so"
if (cached.get("etag"), cached.get("last_modified")) != (stamp["etag"], stamp["last_modified"]) \ 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 = target.parent / f"{name}_libretro.so.zip"
archive.parent.mkdir(parents=True, exist_ok=True) archive.parent.mkdir(parents=True, exist_ok=True)
@@ -265,7 +266,7 @@ class Cores:
self.retrying(f"{name} nightly", download) self.retrying(f"{name} nightly", download)
safe_extract_so(archive, f"{name}_libretro.so", target) safe_extract_so(archive, f"{name}_libretro.so", target)
archive.unlink() 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.state["cores"][name] = cached
self.c.log(f"core {name}: new nightly {cached['sha256'][:12]} ({stamp['last_modified']})") 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 repo = profile.get("source") if isinstance(profile.get("source"), str) else None
@@ -295,7 +296,7 @@ class Cores:
command = record.get("command") or "make" command = record.get("command") or "make"
self.c.state["builds"][emulator] = {"commit": commit, "command": command, self.c.state["builds"][emulator] = {"commit": commit, "command": command,
"so": built[0].name, "at": now_iso()} "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) repo=source, commit=commit, build_command=command)
def mirror(self, url: str) -> Path: def mirror(self, url: str) -> Path:
+1 -18
View File
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
import contextlib import contextlib
import hashlib
import http.client import http.client
import os import os
import re import re
@@ -29,8 +28,6 @@ if TYPE_CHECKING:
CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml"
LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV
NETWORK_DELAYS = (10, 60, 300) 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" 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 @contextlib.contextmanager
def host_lock(lock_path: Path) -> Iterator[None]: def host_lock(lock_path: Path) -> Iterator[None]:
"""The automation lock, unless the autorun job running us holds it.""" """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 yield
return return
with hostguard.global_lock(lock_path): with hostguard.global_lock(lock_path):
+3 -10
View File
@@ -2,7 +2,6 @@
from __future__ import annotations from __future__ import annotations
import hashlib
import json import json
import shutil import shutil
import subprocess import subprocess
@@ -12,6 +11,7 @@ from collections.abc import Sequence
from dataclasses import dataclass, field from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from core.hashing import file_digest
from core.paths import REPO_ROOT from core.paths import REPO_ROOT
from core.ziptools import safe_extract_zip 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()) 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: def pack_layout(pack: Path, root: Path, identity: dict) -> Layout:
"""The pack extracted as a user does, at the root of the BIOS folder. """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: def pack_identity(pack: Path) -> dict:
with zipfile.ZipFile(pack) as handle: with zipfile.ZipFile(pack) as handle:
members = sum(1 for info in handle.infolist() if not info.is_dir()) 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} "members": members}
@@ -118,7 +111,7 @@ def installer_layout(platform: str, pack: Path, identity: dict, manifest_path: P
"pack": identity, "pack": identity,
"manifest": {"path": manifest_path.relative_to(REPO_ROOT).as_posix() if manifest_path.is_relative_to(REPO_ROOT) "manifest": {"path": manifest_path.relative_to(REPO_ROOT).as_posix() if manifest_path.is_relative_to(REPO_ROOT)
else manifest_path.name, 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")}, "generated": manifest.get("generated"), "pack_files": manifest.get("pack_files")},
"save_dir_files": len(walk(save_dir)) if save_dir.is_dir() else 0, "save_dir_files": len(walk(save_dir)) if save_dir.is_dir() else 0,
"installer_summary": installer_summary(proc.stdout, system_dir, save_dir), "installer_summary": installer_summary(proc.stdout, system_dir, save_dir),
+8 -14
View File
@@ -18,6 +18,8 @@ from dataclasses import dataclass
from pathlib import Path from pathlib import Path
import autorun 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.paths import REPO_ROOT
from core.statefile import now_iso from core.statefile import now_iso
from model import measurements as mr 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.content import Content, load_content, load_file, verify_identity
from probes.cores import BUILDBOT, safe_extract_so from probes.cores import BUILDBOT, safe_extract_so
from probes.entries import entry_dest 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 ( from probes.packlayout import (
Layout, Layout,
ProbeFailure, ProbeFailure,
build_pack, build_pack,
file_sha,
installer_layout, installer_layout,
pack_identity, pack_identity,
pack_layout, pack_layout,
@@ -48,17 +49,10 @@ PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml"
CONTENT_DIR = MAIN / ".cache" / "test-content" CONTENT_DIR = MAIN / ".cache" / "test-content"
CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores" CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores"
PACK_PROBES = mr.PACK_PROBES
VERDICTS = ("boots", "bios_error", "crash", "hang", "unknown")
MAX_ROUNDS = 6 MAX_ROUNDS = 6
PROBE_TIMEOUT = 900
IDLE_WAIT = 1800 IDLE_WAIT = 1800
PROBE_LOCK_ENV = "RETROBIOS_PROBE_LOCK" PROBE_LOCK = probe_lock_path()
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 EXIT_BUSY = 3
# The hardware target each platform is probed for: the one whose libretro # 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" so, meta_path = folder / f"{name}_libretro.so", folder / "build.json"
if so.is_file() and meta_path.is_file() and not refresh: if so.is_file() and meta_path.is_file() and not refresh:
meta = json.loads(meta_path.read_text(encoding="utf-8")) 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)} return {**meta, "path": str(so)}
url = f"{BUILDBOT}{name}_libretro.so.zip" url = f"{BUILDBOT}{name}_libretro.so.zip"
folder.mkdir(parents=True, exist_ok=True) 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") modified = response.headers.get("Last-Modified")
safe_extract_so(archive, f"{name}_libretro.so", so) safe_extract_so(archive, f"{name}_libretro.so", so)
archive.unlink() 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()} "fetched_at": now_iso()}
meta_path.write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8") meta_path.write_text(json.dumps(meta, indent=1) + "\n", encoding="utf-8")
return {**meta, "path": str(so)} return {**meta, "path": str(so)}
@@ -449,8 +443,8 @@ def git_head() -> str | None:
def append_line(line: dict, root: Path = REPO_ROOT) -> dict: def append_line(line: dict, root: Path = REPO_ROOT) -> dict:
sealed = mr.seal_line(line, mr.CAMPAIGN_FILES[PACK_PROBES][0]) sealed = mr.seal_line(line, mr.CAMPAIGN_FILES[mr.PACK_PROBES][0])
path = root / mr.records_path(PACK_PROBES) path = root / mr.records_path(mr.PACK_PROBES)
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as handle: with path.open("a", encoding="utf-8") as handle:
handle.write(mr.line_text(sealed) + "\n") handle.write(mr.line_text(sealed) + "\n")
+3 -13
View File
@@ -16,9 +16,11 @@ from pathlib import Path
import yaml import yaml
from core.paths import REPO_ROOT 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" CORES = REPO_ROOT / ".cache" / "region" / "cores"
NIGHTLY = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/{core}_libretro.so.zip" NIGHTLY = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/{core}_libretro.so.zip"
VARIANTS = ("full", "own", "others", "pack") VARIANTS = ("full", "own", "others", "pack")
@@ -32,16 +34,6 @@ REGION_WORDS = {"japan": "Japanese", "north-america": "US", "europe": "European"
# Pure rules # 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]: 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: def staged_name(used: str | None) -> str | None:
"""The file a bios_used names, or None.""" """The file a bios_used names, or None."""
-4
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import json import json
from pathlib import Path from pathlib import Path
from core import statefile
from model import measurements as mr from model import measurements as mr
@@ -31,9 +30,6 @@ def load_state(path: Path) -> dict:
return state 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: 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 """A check runs again when it never ran, is pending, or ran against
+6 -5
View File
@@ -32,6 +32,7 @@ import autorun
import campaign import campaign
import core_probe import core_probe
from core import hostguard from core import hostguard
from core.hashing import file_digest
from probes import campaign as probes_campaign from probes import campaign as probes_campaign
from probes import content as probes_content from probes import content as probes_content
from probes import cores from probes import cores
@@ -487,7 +488,7 @@ class StateAndResume(Workspace):
def test_state_survives_a_reload(self) -> None: def test_state_survives_a_reload(self) -> None:
c = self.make() c = self.make()
c.pending("fake", "fake/fake-system/x/files", "content: romfetch not found") 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() again = self.make()
self.assertEqual(again.state["checks"]["fake"]["fake/fake-system/x/files"]["status"], "pending") 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 hostguard.global_lock(lock):
with self.assertRaises(hostguard.LockBusy), probes_host.host_lock(lock): with self.assertRaises(hostguard.LockBusy), probes_host.host_lock(lock):
pass pass
os.environ[probes_host.LOCK_HELD_ENV] = "1" os.environ[hostguard.LOCK_HELD_ENV] = "1"
try: try:
with probes_host.host_lock(lock): with probes_host.host_lock(lock):
pass pass
finally: finally:
del os.environ[probes_host.LOCK_HELD_ENV] del os.environ[hostguard.LOCK_HELD_ENV]
class ChildEnvironment(unittest.TestCase): class ChildEnvironment(unittest.TestCase):
@@ -1093,7 +1094,7 @@ class FakeCorePasses(Workspace):
c = probes_campaign.Campaign(self.paths, probes_host.Settings(**values), host, c = probes_campaign.Campaign(self.paths, probes_host.Settings(**values), host,
lock_path=self.tmp / "auto.lock") lock_path=self.tmp / "auto.lock")
so = core or self.cores[kind] 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 return c
def test_a_stand_in_is_proven_and_written(self) -> None: 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, check_repeat=2, probe_timeout=30, delays=(1,), echo=False), host,
lock_path=workspace.tmp / "auto.lock") lock_path=workspace.tmp / "auto.lock")
so = self.cores["hle"] 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 return c
def test_missing_content_leaves_the_checks_pending(self) -> None: def test_missing_content_leaves_the_checks_pending(self) -> None: