| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- #!/usr/bin/env python3
- """Run mod-ui under pw-jack and keep its mod-host session active."""
- import argparse
- import http.client
- import signal
- import subprocess
- import sys
- import time
- from pathlib import Path
- from urllib.request import urlopen
- from mod_ui_websocket import ModUiWebSocketClient
- def run_service(
- launcher,
- pw_jack,
- host,
- port,
- websocket_path,
- timeout,
- popen=subprocess.Popen,
- healthcheck=None,
- ):
- """Launch mod-ui and retain the WebSocket session needed by mod-host.
- This process supervises mod-ui and owns its session connection only. It
- deliberately does not decide whether the pedalboard loaded or whether
- PipeWire links are present; those are separate diagnostics.
- """
- process = popen([str(pw_jack), str(launcher)])
- stopping = [False]
- def request_stop(_signum, _frame):
- stopping[0] = True
- old_term = signal.signal(signal.SIGTERM, request_stop)
- old_int = signal.signal(signal.SIGINT, request_stop)
- client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
- check_health = healthcheck or (lambda: check_http_health(host, port, timeout=2))
- deadline = time.monotonic() + timeout
- try:
- if not stopping[0]:
- deadline = time.monotonic() + timeout
- while not stopping[0] and time.monotonic() < deadline:
- if process.poll() is not None:
- raise RuntimeError(
- f"mod-ui launcher exited with status {process.returncode}"
- )
- try:
- if check_health():
- break
- except (OSError, TimeoutError, http.client.HTTPException):
- pass
- time.sleep(0.25)
- else:
- if not stopping[0]:
- raise RuntimeError("mod-ui HTTP endpoint did not become ready")
- print("mod-ui HTTP endpoint ready")
- next_connect_attempt = 0.0
- while not stopping[0]:
- if process.poll() is not None:
- raise RuntimeError(
- f"mod-ui launcher exited with status {process.returncode}"
- )
- try:
- if client.connection is None:
- if time.monotonic() < next_connect_attempt:
- time.sleep(min(0.25, next_connect_attempt - time.monotonic()))
- continue
- try:
- client.connect()
- print("mod-ui WebSocket session active; keeping mod-host connected")
- except (OSError, TimeoutError):
- client.close()
- client = ModUiWebSocketClient(
- host, port, websocket_path, timeout=2
- )
- next_connect_attempt = time.monotonic() + 0.25
- continue
- if not getattr(client, "session_ready", False):
- try:
- client.wait_for_loading_start()
- except (OSError, TimeoutError, ConnectionError):
- client.close()
- client = ModUiWebSocketClient(
- host, port, websocket_path, timeout=2
- )
- next_connect_attempt = time.monotonic() + 0.25
- continue
- print("mod-ui WebSocket session initialized")
- client.serve_once(timeout=0.5)
- except (OSError, TimeoutError, ConnectionError):
- client.close()
- client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
- next_connect_attempt = time.monotonic() + 0.25
- finally:
- signal.signal(signal.SIGTERM, old_term)
- signal.signal(signal.SIGINT, old_int)
- client.close()
- if process.poll() is None:
- process.terminate()
- try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- process.kill()
- process.wait()
- def check_http_health(host, port, timeout=2):
- with urlopen(f"http://{host}:{port}/ping/", timeout=timeout) as response:
- return 200 <= response.status < 400
- def main(argv=None):
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--launcher", type=Path, required=True)
- parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
- parser.add_argument("--host", default="127.0.0.1")
- parser.add_argument("--port", type=int, default=8888)
- parser.add_argument("--websocket-path", default="/websocket")
- parser.add_argument("--timeout", type=float, default=60)
- args = parser.parse_args(argv)
- if not args.launcher.is_file():
- print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
- return 1
- if not args.pw_jack.is_file():
- print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
- return 1
- try:
- run_service(
- args.launcher,
- args.pw_jack,
- args.host,
- args.port,
- args.websocket_path,
- args.timeout,
- )
- except (OSError, RuntimeError, ValueError) as error:
- print(f"ERROR: {error}", file=sys.stderr)
- return 1
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|