cgroup_cleanup.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """SIGKILL any process left in this systemd unit's cgroup.
  2. Runs as ``ExecStopPost=`` after the gateway's main process has exited: the
  3. safety net for long-lived helpers the gateway doesn't track (``adb``, platform
  4. bridges) that would otherwise be orphaned in the cgroup and block
  5. ``Restart=always``. Per-PID SIGKILLs over ``cgroup.procs`` are used instead of
  6. writing ``1`` to ``cgroup.kill``: the kernel has returned ``EINVAL`` on the
  7. cgroup-wide kill while per-PID signal delivery still works.
  8. """
  9. from __future__ import annotations
  10. import contextlib
  11. import os
  12. import re
  13. import signal
  14. import sys
  15. from pathlib import Path
  16. def _own_cgroup_path() -> str | None:
  17. """Return the cgroup v2 path for the calling process, or None."""
  18. try:
  19. text = Path("/proc/self/cgroup").read_text(encoding="utf-8")
  20. except OSError:
  21. return None
  22. match = re.search(r"^0::(.+)$", text, re.MULTILINE)
  23. return match.group(1).strip() if match else None
  24. def _read_cgroup_pids(cgroup_path: str) -> list[int]:
  25. try:
  26. raw = Path(f"/sys/fs/cgroup{cgroup_path}/cgroup.procs").read_text(encoding="utf-8")
  27. except OSError:
  28. return []
  29. pids: list[int] = []
  30. for line in raw.splitlines():
  31. with contextlib.suppress(ValueError):
  32. pids.append(int(line.strip()))
  33. return pids
  34. def _parent_is_systemd() -> bool:
  35. """True when this process was spawned by a systemd manager (ExecStopPost etc.).
  36. Any other parent (an agent terminal tool, a shell) shares a *live*
  37. process's cgroup, so reaping there would SIGKILL that process. No PID-1
  38. shortcut: in a container the gateway itself can be PID 1 (or init can be
  39. ``tini``), so PID 1 must present as systemd too; an unreadable
  40. ``/proc/<ppid>/comm`` fails closed.
  41. """
  42. ppid = os.getppid()
  43. try:
  44. return Path(f"/proc/{ppid}/comm").read_text(encoding="utf-8").strip() == "systemd"
  45. except OSError:
  46. return False
  47. def _live_gateway_among(pids: list[int]) -> bool:
  48. """True when one of ``pids`` is a live Hermes gateway runtime.
  49. A PID whose command line can't be read has already exited (or is a
  50. zombie) — exactly what the reaper clears — so only a readable,
  51. gateway-shaped command line blocks. Uses the *runtime* matcher (``run``
  52. or ``restart``): without a service manager, ``gateway restart`` runs the
  53. gateway in-process and is itself the live runtime.
  54. """
  55. from gateway.status import _read_process_cmdline, looks_like_gateway_runtime_command_line
  56. for pid in pids:
  57. cmdline = _read_process_cmdline(pid)
  58. if cmdline and looks_like_gateway_runtime_command_line(cmdline):
  59. return True
  60. return False
  61. def reap_cgroup(cgroup_path: str | None = None) -> int | None:
  62. """SIGKILL every PID in the cgroup other than the caller. Returns the count killed.
  63. Returns None (no signals) when a live gateway process is still in the
  64. cgroup — the reaper must never signal the live gateway, however invoked.
  65. """
  66. cgroup_path = _own_cgroup_path() if cgroup_path is None else cgroup_path
  67. if not cgroup_path:
  68. return 0
  69. me = os.getpid()
  70. others = [pid for pid in _read_cgroup_pids(cgroup_path) if pid != me]
  71. if not others:
  72. return 0
  73. if _live_gateway_among(others):
  74. print(
  75. "cgroup_cleanup: refusing — a live gateway process is still in the "
  76. "cgroup; reaping would SIGKILL it. Stop the service first (then "
  77. "ExecStopPost reaps its orphans), or call reap_cgroup(path) once "
  78. "the gateway process has exited.",
  79. file=sys.stderr,
  80. )
  81. return None
  82. killed = 0
  83. # Kill from a fresh read: the guard above can take seconds (status import,
  84. # per-PID cmdline/ps fallback), so `others` may hold exited/reused PIDs and
  85. # miss orphans spawned meanwhile.
  86. for pid in _read_cgroup_pids(cgroup_path):
  87. if pid == me:
  88. continue
  89. try:
  90. os.kill(pid, signal.SIGKILL) # windows-footgun: ok — Linux-only (reads /proc, /sys/fs/cgroup; runs from a systemd unit)
  91. killed += 1
  92. except (ProcessLookupError, PermissionError):
  93. continue
  94. return killed
  95. def main() -> int:
  96. if not _parent_is_systemd():
  97. print(
  98. "cgroup_cleanup: refusing — not spawned by systemd. Running this "
  99. "inside a live process's cgroup would SIGKILL that process. "
  100. "Run it via the systemd unit's ExecStopPost, or call "
  101. "reap_cgroup(cgroup_path) with an explicit stopped-service path.",
  102. file=sys.stderr,
  103. )
  104. return 1
  105. return 1 if reap_cgroup() is None else 0
  106. if __name__ == "__main__":
  107. sys.exit(main())