observe_pipewire.py 14 KB

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