reset_engine.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. #!/usr/bin/env python3
  2. """Perform an explicit full restart of the Rigforge user audio engine."""
  3. import argparse
  4. import json
  5. import socket
  6. import subprocess
  7. import sys
  8. from pathlib import Path
  9. import yaml
  10. import deploy
  11. from validate_desired_state import validate_state
  12. ROOT = Path(__file__).resolve().parents[1]
  13. PIPEWIRE_UNIT = "pipewire.service"
  14. WIREPLUMBER_UNIT = "wireplumber.service"
  15. def load_state():
  16. state_path = ROOT / "config" / "desired-state.yaml"
  17. with state_path.open(encoding="utf-8") as stream:
  18. state = yaml.safe_load(stream)
  19. errors = validate_state(state)
  20. if errors:
  21. raise ValueError("invalid desired state: " + "; ".join(errors))
  22. return state
  23. def call_systemctl(unit, verb, runner=subprocess.run):
  24. return runner(
  25. ["systemctl", "--user", verb, "--quiet", unit],
  26. check=False,
  27. capture_output=True,
  28. text=True,
  29. )
  30. def inspect_unit(unit, runner=subprocess.run):
  31. result = runner(
  32. ["systemctl", "--user", "show", "--property=LoadState", "--value", unit],
  33. check=False,
  34. capture_output=True,
  35. text=True,
  36. )
  37. if result.returncode:
  38. detail = result.stderr.strip() or result.stdout.strip()
  39. raise RuntimeError(f"cannot inspect {unit}: {detail or 'systemd user manager failed'}")
  40. if result.stdout.strip() == "not-found":
  41. return {"present": False, "active": False, "enabled": False}
  42. active = call_systemctl(unit, "is-active", runner).returncode == 0
  43. enabled = call_systemctl(unit, "is-enabled", runner).returncode == 0
  44. return {"present": True, "active": active, "enabled": enabled}
  45. def checked_command(command, runner=subprocess.run):
  46. result = runner(command, check=False, capture_output=True, text=True)
  47. if result.returncode:
  48. detail = result.stderr.strip() or result.stdout.strip()
  49. raise RuntimeError(
  50. f"command failed ({result.returncode}): {' '.join(command)}"
  51. + (f"\n{detail}" if detail else "")
  52. )
  53. if result.stdout.strip():
  54. print(result.stdout.rstrip())
  55. return result
  56. def unit_map(deployment):
  57. return {
  58. "filter_chain": deployment["pipewire"]["user_service"],
  59. "quantum": deployment["pipewire"]["quantum_user_service"],
  60. "ports": deployment["mod_host_ports"]["user_service"],
  61. "mod_host": deployment["mod_host"]["user_service"],
  62. "mod_ui": deployment["mod_ui"]["user_service"],
  63. "midi_bridge": deployment["midi_bridge"]["user_service"],
  64. "sooperlooper": deployment["sooperlooper"]["user_service"],
  65. "slweb": deployment["slweb"]["user_service"],
  66. "reconcile_service": deployment["reconcile"]["user_service"],
  67. "reconcile_timer": deployment["reconcile"]["user_timer"],
  68. }
  69. def selected_roles(units, statuses):
  70. selected = {
  71. role
  72. for role, unit in units.items()
  73. if role in {
  74. "filter_chain",
  75. "ports",
  76. "mod_host",
  77. "mod_ui",
  78. "midi_bridge",
  79. "sooperlooper",
  80. "slweb",
  81. }
  82. and statuses[unit]["present"]
  83. and (statuses[unit]["active"] or statuses[unit]["enabled"])
  84. }
  85. dependencies = {
  86. "ports": ("filter_chain",),
  87. "sooperlooper": ("filter_chain",),
  88. "mod_host": ("ports", "filter_chain"),
  89. "mod_ui": ("mod_host", "ports", "filter_chain"),
  90. "midi_bridge": ("mod_ui", "mod_host", "ports", "filter_chain"),
  91. "slweb": ("sooperlooper",),
  92. }
  93. pending = list(selected)
  94. while pending:
  95. role = pending.pop()
  96. for dependency in dependencies.get(role, ()):
  97. unit = units[dependency]
  98. if not statuses[unit]["present"]:
  99. raise RuntimeError(
  100. f"{units[role]} is enabled or active but its required unit "
  101. f"{unit} is not installed"
  102. )
  103. if dependency not in selected:
  104. selected.add(dependency)
  105. pending.append(dependency)
  106. return selected
  107. def reset_engine(deployment, registry, runner=subprocess.run):
  108. units = unit_map(deployment)
  109. all_units = {PIPEWIRE_UNIT, WIREPLUMBER_UNIT, *units.values()}
  110. statuses = {unit: inspect_unit(unit, runner) for unit in sorted(all_units)}
  111. for unit in (PIPEWIRE_UNIT, WIREPLUMBER_UNIT):
  112. if not statuses[unit]["present"]:
  113. raise RuntimeError(f"required audio service is not installed: {unit}")
  114. if not statuses[units["mod_host"]]["active"] and any(
  115. deploy.mod_host_port_is_open(port)
  116. for port in (
  117. deployment["mod_host"]["socket_port"],
  118. deployment["mod_host"]["feedback_port"],
  119. )
  120. ):
  121. raise RuntimeError(
  122. "mod-host ports are open while the managed service is inactive; "
  123. "stop the unmanaged/manual process before resetting"
  124. )
  125. if (
  126. not statuses[units["mod_ui"]]["active"]
  127. and deploy.mod_ui_port_is_open(
  128. deployment["mod_ui"]["websocket_host"],
  129. deployment["mod_ui"]["websocket_port"],
  130. )
  131. ):
  132. raise RuntimeError(
  133. "the mod-ui web port is open while its managed service is inactive; "
  134. "stop the unmanaged/manual process before resetting"
  135. )
  136. roles = selected_roles(units, statuses)
  137. if "mod_ui" in roles and "mod_ui" not in registry:
  138. raise RuntimeError(
  139. "mod-ui is enabled or active but not deployment-managed; refusing to reset "
  140. "its pedalboard state"
  141. )
  142. timer_unit = units["reconcile_timer"]
  143. restore_timer = statuses[timer_unit]["present"] and (
  144. statuses[timer_unit]["active"] or statuses[timer_unit]["enabled"]
  145. )
  146. print("Stopping the reconciliation timer and Rigforge audio services.")
  147. for unit in (units["reconcile_timer"], units["reconcile_service"]):
  148. if statuses[unit]["present"]:
  149. checked_command(["systemctl", "--user", "stop", unit], runner)
  150. stop_order = (
  151. "slweb",
  152. "midi_bridge",
  153. "mod_ui",
  154. "mod_host",
  155. "sooperlooper",
  156. "ports",
  157. "filter_chain",
  158. )
  159. for role in stop_order:
  160. if role in roles:
  161. checked_command(["systemctl", "--user", "stop", units[role]], runner)
  162. print("Restarting PipeWire, then bringing WirePlumber back on its graph.")
  163. checked_command(["systemctl", "--user", "stop", WIREPLUMBER_UNIT], runner)
  164. checked_command(["systemctl", "--user", "restart", PIPEWIRE_UNIT], runner)
  165. checked_command(["systemctl", "--user", "is-active", "--quiet", PIPEWIRE_UNIT], runner)
  166. checked_command(["systemctl", "--user", "start", WIREPLUMBER_UNIT], runner)
  167. checked_command(["systemctl", "--user", "is-active", "--quiet", WIREPLUMBER_UNIT], runner)
  168. quantum_unit = units["quantum"]
  169. quantum_status = statuses[quantum_unit]
  170. if quantum_status["present"] and (
  171. quantum_status["active"] or quantum_status["enabled"]
  172. ):
  173. checked_command(["systemctl", "--user", "start", quantum_unit], runner)
  174. start_order = (
  175. "filter_chain",
  176. "ports",
  177. "sooperlooper",
  178. "mod_host",
  179. "mod_ui",
  180. "midi_bridge",
  181. "slweb",
  182. )
  183. print("Starting enabled or previously active Rigforge services in dependency order.")
  184. for role in start_order:
  185. if role in roles:
  186. checked_command(["systemctl", "--user", "start", units[role]], runner)
  187. observer = ROOT / deployment["reconcile"]["observer_script"]
  188. python = sys.executable
  189. print("Rebuilding the declared PipeWire links.")
  190. checked_command(
  191. [
  192. python,
  193. str(observer),
  194. "--state",
  195. str(ROOT / "config" / "desired-state.yaml"),
  196. "--reconcile-once",
  197. ],
  198. runner,
  199. )
  200. print("Checking the resulting PipeWire graph.")
  201. graph_report = checked_command(
  202. [python, str(observer), "--state", str(ROOT / "config" / "desired-state.yaml")],
  203. runner,
  204. )
  205. try:
  206. differences = json.loads(graph_report.stdout)["differences"]
  207. except (json.JSONDecodeError, KeyError, TypeError) as error:
  208. raise RuntimeError(
  209. f"could not validate the final PipeWire graph report: {error}"
  210. ) from error
  211. if differences:
  212. raise RuntimeError(
  213. "the final PipeWire graph still differs from desired state: "
  214. + json.dumps(differences, sort_keys=True)
  215. )
  216. for role in start_order:
  217. if role in roles:
  218. checked_command(
  219. ["systemctl", "--user", "is-active", "--quiet", units[role]], runner
  220. )
  221. if restore_timer:
  222. checked_command(["systemctl", "--user", "start", timer_unit], runner)
  223. checked_command(["systemctl", "--user", "is-active", "--quiet", timer_unit], runner)
  224. print("Rigforge engine reset completed.")
  225. def confirm_reset(yes):
  226. print(
  227. "WARNING: this interrupts audio, restarts PipeWire and WirePlumber, "
  228. "and restarts enabled Rigforge audio services. In-memory SooperLooper "
  229. "recordings may be lost. mod-ui will restore its saved user pedalboard."
  230. )
  231. if yes:
  232. return True
  233. if not sys.stdin.isatty():
  234. print("Refusing non-interactive reset without --yes.", file=sys.stderr)
  235. return False
  236. return input("Continue with full engine reset? [y/N] ").strip().lower() in {
  237. "y",
  238. "yes",
  239. }
  240. def main(argv=None):
  241. parser = argparse.ArgumentParser(
  242. description="Fully restart Rigforge's PipeWire audio engine and managed services."
  243. )
  244. parser.add_argument(
  245. "--yes",
  246. action="store_true",
  247. help="skip the interactive confirmation prompt",
  248. )
  249. args = parser.parse_args(argv)
  250. try:
  251. state = load_state()
  252. target = state["system"]["target"]["hostname"]
  253. actual_host = socket.gethostname().split(".", 1)[0]
  254. if actual_host != target:
  255. raise RuntimeError(
  256. f"refusing to reset on host {actual_host!r}; desired-state target is {target!r}"
  257. )
  258. deployment = deploy.load_deployment()
  259. registry = deploy.read_registry()
  260. if not confirm_reset(args.yes):
  261. return 1
  262. reset_engine(deployment, registry)
  263. except (
  264. OSError,
  265. RuntimeError,
  266. ValueError,
  267. KeyError,
  268. yaml.YAMLError,
  269. subprocess.CalledProcessError,
  270. ) as error:
  271. print(f"ERROR: {error}", file=sys.stderr)
  272. print(
  273. "Reset did not complete. The reconciliation timer may remain stopped; "
  274. "inspect user-service status and journals before restarting it.",
  275. file=sys.stderr,
  276. )
  277. return 1
  278. return 0
  279. if __name__ == "__main__":
  280. raise SystemExit(main())