gateway_setup_service.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. """Gateway service setup orchestration; runtime startup is separate."""
  2. import logging
  3. import sys
  4. logger = logging.getLogger(__name__)
  5. SERVICE_INSTALL_QUESTION = (
  6. "Install the gateway service so Hermes starts automatically at login "
  7. "and keeps scheduled jobs and messaging available?"
  8. )
  9. def record_service_choice(choice: str, config: dict | None = None) -> None:
  10. from hermes_cli.config import load_config, save_config
  11. if choice not in {"install", "decline"}:
  12. raise ValueError("service_install_choice must be install or decline")
  13. current = load_config()
  14. current.setdefault("gateway", {})["service_install_choice"] = choice
  15. save_config(current)
  16. # Setup keeps a working config which it saves again after this step.
  17. if config is not None:
  18. config.setdefault("gateway", {})["service_install_choice"] = choice
  19. def wants_service_install(*, interactive: bool, install: bool = False,
  20. config: dict | None = None) -> bool:
  21. from hermes_cli.config import load_config
  22. from hermes_cli.gateway import prompt_yes_no
  23. if install:
  24. return True
  25. if not interactive or not sys.stdin.isatty():
  26. return False
  27. choice = (config if config is not None else load_config()).get("gateway", {}).get("service_install_choice")
  28. if choice is None:
  29. if prompt_yes_no(SERVICE_INSTALL_QUESTION, False):
  30. return True
  31. record_service_choice("decline", config)
  32. return choice == "install"
  33. def ensure_gateway_service(context: str = "setup", *, interactive: bool = False,
  34. install: bool = False, config: dict | None = None) -> bool:
  35. """Start existing services; install only with explicit setup consent.
  36. Import and ordinary noninteractive callers cannot install, even with a saved
  37. install preference. False leaves foreground/unmanaged startup to the caller.
  38. """
  39. from hermes_cli import gateway as gw
  40. from hermes_constants import is_container
  41. if is_container():
  42. gw.print_info("Run hermes gateway run as the container main process; use a Docker restart policy for persistence.")
  43. return False
  44. supports_systemd = gw.supports_systemd_services()
  45. if not (supports_systemd or gw.is_macos() or gw.is_windows()):
  46. gw.print_info("No supported service manager found. Run: hermes gateway run")
  47. return False
  48. try:
  49. if gw._is_service_running():
  50. return True
  51. if gw._served_profile_needs_no_service():
  52. return True
  53. if not gw._is_service_installed():
  54. if context == "import" or not wants_service_install(
  55. interactive=interactive, install=install, config=config
  56. ):
  57. gw.print_info("No service installed. Run: hermes gateway run")
  58. gw.print_info("Without a service, scheduled jobs and messaging stop at logout/reboot; jobs cannot run while the host is off.")
  59. return False
  60. if supports_systemd and gw.has_conflicting_systemd_units():
  61. gw.print_systemd_scope_conflict_warning()
  62. return False
  63. if supports_systemd:
  64. gw.systemd_install(force=False, non_interactive=True)
  65. elif gw.is_macos():
  66. gw.launchd_install(force=False)
  67. else:
  68. gw._gw_windows().install(force=False, start_now=True, start_on_login=True)
  69. # Installers can refuse without raising (e.g. temporary-home guard).
  70. if not gw._is_service_installed():
  71. gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")
  72. return False
  73. record_service_choice("install", config)
  74. if supports_systemd:
  75. gw.systemd_start()
  76. elif gw.is_macos():
  77. gw.launchd_start()
  78. else:
  79. gw._gw_windows().start()
  80. gw.print_success("Gateway service running (cron jobs + messaging platforms).")
  81. return True
  82. except gw.UserSystemdUnavailableError as exc:
  83. gw.print_warning("Could not reach user systemd to start the gateway service:")
  84. gw._print_indented(str(exc), gw.print_info)
  85. except gw.SystemScopeRequiresRootError as exc:
  86. gw.print_warning(f"Gateway service needs root for this scope: {exc}")
  87. gw._print_system_scope_remediation("start")
  88. except SystemExit:
  89. gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")
  90. except Exception as exc:
  91. # Setup/import boundary: a service-manager failure of any kind degrades to the printed
  92. # manual retry (False); it never aborts the setup wizard or a restore.
  93. logger.debug("gateway service setup failed", exc_info=True)
  94. gw.print_warning(f"Gateway service setup failed: {exc}")
  95. gw.print_info("You can retry manually: hermes gateway install")
  96. return False
  97. def _wizard_install_service(backend: str) -> None:
  98. """Choose persistence once; start-now without persistence stays unmanaged."""
  99. import subprocess
  100. from hermes_cli import gateway as gw
  101. from hermes_cli.gateway_runtime import ensure_gateway_runtime
  102. if not sys.stdin.isatty():
  103. return
  104. start_now = gw.prompt_yes_no(" Start the gateway now?", True)
  105. if not wants_service_install(interactive=True):
  106. gw.print_info("Without a service, messaging and scheduled jobs stop at logout/reboot; jobs cannot run while the host is off.")
  107. if start_now:
  108. result = ensure_gateway_runtime(gw.get_hermes_home(), timeout=5.0)
  109. if result.state == "ready":
  110. gw.print_success("Gateway runtime ready; no service was installed.")
  111. else:
  112. gw.print_info(f"Gateway runtime: {result.state} ({result.reason_code or 'pending'}). Check: hermes gateway status")
  113. else:
  114. gw.print_info("Run later: hermes gateway run. Install later: hermes gateway install")
  115. return
  116. try:
  117. scope, did_install = None, True
  118. if backend == "systemd":
  119. scope, did_install = gw.install_linux_gateway_from_setup(force=False, enable_on_startup=True)
  120. elif backend == "launchd":
  121. gw.launchd_install(force=False)
  122. else:
  123. gw._gw_windows().install(force=False, start_now=start_now, start_on_login=True)
  124. if not did_install or not gw._is_service_installed():
  125. gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")
  126. return
  127. record_service_choice("install")
  128. if start_now and backend != "windows":
  129. gw._setup_service_action("start", failed_label="Start failed", system=scope == "system")
  130. except (subprocess.CalledProcessError, SystemExit) as exc:
  131. gw.print_error(f"Install failed: {exc}")
  132. gw.print_info("You can try manually: hermes gateway install")