| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230 |
- import argparse
- import json
- import re
- import subprocess
- import sys
- from pathlib import Path
- import yaml
- from validate_desired_state import validate_state as validate_desired_state
- MANAGED_ENDPOINT_PATTERN = re.compile(
- r"^(?:"
- r"alsa_input\.hw_U192k_0:capture_AUX[0-3]|"
- r"alsa_output\.hw_U192k_0:playback_AUX[0-3]|"
- r"rigforge\.direct-mix\.input:playback_AUX[0-3]|"
- r"rigforge\.direct-mix\.output:capture_FL"
- r")$"
- )
- def load_state(path):
- with path.open(encoding="utf-8") as state_stream:
- state = yaml.safe_load(state_stream)
- errors = validate_desired_state(state)
- errors.extend(validate_managed_links(state))
- if errors:
- raise ValueError("invalid desired state: " + "; ".join(errors))
- return state
- def validate_managed_links(state):
- errors = []
- if not isinstance(state, dict):
- return ["document root must be a mapping"]
- routing = state.get("routing")
- if not isinstance(routing, dict):
- return ["routing must be a mapping"]
- managed_ports = routing.get("managed_ports")
- if not isinstance(managed_ports, list):
- errors.append("routing.managed_ports must be a list")
- managed_ports = []
- for index, port in enumerate(managed_ports):
- if not isinstance(port, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(port):
- errors.append(f"routing.managed_ports[{index}] is not an approved observed Rigforge or UMC port")
- if len(managed_ports) != len(set(port for port in managed_ports if isinstance(port, str))):
- errors.append("routing.managed_ports must not contain duplicate ports")
- managed_links = routing.get("managed_links")
- if not isinstance(managed_links, list):
- errors.append("routing.managed_links must be a list")
- managed_links = []
- for index, link in enumerate(managed_links):
- if not isinstance(link, dict):
- errors.append(f"routing.managed_links[{index}] must be a mapping")
- continue
- source = link.get("from")
- destination = link.get("to")
- if not isinstance(source, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(source):
- errors.append(f"routing.managed_links[{index}].from is not an approved observed Rigforge or UMC port")
- if not isinstance(destination, str) or not MANAGED_ENDPOINT_PATTERN.fullmatch(destination):
- errors.append(f"routing.managed_links[{index}].to is not an approved observed Rigforge or UMC port")
- if (
- isinstance(source, str)
- and isinstance(destination, str)
- and (source not in managed_ports or destination not in managed_ports)
- ):
- errors.append(f"routing.managed_links[{index}] endpoints must be listed in routing.managed_ports")
- if source == destination:
- errors.append(f"routing.managed_links[{index}] cannot link a port to itself")
- if link.get("status") not in {"planned", "observed"}:
- errors.append(f"routing.managed_links[{index}].status must be planned or observed")
- return errors
- def parse_pw_link_output(text):
- links = set()
- current_source = None
- for line in text.splitlines():
- if not line.strip():
- continue
- if line.startswith(" |-> "):
- if current_source is None:
- raise ValueError("pw-link output has a destination without a source")
- destination = line.removeprefix(" |-> ")
- links.add((current_source, destination))
- continue
- if line.startswith(" |<- "):
- destination = line.removeprefix(" |<- ")
- links.add((destination, current_source))
- continue
- current_source = line.strip()
- return links
- def observe(state, links):
- managed_ports = set(state["routing"]["managed_ports"])
- managed = {
- (link["from"], link["to"])
- for link in state["routing"]["managed_links"]
- if link["status"] in {"planned", "observed"}
- }
- observed_managed = {
- link
- for link in links
- if link[0] in managed_ports and link[1] in managed_ports
- }
- reports = []
- for source, destination in sorted(managed - observed_managed):
- reports.append({"kind": "missing", "from": source, "to": destination, "action": "would-link"})
- for source, destination in sorted(observed_managed - managed):
- reports.append({"kind": "unexpected", "from": source, "to": destination, "action": "would-review"})
- return reports
- def list_ports(runner, direction):
- result = runner(
- ["pw-link", direction],
- check=True,
- capture_output=True,
- text=True,
- )
- return {line.strip() for line in result.stdout.splitlines() if line.strip()}
- def reconcile_once(state, runner=subprocess.run):
- initial_result = runner(
- ["pw-link", "-l"],
- check=True,
- capture_output=True,
- text=True,
- )
- initial_links = parse_pw_link_output(initial_result.stdout)
- initial_reports = observe(state, initial_links)
- missing_links = [report for report in initial_reports if report["kind"] == "missing"]
- actions = []
- if missing_links:
- outputs = list_ports(runner, "-o")
- inputs = list_ports(runner, "-i")
- for report in missing_links:
- source = report["from"]
- destination = report["to"]
- if source not in outputs or destination not in inputs:
- actions.append(
- {
- "kind": "unavailable-port",
- "from": source,
- "to": destination,
- "result": "not-linked",
- }
- )
- continue
- try:
- runner(
- ["pw-link", source, destination],
- check=True,
- capture_output=True,
- text=True,
- )
- actions.append(
- {"kind": "link", "from": source, "to": destination, "result": "requested"}
- )
- except (OSError, subprocess.CalledProcessError) as error:
- detail = str(error)
- if isinstance(error, subprocess.CalledProcessError) and error.stderr:
- detail = error.stderr.strip() or detail
- actions.append(
- {
- "kind": "link-failed",
- "from": source,
- "to": destination,
- "result": detail,
- }
- )
- final_result = runner(
- ["pw-link", "-l"],
- check=True,
- capture_output=True,
- text=True,
- )
- final_links = parse_pw_link_output(final_result.stdout)
- return {
- "mode": "reconcile-once",
- "managed_links": len(state["routing"]["managed_links"]),
- "actions": actions,
- "differences": observe(state, final_links),
- }
- def main(argv=None):
- parser = argparse.ArgumentParser()
- parser.add_argument(
- "--state",
- type=Path,
- default=Path(__file__).resolve().parents[1] / "config" / "desired-state.yaml",
- )
- parser.add_argument(
- "--reconcile-once",
- action="store_true",
- help="create missing declared links once; never remove links or restart services",
- )
- args = parser.parse_args(argv)
- try:
- state = load_state(args.state)
- if args.reconcile_once:
- result = reconcile_once(state)
- print(json.dumps(result, indent=2))
- return 0 if not result["differences"] else 1
- result = subprocess.run(
- ["pw-link", "-l"],
- check=True,
- capture_output=True,
- text=True,
- )
- links = parse_pw_link_output(result.stdout)
- except (OSError, subprocess.CalledProcessError, ValueError, yaml.YAMLError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 2
- reports = observe(state, links)
- print(json.dumps({"mode": "observe-only", "managed_links": len(state["routing"]["managed_links"]), "differences": reports}, indent=2))
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|