Files
libretro/scripts/check_buildbot_system.py
T
Abdessamad Derraz 4eacb6ff39 chore: lint scripts and tests with ruff
pyproject.toml now carries the ruff rule set: pyflakes, the B rules,
simplify, perf, pyupgrade, complexity and size limits. This commit
applies the fixes that change no behavior and the small defects the
first run named:

- tests/test_install.py used argparse without importing it
- three loops rebound the outer `profile` with each layout
  (packextras, slots, verify); the loop variable is now `layout`
- profile_sync loops shadowed dataclasses.field
- generate_readme and packextras computed values nothing read
- stale noqa markers for rules the project does not enforce

Complexity, size and the remaining findings are handled next.
2026-11-17 07:07:48 +01:00

238 lines
7.5 KiB
Python

#!/usr/bin/env python3
"""Check buildbot system directory for changes against local registry.
Compares the live buildbot assets/system/.index against _data_dirs.yml
entries using HTTP ETag headers for change detection.
Usage:
python scripts/check_buildbot_system.py
python scripts/check_buildbot_system.py --update
python scripts/check_buildbot_system.py --json
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import logging
import os
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from common import InputMissing, yaml_load
log = logging.getLogger(__name__)
BUILDBOT_SYSTEM_URL = "https://buildbot.libretro.com/assets/system/"
INDEX_URL = BUILDBOT_SYSTEM_URL + ".index"
USER_AGENT = "retrobios/1.0"
REQUEST_TIMEOUT = 15
DEFAULT_REGISTRY = "platforms/_data_dirs.yml"
VERSIONS_FILE = "data/.versions.json"
def fetch_index() -> set[str]:
"""Fetch .index from buildbot, return set of ZIP filenames."""
req = urllib.request.Request(INDEX_URL, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return {
line.strip() for line in resp.read().decode().splitlines() if line.strip()
}
def load_tracked_entries(
registry_path: str = DEFAULT_REGISTRY,
) -> dict[str, tuple[str, str]]:
"""Load buildbot entries from _data_dirs.yml.
Returns {decoded_zip_name: (key, source_url)}.
"""
if importlib.util.find_spec("yaml") is None:
print("Error: PyYAML required", file=sys.stderr)
sys.exit(1)
with open(registry_path) as f:
data = yaml_load(f) or {}
entries: dict[str, tuple[str, str]] = {}
for key, entry in data.get("data_directories", {}).items():
url = entry.get("source_url", "")
if "buildbot.libretro.com/assets/system" not in url:
continue
zip_name = urllib.parse.unquote(url.rsplit("/", 1)[-1])
entries[zip_name] = (key, url)
return entries
def get_remote_etag(url: str) -> str | None:
"""HEAD request to get ETag."""
try:
req = urllib.request.Request(
url, method="HEAD", headers={"User-Agent": USER_AGENT}
)
with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT) as resp:
return resp.headers.get("ETag") or resp.headers.get("Last-Modified") or ""
except (urllib.error.URLError, OSError):
return None
def load_versions(versions_path: str = VERSIONS_FILE) -> dict:
"""Load cached version/ETag data."""
path = Path(versions_path)
if not path.exists():
return {}
with open(path) as f:
return json.load(f)
def check(registry_path: str = DEFAULT_REGISTRY) -> dict:
"""Run the buildbot check. Returns structured report."""
try:
index_zips = fetch_index()
except (urllib.error.URLError, OSError) as exc:
log.warning("buildbot unreachable: %s", exc)
return {"error": str(exc), "entries": []}
tracked = load_tracked_entries(registry_path)
versions = load_versions()
buildbot_set = set(index_zips)
tracked_set = set(tracked.keys())
results: list[dict] = []
for z in sorted(buildbot_set - tracked_set):
results.append({"zip": z, "status": "NEW", "key": None})
for z in sorted(tracked_set - buildbot_set):
key, _ = tracked[z]
results.append({"zip": z, "status": "STALE", "key": key})
for z in sorted(tracked_set & buildbot_set):
key, url = tracked[z]
stored = versions.get(key, {}).get("sha", "")
remote = get_remote_etag(url)
if remote is None:
status = "UNKNOWN"
elif remote == stored:
status = "OK"
else:
status = "UPDATED"
results.append(
{
"zip": z,
"status": status,
"key": key,
"stored_etag": stored,
"remote_etag": remote or "",
}
)
return {"entries": results}
def print_report(report: dict) -> None:
"""Print human-readable report."""
if report.get("error"):
print(f"WARNING: {report['error']}")
return
entries = report["entries"]
print(f"Buildbot system check ({len(entries)} entries):")
for e in entries:
pad = 40 - len(e["zip"])
dots = "." * max(pad, 2)
print(f" {e['zip']} {dots} {e['status']}")
counts: dict[str, int] = {}
for e in entries:
counts[e["status"]] = counts.get(e["status"], 0) + 1
parts = [f"{v} {k.lower()}" for k, v in sorted(counts.items())]
print(f"\nSummary: {', '.join(parts)}")
def update_changed(report: dict) -> list[str]:
"""Refresh entries that have changed and return the keys whose refresh failed."""
failed: list[str] = []
for e in report.get("entries", []):
if e["status"] == "UPDATED" and e.get("key"):
log.info("refreshing %s ...", e["key"])
result = subprocess.run(
[
sys.executable,
"scripts/refresh_data_dirs.py",
"--force",
"--key",
e["key"],
],
check=False,
)
if result.returncode != 0:
log.error("refresh of %s failed (exit %d)", e["key"], result.returncode)
failed.append(e["key"])
return failed
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(message)s")
parser = argparse.ArgumentParser(
allow_abbrev=False,
description="Check buildbot system directory for changes",
)
parser.add_argument(
"--update", action="store_true", help="Auto-refresh changed entries"
)
parser.add_argument(
"--json",
action="store_true",
dest="json_output",
help="Machine-readable JSON output",
)
parser.add_argument(
"--registry", default=DEFAULT_REGISTRY,
help="the data directory registry to check (default: %(default)s)",
)
args = parser.parse_args()
# Read after the buildbot answered, a mistyped path ended on a trace.
if not os.path.isfile(args.registry):
raise InputMissing(f"Registry not found: {args.registry}")
report = check(args.registry)
if args.json_output:
print(json.dumps(report, indent=2))
else:
print_report(report)
if args.update:
failed = update_changed(report)
if failed:
print(f"ERROR: refresh failed for {', '.join(failed)}", file=sys.stderr)
sys.exit(1)
# Unreachable upstream means the freshness question was not answered, and
# a zero exit says it was answered "fresh". An asset whose HEAD went
# unanswered is the same question left open, as check_freshness counts
# UNKNOWN. A new asset nobody tracks, or a tracked one the buildbot
# dropped, is a change to act on: a zero exit there let the online
# pipeline call the system directory current.
if report.get("error") or pending(report) or unanswered(report):
raise SystemExit(1)
def pending(report: dict) -> list[dict]:
"""Entries a maintainer has to act on: not tracked yet, or gone."""
return [e for e in report.get("entries", []) if e["status"] in ("NEW", "STALE")]
def unanswered(report: dict) -> list[dict]:
"""Tracked entries whose remote version could not be read."""
return [e for e in report.get("entries", []) if e["status"] == "UNKNOWN"]
if __name__ == "__main__":
from common import run_cli
run_cli(main)