status_scoped_locks.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Scoped-lock ownership and release, split from :mod:`gateway.status` (acquire stays there).
  2. Helpers read status through the module at call time, preserving its patch seams.
  3. The acquire path imports the ownership check lazily to avoid an import cycle.
  4. """
  5. from __future__ import annotations
  6. import contextlib
  7. import os
  8. from typing import Any, Optional
  9. from gateway import status as _status
  10. def _scoped_lock_record_is_stale(existing: dict[str, Any], existing_pid: Optional[int]) -> bool:
  11. """Recover dead/reused/stopped owners. Gateway locks also validate gateway argv.
  12. An explicitly process-owned reservation can belong to a dashboard or setup
  13. worker. Unknown identity stays reserved instead of guessing that it is dead.
  14. """
  15. if existing_pid is None or not _status._pid_exists(existing_pid):
  16. return True
  17. recorded_start = existing.get("start_time")
  18. current_start = _status._get_process_start_time(existing_pid)
  19. if _status._start_times_conflict(recorded_start, current_start):
  20. return True
  21. metadata = existing.get("metadata")
  22. process_owner = isinstance(metadata, dict) and metadata.get("owner_kind") == "process"
  23. if not process_owner and not _status._looks_like_gateway_process(existing_pid):
  24. if _status._read_process_cmdline(existing_pid) is not None:
  25. return True
  26. if None in (recorded_start, current_start) and not _status._record_looks_like_gateway(existing):
  27. return True
  28. return _status._process_is_stopped(existing_pid)
  29. def release_scoped_lock(scope: str, identity: str) -> None:
  30. """Release a scope lock owned by this PID. No start_time equality check: on-disk null vs a live
  31. fingerprint would wedge reconnects."""
  32. lock_path = _status._get_scope_lock_path(scope, identity)
  33. if (_status._read_json_file(lock_path) or {}).get("pid") == os.getpid():
  34. _status._unlink_quietly(lock_path)
  35. def release_all_scoped_locks(
  36. *, owner_pid: Optional[int] = None, owner_start_time: Optional[int] = None
  37. ) -> int:
  38. """Remove scoped lock files (--replace cleanup); returns the count removed. With ``owner_pid``
  39. only that gateway's records go (``owner_start_time`` narrows against PID reuse)."""
  40. lock_dir = _status._get_lock_dir()
  41. if not lock_dir.exists():
  42. return 0
  43. removed = 0
  44. for lock_file in lock_dir.glob("*.lock"):
  45. if owner_pid is not None:
  46. record = _status._read_json_file(lock_file) or {}
  47. if _status._pid_from_record(record) != owner_pid or (
  48. owner_start_time is not None and record.get("start_time") != owner_start_time
  49. ):
  50. continue
  51. with contextlib.suppress(OSError):
  52. lock_file.unlink(missing_ok=True)
  53. removed += 1
  54. return removed