profiles_remove.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. """Profile directory removal: wait out the live owner, then rmtree with a short retry."""
  2. from __future__ import annotations
  3. import contextlib
  4. import os
  5. from pathlib import Path
  6. import shutil
  7. import stat
  8. import time
  9. # A multiplexer answers a delete's rescan ``pending`` after 5 s and keeps tearing the profile down;
  10. # its gateway.lock reservation is released last, once the profile's writers are gone.
  11. OWNER_RELEASE_WAIT_SECONDS = 60.0
  12. def wait_profile_unowned(profile_dir: Path, *, timeout: float | None = None) -> bool:
  13. """True once no gateway runtime holds ``profile_dir``'s ``gateway.lock`` (taken and released
  14. through ``exclusive_maintenance``); False when it is still held after ``timeout`` seconds."""
  15. from gateway.runtime_ownership import OwnershipConflict, exclusive_maintenance
  16. deadline = time.monotonic() + (OWNER_RELEASE_WAIT_SECONDS if timeout is None else timeout)
  17. while True:
  18. try:
  19. with exclusive_maintenance([profile_dir]):
  20. return True
  21. except OwnershipConflict:
  22. pass
  23. except OSError:
  24. # A read-only copy (0555 home, 0444 lock) cannot host a reservation: probe it instead.
  25. if _lock_unheld_read_only(profile_dir / 'gateway.lock'):
  26. return True
  27. if time.monotonic() >= deadline:
  28. return False
  29. time.sleep(0.25)
  30. def _lock_unheld_read_only(path: Path) -> bool:
  31. """A missing lock, or one our own flock through a read-only descriptor wins, has no holder."""
  32. if os.name == 'nt':
  33. return False # a sharing violation there is a live holder
  34. import fcntl
  35. try:
  36. fd = os.open(path, os.O_RDONLY | getattr(os, 'O_NOFOLLOW', 0) | os.O_NONBLOCK)
  37. except FileNotFoundError:
  38. return True
  39. try:
  40. fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  41. return True
  42. except OSError:
  43. return False
  44. finally:
  45. os.close(fd)
  46. def _rmtree_make_writable(func, path, exc):
  47. """onexc/onerror handler: add +w on PermissionError so rmtree can proceed. Covers NixOS-
  48. style read-only copies where the path itself (0444) or its parent (0555) isn't writable."""
  49. # onexc(func, path, exc_instance) on 3.12+; onerror(func, path, exc_info_tuple) on 3.11.
  50. if isinstance(exc, tuple):
  51. exc = exc[1]
  52. if not isinstance(exc, PermissionError):
  53. raise
  54. for target in (path, os.path.dirname(path)): # parent needed for unlink/rmdir
  55. if target:
  56. with contextlib.suppress(OSError):
  57. os.chmod(target, os.stat(target).st_mode | stat.S_IWUSR)
  58. func(path)
  59. def _rmtree_with_retry(profile_dir: Path, onexc_handler) -> None:
  60. """``shutil.rmtree`` with a short retry loop: a just-terminated process can leave in-flight
  61. writes (SQLite -wal/-shm checkpoints, sandbox temp files) landing after rmtree walked
  62. past a directory — ENOTEMPTY on POSIX, transient PermissionError on Windows."""
  63. attempts = 3
  64. last_exc: OSError | None = None
  65. for attempt in range(attempts):
  66. try:
  67. try:
  68. shutil.rmtree(profile_dir, onexc=onexc_handler)
  69. except TypeError: # ``onexc`` is 3.12+; 3.11 has ``onerror``
  70. shutil.rmtree(profile_dir, onerror=onexc_handler)
  71. return
  72. except OSError as e:
  73. last_exc = e
  74. if not profile_dir.exists():
  75. return
  76. if attempt < attempts - 1:
  77. time.sleep(0.3 * (attempt + 1))
  78. if last_exc is not None:
  79. raise last_exc