#!/usr/bin/env python3 """Perform an explicit full restart of the Rigforge user audio engine.""" import argparse import json import socket import subprocess import sys from pathlib import Path import yaml import deploy from validate_desired_state import validate_state ROOT = Path(__file__).resolve().parents[1] PIPEWIRE_UNIT = "pipewire.service" WIREPLUMBER_UNIT = "wireplumber.service" def load_state(): state_path = ROOT / "config" / "desired-state.yaml" with state_path.open(encoding="utf-8") as stream: state = yaml.safe_load(stream) errors = validate_state(state) if errors: raise ValueError("invalid desired state: " + "; ".join(errors)) return state def call_systemctl(unit, verb, runner=subprocess.run): return runner( ["systemctl", "--user", verb, "--quiet", unit], check=False, capture_output=True, text=True, ) def inspect_unit(unit, runner=subprocess.run): result = runner( ["systemctl", "--user", "show", "--property=LoadState", "--value", unit], check=False, capture_output=True, text=True, ) if result.returncode: detail = result.stderr.strip() or result.stdout.strip() raise RuntimeError(f"cannot inspect {unit}: {detail or 'systemd user manager failed'}") if result.stdout.strip() == "not-found": return {"present": False, "active": False, "enabled": False} active = call_systemctl(unit, "is-active", runner).returncode == 0 enabled = call_systemctl(unit, "is-enabled", runner).returncode == 0 return {"present": True, "active": active, "enabled": enabled} def checked_command(command, runner=subprocess.run): result = runner(command, check=False, capture_output=True, text=True) if result.returncode: detail = result.stderr.strip() or result.stdout.strip() raise RuntimeError( f"command failed ({result.returncode}): {' '.join(command)}" + (f"\n{detail}" if detail else "") ) if result.stdout.strip(): print(result.stdout.rstrip()) return result def unit_map(deployment): return { "filter_chain": deployment["pipewire"]["user_service"], "quantum": deployment["pipewire"]["quantum_user_service"], "ports": deployment["mod_host_ports"]["user_service"], "mod_host": deployment["mod_host"]["user_service"], "mod_ui": deployment["mod_ui"]["user_service"], "midi_bridge": deployment["midi_bridge"]["user_service"], "sooperlooper": deployment["sooperlooper"]["user_service"], "slweb": deployment["slweb"]["user_service"], "reconcile_service": deployment["reconcile"]["user_service"], "reconcile_timer": deployment["reconcile"]["user_timer"], } def selected_roles(units, statuses): selected = { role for role, unit in units.items() if role in { "filter_chain", "ports", "mod_host", "mod_ui", "midi_bridge", "sooperlooper", "slweb", } and statuses[unit]["present"] and (statuses[unit]["active"] or statuses[unit]["enabled"]) } dependencies = { "ports": ("filter_chain",), "sooperlooper": ("filter_chain",), "mod_host": ("ports", "filter_chain"), "mod_ui": ("mod_host", "ports", "filter_chain"), "midi_bridge": ("mod_ui", "mod_host", "ports", "filter_chain"), "slweb": ("sooperlooper",), } pending = list(selected) while pending: role = pending.pop() for dependency in dependencies.get(role, ()): unit = units[dependency] if not statuses[unit]["present"]: raise RuntimeError( f"{units[role]} is enabled or active but its required unit " f"{unit} is not installed" ) if dependency not in selected: selected.add(dependency) pending.append(dependency) return selected def reset_engine(deployment, registry, runner=subprocess.run): units = unit_map(deployment) all_units = {PIPEWIRE_UNIT, WIREPLUMBER_UNIT, *units.values()} statuses = {unit: inspect_unit(unit, runner) for unit in sorted(all_units)} for unit in (PIPEWIRE_UNIT, WIREPLUMBER_UNIT): if not statuses[unit]["present"]: raise RuntimeError(f"required audio service is not installed: {unit}") if not statuses[units["mod_host"]]["active"] and any( deploy.mod_host_port_is_open(port) for port in ( deployment["mod_host"]["socket_port"], deployment["mod_host"]["feedback_port"], ) ): raise RuntimeError( "mod-host ports are open while the managed service is inactive; " "stop the unmanaged/manual process before resetting" ) if ( not statuses[units["mod_ui"]]["active"] and deploy.mod_ui_port_is_open( deployment["mod_ui"]["websocket_host"], deployment["mod_ui"]["websocket_port"], ) ): raise RuntimeError( "the mod-ui web port is open while its managed service is inactive; " "stop the unmanaged/manual process before resetting" ) roles = selected_roles(units, statuses) if "mod_ui" in roles and "mod_ui" not in registry: raise RuntimeError( "mod-ui is enabled or active but not deployment-managed; refusing to reset " "its pedalboard state" ) timer_unit = units["reconcile_timer"] restore_timer = statuses[timer_unit]["present"] and ( statuses[timer_unit]["active"] or statuses[timer_unit]["enabled"] ) print("Stopping the reconciliation timer and Rigforge audio services.") for unit in (units["reconcile_timer"], units["reconcile_service"]): if statuses[unit]["present"]: checked_command(["systemctl", "--user", "stop", unit], runner) stop_order = ( "slweb", "midi_bridge", "mod_ui", "mod_host", "sooperlooper", "ports", "filter_chain", ) for role in stop_order: if role in roles: checked_command(["systemctl", "--user", "stop", units[role]], runner) print("Restarting PipeWire, then bringing WirePlumber back on its graph.") checked_command(["systemctl", "--user", "stop", WIREPLUMBER_UNIT], runner) checked_command(["systemctl", "--user", "restart", PIPEWIRE_UNIT], runner) checked_command(["systemctl", "--user", "is-active", "--quiet", PIPEWIRE_UNIT], runner) checked_command(["systemctl", "--user", "start", WIREPLUMBER_UNIT], runner) checked_command(["systemctl", "--user", "is-active", "--quiet", WIREPLUMBER_UNIT], runner) quantum_unit = units["quantum"] quantum_status = statuses[quantum_unit] if quantum_status["present"] and ( quantum_status["active"] or quantum_status["enabled"] ): checked_command(["systemctl", "--user", "start", quantum_unit], runner) start_order = ( "filter_chain", "ports", "sooperlooper", "mod_host", "mod_ui", "midi_bridge", "slweb", ) print("Starting enabled or previously active Rigforge services in dependency order.") for role in start_order: if role in roles: checked_command(["systemctl", "--user", "start", units[role]], runner) observer = ROOT / deployment["reconcile"]["observer_script"] python = sys.executable print("Rebuilding the declared PipeWire links.") checked_command( [ python, str(observer), "--state", str(ROOT / "config" / "desired-state.yaml"), "--reconcile-once", ], runner, ) print("Checking the resulting PipeWire graph.") graph_report = checked_command( [python, str(observer), "--state", str(ROOT / "config" / "desired-state.yaml")], runner, ) try: differences = json.loads(graph_report.stdout)["differences"] except (json.JSONDecodeError, KeyError, TypeError) as error: raise RuntimeError( f"could not validate the final PipeWire graph report: {error}" ) from error if differences: raise RuntimeError( "the final PipeWire graph still differs from desired state: " + json.dumps(differences, sort_keys=True) ) for role in start_order: if role in roles: checked_command( ["systemctl", "--user", "is-active", "--quiet", units[role]], runner ) if restore_timer: checked_command(["systemctl", "--user", "start", timer_unit], runner) checked_command(["systemctl", "--user", "is-active", "--quiet", timer_unit], runner) print("Rigforge engine reset completed.") def confirm_reset(yes): print( "WARNING: this interrupts audio, restarts PipeWire and WirePlumber, " "and restarts enabled Rigforge audio services. In-memory SooperLooper " "recordings may be lost. mod-ui will restore its saved user pedalboard." ) if yes: return True if not sys.stdin.isatty(): print("Refusing non-interactive reset without --yes.", file=sys.stderr) return False return input("Continue with full engine reset? [y/N] ").strip().lower() in { "y", "yes", } def main(argv=None): parser = argparse.ArgumentParser( description="Fully restart Rigforge's PipeWire audio engine and managed services." ) parser.add_argument( "--yes", action="store_true", help="skip the interactive confirmation prompt", ) args = parser.parse_args(argv) try: state = load_state() target = state["system"]["target"]["hostname"] actual_host = socket.gethostname().split(".", 1)[0] if actual_host != target: raise RuntimeError( f"refusing to reset on host {actual_host!r}; desired-state target is {target!r}" ) deployment = deploy.load_deployment() registry = deploy.read_registry() if not confirm_reset(args.yes): return 1 reset_engine(deployment, registry) except ( OSError, RuntimeError, ValueError, KeyError, yaml.YAMLError, subprocess.CalledProcessError, ) as error: print(f"ERROR: {error}", file=sys.stderr) print( "Reset did not complete. The reconciliation timer may remain stopped; " "inspect user-service status and journals before restarting it.", file=sys.stderr, ) return 1 return 0 if __name__ == "__main__": raise SystemExit(main())