run_mod_ui_service.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. #!/usr/bin/env python3
  2. """Run mod-ui under pw-jack and keep its mod-host session active."""
  3. import argparse
  4. import http.client
  5. import signal
  6. import subprocess
  7. import sys
  8. import time
  9. from pathlib import Path
  10. from urllib.request import urlopen
  11. from mod_ui_websocket import ModUiWebSocketClient
  12. def run_service(
  13. launcher,
  14. pw_jack,
  15. host,
  16. port,
  17. websocket_path,
  18. timeout,
  19. popen=subprocess.Popen,
  20. healthcheck=None,
  21. ):
  22. """Launch mod-ui and retain the WebSocket session needed by mod-host.
  23. This process supervises mod-ui and owns its session connection only. It
  24. deliberately does not decide whether the pedalboard loaded or whether
  25. PipeWire links are present; those are separate diagnostics.
  26. """
  27. process = popen([str(pw_jack), str(launcher)])
  28. stopping = [False]
  29. def request_stop(_signum, _frame):
  30. stopping[0] = True
  31. old_term = signal.signal(signal.SIGTERM, request_stop)
  32. old_int = signal.signal(signal.SIGINT, request_stop)
  33. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  34. check_health = healthcheck or (lambda: check_http_health(host, port, timeout=2))
  35. deadline = time.monotonic() + timeout
  36. try:
  37. if not stopping[0]:
  38. deadline = time.monotonic() + timeout
  39. while not stopping[0] and time.monotonic() < deadline:
  40. if process.poll() is not None:
  41. raise RuntimeError(
  42. f"mod-ui launcher exited with status {process.returncode}"
  43. )
  44. try:
  45. if check_health():
  46. break
  47. except (OSError, TimeoutError, http.client.HTTPException):
  48. pass
  49. time.sleep(0.25)
  50. else:
  51. if not stopping[0]:
  52. raise RuntimeError("mod-ui HTTP endpoint did not become ready")
  53. print("mod-ui HTTP endpoint ready")
  54. next_connect_attempt = 0.0
  55. while not stopping[0]:
  56. if process.poll() is not None:
  57. raise RuntimeError(
  58. f"mod-ui launcher exited with status {process.returncode}"
  59. )
  60. try:
  61. if client.connection is None:
  62. if time.monotonic() < next_connect_attempt:
  63. time.sleep(min(0.25, next_connect_attempt - time.monotonic()))
  64. continue
  65. try:
  66. client.connect()
  67. print("mod-ui WebSocket session active; keeping mod-host connected")
  68. except (OSError, TimeoutError):
  69. client.close()
  70. client = ModUiWebSocketClient(
  71. host, port, websocket_path, timeout=2
  72. )
  73. next_connect_attempt = time.monotonic() + 0.25
  74. continue
  75. client.serve_once(timeout=0.5)
  76. except (OSError, TimeoutError, ConnectionError):
  77. client.close()
  78. client = ModUiWebSocketClient(host, port, websocket_path, timeout=2)
  79. next_connect_attempt = time.monotonic() + 0.25
  80. finally:
  81. signal.signal(signal.SIGTERM, old_term)
  82. signal.signal(signal.SIGINT, old_int)
  83. client.close()
  84. if process.poll() is None:
  85. process.terminate()
  86. try:
  87. process.wait(timeout=5)
  88. except subprocess.TimeoutExpired:
  89. process.kill()
  90. process.wait()
  91. def check_http_health(host, port, timeout=2):
  92. with urlopen(f"http://{host}:{port}/ping/", timeout=timeout) as response:
  93. return 200 <= response.status < 400
  94. def main(argv=None):
  95. parser = argparse.ArgumentParser(description=__doc__)
  96. parser.add_argument("--launcher", type=Path, required=True)
  97. parser.add_argument("--pw-jack", type=Path, default=Path("/usr/bin/pw-jack"))
  98. parser.add_argument("--host", default="127.0.0.1")
  99. parser.add_argument("--port", type=int, default=8888)
  100. parser.add_argument("--websocket-path", default="/websocket")
  101. parser.add_argument("--timeout", type=float, default=60)
  102. args = parser.parse_args(argv)
  103. if not args.launcher.is_file():
  104. print(f"ERROR: mod-ui launcher is missing: {args.launcher}", file=sys.stderr)
  105. return 1
  106. if not args.pw_jack.is_file():
  107. print(f"ERROR: pw-jack is missing: {args.pw_jack}", file=sys.stderr)
  108. return 1
  109. try:
  110. run_service(
  111. args.launcher,
  112. args.pw_jack,
  113. args.host,
  114. args.port,
  115. args.websocket_path,
  116. args.timeout,
  117. )
  118. except (OSError, RuntimeError, ValueError) as error:
  119. print(f"ERROR: {error}", file=sys.stderr)
  120. return 1
  121. return 0
  122. if __name__ == "__main__":
  123. raise SystemExit(main())