| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 |
- import argparse
- import socket
- import subprocess
- import sys
- import time
- from pathlib import Path, PurePosixPath
- import yaml
- from validate_desired_state import validate_state
- def run(command):
- return subprocess.run(command, check=True, capture_output=True, text=True)
- def mod_host_command(port, command, timeout=10):
- payload = command.encode("utf-8") + b"\0"
- with socket.create_connection(("127.0.0.1", port), timeout=timeout) as connection:
- connection.settimeout(timeout)
- connection.sendall(payload)
- response = bytearray()
- while b"\0" not in response:
- chunk = connection.recv(4096)
- if not chunk:
- raise RuntimeError(f"mod-host closed the socket before replying to {command!r}")
- response.extend(chunk)
- return bytes(response).split(b"\0", 1)[0].decode("utf-8", errors="replace")
- def response_status(response, command):
- fields = response.split()
- if len(fields) < 2 or fields[0] != "resp":
- raise RuntimeError(f"unexpected mod-host response to {command!r}: {response!r}")
- try:
- status = int(fields[1])
- except ValueError as error:
- raise RuntimeError(f"invalid mod-host response to {command!r}: {response!r}") from error
- if status < 0:
- raise RuntimeError(f"mod-host rejected {command!r}: {response}")
- return status
- def ensure_plugin(port, processor, bundle_path, command=mod_host_command):
- instance = processor["instance"]
- add_command = f"add {processor['plugin_uri']} {instance}"
- response = command(port, add_command)
- fields = response.split()
- if fields == ["resp", "-101"]:
- bundle_command = f"bundle_add {bundle_path}"
- response_status(command(port, bundle_command), bundle_command)
- response = command(port, add_command)
- status = response_status(response, add_command)
- if status != instance:
- raise RuntimeError(
- f"mod-host returned instance {status} for requested instance {instance}"
- )
- def wait_for_mod_host(port, timeout=20, command=mod_host_command, sleeper=time.sleep):
- deadline = time.monotonic() + timeout
- last_error = None
- while True:
- try:
- response_status(command(port, "cpu_load"), "cpu_load")
- return
- except OSError as error:
- last_error = error
- if time.monotonic() >= deadline:
- raise RuntimeError(f"mod-host control socket did not become ready: {last_error}")
- sleeper(0.2)
- def parse_links(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 RuntimeError("pw-link output has a destination without a source")
- links.add((current_source, line.removeprefix(" |-> ")))
- elif line.startswith(" |<- "):
- if current_source is None:
- raise RuntimeError("pw-link output has a destination without a source")
- links.add((line.removeprefix(" |<- "), current_source))
- else:
- current_source = line.strip()
- return links
- def list_ports(direction, runner=run):
- result = runner(["pw-link", direction])
- return {line.strip() for line in result.stdout.splitlines() if line.strip()}
- def wait_for_ports(required_outputs, required_inputs, timeout=20, runner=run, sleeper=time.sleep):
- deadline = time.monotonic() + timeout
- while True:
- outputs = list_ports("-o", runner)
- inputs = list_ports("-i", runner)
- missing_outputs = required_outputs - outputs
- missing_inputs = required_inputs - inputs
- if not missing_outputs and not missing_inputs:
- return
- if time.monotonic() >= deadline:
- raise RuntimeError(
- "mod-host ports did not appear; "
- f"missing outputs={sorted(missing_outputs)}, inputs={sorted(missing_inputs)}"
- )
- sleeper(0.2)
- def resolve_asset(repo_root, relative_path):
- path = PurePosixPath(relative_path)
- if path.is_absolute() or ".." in path.parts or not path.parts:
- raise RuntimeError(f"unsafe repository asset path: {relative_path!r}")
- resolved = (repo_root / Path(*path.parts)).resolve()
- if not resolved.is_relative_to(repo_root.resolve()) or not resolved.is_file():
- raise RuntimeError(f"declared mod-host asset is missing or escapes the repository: {resolved}")
- return resolved
- def configure(state, repo_root, runner=run, sleeper=time.sleep, command=mod_host_command):
- deployment = state["deployment"]["mod_host"]
- chain = state["routing"]["mod_host_chains"]["guitar"]
- port = deployment["socket_port"]
- processors = chain["processors"]
- # A short, read-only command both waits for socket readiness and exercises
- # the same NUL-terminated protocol used for all subsequent control requests.
- wait_for_mod_host(port, command=command, sleeper=sleeper)
- for processor in processors:
- bundle_relative = PurePosixPath(processor["bundle_path"])
- if bundle_relative.is_absolute() or ".." in bundle_relative.parts:
- raise RuntimeError(f"unsafe LV2 bundle path: {processor['bundle_path']!r}")
- bundle_path = Path.home().joinpath(*bundle_relative.parts)
- asset_path = resolve_asset(repo_root, processor["asset_path"])
- ensure_plugin(port, processor, bundle_path, command=command)
- patch_command = (
- f"patch_set {processor['instance']} {processor['file_property']} {asset_path}"
- )
- response_status(command(port, patch_command), patch_command)
- for symbol, value in processor.get("parameters", {}).items():
- parameter_command = f"param_set {processor['instance']} {symbol} {value}"
- response_status(command(port, parameter_command), parameter_command)
- first = processors[0]
- required_outputs = {chain["source_port"]}
- required_inputs = {chain["mix_input"]}
- for processor in processors:
- required_inputs.add(processor["input_port"])
- required_outputs.add(processor["output_port"])
- wait_for_ports(required_outputs, required_inputs, runner=runner, sleeper=sleeper)
- result = runner(["pw-link", "-l"])
- links = parse_links(result.stdout)
- expected_links = []
- for source, destination in zip(processors, processors[1:]):
- expected_links.append((source["output_port"], destination["input_port"]))
- expected_links.append((processors[-1]["output_port"], chain["mix_input"]))
- for source, destination in expected_links:
- if (source, destination) not in links:
- runner(["pw-link", source, destination])
- links.add((source, destination))
- bypass = (chain["bypass_link"]["from"], chain["bypass_link"]["to"])
- if bypass in links:
- runner(["pw-link", "-d", bypass[0], bypass[1]])
- links.remove(bypass)
- source_link = (chain["source_port"], first["input_port"])
- if source_link not in links:
- runner(["pw-link", source_link[0], source_link[1]])
- links.add(source_link)
- result = runner(["pw-link", "-l"])
- final_links = parse_links(result.stdout)
- expected_links.append(source_link)
- missing = [link for link in expected_links if link not in final_links]
- if missing:
- raise RuntimeError(f"mod-host chain links are still missing: {missing}")
- if bypass in final_links:
- raise RuntimeError("direct guitar bypass link remains connected")
- return {
- "instances": [processor["instance"] for processor in processors],
- "links": expected_links,
- "bypass_disconnected": bypass not in final_links,
- }
- def main(argv=None):
- root = Path(__file__).resolve().parents[1]
- parser = argparse.ArgumentParser()
- parser.add_argument("--state", type=Path, default=root / "config" / "desired-state.yaml")
- parser.add_argument("--repo-root", type=Path, default=root)
- args = parser.parse_args(argv)
- try:
- with args.state.open(encoding="utf-8") as stream:
- state = yaml.safe_load(stream)
- errors = validate_state(state)
- if errors:
- raise ValueError("invalid desired state: " + "; ".join(errors))
- result = configure(state, args.repo_root.resolve())
- except (OSError, RuntimeError, ValueError, KeyError, TypeError, yaml.YAMLError,
- subprocess.CalledProcessError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- print(f"Configured mod-host chain: {result}")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|