hermes_state_pidns.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. """PID-namespace identity for state.db lock/lease holders.
  2. A ``pid=<n>`` holder is relative to its writer's PID namespace; a reader in a
  3. sibling namespace (two containers on one volume, systemd ``PrivatePIDs=``) sees
  4. a live holder as absent and would reclaim its unexpired row. Holders are
  5. stamped with ``pidns=<inode of /proc/self/ns/pid>`` and a foreign stamp is
  6. never probed. Unstamped (pre-upgrade) records differ by policy:
  7. * :func:`holder_pid_checkable` — STRICT, for TTL rows (compression locks,
  8. turn leases): unstamped defers to its expiry (<= TTL; a false defer
  9. self-heals, a false reclaim ends a live turn).
  10. * :func:`persistent_record_pidns_checkable` — LEGACY, for no-expiry flock
  11. records: unstamped keeps probing so orphaned-lock cleanup still works.
  12. Platforms without PID namespaces (macOS, Windows) keep the plain pid probe; a
  13. failed Linux lookup is not cached and makes every holder unverifiable.
  14. """
  15. from __future__ import annotations
  16. import os
  17. import re
  18. import sys
  19. from typing import NamedTuple, Optional
  20. # ``pidns=`` token inside a structured holder string (``pid=123:pidns=4026533184:turn=…``).
  21. _PIDNS_TOKEN_RE = re.compile(r"(?:^|:)pidns=(\d+)(?::|$)")
  22. class LocalPidNamespace(NamedTuple):
  23. """What this process knows about its own PID namespace.
  24. Three states, and the ``checkable`` predicates treat each differently:
  25. ``supported`` False — the platform has no namespace identity at all;
  26. ``supported`` True with an ``id`` — resolved; ``supported`` True with an
  27. ``id`` of None — resolution failed, see the module docstring.
  28. """
  29. id: Optional[str]
  30. supported: bool
  31. _UNSUPPORTED = LocalPidNamespace(None, False)
  32. # Cached once there is a definite answer: a process cannot move itself into
  33. # another PID namespace (``setns`` applies to its future children), so a
  34. # successful read never changes for us. A failed read is NOT cached — it may
  35. # be transient, and while it lasts every structured holder is unverifiable.
  36. _LOCAL_PID_NS: Optional[LocalPidNamespace] = None
  37. def _resolve_local_pid_namespace() -> LocalPidNamespace:
  38. if sys.platform != "linux":
  39. return _UNSUPPORTED
  40. try:
  41. link = os.readlink("/proc/self/ns/pid")
  42. except OSError:
  43. return LocalPidNamespace(None, True)
  44. match = re.search(r"\[(\d+)\]", link) # "pid:[4026532534]"
  45. return LocalPidNamespace(match.group(1) if match else None, True)
  46. def _local_pid_namespace() -> LocalPidNamespace:
  47. """This process' PID-namespace identity (see :class:`LocalPidNamespace`)."""
  48. global _LOCAL_PID_NS
  49. if _LOCAL_PID_NS is None:
  50. local = _resolve_local_pid_namespace()
  51. if local.id is not None or not local.supported:
  52. _LOCAL_PID_NS = local
  53. return local
  54. return _LOCAL_PID_NS
  55. def pid_namespace_id() -> Optional[str]:
  56. """What a holder records: the ``/proc/self/ns/pid`` inode on Linux, ``None``
  57. where there is no namespace identity or the lookup failed. A holder never
  58. asserts a namespace it cannot prove."""
  59. return _local_pid_namespace().id
  60. def holder_namespace_token() -> str:
  61. """The ``:pidns=<id>`` fragment to append to a new holder string, or ``""``.
  62. Callers build ``f"pid={os.getpid()}{holder_namespace_token()}:turn=…"``.
  63. """
  64. ns = pid_namespace_id()
  65. return f":pidns={ns}" if ns else ""
  66. def _recorded_namespace(holder: str) -> Optional[str]:
  67. """The ``pidns=`` stamp from a holder string, or None when it carries none."""
  68. match = _PIDNS_TOKEN_RE.search(holder or "")
  69. return match.group(1) if match else None
  70. def _qualify(recorded: Optional[str], *, unstamped_checkable: bool) -> bool:
  71. """The shared matrix; *unstamped_checkable* is the policy for a record that
  72. carries no namespace (see the module docstring for why there are two)."""
  73. local = _local_pid_namespace()
  74. if not local.supported:
  75. return True # single-namespace platform: a pid is evidence on its own
  76. if recorded is None:
  77. return unstamped_checkable
  78. if local.id is None:
  79. return False # our own lookup failed: unknown authority is not authority
  80. return recorded == local.id
  81. def holder_pid_checkable(holder: str) -> bool:
  82. """STRICT: may a structured holder string's ``pid=`` be probed here?
  83. The policy for TTL-bounded rows (compression locks, session turn leases):
  84. a foreign-namespace or unstamped holder is never probed — it defers to the
  85. row's own expiry instead (at most the remaining TTL; a false defer
  86. self-heals, a false reclaim ends a live turn).
  87. """
  88. return _qualify(_recorded_namespace(holder), unstamped_checkable=False)
  89. def persistent_record_pidns_checkable(recorded: Optional[str]) -> bool:
  90. """LEGACY ROLLOUT: may a persistent record (no expiry) be probed here?
  91. The policy for the flock holder records: a foreign-namespace record is
  92. never probed, while an unstamped one keeps main's behavior — those records
  93. never expire, so refusing to probe them would permanently disable
  94. orphaned-lock cleanup (see the module docstring).
  95. """
  96. return _qualify(recorded, unstamped_checkable=True)