observe_pipewire.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. if source not in outputs or destination not in inputs:
  181. actions.append(
  182. {
  183. "kind": "unavailable-port",
  184. "from": source,
  185. "to": destination,
  186. "result": "not-linked",
  187. }
  188. )
  189. continue
  190. try:
  191. runner(
  192. ["pw-link", source, destination],
  193. check=True,
  194. capture_output=True,
  195. text=True,
  196. )
  197. actions.append(
  198. {"kind": "link", "from": source, "to": destination, "result": "requested"}
  199. )
  200. except (OSError, subprocess.CalledProcessError) as error:
  201. detail = str(error)
  202. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  203. detail = error.stderr.strip() or detail
  204. actions.append(
  205. {
  206. "kind": "link-failed",
  207. "from": source,
  208. "to": destination,
  209. "result": detail,
  210. }
  211. )
  212. # Remove only explicitly declared stale edges, and only after every
  213. # desired managed link is present. This avoids disconnecting an old path
  214. # when its replacement could not be established.
  215. if missing_links:
  216. before_unlink_result = runner(
  217. ["pw-link", "-l"],
  218. check=True,
  219. capture_output=True,
  220. text=True,
  221. )
  222. before_unlink_links = parse_pw_link_output(before_unlink_result.stdout)
  223. else:
  224. before_unlink_links = initial_links
  225. remaining_missing = [
  226. report
  227. for report in observe(state, before_unlink_links)
  228. if report["kind"] == "missing"
  229. ]
  230. managed_ports = set(state["routing"]["managed_ports"])
  231. scheduled_unlinks = [
  232. (link["from"], link["to"])
  233. for link in state["routing"]["managed_unlinks"]
  234. if link["from"] in managed_ports
  235. and link["to"] in managed_ports
  236. and (link["from"], link["to"]) in before_unlink_links
  237. ]
  238. if remaining_missing:
  239. for source, destination in scheduled_unlinks:
  240. actions.append(
  241. {
  242. "kind": "unlink-deferred",
  243. "from": source,
  244. "to": destination,
  245. "result": "desired managed links are still missing",
  246. }
  247. )
  248. else:
  249. for source, destination in scheduled_unlinks:
  250. try:
  251. runner(
  252. ["pw-link", "-d", source, destination],
  253. check=True,
  254. capture_output=True,
  255. text=True,
  256. )
  257. actions.append(
  258. {"kind": "unlink", "from": source, "to": destination, "result": "requested"}
  259. )
  260. except (OSError, subprocess.CalledProcessError) as error:
  261. detail = str(error)
  262. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  263. detail = error.stderr.strip() or detail
  264. actions.append(
  265. {
  266. "kind": "unlink-failed",
  267. "from": source,
  268. "to": destination,
  269. "result": detail,
  270. }
  271. )
  272. final_result = runner(
  273. ["pw-link", "-l"],
  274. check=True,
  275. capture_output=True,
  276. text=True,
  277. )
  278. final_links = parse_pw_link_output(final_result.stdout)
  279. return {
  280. "mode": "reconcile-once",
  281. "managed_links": len(state["routing"]["managed_links"]),
  282. "managed_unlinks": len(state["routing"]["managed_unlinks"]),
  283. "actions": actions,
  284. "differences": observe(state, final_links),
  285. }
  286. def main(argv=None):
  287. parser = argparse.ArgumentParser()
  288. parser.add_argument(
  289. "--state",
  290. type=Path,
  291. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  292. )
  293. parser.add_argument(
  294. "--reconcile-once",
  295. action="store_true",
  296. help=(
  297. "create missing declared links and remove only explicitly declared "
  298. "managed_unlinks once; never alter other links or restart services"
  299. ),
  300. )
  301. args = parser.parse_args(argv)
  302. try:
  303. state = load_state(args.state)
  304. if args.reconcile_once:
  305. result = reconcile_once(state)
  306. print(json.dumps(result, indent=2))
  307. return 0 if not result["differences"] else 1
  308. result = subprocess.run(
  309. ["pw-link", "-l"],
  310. check=True,
  311. capture_output=True,
  312. text=True,
  313. )
  314. links = parse_pw_link_output(result.stdout)
  315. except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
  316. print(f"ERROR: {error}", file=sys.stderr)
  317. return 2
  318. reports = observe(state, links)
  319. print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
  320. return 0
  321. if __name__ == "__main__":
  322. raise SystemExit(main())