observe_pipewire.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. import argparse
  2. import json
  3. import re
  4. import subprocess
  5. import sys
  6. from pathlib import Path
  7. import yaml
  8. from validate_desired_state import validate_state as validate_desired_state
  9. MANAGED_ENDPOINT_PATTERN = re.compile(
  10. r"^(?:"
  11. r"alsa_input\.hw_U192k_0:capture_AUX[0-3]|"
  12. r"alsa_output\.hw_U192k_0:playback_AUX[0-3]|"
  13. r"rigforge\.direct-mix\.input:playback_AUX[0-7]|"
  14. r"rigforge\.direct-mix\.output:capture_FL|"
  15. r"rigforge\.mod-host-input:playback_AUX[0-3]|"
  16. r"rigforge\.mod-host-output:capture_AUX[0-3]|"
  17. r"sooperlooper:loop0_(?:in|out)_[1-4]|"
  18. r"sooperlooper:midi_in|"
  19. r"Midi-Bridge:UMC404HD 192k MIDI 1 \(capture\)"
  20. r")$"
  21. )
  22. def load_state(path):
  23. with path.open(encoding="utf-8") as state_stream:
  24. state = yaml.safe_load(state_stream)
  25. errors = validate_desired_state(state)
  26. errors.extend(validate_managed_links(state))
  27. if errors:
  28. raise ValueError("invalid desired state: " + "; ".join(errors))
  29. return state
  30. def validate_managed_links(state):
  31. errors = []
  32. if not isinstance(state, dict):
  33. return ["document root must be a mapping"]
  34. routing = state.get("routing")
  35. if not isinstance(routing, dict):
  36. return ["routing must be a mapping"]
  37. managed_ports = routing.get("managed_ports")
  38. if not isinstance(managed_ports, list):
  39. errors.append("routing.managed_ports must be a list")
  40. managed_ports = []
  41. for index, port in enumerate(managed_ports):
  42. if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port):
  43. errors.append(
  44. f"routing.managed_ports[{index}] is not an approved Rigforge boundary, UMC, or MIDI port"
  45. )
  46. if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))):
  47. errors.append("routing.managed_ports must not contain duplicate ports")
  48. managed_links = routing.get("managed_links")
  49. if not isinstance(managed_links, list):
  50. errors.append("routing.managed_links must be a list")
  51. managed_links = []
  52. for index, link in enumerate(managed_links):
  53. if not isinstance(link, dict):
  54. errors.append(f"routing.managed_links[{index}] must be a mapping")
  55. continue
  56. source = link.get("from")
  57. destination = link.get("to")
  58. if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
  59. errors.append(
  60. f"routing.managed_links[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port"
  61. )
  62. if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
  63. errors.append(
  64. f"routing.managed_links[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port"
  65. )
  66. if (
  67. isinstance(source, str)
  68. and isinstance(destination, str)
  69. and (source not in managed_ports or destination not in managed_ports)
  70. ):
  71. errors.append(f"routing.managed_links[{index}] endpoints must be listed in routing.managed_ports")
  72. if source == destination:
  73. errors.append(f"routing.managed_links[{index}] cannot link a port to itself")
  74. if link.get("status") not in {"planned", "observed"}:
  75. errors.append(f"routing.managed_links[{index}].status must be planned or observed")
  76. managed_unlinks = routing.get("managed_unlinks")
  77. if not isinstance(managed_unlinks, list):
  78. errors.append("routing.managed_unlinks must be a list")
  79. managed_unlinks = []
  80. unlink_edges = set()
  81. for index, link in enumerate(managed_unlinks):
  82. if not isinstance(link, dict):
  83. errors.append(f"routing.managed_unlinks[{index}] must be a mapping")
  84. continue
  85. source = link.get("from")
  86. destination = link.get("to")
  87. if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
  88. errors.append(
  89. f"routing.managed_unlinks[{index}].from is not an approved Rigforge boundary, UMC, or MIDI port"
  90. )
  91. if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
  92. errors.append(
  93. f"routing.managed_unlinks[{index}].to is not an approved Rigforge boundary, UMC, or MIDI port"
  94. )
  95. if (
  96. isinstance(source, str)
  97. and isinstance(destination, str)
  98. and (source not in managed_ports or destination not in managed_ports)
  99. ):
  100. errors.append(
  101. f"routing.managed_unlinks[{index}] endpoints must be listed in routing.managed_ports"
  102. )
  103. if source == destination:
  104. errors.append(f"routing.managed_unlinks[{index}] cannot unlink a port from itself")
  105. if link.get("status") not in {"planned", "observed"}:
  106. errors.append(f"routing.managed_unlinks[{index}].status must be planned or observed")
  107. if isinstance(source, str) and isinstance(destination, str):
  108. edge = (source, destination)
  109. if edge in unlink_edges:
  110. errors.append(f"duplicate managed unlink: {source} -> {destination}")
  111. unlink_edges.add(edge)
  112. managed_edges = {
  113. (link.get("from"), link.get("to"))
  114. for link in managed_links
  115. if isinstance(link, dict)
  116. and isinstance(link.get("from"), str)
  117. and isinstance(link.get("to"), str)
  118. }
  119. for source, destination in sorted(unlink_edges & managed_edges):
  120. errors.append(f"link cannot be both managed and scheduled for removal: {source} -> {destination}")
  121. return errors
  122. def parse_pw_link_output(text):
  123. links = set()
  124. current_source = None
  125. for line in text.splitlines():
  126. if not line.strip():
  127. continue
  128. if line.startswith(" |-> "):
  129. if current_source is None:
  130. raise ValueError("pw-link output has a destination without a source")
  131. destination = line.removeprefix(" |-> ")
  132. links.add((current_source, destination))
  133. continue
  134. if line.startswith(" |<- "):
  135. destination = line.removeprefix(" |<- ")
  136. links.add((destination, current_source))
  137. continue
  138. current_source = line.strip()
  139. return links
  140. def observe(state, links):
  141. managed_ports = set(state["routing"]["managed_ports"])
  142. managed = {
  143. (link["from"], link["to"])
  144. for link in state["routing"]["managed_links"]
  145. if link["status"] in {"planned", "observed"}
  146. }
  147. managed_unlinks = {
  148. (link["from"], link["to"])
  149. for link in state["routing"]["managed_unlinks"]
  150. if link["status"] in {"planned", "observed"}
  151. }
  152. observed_managed = {
  153. link
  154. for link in links
  155. if link[0] in managed_ports and link[1] in managed_ports
  156. }
  157. reports = []
  158. for source, destination in sorted(managed - observed_managed):
  159. reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
  160. for source, destination in sorted(observed_managed - managed):
  161. action = "would-unlink" if (source, destination) in managed_unlinks else "would-review"
  162. reports.append({"kind": "unexpected", "from": source, "to": destination, "action": action})
  163. return reports
  164. def list_ports(runner, direction):
  165. result = runner(
  166. ["pw-link", direction],
  167. check=True,
  168. capture_output=True,
  169. text=True,
  170. )
  171. return {line.strip() for line in result.stdout.splitlines() if line.strip()}
  172. def reconcile_once(state, runner=subprocess.run):
  173. initial_result = runner(
  174. ["pw-link", "-l"],
  175. check=True,
  176. capture_output=True,
  177. text=True,
  178. )
  179. initial_links = parse_pw_link_output(initial_result.stdout)
  180. initial_reports = observe(state, initial_links)
  181. missing_links = [report for report in initial_reports if report["kind"] == "missing"]
  182. actions = []
  183. if missing_links:
  184. outputs = list_ports(runner, "-o")
  185. inputs = list_ports(runner, "-i")
  186. for report in missing_links:
  187. source = report["from"]
  188. destination = report["to"]
  189. unavailable = []
  190. if source not in outputs:
  191. unavailable.append({"port": source, "direction": "output"})
  192. if destination not in inputs:
  193. unavailable.append({"port": destination, "direction": "input"})
  194. if unavailable:
  195. action = {
  196. "kind": "unavailable-port",
  197. "from": source,
  198. "to": destination,
  199. "missing_ports": unavailable,
  200. "result": "not-linked",
  201. "reason": (
  202. "required PipeWire port(s) are not present in the current graph"
  203. ),
  204. }
  205. if any(
  206. item["port"].startswith("rigforge.mod-host-")
  207. for item in unavailable
  208. ):
  209. action["hint"] = (
  210. "Rigforge mod-host boundary ports must be running; mod-ui provides the "
  211. "internal NAM/IR connections"
  212. )
  213. elif any(item["port"] == "sooperlooper:midi_in" for item in unavailable):
  214. action["hint"] = (
  215. "SooperLooper must be running under pw-jack and expose its JACK MIDI input"
  216. )
  217. actions.append(action)
  218. continue
  219. try:
  220. runner(
  221. ["pw-link", source, destination],
  222. check=True,
  223. capture_output=True,
  224. text=True,
  225. )
  226. actions.append(
  227. {"kind": "link", "from": source, "to": destination, "result": "requested"}
  228. )
  229. except (OSError, subprocess.CalledProcessError) as error:
  230. detail = str(error)
  231. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  232. detail = error.stderr.strip() or detail
  233. actions.append(
  234. {
  235. "kind": "link-failed",
  236. "from": source,
  237. "to": destination,
  238. "result": detail,
  239. }
  240. )
  241. # Remove only explicitly declared stale edges, and only after every
  242. # desired managed link is present. This avoids disconnecting an old path
  243. # when its replacement could not be established.
  244. if missing_links:
  245. before_unlink_result = runner(
  246. ["pw-link", "-l"],
  247. check=True,
  248. capture_output=True,
  249. text=True,
  250. )
  251. before_unlink_links = parse_pw_link_output(before_unlink_result.stdout)
  252. else:
  253. before_unlink_links = initial_links
  254. remaining_missing = [
  255. report
  256. for report in observe(state, before_unlink_links)
  257. if report["kind"] == "missing"
  258. ]
  259. managed_ports = set(state["routing"]["managed_ports"])
  260. scheduled_unlinks = [
  261. (link["from"], link["to"])
  262. for link in state["routing"]["managed_unlinks"]
  263. if link["from"] in managed_ports
  264. and link["to"] in managed_ports
  265. and (link["from"], link["to"]) in before_unlink_links
  266. ]
  267. if remaining_missing:
  268. for source, destination in scheduled_unlinks:
  269. actions.append(
  270. {
  271. "kind": "unlink-deferred",
  272. "from": source,
  273. "to": destination,
  274. "result": "desired managed links are still missing",
  275. }
  276. )
  277. else:
  278. for source, destination in scheduled_unlinks:
  279. try:
  280. runner(
  281. ["pw-link", "-d", source, destination],
  282. check=True,
  283. capture_output=True,
  284. text=True,
  285. )
  286. actions.append(
  287. {"kind": "unlink", "from": source, "to": destination, "result": "requested"}
  288. )
  289. except (OSError, subprocess.CalledProcessError) as error:
  290. detail = str(error)
  291. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  292. detail = error.stderr.strip() or detail
  293. actions.append(
  294. {
  295. "kind": "unlink-failed",
  296. "from": source,
  297. "to": destination,
  298. "result": detail,
  299. }
  300. )
  301. final_result = runner(
  302. ["pw-link", "-l"],
  303. check=True,
  304. capture_output=True,
  305. text=True,
  306. )
  307. final_links = parse_pw_link_output(final_result.stdout)
  308. return {
  309. "mode": "reconcile-once",
  310. "managed_links": len(state["routing"]["managed_links"]),
  311. "managed_unlinks": len(state["routing"]["managed_unlinks"]),
  312. "actions": actions,
  313. "differences": observe(state, final_links),
  314. }
  315. def main(argv=None):
  316. parser = argparse.ArgumentParser()
  317. parser.add_argument(
  318. "--state",
  319. type=Path,
  320. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  321. )
  322. parser.add_argument(
  323. "--reconcile-once",
  324. action="store_true",
  325. help=(
  326. "create missing declared links and remove only explicitly declared "
  327. "managed_unlinks once; never alter other links or restart services"
  328. ),
  329. )
  330. parser.add_argument(
  331. "--quiet-if-clean",
  332. action="store_true",
  333. help="with --reconcile-once, suppress output when no action or difference remains",
  334. )
  335. args = parser.parse_args(argv)
  336. if args.quiet_if_clean and not args.reconcile_once:
  337. parser.error("--quiet-if-clean requires --reconcile-once")
  338. try:
  339. state = load_state(args.state)
  340. if args.reconcile_once:
  341. result = reconcile_once(state)
  342. if args.quiet_if_clean and not result["actions"] and not result["differences"]:
  343. return 0
  344. print(json.dumps(result, indent=2))
  345. return 0 if not result["differences"] else 1
  346. result = subprocess.run(
  347. ["pw-link", "-l"],
  348. check=True,
  349. capture_output=True,
  350. text=True,
  351. )
  352. links = parse_pw_link_output(result.stdout)
  353. except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
  354. print(f"ERROR: {error}", file=sys.stderr)
  355. return 2
  356. reports = observe(state, links)
  357. print(
  358. json.dumps(
  359. {
  360. "mode": "observe-only",
  361. "managed_links": len(state["routing"]["managed_links"]),
  362. "managed_unlinks": len(state["routing"]["managed_unlinks"]),
  363. "differences": reports,
  364. },
  365. indent=2,
  366. )
  367. )
  368. return 0
  369. if __name__ == "__main__":
  370. raise SystemExit(main())