observe_pipewire.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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. return errors
  68. def parse_pw_link_output(text):
  69. links = set()
  70. current_source = None
  71. for line in text.splitlines():
  72. if not line.strip():
  73. continue
  74. if line.startswith(" |-> "):
  75. if current_source is None:
  76. raise ValueError("pw-link output has a destination without a source")
  77. destination = line.removeprefix(" |-> ")
  78. links.add((current_source, destination))
  79. continue
  80. if line.startswith(" |<- "):
  81. destination = line.removeprefix(" |<- ")
  82. links.add((destination, current_source))
  83. continue
  84. current_source = line.strip()
  85. return links
  86. def observe(state, links):
  87. managed_ports = set(state["routing"]["managed_ports"])
  88. managed = {
  89. (link["from"], link["to"])
  90. for link in state["routing"]["managed_links"]
  91. if link["status"] in {"planned", "observed"}
  92. }
  93. observed_managed = {
  94. link
  95. for link in links
  96. if link[0] in managed_ports and link[1] in managed_ports
  97. }
  98. reports = []
  99. for source, destination in sorted(managed - observed_managed):
  100. reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
  101. for source, destination in sorted(observed_managed - managed):
  102. reports.append({"kind": "unexpected", "from": source, "to": destination, "action": "would-review"})
  103. return reports
  104. def list_ports(runner, direction):
  105. result = runner(
  106. ["pw-link", direction],
  107. check=True,
  108. capture_output=True,
  109. text=True,
  110. )
  111. return {line.strip() for line in result.stdout.splitlines() if line.strip()}
  112. def reconcile_once(state, runner=subprocess.run):
  113. initial_result = runner(
  114. ["pw-link", "-l"],
  115. check=True,
  116. capture_output=True,
  117. text=True,
  118. )
  119. initial_links = parse_pw_link_output(initial_result.stdout)
  120. initial_reports = observe(state, initial_links)
  121. missing_links = [report for report in initial_reports if report["kind"] == "missing"]
  122. actions = []
  123. if missing_links:
  124. outputs = list_ports(runner, "-o")
  125. inputs = list_ports(runner, "-i")
  126. for report in missing_links:
  127. source = report["from"]
  128. destination = report["to"]
  129. if source not in outputs or destination not in inputs:
  130. actions.append(
  131. {
  132. "kind": "unavailable-port",
  133. "from": source,
  134. "to": destination,
  135. "result": "not-linked",
  136. }
  137. )
  138. continue
  139. try:
  140. runner(
  141. ["pw-link", source, destination],
  142. check=True,
  143. capture_output=True,
  144. text=True,
  145. )
  146. actions.append(
  147. {"kind": "link", "from": source, "to": destination, "result": "requested"}
  148. )
  149. except (OSError, subprocess.CalledProcessError) as error:
  150. detail = str(error)
  151. if isinstance(error, subprocess.CalledProcessError) and error.stderr:
  152. detail = error.stderr.strip() or detail
  153. actions.append(
  154. {
  155. "kind": "link-failed",
  156. "from": source,
  157. "to": destination,
  158. "result": detail,
  159. }
  160. )
  161. final_result = runner(
  162. ["pw-link", "-l"],
  163. check=True,
  164. capture_output=True,
  165. text=True,
  166. )
  167. final_links = parse_pw_link_output(final_result.stdout)
  168. return {
  169. "mode": "reconcile-once",
  170. "managed_links": len(state["routing"]["managed_links"]),
  171. "actions": actions,
  172. "differences": observe(state, final_links),
  173. }
  174. def main(argv=None):
  175. parser = argparse.ArgumentParser()
  176. parser.add_argument(
  177. "--state",
  178. type=Path,
  179. default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
  180. )
  181. parser.add_argument(
  182. "--reconcile-once",
  183. action="store_true",
  184. help="create missing declared links once; never remove links or restart services",
  185. )
  186. args = parser.parse_args(argv)
  187. try:
  188. state = load_state(args.state)
  189. if args.reconcile_once:
  190. result = reconcile_once(state)
  191. print(json.dumps(result, indent=2))
  192. return 0 if not result["differences"] else 1
  193. result = subprocess.run(
  194. ["pw-link", "-l"],
  195. check=True,
  196. capture_output=True,
  197. text=True,
  198. )
  199. links = parse_pw_link_output(result.stdout)
  200. except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
  201. print(f"ERROR: {error}", file=sys.stderr)
  202. return 2
  203. reports = observe(state, links)
  204. print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
  205. return 0
  206. if __name__ == "__main__":
  207. raise SystemExit(main())