gateway_command_errors.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """User-facing copy for ``hermes gateway start/stop/restart`` failures on systemd hosts.
  2. ``hermes_cli/gateway.py`` is a facade; this sibling owns the small exception -> guidance table so
  3. the most common Linux service failures (``systemctl`` exited non-zero, or there is no ``systemctl``
  4. at all) end as a next step instead of a traceback.
  5. """
  6. from __future__ import annotations
  7. import subprocess
  8. class SystemctlUnavailableError(RuntimeError):
  9. """``systemctl`` is not installed (Alpine, minimal containers, some WSL setups)."""
  10. def __init__(self) -> None:
  11. super().__init__("systemctl is not available on this system")
  12. _JOURNAL_HINT = 'journalctl --user -u hermes-gateway --since "5 min ago"'
  13. _SYSTEMCTL_FAILED_LINES = (
  14. "Could not {verb} the gateway service; systemd reported an error.",
  15. "See why with `hermes gateway status --deep` or `{journal}`.",
  16. "To reinstall the service run `hermes gateway install --force`.",
  17. )
  18. _NO_SYSTEMCTL_LINES = (
  19. "This system has no systemd, so Hermes cannot install a background service here.",
  20. "Run the gateway directly with `hermes gateway run` (keep it alive with tmux or screen).",
  21. )
  22. def _verb_for(exc: subprocess.CalledProcessError) -> str:
  23. cmd = exc.cmd if isinstance(exc.cmd, (list, tuple)) else str(exc.cmd).split()
  24. for token in cmd:
  25. if token in ("start", "stop", "restart"):
  26. return token
  27. return "start"
  28. def explain_service_failure(exc: BaseException) -> list[str] | None:
  29. """Lines to print for a systemd service failure escaping the gateway command, or None
  30. when *exc* is not one this module knows how to explain (callers re-raise)."""
  31. if isinstance(exc, SystemctlUnavailableError):
  32. return list(_NO_SYSTEMCTL_LINES)
  33. if isinstance(exc, subprocess.CalledProcessError):
  34. lines = [line.format(verb=_verb_for(exc), journal=_JOURNAL_HINT) for line in _SYSTEMCTL_FAILED_LINES]
  35. lines.append(f"Details: {exc}")
  36. return lines
  37. return None