refactor: move campaign and probe modes to probes

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 15:47:20 +01:00
1 parent fd1c2e1c16
commit 2123bd8317
7 files changed
+206 -178

No files matched your search

+6 -111
View File
@@ -61,8 +61,6 @@ job runs it on a schedule.
from __future__ import annotations
import argparse
import json
import signal
import sys
from collections.abc import Sequence
from pathlib import Path
@@ -76,27 +74,18 @@ if sys.version_info < (3, 9):
sys.path.insert(0, str(Path(__file__).resolve().parent))
import yaml
from unattended import worktree
from core import hostguard
from probes.profileedit import ProfileEditError
from core.paths import REPO_ROOT
from probes.campaign import Campaign
from probes.campaignmodes import run_mode
from probes.content import ROMFETCH_ENV
from probes.gate import changed_profiles, gate
from probes.host import CONTENT_FILE, Paths, Settings, host_lock, parse_budget
from probes.reports import REVIEWED, open_findings, pass_report, render_status, review_finding, status_report
EXIT_REFUSED = 3
from probes.host import CONTENT_FILE, parse_budget
from probes.reports import REVIEWED
# --------------------------------------------------------------------------
# Command line
# --------------------------------------------------------------------------
def _parser() -> argparse.ArgumentParser:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__.split("\n\n")[0],
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = parser.add_subparsers(dest="command", required=True)
@@ -147,103 +136,9 @@ def _parser() -> argparse.ArgumentParser:
return parser
def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Paths) -> int:
updates: dict[str, object] = {}
for item in args.set:
name, sep, value = item.partition("=")
if not sep or not name:
parser.error(f"--set {item!r}: FIELD=YAML")
updates[name] = yaml.safe_load(value)
try:
line = review_finding(paths.root, args.key, args.status, args.reason, updates,
args.index)
except (ValueError, ProfileEditError) as exc:
print(f"campaign: {exc}", file=sys.stderr)
return 1
print(f"{line['status']} {line['key']} [{line['id']}]")
return 0
def _findings(args: argparse.Namespace, paths: Paths) -> int:
lines = open_findings(paths.root, args.all)
if args.json:
print(json.dumps(lines, indent=2))
for line in [] if args.json else lines:
print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, "
f"run shows {json.dumps(line['run_shows'])}. {line['statement']} "
f"[{', '.join(line['evidence'])}]")
return 0
def _settings(args: argparse.Namespace) -> Settings:
if args.command == "run":
return Settings(budget=args.budget, max_load_wait=args.max_load_wait,
min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb,
romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed, bench=args.bench)
if args.command == "references":
return Settings(romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed)
return Settings()
def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) -> int:
try:
with host_lock(campaign.lock_path):
listed = campaign.references(only, args.system, Path(args.png_dir))
except hostguard.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(listed, indent=2))
return 0
def main(argv: Sequence[str] | None = None) -> int:
parser = _parser()
args = parser.parse_args(argv)
paths = Paths.default()
if args.command == "gate":
return gate(paths.root, changed_profiles(paths.root))
if args.command == "review":
return _review(parser, args, paths)
if args.command == "findings":
return _findings(args, paths)
settings = _settings(args)
if args.command in ("run", "references"):
paths.content_file = Path(args.content_file)
campaign = Campaign(paths, settings)
if args.command == "status":
report = status_report(campaign)
print(json.dumps(report, indent=2) if args.json else render_status(report))
return 0
only = {item.strip() for item in args.only.split(",") if item.strip()}
if args.command == "references":
return _references(campaign, args, only)
if args.dry_run:
campaign.run(only, args.system, dry_run=True)
return 0
return _run_pass(campaign, args, only, paths)
def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int:
campaign.dirty_at_start = set(worktree.changed_files(paths.root)) if args.commit else set()
def stop(signum: int, frame: object) -> None:
# SIGTERM ends the pass like Ctrl-C: state saved, pass line written.
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, stop)
try:
with host_lock(campaign.lock_path):
current = campaign.run(only, args.system, commit_every=args.commit_every,
commit=args.commit)
except hostguard.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(pass_report(campaign, current)))
if current.result == "refused":
return EXIT_REFUSED
return 75 if current.result == "paused" else 0
parser = build_parser()
return run_mode(parser, parser.parse_args(argv))
if __name__ == "__main__":
+117
View File
@@ -0,0 +1,117 @@
"""The campaign command's modes: gate, review, findings, status, references and a pass."""
from __future__ import annotations
import argparse
import json
import signal
import sys
from pathlib import Path
import yaml
from unattended import worktree
from core import hostguard
from probes.campaign import Campaign
from probes.gate import changed_profiles, gate
from probes.host import Paths, Settings, host_lock
from probes.profileedit import ProfileEditError
from probes.reports import open_findings, pass_report, render_status, review_finding, status_report
EXIT_REFUSED = 3
def run_mode(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
paths = Paths.default()
if args.command == "gate":
return gate(paths.root, changed_profiles(paths.root))
if args.command == "review":
return _review(parser, args, paths)
if args.command == "findings":
return _findings(args, paths)
settings = _settings(args)
if args.command in ("run", "references"):
paths.content_file = Path(args.content_file)
campaign = Campaign(paths, settings)
if args.command == "status":
report = status_report(campaign)
print(json.dumps(report, indent=2) if args.json else render_status(report))
return 0
only = {item.strip() for item in args.only.split(",") if item.strip()}
if args.command == "references":
return _references(campaign, args, only)
if args.dry_run:
campaign.run(only, args.system, dry_run=True)
return 0
return _run_pass(campaign, args, only, paths)
def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Paths) -> int:
updates: dict[str, object] = {}
for item in args.set:
name, sep, value = item.partition("=")
if not sep or not name:
parser.error(f"--set {item!r}: FIELD=YAML")
updates[name] = yaml.safe_load(value)
try:
line = review_finding(paths.root, args.key, args.status, args.reason, updates,
args.index)
except (ValueError, ProfileEditError) as exc:
print(f"campaign: {exc}", file=sys.stderr)
return 1
print(f"{line['status']} {line['key']} [{line['id']}]")
return 0
def _findings(args: argparse.Namespace, paths: Paths) -> int:
lines = open_findings(paths.root, args.all)
if args.json:
print(json.dumps(lines, indent=2))
for line in [] if args.json else lines:
print(f"{line['status']:8} {line['key']}: profile says {json.dumps(line['profile_says'])}, "
f"run shows {json.dumps(line['run_shows'])}. {line['statement']} "
f"[{', '.join(line['evidence'])}]")
return 0
def _settings(args: argparse.Namespace) -> Settings:
if args.command == "run":
return Settings(budget=args.budget, max_load_wait=args.max_load_wait,
min_free_gb=args.min_free_gb, cache_cap_gb=args.cache_cap_gb,
romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed, bench=args.bench)
if args.command == "references":
return Settings(romfetch=args.romfetch, network=not args.offline,
allow_unsandboxed=args.allow_unsandboxed)
return Settings()
def _references(campaign: Campaign, args: argparse.Namespace, only: set[str]) -> int:
try:
with host_lock(campaign.lock_path):
listed = campaign.references(only, args.system, Path(args.png_dir))
except hostguard.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(listed, indent=2))
return 0
def _run_pass(campaign: Campaign, args: argparse.Namespace, only: set[str], paths: Paths) -> int:
campaign.dirty_at_start = set(worktree.changed_files(paths.root)) if args.commit else set()
def stop(signum: int, frame: object) -> None:
# SIGTERM ends the pass like Ctrl-C: state saved, pass line written.
raise KeyboardInterrupt
signal.signal(signal.SIGTERM, stop)
try:
with host_lock(campaign.lock_path):
current = campaign.run(only, args.system, commit_every=args.commit_every,
commit=args.commit)
except hostguard.LockBusy as exc:
print(f"campaign: deferred, {exc}", file=sys.stderr)
return 75
print(json.dumps(pass_report(campaign, current)))
if current.result == "refused":
return EXIT_REFUSED
return 75 if current.result == "paused" else 0
+72
View File
@@ -0,0 +1,72 @@
"""The standalone_probe modes: resolve and fetch the asset, run or check it under the probe lock."""
from __future__ import annotations
import argparse
import http.client
import json
import subprocess
import sys
from pathlib import Path
import core_probe as cp
from core import upstream
from probes.appimage import fetch, github_releases, select_asset
from probes.standaloneemulators import EMULATORS, Emulator
from probes.standalonerecord import Busy, RunFailed, measure, validate
def run_mode(args: argparse.Namespace) -> int:
emu = EMULATORS[args.emulator]
if args.mode == "resolve":
try:
releases = github_releases(emu.repo)
except cp.ProbeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
asset = select_asset(releases, emu.asset_endswith, emu.asset_contains)
print(json.dumps({"emulator": emu.name, "platform": emu.platform,
"installer_ref": emu.installer_ref, "asset": asset}, indent=2))
return 0 if asset else 1
if args.mode == "fetch":
try:
print(json.dumps(fetch(emu), indent=2))
except (cp.ProbeError, upstream.UpstreamError, OSError, http.client.HTTPException,
subprocess.CalledProcessError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
return 0
return probe(args)
def probe(args: argparse.Namespace) -> int:
emu = EMULATORS[args.emulator]
problems = validate(args)
if problems:
for problem in problems:
print(f"ERROR: {problem}", file=sys.stderr)
return 2
# One run on the host at a time, as core_probe: the lock is held for
# this run, its load check included, and freed when it ends.
with cp.host_probe_lock():
return _probe(args, emu)
def _probe(args: argparse.Namespace, emu: Emulator) -> int:
try:
record = measure(args, emu)
except RunFailed as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
except Busy as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 3
if args.record:
try:
lines, record = cp.write_record(Path(args.record), record)
except cp.ProbeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
print(f"recorded {lines}", file=sys.stderr)
print(json.dumps(record, indent=2))
return 0
+1 -1
View File
@@ -28,7 +28,7 @@ SCRIPT_PATH = REPO_ROOT / SCRIPT
# of them differs from the commit says so.
CODE_FILES = (SCRIPT, "scripts/probes/standaloneemulators.py", "scripts/probes/appimage.py",
"scripts/probes/xvfb.py", "scripts/probes/standalonerun.py",
"scripts/probes/standalonerecord.py")
"scripts/probes/standalonerecord.py", "scripts/probes/standalonemodes.py")
class RunFailed(Exception):
+4 -61
View File
@@ -26,9 +26,6 @@ of the emulator in its log, the process dying, a uniform screen to the end.
from __future__ import annotations
import argparse
import http.client
import json
import subprocess
import sys
from collections.abc import Sequence
from pathlib import Path
@@ -36,44 +33,10 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import core_probe as cp
from core import upstream
from core.paths import REPO_ROOT
from probes.appimage import fetch, github_releases, select_asset
from probes.standaloneemulators import EMULATORS, Emulator
from probes.standalonerecord import DEFAULT_WORK_DIR, Busy, RunFailed, measure, validate
def probe(args: argparse.Namespace) -> int:
emu = EMULATORS[args.emulator]
problems = validate(args)
if problems:
for problem in problems:
print(f"ERROR: {problem}", file=sys.stderr)
return 2
# One run on the host at a time, as core_probe: the lock is held for
# this run, its load check included, and freed when it ends.
with cp.host_probe_lock():
return _probe(args, emu)
def _probe(args: argparse.Namespace, emu: Emulator) -> int:
try:
record = measure(args, emu)
except RunFailed as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
except Busy as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 3
if args.record:
try:
lines, record = cp.write_record(Path(args.record), record)
except cp.ProbeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
print(f"recorded {lines}", file=sys.stderr)
print(json.dumps(record, indent=2))
return 0
from probes.standaloneemulators import EMULATORS
from probes.standalonemodes import run_mode
from probes.standalonerecord import DEFAULT_WORK_DIR
# --------------------------------------------------------------------------
@@ -127,27 +90,7 @@ def build_parser() -> argparse.ArgumentParser:
def main(argv: Sequence[str] | None = None) -> int:
args = build_parser().parse_args(argv)
emu = EMULATORS[args.emulator]
if args.mode == "resolve":
try:
releases = github_releases(emu.repo)
except cp.ProbeError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
asset = select_asset(releases, emu.asset_endswith, emu.asset_contains)
print(json.dumps({"emulator": emu.name, "platform": emu.platform,
"installer_ref": emu.installer_ref, "asset": asset}, indent=2))
return 0 if asset else 1
if args.mode == "fetch":
try:
print(json.dumps(fetch(emu), indent=2))
except (cp.ProbeError, upstream.UpstreamError, OSError, http.client.HTTPException,
subprocess.CalledProcessError) as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
return 0
return probe(args)
return run_mode(build_parser().parse_args(argv))
if __name__ == "__main__":
+2 -2
View File
@@ -141,11 +141,11 @@ COMMANDS = {
"campaign.py": (
"probes/campaign.py", "probes/host.py", "probes/content.py", "probes/cores.py",
"probes/rules.py", "probes/state.py", "probes/gate.py", "probes/reports.py",
"probes/profileedit.py",
"probes/profileedit.py", "probes/entries.py", "probes/campaignmodes.py",
),
"standalone_probe.py": (
"probes/standaloneemulators.py", "probes/appimage.py", "probes/xvfb.py",
"probes/standalonerun.py", "probes/standalonerecord.py",
"probes/standalonerun.py", "probes/standalonerecord.py", "probes/standalonemodes.py",
),
"profile_sync.py": (
"profiling/citations.py", "profiling/anchoring.py", "profiling/repos.py",
+4 -3
View File
@@ -12,7 +12,7 @@ from pathlib import Path
import core_probe as cp
import standalone_probe as sp
from probes import appimage, standaloneemulators as emus, standalonerecord, standalonerun, xvfb
from probes import appimage, standaloneemulators as emus, standalonemodes, standalonerecord, standalonerun, xvfb
ROOT = Path(__file__).resolve().parent.parent
@@ -199,9 +199,10 @@ class HostLock(unittest.TestCase):
return 0
with tempfile.NamedTemporaryFile(suffix=".cue") as content, \
mock.patch.object(sp.cp, "host_probe_lock", lock), mock.patch.object(sp, "_probe", body):
mock.patch.object(standalonemodes.cp, "host_probe_lock", lock), \
mock.patch.object(standalonemodes, "_probe", body):
args = sp.build_parser().parse_args(["run", "duckstation", "--content", content.name])
self.assertEqual(sp.probe(args), 0)
self.assertEqual(standalonemodes.probe(args), 0)
self.assertEqual(events, ["take", "run", "free"])