observe_pipewire.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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")$"
  16. )
  17. def load_state(path):
  18. with path.open(encoding="utf-8") as state_stream:
  19. state = yaml.safe_load(state_stream)
  20. errors = validate_desired_state(state)
  21. errors.extend(validate_managed_links(state))
  22. if errors:
  23. raise ValueError("invalid desired state: " + "; ".join(errors))
  24. return state
  25. def validate_managed_links(state):
  26. errors = []
  27. if not isinstance(state, dict):
  28. return ["document root must be a mapping"]
  29. routing = state.get("routing")
  30. if not isinstance(routing, dict):
  31. return ["routing must be a mapping"]
  32. managed_ports = routing.get("managed_ports")
  33. if not isinstance(managed_ports, list):
  34. errors.append("routing.managed_ports must be a list")
  35. managed_ports = []
  36. for index, port in enumerate(managed_ports):
  37. if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port):
  38. errors.append(f"routing.managed_ports[{index}] is not an approved observed Rigforge or UMC port")
  39. if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))):
  40. errors.append("routing.managed_ports must not contain duplicate ports")
  41. managed_links = routing.get("managed_links")
  42. if not isinstance(managed_links, list):
  43. errors.append("routing.managed_links must be a list")
  44. managed_links = []
  45. for index, link in enumerate(managed_links):
  46. if not isinstance(link, dict):
  47. errors.append(f"routing.managed_links[{index}] must be a mapping")
  48. continue
  49. source = link.get("from")
  50. destination = link.get("to")
  51. if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
  52. errors.append(f"routing.managed_links[{index}].from is not an approved observed Rigforge or UMC port")
  53. if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
  54. errors.append(f"routing.managed_links[{index}].to is not an approved observed Rigforge or UMC port")
  55. if (
  56. isinstance(source, str)
  57. and isinstance(destination, str)
  58. and (source not in managed_ports or destination not in managed_ports)
  59. ):
  60. errors.append(f"routing.managed_links[{index}] endpoints must be listed in routing.managed_ports")
  61. if source == destination:
  62. errors.append(f"routing.managed_links[{index}] cannot link a port to itself")
  63. if link.get("status") not in {"planned", "observed"}:
  64. errors.append(f"routing.managed_links[{index}].status must be planned or observed")
  65. return errors
  66. def parse_pw_link_output(text):
  67. links = set()
  68. current_source = None
  69. for line in text.splitlines():
  70. if not line.strip():
  71. continue
  72. if line.startswith(" |-> "):
  73. if current_source is None:
  74. raise ValueError("pw-link output has a destination without a source")
  75. destination = line.removeprefix(" |-> ")
  76. links.add((current_source, destination))
  77. continue
  78. if line.startswith(" |<- "):
  79. destination = line.removeprefix(" |<- ")
  80. links.add((destination, current_source))
  81. continue
  82. current_source = line.strip()
  83. return links
  84. def observe(state, links):
  85. managed_ports = set(state["routing"]["managed_ports"])
  86. managed = {
  87. (link["from"], link["to"])
  88. for link in state["routing"]["managed_links"]
  89. if link["status"] in {"planned", "observed"}
  90. }
  91. observed_managed = {
  92. link
  93. for link in links
  94. if link[0] in managed_ports and link[1] in managed_ports
  95. }
  96. reports = []
  97. for source, destination in sorted(managed - observed_managed):
  98. reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
  99. for source, destination in sorted(observed_managed - managed):
  100. reports.append({"kind": "unexpected", "from": source, "to": destination, "action": "would-review"})
  101. return reports
  102. def list_ports(runner, direction):
  103. result = runner(
  104. ["pw-link", direction],
  105. check=True,
  106. capture_output=True,
  107. text=True,
  108. )
  109. return {line.strip() for line in result.stdout.splitlines() if line.strip()}
  110. def reconcile_once(state, runner=subprocess.run):
  111. initial_result = runner(
  112. ["pw-link", "-l"],
  113. check=True,
  114. capture_output=True,
  115. text=True,
  116. )
  117. initial_links = parse_pw_link_output(initial_result.stdout)
  118. initial_reports = observe(state, initial_links)
  119. missing_links = [report for report in initial_reports if report["kind"] == "missing"]
  120. actions = []
  121. if missing_links:
  122. outputs = list_ports(runner, "-o")
  123. inputs = list_ports(runner, "-i")
  124. for report in missing_links:
  125. source = report["from"]
  126. destination = report["to"]
  127. if source not in outputs or destination not in inputs:
  128. actions.append(
  129. {
  130. "kind": "unavailable-port",
  131. "from": source,
  132. "to": destination,
  133. "result": "not-linked",
  134. }
  135. )
  136. continue
  137. try:
  138. runner(
  139. ["pw-link", source, destination],
  140. check=True,
  141. capture_output=True,
  142. text=True,
  143. )
  144. actions.append(
  145. {"kind": "link", "from": source, "to": destination, "result": "requested"}
  146. )
  147. except (OSError, subprocess.CalledProcessError) as error:
  148. detail = str(error)
  149. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  150. detail = error.stderr.strip() or detail
  151. actions.append(
  152. {
  153. "kind": "link-failed",
  154. "from": source,
  155. "to": destination,
  156. "result": detail,
  157. }
  158. )
  159. final_result = runner(
  160. ["pw-link", "-l"],
  161. check=True,
  162. capture_output=True,
  163. text=True,
  164. )
  165. final_links = parse_pw_link_output(final_result.stdout)
  166. return {
  167. "mode": "reconcile-once",
  168. "managed_links": len(state["routing"]["managed_links"]),
  169. "actions": actions,
  170. "differences": observe(state, final_links),
  171. }
  172. def main(argv=None):
  173. parser = argparse.ArgumentParser()
  174. parser.add_argument(
  175. "--state",
  176. type=Path,
  177. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  178. )
  179. parser.add_argument(
  180. "--reconcile-once",
  181. action="store_true",
  182. help="create missing declared links once; never remove links or restart services",
  183. )
  184. args = parser.parse_args(argv)
  185. try:
  186. state = load_state(args.state)
  187. if args.reconcile_once:
  188. result = reconcile_once(state)
  189. print(json.dumps(result, indent=2))
  190. return 0 if not result["differences"] else 1
  191. result = subprocess.run(
  192. ["pw-link", "-l"],
  193. check=True,
  194. capture_output=True,
  195. text=True,
  196. )
  197. links = parse_pw_link_output(result.stdout)
  198. except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
  199. print(f"ERROR: {error}", file=sys.stderr)
  200. return 2
  201. reports = observe(state, links)
  202. print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
  203. return 0
  204. if __name__ == "__main__":
  205. raise SystemExit(main())