observe_pipewire.py 14 KB

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