systemd_stop_mark.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Mark a supervisor-ordered stop as planned so SIGTERM exits cleanly.
  2. Runs as systemd ``ExecStop=`` before ``KillSignal=SIGTERM``. A raw
  3. ``systemctl restart/stop hermes-gateway`` bypasses the ``hermes gateway``
  4. CLI, so no takeover (``--replace``) or planned-stop marker exists when the
  5. SIGTERM lands; the gateway classifies it as an unexpected kill, exits
  6. non-zero, and the journal records ``Failed with result exit-code`` even
  7. though the restart was intentional.
  8. The unit's ``Environment=HERMES_HOME=`` is inherited here, so the shared
  9. :func:`gateway.status.write_planned_stop_marker` helper lands the marker in
  10. the right profile home with PID + start-time identity. Best-effort and
  11. never blocking: any failure returns 0 so the stop/restart proceeds.
  12. """
  13. from __future__ import annotations
  14. import os
  15. import sys
  16. def _resolve_target_pid(argv: list[str] | tuple[str, ...]) -> int | None:
  17. """Explicit ``argv[1]``, else systemd's ``$MAINPID``. None when unknown.
  18. No PID-file fallback on purpose: marking the recorded PID without proof
  19. it is the process systemd is about to signal could mislabel an unrelated
  20. shutdown as planned.
  21. """
  22. raw: object = None
  23. if len(argv) > 1 and argv[1]:
  24. raw = argv[1]
  25. else:
  26. raw = os.environ.get("MAINPID")
  27. try:
  28. pid = int(str(raw).strip())
  29. except (TypeError, ValueError, AttributeError):
  30. return None
  31. return pid if pid > 0 else None
  32. def main(argv: list[str] | tuple[str, ...] | None = None) -> int:
  33. """Write the planned-stop marker for the supervised PID. Always 0."""
  34. try:
  35. pid = _resolve_target_pid(list(argv) if argv is not None else sys.argv)
  36. if pid is None:
  37. return 0
  38. from gateway.status import write_planned_stop_marker
  39. write_planned_stop_marker(pid)
  40. except Exception:
  41. pass
  42. return 0
  43. if __name__ == "__main__":
  44. sys.exit(main())