status_pid_records.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """Which runtime records name the gateway that holds ``gateway.lock`` right now.
  2. ``gateway.status.get_running_pid_identity_strict`` validates the PID file and the
  3. lock record against one live process. The PID file is advisory beside a HELD
  4. lock: a launch-service gateway keeps serving after ``gateway.pid`` was unlinked
  5. (#110166), and ``gateway run --replace`` rewrites the lock but can leave the
  6. previous gateway's PID file behind (#143331). That leftover names a different
  7. process instance (its own start time) that is gone or whose PID was recycled,
  8. and comparing it with the lock aborted every following ``hermes update`` at the
  9. Windows gateway pause stage until the file was removed by hand.
  10. A PID file claiming the lock holder's own start time under another PID is not a
  11. leftover but garbled state, so it still reaches the comparison and fails closed;
  12. so does a PID file naming another LIVE instance.
  13. """
  14. from __future__ import annotations
  15. from pathlib import Path
  16. from typing import Any, Optional
  17. def strict_identity_records(pid_path: Path, lock_record: Optional[dict[str, Any]],
  18. pid_exists: bool) -> tuple:
  19. """Records the strict identity check must agree on; a previous gateway's PID file drops out."""
  20. from gateway import status
  21. if not pid_exists:
  22. return (lock_record,)
  23. pid_record = status._read_pid_record(pid_path)
  24. if pid_record and lock_record and names_a_previous_gateway(pid_record, lock_record):
  25. return (lock_record,)
  26. return (pid_record, lock_record)
  27. def names_a_previous_gateway(pid_record: dict[str, Any], lock_record: dict[str, Any]) -> bool:
  28. """True when *pid_record* is another instance than the lock holder and that instance is gone."""
  29. from gateway import status
  30. pid = status._pid_from_record(pid_record)
  31. recorded, held = pid_record.get("start_time"), lock_record.get("start_time")
  32. if pid is None or pid <= 0 or recorded is None or held is None:
  33. return False
  34. try:
  35. if status._start_times_agree(held, recorded):
  36. return False
  37. if not status._pid_exists(pid):
  38. return True
  39. live = status._get_process_start_time(pid)
  40. return live is not None and not status._start_times_agree(live, recorded)
  41. except (TypeError, ValueError):
  42. return False