| 1 |
"""Cross-process and cross-host reader/writer lock over a generation log of immutable snapshots.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import atexit |
| 6 |
import os |
| 7 |
import threading |
| 8 |
import time |
| 9 |
from contextlib import contextmanager, suppress |
| 10 |
from dataclasses import dataclass |
| 11 |
from math import isfinite |
| 12 |
from pathlib import Path |
| 13 |
from typing import TYPE_CHECKING, Final |
| 14 |
from weakref import WeakValueDictionary |
| 15 |
|
| 16 |
from filelock._api import ( |
| 17 |
AcquireReturnProxy, |
| 18 |
_canonical, |
| 19 |
_ensure_current_process, |
| 20 |
_register_fork_class, |
| 21 |
_register_fork_object, |
| 22 |
) |
| 23 |
from filelock._error import Timeout |
| 24 |
from filelock._lease import LeaseCompromise |
| 25 |
|
| 26 |
from ._protocol import GenerationLog, Ledger, Mode, Participant |
| 27 |
from ._storage import OsFiles |
| 28 |
|
| 29 |
if TYPE_CHECKING: |
| 30 |
from collections.abc import Callable, Generator |
| 31 |
|
| 32 |
from filelock._lease import CompromiseReason |
| 33 |
|
| 34 |
_ALL_INSTANCES: Final[WeakValueDictionary[int, SoftReadWriteLock]] = WeakValueDictionary() |
| 35 |
_ALL_INSTANCES_LOCK: threading.Lock = threading.Lock() |
| 36 |
_SINGLETONS_UNDER_CONSTRUCTION: Final[set[Path]] = set() |
| 37 |
|
| 38 |
|
| 39 |
class _SoftRWMeta(type): |
| 40 |
_instances: WeakValueDictionary[Path, SoftReadWriteLock] |
| 41 |
_instances_lock: threading.RLock |
| 42 |
|
| 43 |
def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters |
| 44 |
cls, |
| 45 |
lock_file: str | os.PathLike[str], |
| 46 |
timeout: float = -1, |
| 47 |
*, |
| 48 |
blocking: bool = True, |
| 49 |
is_singleton: bool = True, |
| 50 |
heartbeat_interval: float = 30.0, |
| 51 |
stale_threshold: float | None = None, |
| 52 |
poll_interval: float = 0.25, |
| 53 |
on_compromise: Callable[[LeaseCompromise], None] | None = None, |
| 54 |
) -> SoftReadWriteLock: |
| 55 |
_ensure_current_process() |
| 56 |
# Passed through only when set, so a subclass that declares its own constructor without it keeps working. |
| 57 |
extra = {} if on_compromise is None else {"on_compromise": on_compromise} |
| 58 |
if not is_singleton: |
| 59 |
return super().__call__( |
| 60 |
lock_file, |
| 61 |
timeout, |
| 62 |
blocking=blocking, |
| 63 |
is_singleton=is_singleton, |
| 64 |
heartbeat_interval=heartbeat_interval, |
| 65 |
stale_threshold=stale_threshold, |
| 66 |
poll_interval=poll_interval, |
| 67 |
**extra, |
| 68 |
) |
| 69 |
|
| 70 |
normalized = Path(lock_file).resolve() |
| 71 |
with cls._instances_lock: |
| 72 |
instance = cls._instances.get(normalized) |
| 73 |
if instance is None: |
| 74 |
if normalized in _SINGLETONS_UNDER_CONSTRUCTION: # pragma: needs fork |
| 75 |
msg = f"Singleton lock construction is already active for {lock_file!s}" |
| 76 |
raise RuntimeError(msg) |
| 77 |
construction_pid = os.getpid() |
| 78 |
_SINGLETONS_UNDER_CONSTRUCTION.add(normalized) |
| 79 |
try: |
| 80 |
instance = super().__call__( |
| 81 |
lock_file, |
| 82 |
timeout, |
| 83 |
blocking=blocking, |
| 84 |
is_singleton=is_singleton, |
| 85 |
heartbeat_interval=heartbeat_interval, |
| 86 |
stale_threshold=stale_threshold, |
| 87 |
poll_interval=poll_interval, |
| 88 |
**extra, |
| 89 |
) |
| 90 |
finally: |
| 91 |
_SINGLETONS_UNDER_CONSTRUCTION.discard(normalized) |
| 92 |
if os.getpid() != construction_pid: # pragma: needs fork |
| 93 |
msg = "Lock construction cannot continue after fork; construct a new lock in the child" |
| 94 |
raise RuntimeError(msg) |
| 95 |
cls._instances[normalized] = instance |
| 96 |
elif instance.timeout != timeout or instance.blocking != blocking: |
| 97 |
msg = ( |
| 98 |
f"Singleton lock created with timeout={instance.timeout}, blocking={instance.blocking}," |
| 99 |
f" cannot be changed to timeout={timeout}, blocking={blocking}" |
| 100 |
) |
| 101 |
raise ValueError(msg) |
| 102 |
elif on_compromise is not None and instance._on_compromise != on_compromise: # ruff: ignore[private-member-access] # the metaclass owns the singleton it compares |
| 103 |
# A tuning difference keeps the first caller's values; a different loss callback is a different safety |
| 104 |
# contract, and returning the cached instance would silently drop it. |
| 105 |
msg = f"Singleton lock created with a different on_compromise callback for {lock_file!s}" |
| 106 |
raise ValueError(msg) |
| 107 |
else: |
| 108 |
_validate_intervals(heartbeat_interval, stale_threshold, poll_interval) |
| 109 |
return instance |
| 110 |
|
| 111 |
|
| 112 |
class SoftReadWriteLock(metaclass=_SoftRWMeta): |
| 113 |
""" |
| 114 |
Cross-process and cross-host reader/writer lock for shared filesystems. |
| 115 |
|
| 116 |
Use this class instead of :class:`~filelock.ReadWriteLock` when the lock file lives on a network filesystem (NFS, |
| 117 |
Lustre, HPC cluster shared storage). ``ReadWriteLock`` is backed by SQLite and cannot run on NFS because SQLite's |
| 118 |
``fcntl`` locking is unreliable there. |
| 119 |
|
| 120 |
The lock's state is a log of immutable snapshots under ``foo.lock.rw/gen/<N>``, each naming the writer and the |
| 121 |
readers holding the lock at generation ``N``. Every acquire, release, and eviction publishes the next snapshot with |
| 122 |
one atomic no-replace hard link, so no transition can be left half done by a crash on any host. Each participant |
| 123 |
also keeps ``foo.lock.rw/holders/<token>``, a record whose nonce a daemon heartbeat thread rewrites every |
| 124 |
``heartbeat_interval`` seconds. A contender evicts a member whose record has not changed for ``stale_threshold`` |
| 125 |
seconds of the contender's own monotonic clock; no clock is ever compared across hosts, so skew between hosts or |
| 126 |
against the file server cannot make a live holder look dead. |
| 127 |
|
| 128 |
Writer acquire is writer-preferring: a writer enters the snapshot as soon as no live writer is named, which blocks |
| 129 |
any new reader, then waits for the named readers to leave. Writer starvation is impossible. |
| 130 |
|
| 131 |
An expired holder is not fenced by the lock: a process paused past ``stale_threshold`` resumes believing it holds |
| 132 |
the lock until its next heartbeat reports the loss through ``on_compromise``. :attr:`generation` is a monotonic |
| 133 |
fencing token for the protected resource: a store that rejects writes carrying a lower generation than the highest |
| 134 |
it has accepted refuses such a holder. |
| 135 |
|
| 136 |
Reentrancy, upgrade/downgrade rules, thread pinning, and singleton caching by resolved path match |
| 137 |
:class:`~filelock.ReadWriteLock`. |
| 138 |
|
| 139 |
Forking invalidates the inherited instance in the child so the child cannot double-own the lock with its parent; |
| 140 |
``release()`` on that instance is a no-op, and the child must construct a new instance if it needs a lock. |
| 141 |
|
| 142 |
Trust boundary: protects against same-UID non-cooperating processes (one host or cross-host) and same-host |
| 143 |
different-UID users via ``0o600`` / ``0o700`` permissions. Does not protect against root compromise or multi-tenant |
| 144 |
mounts where hostile co-tenants share the UID. |
| 145 |
|
| 146 |
:param lock_file: path to the lock file; the protocol directory lives next to it as ``<lock_file>.rw`` |
| 147 |
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely |
| 148 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately on contention |
| 149 |
:param is_singleton: if ``True``, reuse existing instances for the same resolved path |
| 150 |
:param heartbeat_interval: seconds between heartbeat refreshes; default 30 s |
| 151 |
:param stale_threshold: seconds a holder record may stay unchanged before a contender evicts it; defaults to |
| 152 |
``3 * heartbeat_interval``, matching etcd's ``LeaseKeepAlive`` convention |
| 153 |
:param poll_interval: seconds between acquire retries under contention; default 0.25 s |
| 154 |
:param on_compromise: called from the heartbeat thread with a :class:`~filelock.LeaseCompromise` when the hold is |
| 155 |
lost: a peer evicted it, or refreshes failed for long enough that a peer could have |
| 156 |
|
| 157 |
.. versionadded:: 3.27.0 |
| 158 |
|
| 159 |
.. versionchanged:: 3.33.0 |
| 160 |
|
| 161 |
The on-disk protocol is a generation log; earlier releases cannot share a lock path with this one. |
| 162 |
|
| 163 |
""" |
| 164 |
|
| 165 |
_instances: WeakValueDictionary[Path, SoftReadWriteLock] = WeakValueDictionary() |
| 166 |
_instances_lock = threading.RLock() |
| 167 |
|
| 168 |
def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option |
| 169 |
self, |
| 170 |
lock_file: str | os.PathLike[str], |
| 171 |
timeout: float = -1, |
| 172 |
*, |
| 173 |
blocking: bool = True, |
| 174 |
is_singleton: bool = True, # ruff:ignore[unused-method-argument] # consumed by _SoftRWMeta.__call__ |
| 175 |
heartbeat_interval: float = 30.0, |
| 176 |
stale_threshold: float | None = None, |
| 177 |
poll_interval: float = 0.25, |
| 178 |
on_compromise: Callable[[LeaseCompromise], None] | None = None, |
| 179 |
) -> None: |
| 180 |
self._creator_pid = os.getpid() |
| 181 |
stale_threshold = _validate_intervals(heartbeat_interval, stale_threshold, poll_interval) |
| 182 |
|
| 183 |
self.lock_file: str = os.fspath(lock_file) |
| 184 |
self.timeout: float = timeout |
| 185 |
self.blocking: bool = blocking |
| 186 |
self.heartbeat_interval: float = heartbeat_interval |
| 187 |
self.stale_threshold: float = stale_threshold |
| 188 |
self.poll_interval: float = poll_interval |
| 189 |
|
| 190 |
# Resolved once: a relative lock path must keep naming the same log after the process changes directory. |
| 191 |
self._root = f"{_canonical(self.lock_file)}.rw" |
| 192 |
self._files = OsFiles(self.lock_file) |
| 193 |
self._ledger = Ledger(time.monotonic) |
| 194 |
self._log = GenerationLog(self._files, self.lock_file, self._root) |
| 195 |
self._on_compromise = on_compromise |
| 196 |
self._locks = _Locks(internal=threading.Lock(), transaction=threading.Lock()) |
| 197 |
self._hold: _Hold | None = None |
| 198 |
self._compromise: LeaseCompromise | None = None |
| 199 |
self._closed: bool = False |
| 200 |
|
| 201 |
with _ALL_INSTANCES_LOCK: |
| 202 |
_ALL_INSTANCES[id(self)] = self |
| 203 |
_register_fork_object(self) |
| 204 |
|
| 205 |
@classmethod |
| 206 |
def _reset_class_after_fork(cls) -> None: # pragma: forked child |
| 207 |
global _ALL_INSTANCES_LOCK # ruff:ignore[global-statement] # rebinds the module lock to a fresh one in the fork child |
| 208 |
_ALL_INSTANCES_LOCK = threading.Lock() |
| 209 |
cls._instances = WeakValueDictionary() |
| 210 |
cls._instances_lock = threading.RLock() |
| 211 |
_SINGLETONS_UNDER_CONSTRUCTION.clear() |
| 212 |
|
| 213 |
@property |
| 214 |
def generation(self) -> int | None: |
| 215 |
""" |
| 216 |
The generation at which the current hold was granted, or ``None`` when no lock is held. |
| 217 |
|
| 218 |
Generations are monotonic across all participants and hosts, so this is a fencing token: pass it to the |
| 219 |
protected resource and have the resource reject any operation carrying a lower generation than the highest it |
| 220 |
has accepted. That refuses a holder that paused past ``stale_threshold``, was evicted, and resumed. |
| 221 |
|
| 222 |
.. versionadded:: 3.33.0 |
| 223 |
|
| 224 |
""" |
| 225 |
with self._locks.internal: |
| 226 |
return None if self._hold is None else self._hold.participant.generation |
| 227 |
|
| 228 |
@property |
| 229 |
def compromise(self) -> LeaseCompromise | None: |
| 230 |
""" |
| 231 |
How the current hold was lost, or ``None`` while it stands. |
| 232 |
|
| 233 |
Set by the heartbeat thread once a peer has evicted this holder or refreshes have failed for long enough that a |
| 234 |
peer could have. The holder should stop using the protected resource when it is set. |
| 235 |
|
| 236 |
.. versionadded:: 3.33.0 |
| 237 |
|
| 238 |
""" |
| 239 |
with self._locks.internal: |
| 240 |
return self._compromise |
| 241 |
|
| 242 |
@contextmanager |
| 243 |
def read_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: |
| 244 |
""" |
| 245 |
Context manager that acquires and releases a shared read lock. |
| 246 |
|
| 247 |
Falls back to instance defaults for *timeout* and *blocking* when ``None``. |
| 248 |
|
| 249 |
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default |
| 250 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default |
| 251 |
|
| 252 |
:raises RuntimeError: if a write lock is already held on this instance |
| 253 |
:raises Timeout: if the lock cannot be acquired within *timeout* seconds |
| 254 |
|
| 255 |
""" |
| 256 |
self.acquire_read(timeout, blocking=blocking) |
| 257 |
try: |
| 258 |
yield |
| 259 |
finally: |
| 260 |
self.release() |
| 261 |
|
| 262 |
@contextmanager |
| 263 |
def write_lock(self, timeout: float | None = None, *, blocking: bool | None = None) -> Generator[None]: |
| 264 |
""" |
| 265 |
Context manager that acquires and releases an exclusive write lock. |
| 266 |
|
| 267 |
Falls back to instance defaults for *timeout* and *blocking* when ``None``. |
| 268 |
|
| 269 |
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default |
| 270 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately; ``None`` uses the instance default |
| 271 |
|
| 272 |
:raises RuntimeError: if a read lock is already held, or a write lock is held by a different thread |
| 273 |
:raises Timeout: if the lock cannot be acquired within *timeout* seconds |
| 274 |
|
| 275 |
""" |
| 276 |
self.acquire_write(timeout, blocking=blocking) |
| 277 |
try: |
| 278 |
yield |
| 279 |
finally: |
| 280 |
self.release() |
| 281 |
|
| 282 |
def acquire_read(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: |
| 283 |
""" |
| 284 |
Acquire a shared read lock. |
| 285 |
|
| 286 |
If this instance already holds a read lock, the lock level is incremented (reentrant). Attempting to acquire a |
| 287 |
read lock while holding a write lock raises :class:`RuntimeError` (downgrade not allowed). On the 0→1 |
| 288 |
transition the reader publishes its holder record, enters the next snapshot once no live writer is named, and |
| 289 |
starts a daemon heartbeat thread that rewrites the record's nonce every ``heartbeat_interval`` seconds so peers |
| 290 |
on other hosts do not evict it. |
| 291 |
|
| 292 |
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block |
| 293 |
indefinitely |
| 294 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; |
| 295 |
``None`` uses the instance default |
| 296 |
|
| 297 |
:returns: a proxy that can be used as a context manager to release the lock |
| 298 |
|
| 299 |
:raises RuntimeError: if a write lock is already held on this instance, if this instance was invalidated by |
| 300 |
:func:`os.fork`, or if :meth:`close` was called |
| 301 |
:raises Timeout: if the lock cannot be acquired within *timeout* seconds |
| 302 |
:raises SoftFileLockProtocolError: if a snapshot cannot be read without risking overlap, or the filesystem |
| 303 |
refuses the no-replace hard links the protocol commits with |
| 304 |
|
| 305 |
""" |
| 306 |
return self._acquire("read", timeout, blocking=blocking) |
| 307 |
|
| 308 |
def acquire_write(self, timeout: float | None = None, *, blocking: bool | None = None) -> AcquireReturnProxy: |
| 309 |
""" |
| 310 |
Acquire an exclusive write lock. |
| 311 |
|
| 312 |
If this instance already holds a write lock from the same thread, the lock level is incremented (reentrant). |
| 313 |
Attempting to acquire a write lock while holding a read lock raises :class:`RuntimeError` (upgrade not |
| 314 |
allowed). Write locks are pinned to the acquiring thread: a different thread trying to re-enter also raises |
| 315 |
:class:`RuntimeError`. |
| 316 |
|
| 317 |
A writer enters the next snapshot as its writer as soon as no live writer is named, which blocks every new |
| 318 |
reader on every host, then waits for the readers that snapshot names to leave. Writer starvation is impossible: |
| 319 |
new readers see the named writer and wait behind it. |
| 320 |
|
| 321 |
:param timeout: maximum wait time in seconds, or ``None`` to use the instance default; ``-1`` means block |
| 322 |
indefinitely |
| 323 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable; |
| 324 |
``None`` uses the instance default |
| 325 |
|
| 326 |
:returns: a proxy that can be used as a context manager to release the lock |
| 327 |
|
| 328 |
:raises RuntimeError: if a read lock is already held, if a write lock is held by a different thread, if this |
| 329 |
instance was invalidated by :func:`os.fork`, or if :meth:`close` was called |
| 330 |
:raises Timeout: if the lock cannot be acquired within *timeout* seconds |
| 331 |
:raises SoftFileLockProtocolError: if a snapshot cannot be read without risking overlap, or the filesystem |
| 332 |
refuses the no-replace hard links the protocol commits with |
| 333 |
|
| 334 |
""" |
| 335 |
return self._acquire("write", timeout, blocking=blocking) |
| 336 |
|
| 337 |
@classmethod |
| 338 |
def get_lock( |
| 339 |
cls, |
| 340 |
lock_file: str | os.PathLike[str], |
| 341 |
timeout: float = -1, |
| 342 |
*, |
| 343 |
blocking: bool = True, |
| 344 |
) -> SoftReadWriteLock: |
| 345 |
""" |
| 346 |
Return the singleton :class:`SoftReadWriteLock` for *lock_file*. |
| 347 |
|
| 348 |
:param lock_file: path to the lock file; the protocol directory lives next to it as ``<lock_file>.rw`` |
| 349 |
:param timeout: maximum wait time in seconds; ``-1`` means block indefinitely |
| 350 |
:param blocking: if ``False``, raise :class:`~filelock.Timeout` immediately when the lock is unavailable |
| 351 |
|
| 352 |
:returns: the singleton lock instance |
| 353 |
|
| 354 |
:raises ValueError: if an instance already exists for this path with different *timeout* or *blocking* values |
| 355 |
|
| 356 |
""" |
| 357 |
return cls(lock_file, timeout, blocking=blocking) |
| 358 |
|
| 359 |
def close(self) -> None: |
| 360 |
""" |
| 361 |
Release any held lock and mark the instance closed. |
| 362 |
|
| 363 |
Idempotent. After calling this method the instance can no longer acquire locks — subsequent acquires raise |
| 364 |
:class:`RuntimeError`. A fork-invalidated instance is closed without raising. |
| 365 |
""" |
| 366 |
if self._creator_pid != os.getpid(): # pragma: forked child |
| 367 |
return |
| 368 |
self.release(force=True) |
| 369 |
with self._locks.internal: |
| 370 |
self._closed = True |
| 371 |
|
| 372 |
def release(self, *, force: bool = False) -> None: |
| 373 |
""" |
| 374 |
Release one level of the current lock. |
| 375 |
|
| 376 |
When the lock level reaches zero the heartbeat thread is stopped, the participant is committed out of the next |
| 377 |
snapshot, and its holder record is removed. On a fork-invalidated instance (that is, the child of a |
| 378 |
:func:`os.fork` call made while the parent held a lock) this method is a no-op so inherited ``with`` blocks can |
| 379 |
unwind cleanly in the child. |
| 380 |
|
| 381 |
:param force: if ``True``, release the lock completely regardless of the current lock level |
| 382 |
|
| 383 |
:raises RuntimeError: if no lock is currently held and *force* is ``False`` |
| 384 |
|
| 385 |
""" |
| 386 |
if self._creator_pid != os.getpid(): # pragma: forked child |
| 387 |
return |
| 388 |
with self._locks.internal: |
| 389 |
hold = self._hold |
| 390 |
if hold is None: |
| 391 |
if force: |
| 392 |
return |
| 393 |
msg = f"Cannot release a lock on {self.lock_file} (lock id: {id(self)}) that is not held" |
| 394 |
raise RuntimeError(msg) |
| 395 |
if force: |
| 396 |
hold.level = 0 |
| 397 |
else: |
| 398 |
hold.level -= 1 |
| 399 |
if hold.level > 0: |
| 400 |
return |
| 401 |
self._hold = None |
| 402 |
|
| 403 |
# Stop the heartbeat before leaving, so a late tick cannot re-read a snapshot this participant just left and |
| 404 |
# report an eviction that was its own release. on_compromise runs on that thread and may be what called here, |
| 405 |
# in which case there is nothing to join. |
| 406 |
hold.heartbeat_stop.set() |
| 407 |
if hold.heartbeat_thread is not threading.current_thread(): |
| 408 |
hold.heartbeat_thread.join(timeout=self.heartbeat_interval + 1.0) |
| 409 |
hold.participant.leave() |
| 410 |
|
| 411 |
def _acquire( |
| 412 |
self, |
| 413 |
mode: Mode, |
| 414 |
timeout: float | None, |
| 415 |
*, |
| 416 |
blocking: bool | None, |
| 417 |
) -> AcquireReturnProxy: |
| 418 |
if self._creator_pid != os.getpid(): # pragma: forked child |
| 419 |
msg = f"SoftReadWriteLock on {self.lock_file} was invalidated by fork(); construct a new instance" |
| 420 |
raise RuntimeError(msg) |
| 421 |
timeout = self.timeout if timeout is None else timeout |
| 422 |
blocking = self.blocking if blocking is None else blocking |
| 423 |
|
| 424 |
with self._locks.internal: |
| 425 |
if self._closed: |
| 426 |
msg = f"SoftReadWriteLock on {self.lock_file} has been closed" |
| 427 |
raise RuntimeError(msg) |
| 428 |
if self._hold is not None: |
| 429 |
return self._validate_reentrant(mode) |
| 430 |
|
| 431 |
start = time.perf_counter() |
| 432 |
if not blocking: |
| 433 |
acquired = self._locks.transaction.acquire(blocking=False) |
| 434 |
elif timeout == -1: |
| 435 |
acquired = self._locks.transaction.acquire(blocking=True) |
| 436 |
else: |
| 437 |
acquired = self._locks.transaction.acquire(blocking=True, timeout=timeout) |
| 438 |
if not acquired: |
| 439 |
raise Timeout(self.lock_file) from None |
| 440 |
try: |
| 441 |
return self._do_acquire_inner(mode, timeout, start, blocking=blocking) |
| 442 |
finally: |
| 443 |
self._locks.transaction.release() |
| 444 |
|
| 445 |
def _do_acquire_inner( |
| 446 |
self, |
| 447 |
mode: Mode, |
| 448 |
effective_timeout: float, |
| 449 |
start: float, |
| 450 |
*, |
| 451 |
blocking: bool, |
| 452 |
) -> AcquireReturnProxy: |
| 453 |
with self._locks.internal: |
| 454 |
if self._hold is not None: |
| 455 |
return self._validate_reentrant(mode) |
| 456 |
deadline = None if effective_timeout == -1 else start + effective_timeout |
| 457 |
participant = Participant( |
| 458 |
self._files, |
| 459 |
self._root, |
| 460 |
mode, |
| 461 |
stale_threshold=self.stale_threshold, |
| 462 |
clock=time.monotonic, |
| 463 |
ledger=self._ledger, |
| 464 |
log=self._log, |
| 465 |
) |
| 466 |
participant.publish() |
| 467 |
try: |
| 468 |
self._wait_for(participant.advance, deadline=deadline, blocking=blocking) |
| 469 |
except BaseException: |
| 470 |
# A contender that gives up must not stay named in the snapshot: a writer left there would block every |
| 471 |
# reader until a peer waits out the stale threshold. Its own token is all leave() touches, so it cannot |
| 472 |
# undo a peer's claim. |
| 473 |
with suppress(OSError): |
| 474 |
participant.leave() |
| 475 |
raise |
| 476 |
stop_event = threading.Event() |
| 477 |
hold = _Hold( |
| 478 |
level=1, |
| 479 |
mode=mode, |
| 480 |
write_thread_id=threading.get_ident() if mode == "write" else None, |
| 481 |
participant=participant, |
| 482 |
heartbeat_thread=_HeartbeatThread( |
| 483 |
refresh=lambda: self._refresh(participant, hold), |
| 484 |
interval=self.heartbeat_interval, |
| 485 |
stop_event=stop_event, |
| 486 |
name=f"filelock-heartbeat-{id(self):x}", |
| 487 |
), |
| 488 |
heartbeat_stop=stop_event, |
| 489 |
last_refresh=time.monotonic(), |
| 490 |
) |
| 491 |
# Publish the hold and start its heartbeat under one internal-lock section, so a concurrent release() never |
| 492 |
# observes a hold whose thread has not started and joins it. If the OS refuses the thread, clear the hold and |
| 493 |
# leave: left in place, a peer evicts the unrefreshed record and acquires while this instance still believes it |
| 494 |
# holds the lock. |
| 495 |
start_error: BaseException | None = None |
| 496 |
with self._locks.internal: |
| 497 |
self._hold = hold |
| 498 |
self._compromise = None |
| 499 |
try: |
| 500 |
hold.heartbeat_thread.start() |
| 501 |
except BaseException as error: # ruff:ignore[blind-except] # clear the slot below and re-raise |
| 502 |
self._hold = None |
| 503 |
start_error = error |
| 504 |
if start_error is not None: |
| 505 |
participant.leave() |
| 506 |
raise start_error |
| 507 |
return AcquireReturnProxy(lock=self) |
| 508 |
|
| 509 |
def _validate_reentrant(self, mode: Mode) -> AcquireReturnProxy: |
| 510 |
hold = self._hold |
| 511 |
assert hold is not None # ruff:ignore[assert] # callers dispatch here only inside the self._hold is not None branch |
| 512 |
if hold.mode != mode: |
| 513 |
opposite = "write" if mode == "read" else "read" |
| 514 |
direction = "downgrade" if mode == "read" else "upgrade" |
| 515 |
msg = ( |
| 516 |
f"Cannot acquire {mode} lock on {self.lock_file} (lock id: {id(self)}): " |
| 517 |
f"already holding a {opposite} lock ({direction} not allowed)" |
| 518 |
) |
| 519 |
raise RuntimeError(msg) |
| 520 |
if mode == "write" and (cur := threading.get_ident()) != hold.write_thread_id: |
| 521 |
msg = ( |
| 522 |
f"Cannot acquire write lock on {self.lock_file} (lock id: {id(self)}) " |
| 523 |
f"from thread {cur} while it is held by thread {hold.write_thread_id}" |
| 524 |
) |
| 525 |
raise RuntimeError(msg) |
| 526 |
hold.level += 1 |
| 527 |
return AcquireReturnProxy(lock=self) |
| 528 |
|
| 529 |
def _wait_for( |
| 530 |
self, |
| 531 |
predicate: Callable[[], bool], |
| 532 |
*, |
| 533 |
deadline: float | None, |
| 534 |
blocking: bool, |
| 535 |
) -> None: |
| 536 |
while not predicate(): |
| 537 |
now = time.perf_counter() |
| 538 |
if not blocking: |
| 539 |
raise Timeout(self.lock_file) |
| 540 |
if deadline is not None and now >= deadline: |
| 541 |
raise Timeout(self.lock_file) |
| 542 |
sleep_for = self.poll_interval |
| 543 |
if deadline is not None: |
| 544 |
sleep_for = min(sleep_for, max(deadline - now, 0.0)) |
| 545 |
time.sleep(sleep_for) |
| 546 |
|
| 547 |
def _refresh(self, participant: Participant, hold: _Hold) -> bool: |
| 548 |
# The loop ends at the first loss, so the holder hears about it once. A transient filesystem error (ESTALE / |
| 549 |
# EIO on the NFS-style filesystems this lock targets) is not a loss: retry rather than report a false |
| 550 |
# compromise. Report the record unrefreshable only once failures have run long enough that a peer could evict |
| 551 |
# it before the next success would land, a margin before the record actually ages out. |
| 552 |
outcome, error = participant.heartbeat() |
| 553 |
if outcome == "ok": |
| 554 |
hold.last_refresh = time.monotonic() |
| 555 |
return True |
| 556 |
if outcome == "lost": |
| 557 |
self._report_compromise(hold, "evicted", None) |
| 558 |
return False |
| 559 |
if time.monotonic() - hold.last_refresh >= self.stale_threshold - self.heartbeat_interval: |
| 560 |
self._report_compromise(hold, "refresh-failed", error) |
| 561 |
return False |
| 562 |
return True |
| 563 |
|
| 564 |
def _report_compromise(self, hold: _Hold, reason: CompromiseReason, error: OSError | None) -> None: |
| 565 |
# A tick that outlived its release's join must not stamp the old hold's loss onto whatever was acquired since. |
| 566 |
with self._locks.internal: |
| 567 |
if self._hold is not hold: |
| 568 |
return |
| 569 |
compromise = LeaseCompromise( |
| 570 |
lock_file=self.lock_file, token=hold.participant.token, reason=reason, error=error |
| 571 |
) |
| 572 |
self._compromise = compromise |
| 573 |
if self._on_compromise is not None: |
| 574 |
self._on_compromise(compromise) |
| 575 |
|
| 576 |
def _reset_after_fork_in_child(self) -> None: # pragma: forked child |
| 577 |
self._locks = _Locks(internal=threading.Lock(), transaction=threading.Lock()) |
| 578 |
self._hold = None |
| 579 |
|
| 580 |
|
| 581 |
class _HeartbeatThread(threading.Thread): |
| 582 |
def __init__( |
| 583 |
self, |
| 584 |
refresh: Callable[[], bool], |
| 585 |
interval: float, |
| 586 |
stop_event: threading.Event, |
| 587 |
name: str, |
| 588 |
) -> None: |
| 589 |
super().__init__(name=name, daemon=True) |
| 590 |
self._refresh = refresh |
| 591 |
self._interval = interval |
| 592 |
self._stop_event = stop_event |
| 593 |
|
| 594 |
def run(self) -> None: |
| 595 |
while not self._stop_event.wait(self._interval): |
| 596 |
if not self._refresh(): |
| 597 |
self._stop_event.set() |
| 598 |
return |
| 599 |
|
| 600 |
|
| 601 |
def _validate_intervals(heartbeat_interval: float, stale_threshold: float | None, poll_interval: float) -> float: |
| 602 |
if not isfinite(heartbeat_interval) or heartbeat_interval <= 0: |
| 603 |
msg = f"heartbeat_interval must be positive and finite, got {heartbeat_interval}" |
| 604 |
raise ValueError(msg) |
| 605 |
if stale_threshold is None: |
| 606 |
stale_threshold = heartbeat_interval * 3 |
| 607 |
if not isfinite(stale_threshold) or stale_threshold <= heartbeat_interval: |
| 608 |
msg = ( |
| 609 |
f"stale_threshold must exceed heartbeat_interval ({heartbeat_interval}) " |
| 610 |
f"and be finite, got {stale_threshold}" |
| 611 |
) |
| 612 |
raise ValueError(msg) |
| 613 |
if not isfinite(poll_interval) or poll_interval <= 0: |
| 614 |
msg = f"poll_interval must be positive and finite, got {poll_interval}" |
| 615 |
raise ValueError(msg) |
| 616 |
# A waiting writer refreshes its record once per poll, so a poll slower than the threshold reads as dead. |
| 617 |
if poll_interval >= stale_threshold: |
| 618 |
msg = f"poll_interval must be below stale_threshold ({stale_threshold}), got {poll_interval}" |
| 619 |
raise ValueError(msg) |
| 620 |
return stale_threshold |
| 621 |
|
| 622 |
|
| 623 |
@dataclass |
| 624 |
class _Locks: |
| 625 |
internal: threading.Lock |
| 626 |
transaction: threading.Lock |
| 627 |
|
| 628 |
|
| 629 |
@dataclass |
| 630 |
class _Hold: |
| 631 |
"""Everything that exists only while a lock is held; ``None`` when the instance has no lock.""" |
| 632 |
|
| 633 |
level: int |
| 634 |
mode: Mode |
| 635 |
write_thread_id: int | None |
| 636 |
participant: Participant |
| 637 |
heartbeat_thread: _HeartbeatThread |
| 638 |
heartbeat_stop: threading.Event |
| 639 |
last_refresh: float |
| 640 |
|
| 641 |
|
| 642 |
def _cleanup_all_instances() -> None: # pragma: no cover - runs from atexit at interpreter shutdown |
| 643 |
for instance in list(_ALL_INSTANCES.values()): |
| 644 |
with suppress(Exception): |
| 645 |
instance.release(force=True) |
| 646 |
|
| 647 |
|
| 648 |
atexit.register(_cleanup_all_instances) |
| 649 |
_register_fork_class(SoftReadWriteLock) |
| 650 |
|
| 651 |
|
| 652 |
__all__ = [ |
| 653 |
"SoftReadWriteLock", |
| 654 |
] |