configure_mod_host.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. import argparse
  2. import socket
  3. import subprocess
  4. import sys
  5. import time
  6. from pathlib import Path, PurePosixPath
  7. import yaml
  8. from validate_desired_state import validate_state
  9. def run(command):
  10. return subprocess.run(command, check=True, capture_output=True, text=True)
  11. def mod_host_command(port, command, timeout=10):
  12. payload = command.encode("utf-8") + b"\0"
  13. with socket.create_connection(("127.0.0.1", port), timeout=timeout) as connection:
  14. connection.settimeout(timeout)
  15. connection.sendall(payload)
  16. response = bytearray()
  17. while b"\0" not in response:
  18. chunk = connection.recv(4096)
  19. if not chunk:
  20. raise RuntimeError(f"mod-host closed the socket before replying to {command!r}")
  21. response.extend(chunk)
  22. return bytes(response).split(b"\0", 1)[0].decode("utf-8", errors="replace")
  23. def response_status(response, command):
  24. fields = response.split()
  25. if len(fields) < 2 or fields[0] != "resp":
  26. raise RuntimeError(f"unexpected mod-host response to {command!r}: {response!r}")
  27. try:
  28. status = int(fields[1])
  29. except ValueError as error:
  30. raise RuntimeError(f"invalid mod-host response to {command!r}: {response!r}") from error
  31. if status < 0:
  32. raise RuntimeError(f"mod-host rejected {command!r}: {response}")
  33. return status
  34. def ensure_plugin(port, processor, bundle_path, command=mod_host_command):
  35. instance = processor["instance"]
  36. add_command = f"add {processor['plugin_uri']} {instance}"
  37. response = command(port, add_command)
  38. fields = response.split()
  39. if fields == ["resp", "-101"]:
  40. bundle_command = f"bundle_add {bundle_path}"
  41. response_status(command(port, bundle_command), bundle_command)
  42. response = command(port, add_command)
  43. status = response_status(response, add_command)
  44. if status != instance:
  45. raise RuntimeError(
  46. f"mod-host returned instance {status} for requested instance {instance}"
  47. )
  48. def wait_for_mod_host(port, timeout=20, command=mod_host_command, sleeper=time.sleep):
  49. deadline = time.monotonic() + timeout
  50. last_error = None
  51. while True:
  52. try:
  53. response_status(command(port, "cpu_load"), "cpu_load")
  54. return
  55. except OSError as error:
  56. last_error = error
  57. if time.monotonic() >= deadline:
  58. raise RuntimeError(f"mod-host control socket did not become ready: {last_error}")
  59. sleeper(0.2)
  60. def parse_links(text):
  61. links = set()
  62. current_source = None
  63. for line in text.splitlines():
  64. if not line.strip():
  65. continue
  66. if line.startswith(" |-> "):
  67. if current_source is None:
  68. raise RuntimeError("pw-link output has a destination without a source")
  69. links.add((current_source, line.removeprefix(" |-> ")))
  70. elif line.startswith(" |<- "):
  71. if current_source is None:
  72. raise RuntimeError("pw-link output has a destination without a source")
  73. links.add((line.removeprefix(" |<- "), current_source))
  74. else:
  75. current_source = line.strip()
  76. return links
  77. def list_ports(direction, runner=run):
  78. result = runner(["pw-link", direction])
  79. return {line.strip() for line in result.stdout.splitlines() if line.strip()}
  80. def wait_for_ports(required_outputs, required_inputs, timeout=20, runner=run, sleeper=time.sleep):
  81. deadline = time.monotonic() + timeout
  82. while True:
  83. outputs = list_ports("-o", runner)
  84. inputs = list_ports("-i", runner)
  85. missing_outputs = required_outputs - outputs
  86. missing_inputs = required_inputs - inputs
  87. if not missing_outputs and not missing_inputs:
  88. return
  89. if time.monotonic() >= deadline:
  90. raise RuntimeError(
  91. "mod-host ports did not appear; "
  92. f"missing outputs={sorted(missing_outputs)}, inputs={sorted(missing_inputs)}"
  93. )
  94. sleeper(0.2)
  95. def resolve_asset(repo_root, relative_path):
  96. path = PurePosixPath(relative_path)
  97. if path.is_absolute() or ".." in path.parts or not path.parts:
  98. raise RuntimeError(f"unsafe repository asset path: {relative_path!r}")
  99. resolved = (repo_root / Path(*path.parts)).resolve()
  100. if not resolved.is_relative_to(repo_root.resolve()) or not resolved.is_file():
  101. raise RuntimeError(f"declared mod-host asset is missing or escapes the repository: {resolved}")
  102. return resolved
  103. def configure(state, repo_root, runner=run, sleeper=time.sleep, command=mod_host_command):
  104. deployment = state["deployment"]["mod_host"]
  105. chain = state["routing"]["mod_host_chains"]["guitar"]
  106. port = deployment["socket_port"]
  107. processors = chain["processors"]
  108. # A short, read-only command both waits for socket readiness and exercises
  109. # the same NUL-terminated protocol used for all subsequent control requests.
  110. wait_for_mod_host(port, command=command, sleeper=sleeper)
  111. for processor in processors:
  112. bundle_relative = PurePosixPath(processor["bundle_path"])
  113. if bundle_relative.is_absolute() or ".." in bundle_relative.parts:
  114. raise RuntimeError(f"unsafe LV2 bundle path: {processor['bundle_path']!r}")
  115. bundle_path = Path.home().joinpath(*bundle_relative.parts)
  116. asset_path = resolve_asset(repo_root, processor["asset_path"])
  117. ensure_plugin(port, processor, bundle_path, command=command)
  118. patch_command = (
  119. f"patch_set {processor['instance']} {processor['file_property']} {asset_path}"
  120. )
  121. response_status(command(port, patch_command), patch_command)
  122. for symbol, value in processor.get("parameters", {}).items():
  123. parameter_command = f"param_set {processor['instance']} {symbol} {value}"
  124. response_status(command(port, parameter_command), parameter_command)
  125. first = processors[0]
  126. required_outputs = {chain["source_port"]}
  127. required_inputs = {chain["mix_input"]}
  128. for processor in processors:
  129. required_inputs.add(processor["input_port"])
  130. required_outputs.add(processor["output_port"])
  131. wait_for_ports(required_outputs, required_inputs, runner=runner, sleeper=sleeper)
  132. result = runner(["pw-link", "-l"])
  133. links = parse_links(result.stdout)
  134. expected_links = []
  135. for source, destination in zip(processors, processors[1:]):
  136. expected_links.append((source["output_port"], destination["input_port"]))
  137. expected_links.append((processors[-1]["output_port"], chain["mix_input"]))
  138. for source, destination in expected_links:
  139. if (source, destination) not in links:
  140. runner(["pw-link", source, destination])
  141. links.add((source, destination))
  142. bypass = (chain["bypass_link"]["from"], chain["bypass_link"]["to"])
  143. if bypass in links:
  144. runner(["pw-link", "-d", bypass[0], bypass[1]])
  145. links.remove(bypass)
  146. source_link = (chain["source_port"], first["input_port"])
  147. if source_link not in links:
  148. runner(["pw-link", source_link[0], source_link[1]])
  149. links.add(source_link)
  150. result = runner(["pw-link", "-l"])
  151. final_links = parse_links(result.stdout)
  152. expected_links.append(source_link)
  153. missing = [link for link in expected_links if link not in final_links]
  154. if missing:
  155. raise RuntimeError(f"mod-host chain links are still missing: {missing}")
  156. if bypass in final_links:
  157. raise RuntimeError("direct guitar bypass link remains connected")
  158. return {
  159. "instances": [processor["instance"] for processor in processors],
  160. "links": expected_links,
  161. "bypass_disconnected": bypass not in final_links,
  162. }
  163. def main(argv=None):
  164. root = Path(__file__).resolve().parents[1]
  165. parser = argparse.ArgumentParser()
  166. parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
  167. parser.add_argument("--repo-root", type=Path, default=root)
  168. args = parser.parse_args(argv)
  169. try:
  170. with args.state.open(encoding="utf-8") as stream:
  171. state = yaml.safe_load(stream)
  172. errors = validate_state(state)
  173. if errors:
  174. raise ValueError("invalid desired state: " + "; ".join(errors))
  175. result = configure(state, args.repo_root.resolve())
  176. except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError,
  177. subprocess.CalledProcessError) as error:
  178. print(f"ERROR: {error}", file=sys.stderr)
  179. return 1
  180. print(f"Configured mod-host chain: {result}")
  181. return 0
  182. if __name__ == "__main__":
  183. raise SystemExit(main())