| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import inspect |
| 5 |
import logging |
| 6 |
import math |
| 7 |
import os |
| 8 |
import secrets |
| 9 |
import sys |
| 10 |
import time |
| 11 |
import warnings |
| 12 |
from abc import ABCMeta, abstractmethod |
| 13 |
from collections.abc import Callable, Hashable |
| 14 |
from contextlib import contextmanager |
| 15 |
from dataclasses import dataclass |
| 16 |
from itertools import count, starmap |
| 17 |
from threading import Condition, RLock, get_ident, local |
| 18 |
from typing import TYPE_CHECKING, Final, Literal, NoReturn, TypedDict, TypeVar, cast |
| 19 |
from weakref import WeakKeyDictionary, WeakValueDictionary |
| 20 |
|
| 21 |
from ._error import SoftFileLockLifetimeWarning, Timeout |
| 22 |
from ._util import break_lock_file |
| 23 |
|
| 24 |
#: No explicit file permission mode was passed. Lock files then open with 0o666 so umask and default ACLs pick |
| 25 |
#: the final permissions, and fchmod is skipped to preserve POSIX default ACL inheritance. |
| 26 |
_UNSET_FILE_MODE: Final[int] = -1 |
| 27 |
|
| 28 |
#: Ceiling on the retry counter used as a power of two, so a long contended wait cannot overflow the backoff multiply. |
| 29 |
_MAX_BACKOFF_EXPONENT: Final[int] = 20 |
| 30 |
|
| 31 |
#: How a context manager reconciles a body failure with a release failure on exit (see the property of this name). |
| 32 |
ContextErrorPolicy = Literal["chain", "group"] |
| 33 |
_CONTEXT_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"chain", "group"}) |
| 34 |
|
| 35 |
#: What a descriptor-owning backend does with an ``os.close`` failure after relinquishing ownership (see the property). |
| 36 |
CloseErrorPolicy = Literal["default", "raise", "suppress"] |
| 37 |
_CLOSE_ERROR_POLICIES: Final[frozenset[str]] = frozenset({"default", "raise", "suppress"}) |
| 38 |
|
| 39 |
if TYPE_CHECKING: |
| 40 |
from collections.abc import Generator |
| 41 |
from types import TracebackType |
| 42 |
from typing import Protocol |
| 43 |
|
| 44 |
from _typeshed import Unused |
| 45 |
|
| 46 |
from ._read_write import ReadWriteLock |
| 47 |
from ._soft_rw import SoftReadWriteLock |
| 48 |
|
| 49 |
class _ForkResettable(Protocol): |
| 50 |
def _reset_after_fork_in_child(self) -> None: ... |
| 51 |
|
| 52 |
class _ForkDescriptorOwner(Protocol): |
| 53 |
def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: ... |
| 54 |
|
| 55 |
# Matched against the class object itself rather than `type[...]` of it. A metaclass supplies this method to the |
| 56 |
# class while leaving instances without it, so a `type[_ForkResettableClass]` bound rejects `ReadWriteLock`. |
| 57 |
class _ForkResettableClass(Protocol): |
| 58 |
def _reset_class_after_fork(self) -> None: ... |
| 59 |
|
| 60 |
class _RegisterAtFork(Protocol): |
| 61 |
def __call__( |
| 62 |
self, |
| 63 |
*, |
| 64 |
before: Callable[[], None] | None = None, |
| 65 |
after_in_parent: Callable[[], None] | None = None, |
| 66 |
after_in_child: Callable[[], None] | None = None, |
| 67 |
) -> None: ... |
| 68 |
|
| 69 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 70 |
from typing import Self |
| 71 |
else: # pragma: no cover (<py311) |
| 72 |
from typing_extensions import Self |
| 73 |
|
| 74 |
_LOGGER: Final[logging.Logger] = logging.getLogger("filelock") |
| 75 |
_REGISTER_AT_FORK: Final[_RegisterAtFork | None] = cast("_RegisterAtFork | None", getattr(os, "register_at_fork", None)) |
| 76 |
_HAS_REGISTER_AT_FORK: Final[bool] = _REGISTER_AT_FORK is not None |
| 77 |
|
| 78 |
_ExtraValue = TypeVar("_ExtraValue") |
| 79 |
_MarkerValue = TypeVar("_MarkerValue") |
| 80 |
_SubclassValue = TypeVar("_SubclassValue") |
| 81 |
_LockInitValue = float | int | bool | str | None | Callable[[int], None] |
| 82 |
|
| 83 |
|
| 84 |
class LockOptions(TypedDict, total=False): |
| 85 |
"""Every option the metaclass forwards, so a subclass adding its own can still type what it passes through.""" |
| 86 |
|
| 87 |
timeout: float |
| 88 |
mode: int |
| 89 |
thread_local: bool |
| 90 |
blocking: bool |
| 91 |
is_singleton: bool |
| 92 |
poll_interval: float |
| 93 |
lifetime: float | None |
| 94 |
context_error_policy: ContextErrorPolicy |
| 95 |
close_error_policy: CloseErrorPolicy |
| 96 |
fallback_to_soft: bool |
| 97 |
preserve_lock_file: bool |
| 98 |
on_acquired: Callable[[int], None] | None |
| 99 |
|
| 100 |
|
| 101 |
def _exception_group_cls() -> type[BaseException]: |
| 102 |
# BaseExceptionGroup is a builtin on 3.11+; on 3.10 it needs the exceptiongroup backport. filelock keeps zero |
| 103 |
# runtime dependencies, so the backport is imported lazily rather than required, and only group mode needs it. |
| 104 |
if sys.version_info >= (3, 11): # pragma: no cover (py311+) |
| 105 |
return BaseExceptionGroup # ruff:ignore[undefined-name] # builtin on 3.11+ |
| 106 |
# Alias the import so BaseExceptionGroup above stays the builtin rather than an unbound local of this function. |
| 107 |
from exceptiongroup import ( # ruff:ignore[import-outside-top-level] # pragma: no cover (<py311) |
| 108 |
BaseExceptionGroup as _Backport, |
| 109 |
) |
| 110 |
|
| 111 |
return _Backport # pragma: no cover (<py311) |
| 112 |
|
| 113 |
|
| 114 |
def _raise_grouped_errors( |
| 115 |
message: str, |
| 116 |
first_error: BaseException, |
| 117 |
second_error: BaseException, |
| 118 |
*additional_errors: BaseException, |
| 119 |
marker: tuple[str, _MarkerValue] | None = None, |
| 120 |
) -> NoReturn: |
| 121 |
errors = (first_error, second_error, *additional_errors) |
| 122 |
_detach_grouped_contexts(errors) |
| 123 |
group = _exception_group_cls()(message, errors) |
| 124 |
if marker is not None: |
| 125 |
setattr(group, marker[0], marker[1]) |
| 126 |
raise group from None |
| 127 |
|
| 128 |
|
| 129 |
def _detach_grouped_contexts(errors: tuple[BaseException, ...]) -> None: |
| 130 |
seen: set[int] = set() |
| 131 |
pending = list(errors) |
| 132 |
while pending: |
| 133 |
error = pending.pop() |
| 134 |
if id(error) in seen: |
| 135 |
continue |
| 136 |
seen.add(id(error)) |
| 137 |
if (context := error.__context__) is not None and ( |
| 138 |
context is error |
| 139 |
or _same_exception_tree(error, context) |
| 140 |
or any(context is root or _contains_exception(root, context) for root in errors) |
| 141 |
): |
| 142 |
error.__context__ = None |
| 143 |
elif context is not None: |
| 144 |
pending.append(context) |
| 145 |
if error.__cause__ is not None: |
| 146 |
pending.append(error.__cause__) |
| 147 |
if isinstance(error, _exception_group_cls()): |
| 148 |
pending.extend(cast("_ExceptionGroupProtocol", error).exceptions) |
| 149 |
|
| 150 |
|
| 151 |
def _same_exception_tree(first: BaseException, second: BaseException) -> bool: |
| 152 |
pending = [(first, second)] |
| 153 |
seen: set[tuple[int, int]] = set() |
| 154 |
while pending: |
| 155 |
first_error, second_error = pending.pop() |
| 156 |
if first_error is second_error: |
| 157 |
continue |
| 158 |
if (pair := (id(first_error), id(second_error))) in seen: |
| 159 |
continue |
| 160 |
seen.add(pair) |
| 161 |
if ( |
| 162 |
type(first_error) is not type(second_error) |
| 163 |
or not isinstance(first_error, _exception_group_cls()) |
| 164 |
or not isinstance(second_error, _exception_group_cls()) |
| 165 |
): |
| 166 |
return False |
| 167 |
first_group = cast("_ExceptionGroupProtocol", first_error) |
| 168 |
second_group = cast("_ExceptionGroupProtocol", second_error) |
| 169 |
if first_group.message != second_group.message or len(first_group.exceptions) != len(second_group.exceptions): |
| 170 |
return False |
| 171 |
pending.extend(zip(first_group.exceptions, second_group.exceptions, strict=True)) |
| 172 |
return True |
| 173 |
|
| 174 |
|
| 175 |
def _contains_exception(error: BaseException, target: BaseException | None) -> bool: |
| 176 |
if target is None or not isinstance(error, _exception_group_cls()): |
| 177 |
return False |
| 178 |
pending = list(cast("_ExceptionGroupProtocol", error).exceptions) |
| 179 |
seen: set[int] = set() |
| 180 |
while pending: |
| 181 |
child = pending.pop() |
| 182 |
if child is target: |
| 183 |
return True |
| 184 |
if id(child) in seen: |
| 185 |
continue |
| 186 |
seen.add(id(child)) |
| 187 |
if isinstance(child, _exception_group_cls()): |
| 188 |
pending.extend(cast("_ExceptionGroupProtocol", child).exceptions) |
| 189 |
return False |
| 190 |
|
| 191 |
|
| 192 |
def _append_exception_context(error: BaseException, context: BaseException) -> None: |
| 193 |
if _exception_graph_contains(error, context) or _exception_graph_contains(context, error): |
| 194 |
return |
| 195 |
if error.__context__ is None: |
| 196 |
error.__context__ = context |
| 197 |
return |
| 198 |
tail = error |
| 199 |
seen: set[int] = set() |
| 200 |
while id(tail) not in seen: |
| 201 |
seen.add(id(tail)) |
| 202 |
if (next_error := tail.__cause__ if tail.__cause__ is not None else tail.__context__) is None: |
| 203 |
tail.__context__ = context |
| 204 |
return |
| 205 |
tail = next_error |
| 206 |
|
| 207 |
|
| 208 |
def _exception_graph_contains(error: BaseException, target: BaseException) -> bool: |
| 209 |
pending = [error] |
| 210 |
seen: set[int] = set() |
| 211 |
while pending: |
| 212 |
current = pending.pop() |
| 213 |
if current is target: |
| 214 |
return True |
| 215 |
if id(current) in seen: # pragma: no cover - arbitrary caller exceptions can contain cycles |
| 216 |
continue |
| 217 |
seen.add(id(current)) |
| 218 |
if current.__cause__ is not None: |
| 219 |
pending.append(current.__cause__) |
| 220 |
if current.__context__ is not None: |
| 221 |
pending.append(current.__context__) |
| 222 |
if isinstance(current, _exception_group_cls()): |
| 223 |
pending.extend(cast("_ExceptionGroupProtocol", current).exceptions) |
| 224 |
return False |
| 225 |
|
| 226 |
|
| 227 |
def _grouped_errors( |
| 228 |
error: BaseException, message: str, marker: tuple[str, _MarkerValue] |
| 229 |
) -> tuple[BaseException, ...] | None: |
| 230 |
if not isinstance(error, _exception_group_cls()): |
| 231 |
return None |
| 232 |
group = cast("_ExceptionGroupProtocol", error) |
| 233 |
return group.exceptions if group.message == message and getattr(group, marker[0], None) is marker[1] else None |
| 234 |
|
| 235 |
|
| 236 |
if TYPE_CHECKING: |
| 237 |
|
| 238 |
class _ExceptionGroupProtocol(Protocol): |
| 239 |
@property |
| 240 |
def message(self) -> str: ... |
| 241 |
|
| 242 |
@property |
| 243 |
def exceptions(self) -> tuple[BaseException, ...]: ... |
| 244 |
|
| 245 |
|
| 246 |
def _raise_chained_errors(first_error: BaseException, second_error: BaseException | None = None) -> NoReturn: |
| 247 |
if second_error is None: |
| 248 |
first_context = first_error.__context__ |
| 249 |
try: |
| 250 |
raise first_error # ruff:ignore[raise-within-try] # the handler restores caller-supplied context before propagation |
| 251 |
except BaseException: |
| 252 |
first_error.__context__ = first_context |
| 253 |
raise |
| 254 |
if (second_context := second_error.__context__) is not None and second_context is not first_error: |
| 255 |
_detach_exception_context(second_context, first_error) |
| 256 |
_append_exception_context(first_error, second_context) |
| 257 |
first_context = first_error.__context__ |
| 258 |
try: |
| 259 |
raise first_error # ruff:ignore[raise-within-try] # the second raise needs this error as implicit context |
| 260 |
except BaseException: # ruff:ignore[blind-except] # first_error may be a control-flow exception |
| 261 |
first_error.__context__ = first_context |
| 262 |
try: |
| 263 |
raise second_error # ruff:ignore[raise-within-try] # the handler makes the chain interpreter-independent |
| 264 |
except BaseException: |
| 265 |
second_error.__context__ = first_error |
| 266 |
first_error.__context__ = first_context |
| 267 |
raise |
| 268 |
|
| 269 |
|
| 270 |
def _detach_exception_context(error: BaseException, target: BaseException) -> None: |
| 271 |
pending = [error] |
| 272 |
seen: set[int] = set() |
| 273 |
while pending: |
| 274 |
current = pending.pop() |
| 275 |
if id(current) in seen: |
| 276 |
continue |
| 277 |
seen.add(id(current)) |
| 278 |
if current.__context__ is target: |
| 279 |
current.__context__ = None |
| 280 |
elif current.__context__ is not None: |
| 281 |
pending.append(current.__context__) |
| 282 |
if current.__cause__ is not None: |
| 283 |
pending.append(current.__cause__) |
| 284 |
if isinstance(current, _exception_group_cls()): |
| 285 |
pending.extend(cast("_ExceptionGroupProtocol", current).exceptions) |
| 286 |
|
| 287 |
|
| 288 |
def _raise_body_and_release(body_error: BaseException, release_error: BaseException) -> NoReturn: |
| 289 |
# Group mode: surface the body failure and the release failure as sibling leaves instead of letting one hide in the |
| 290 |
# other's __context__. BaseExceptionGroup returns a plain ExceptionGroup when both leaves subclass Exception, so |
| 291 |
# ``except*`` and ``except Exception`` still catch them; a BaseException leaf (KeyboardInterrupt, CancelledError) |
| 292 |
# keeps the group outside ordinary handlers. ``from None`` stops the group itself gaining a redundant __context__. |
| 293 |
_raise_grouped_errors("lock body and release both failed", body_error, release_error) |
| 294 |
|
| 295 |
|
| 296 |
def _raise_cleanup_errors( |
| 297 |
message: str, |
| 298 |
primary_error: BaseException, |
| 299 |
*cleanup_errors: BaseException | None, |
| 300 |
) -> NoReturn: |
| 301 |
_raise_grouped_errors( |
| 302 |
message, |
| 303 |
primary_error, |
| 304 |
*(error for error in cleanup_errors if error is not None), |
| 305 |
) |
| 306 |
|
| 307 |
|
| 308 |
# On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes |
| 309 |
# livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this. |
| 310 |
_resolve_dir: Final[Callable[[str], str]] = os.path.abspath if sys.platform == "win32" else os.path.realpath |
| 311 |
|
| 312 |
|
| 313 |
def _canonical(path: str | os.PathLike[str]) -> str: |
| 314 |
""" |
| 315 |
Return one stable key for *path*, collapsing equivalent spellings without following a final symlink. |
| 316 |
|
| 317 |
Relative, absolute, and ``./`` spellings of one lock file must map to a single singleton instance, deadlock-registry |
| 318 |
entry, and removal key. Resolving the whole path with ``realpath`` would follow a final symlink and alias a lock |
| 319 |
target the backend deliberately rejects, so the registry identity would differ from the backend's. Resolving only |
| 320 |
the parent directory and re-appending the literal final component collapses the equivalent spellings while keeping a |
| 321 |
final symlink a distinct key. On Windows the parent is resolved with ``abspath`` so junctions and reparse points are |
| 322 |
not followed either. |
| 323 |
""" |
| 324 |
parent, name = os.path.split(os.fspath(path)) |
| 325 |
return os.path.join(_resolve_dir(parent or os.curdir), name) # ruff:ignore[os-path-join] # string join matches abspath/realpath |
| 326 |
|
| 327 |
|
| 328 |
class _ThreadLocalRegistry(local): |
| 329 |
def __init__(self) -> None: |
| 330 |
super().__init__() |
| 331 |
self.held: dict[Hashable, int] = {} |
| 332 |
|
| 333 |
|
| 334 |
_registry: Final[_ThreadLocalRegistry] = _ThreadLocalRegistry() |
| 335 |
|
| 336 |
|
| 337 |
_T = TypeVar("_T", bound="BaseFileLock") |
| 338 |
|
| 339 |
|
| 340 |
class FileLockMeta(ABCMeta): |
| 341 |
_instances: WeakValueDictionary[str, BaseFileLock] |
| 342 |
_instances_lock: RLock |
| 343 |
_instances_under_construction: set[str] |
| 344 |
|
| 345 |
def __call__( # ruff:ignore[too-many-arguments] # forwards the public constructor's documented parameters |
| 346 |
cls: type[_T], |
| 347 |
lock_file: str | os.PathLike[str], |
| 348 |
timeout: float = -1, |
| 349 |
mode: int = _UNSET_FILE_MODE, |
| 350 |
thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility |
| 351 |
*, |
| 352 |
blocking: bool = True, |
| 353 |
is_singleton: bool = False, |
| 354 |
poll_interval: float = 0.05, |
| 355 |
lifetime: float | None = None, |
| 356 |
context_error_policy: ContextErrorPolicy = "chain", |
| 357 |
close_error_policy: CloseErrorPolicy = "default", |
| 358 |
fallback_to_soft: bool = True, |
| 359 |
preserve_lock_file: bool = False, |
| 360 |
on_acquired: Callable[[int], None] | None = None, |
| 361 |
**kwargs: _ExtraValue, |
| 362 |
) -> _T: |
| 363 |
_ensure_current_process() |
| 364 |
lifetime = _resolve_lifetime(lifetime, cls, stacklevel=cls._constructor_lifetime_warning_stacklevel) |
| 365 |
poll_interval = _resolve_poll_interval(poll_interval) |
| 366 |
# Validate before building the instance: a raise inside __init__ would leave a half-constructed object whose |
| 367 |
# __del__ then trips over the missing context. |
| 368 |
context_error_policy = _resolve_context_error_policy(context_error_policy) |
| 369 |
close_error_policy = _resolve_close_error_policy(close_error_policy) |
| 370 |
preserve_lock_file = _resolve_preserve_lock_file( |
| 371 |
preserve=preserve_lock_file, supported=cls._preserve_lock_file_supported, cls_name=cls.__name__ |
| 372 |
) |
| 373 |
on_acquired = _resolve_on_acquired(on_acquired, supported=cls._on_acquired_supported, cls_name=cls.__name__) |
| 374 |
params: dict[str, _LockInitValue | _ExtraValue] = { |
| 375 |
"timeout": timeout, |
| 376 |
"mode": mode, |
| 377 |
"thread_local": thread_local, |
| 378 |
"blocking": blocking, |
| 379 |
"is_singleton": is_singleton, |
| 380 |
"poll_interval": poll_interval, |
| 381 |
"lifetime": lifetime, |
| 382 |
"context_error_policy": context_error_policy, |
| 383 |
"close_error_policy": close_error_policy, |
| 384 |
"fallback_to_soft": fallback_to_soft, |
| 385 |
"preserve_lock_file": preserve_lock_file, |
| 386 |
"on_acquired": on_acquired, |
| 387 |
**kwargs, |
| 388 |
} |
| 389 |
if not is_singleton: |
| 390 |
return cls._create_instance(lock_file, params) |
| 391 |
|
| 392 |
# Look up, build and store under one lock. Without it two threads racing the first construction for a |
| 393 |
# path both miss the cache and each build their own instance, so callers relying on is_singleton for |
| 394 |
# reentrant locking across instances end up with two "singletons" and acquire()'s deadlock check then |
| 395 |
# rejects a legitimate reentrant acquire; the unguarded writes to the WeakValueDictionary are a data |
| 396 |
# race besides. ReadWriteLock and SoftReadWriteLock already guard their singleton caches this way. |
| 397 |
# Key the cache on the canonical form so equivalent spellings of one path share a singleton, and it matches the |
| 398 |
# deadlock-registry key acquire() uses. |
| 399 |
singleton_key = _canonical(lock_file) |
| 400 |
with cls._instances_lock: |
| 401 |
if (instance := cls._instances.get(singleton_key)) is None: |
| 402 |
if singleton_key in cls._instances_under_construction: # pragma: needs fork |
| 403 |
msg = f"Singleton lock construction is already active for {lock_file!s}" |
| 404 |
raise RuntimeError(msg) |
| 405 |
construction_registry = cls._instances_under_construction |
| 406 |
construction_pid = os.getpid() |
| 407 |
construction_registry.add(singleton_key) |
| 408 |
try: |
| 409 |
instance = cls._create_instance(lock_file, params) |
| 410 |
finally: |
| 411 |
construction_registry.discard(singleton_key) |
| 412 |
if os.getpid() != construction_pid: # pragma: needs fork |
| 413 |
msg = "Lock construction cannot continue after fork; construct a new lock in the child" |
| 414 |
raise RuntimeError(msg) |
| 415 |
cls._instances[singleton_key] = instance |
| 416 |
return instance |
| 417 |
|
| 418 |
params_to_check = { |
| 419 |
"thread_local": (thread_local, instance.is_thread_local()), |
| 420 |
"timeout": (timeout, instance.timeout), |
| 421 |
"mode": (mode, instance._context.mode), # ruff:ignore[private-member-access] # compares against the managed instance's own context |
| 422 |
"blocking": (blocking, instance.blocking), |
| 423 |
"poll_interval": (poll_interval, instance.poll_interval), |
| 424 |
"lifetime": (lifetime, instance.lifetime), |
| 425 |
"context_error_policy": (context_error_policy, instance.context_error_policy), |
| 426 |
"close_error_policy": (close_error_policy, instance.close_error_policy), |
| 427 |
"fallback_to_soft": (fallback_to_soft, instance.fallback_to_soft), |
| 428 |
"preserve_lock_file": (preserve_lock_file, instance.preserve_lock_file), |
| 429 |
} |
| 430 |
non_matching_params = { |
| 431 |
name: (passed_param, set_param) |
| 432 |
for name, (passed_param, set_param) in params_to_check.items() |
| 433 |
if passed_param != set_param |
| 434 |
} |
| 435 |
# Callables compare by identity, not equality: two equal callables can close over different state, so a |
| 436 |
# singleton must reject a different hook object even if it compares equal. Keep it out of the scalar dict above. |
| 437 |
hook_mismatch = on_acquired is not instance.on_acquired |
| 438 |
if not non_matching_params and not hook_mismatch: |
| 439 |
return instance # ty: ignore[invalid-return-type] # https://github.com/astral-sh/ty/issues/3231 |
| 440 |
|
| 441 |
msg = "Singleton lock instances cannot be initialized with differing arguments" |
| 442 |
msg += "\nNon-matching arguments: " |
| 443 |
for param_name, (passed_param, set_param) in non_matching_params.items(): |
| 444 |
msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)" |
| 445 |
if hook_mismatch: |
| 446 |
msg += f"\n\ton_acquired (existing lock has {instance.on_acquired} but {on_acquired} was passed)" |
| 447 |
raise ValueError(msg) |
| 448 |
|
| 449 |
def _create_instance( |
| 450 |
cls: type[_T], lock_file: str | os.PathLike[str], params: dict[str, _LockInitValue | _ExtraValue] |
| 451 |
) -> _T: |
| 452 |
model = _init_parameter_model(cls) |
| 453 |
if model.accepts_kwargs: |
| 454 |
return super().__call__(lock_file, **params) |
| 455 |
|
| 456 |
unsupported = sorted( |
| 457 |
name |
| 458 |
for name, value in params.items() |
| 459 |
if name not in model.accepted_params |
| 460 |
and ((parameter := model.default_params.get(name)) is None or value != parameter.default) |
| 461 |
) |
| 462 |
if unsupported: |
| 463 |
msg = f"{cls.__name__} does not support non-default lock options: {', '.join(unsupported)}" |
| 464 |
raise TypeError(msg) |
| 465 |
# virtualenv narrows a BaseFileLock descendant's signature; omit base defaults it does not accept (#340). |
| 466 |
return super().__call__( |
| 467 |
lock_file, |
| 468 |
**{name: value for name, value in params.items() if name in model.accepted_params}, |
| 469 |
) |
| 470 |
|
| 471 |
|
| 472 |
_INIT_PARAMETER_MODELS: Final[WeakKeyDictionary[type[BaseFileLock], _InitParameterModel]] = WeakKeyDictionary() |
| 473 |
|
| 474 |
|
| 475 |
def _init_parameter_model(cls: type[BaseFileLock]) -> _InitParameterModel: |
| 476 |
# A strong cache would keep dynamically created subclasses alive for the process lifetime. |
| 477 |
with _fork_transition(), _FORK_STATE.parameter_models_lock: |
| 478 |
if (model := _INIT_PARAMETER_MODELS.get(cls)) is None: |
| 479 |
parameters = inspect.signature(cls.__init__).parameters.values() |
| 480 |
model = _InitParameterModel( |
| 481 |
accepted_params=frozenset( |
| 482 |
parameter.name |
| 483 |
for parameter in parameters |
| 484 |
if parameter.kind in {inspect.Parameter.POSITIONAL_OR_KEYWORD, inspect.Parameter.KEYWORD_ONLY} |
| 485 |
), |
| 486 |
accepts_kwargs=any(parameter.kind is inspect.Parameter.VAR_KEYWORD for parameter in parameters), |
| 487 |
default_params={ |
| 488 |
name: parameter |
| 489 |
for name, parameter in inspect.signature(type(cls).__call__).parameters.items() |
| 490 |
if parameter.default is not inspect.Parameter.empty |
| 491 |
}, |
| 492 |
) |
| 493 |
_INIT_PARAMETER_MODELS[cls] = model |
| 494 |
return model |
| 495 |
|
| 496 |
|
| 497 |
@dataclass(frozen=True) |
| 498 |
class _InitParameterModel: |
| 499 |
accepted_params: frozenset[str] |
| 500 |
accepts_kwargs: bool |
| 501 |
default_params: dict[str, inspect.Parameter] |
| 502 |
|
| 503 |
|
| 504 |
def _resolve_lifetime(lifetime: float | None, cls: type[BaseFileLock], *, stacklevel: int) -> float | None: |
| 505 |
""" |
| 506 |
Validate ``lifetime`` and drop a value the backend cannot honor. |
| 507 |
|
| 508 |
``lifetime`` is a deliberate age-based lease: a lock file older than ``lifetime`` is broken even while its holder is |
| 509 |
still alive. Existence locks (:class:`SoftFileLock`) implement that behavior by unlinking a reclaimable pathname, |
| 510 |
which can overlap a live holder. A native OS lock lives on the inode, so unlinking the pathname by age cannot revoke |
| 511 |
the kernel lock; a contender would lock a fresh inode and overlap the live holder (#590). Ignore the request with a |
| 512 |
warning rather than accept a setting that breaks mutual exclusion. |
| 513 |
""" |
| 514 |
if lifetime is not None: |
| 515 |
if isinstance(lifetime, bool) or not isinstance(lifetime, (int, float)): |
| 516 |
msg = f"lifetime must be a finite non-negative number or None, not {type(lifetime).__name__}" |
| 517 |
raise TypeError(msg) |
| 518 |
if lifetime < 0 or (isinstance(lifetime, float) and not math.isfinite(lifetime)): |
| 519 |
msg = f"lifetime must be finite and non-negative, not {lifetime!r}" |
| 520 |
raise ValueError(msg) |
| 521 |
if lifetime is not None and not cls._lifetime_supported: |
| 522 |
warnings.warn( |
| 523 |
f"lifetime is ignored for {cls.__name__}: {cls._lifetime_unsupported_reason}; " |
| 524 |
f"only SoftFileLock supports lifetime-based expiry", |
| 525 |
stacklevel=stacklevel, |
| 526 |
) |
| 527 |
return None |
| 528 |
if lifetime is not None and cls._lifetime_replacements is not None: |
| 529 |
strict_lock, lease = cls._lifetime_replacements |
| 530 |
warnings.warn( |
| 531 |
f"{cls.__name__}(lifetime=...) uses age-based expiry and can overlap a live holder; " |
| 532 |
f"use {lease} for expiry or {strict_lock} for fail-closed locking", |
| 533 |
SoftFileLockLifetimeWarning, |
| 534 |
stacklevel=stacklevel, |
| 535 |
) |
| 536 |
return lifetime |
| 537 |
|
| 538 |
|
| 539 |
def _resolve_poll_interval(poll_interval: float) -> float: |
| 540 |
"""Validate ``poll_interval`` used for ``time.sleep`` / ``asyncio.sleep`` retries.""" |
| 541 |
if isinstance(poll_interval, bool) or not isinstance(poll_interval, (int, float)): |
| 542 |
msg = f"poll_interval must be a finite non-negative number, not {type(poll_interval).__name__}" |
| 543 |
raise TypeError(msg) |
| 544 |
if poll_interval < 0 or (isinstance(poll_interval, float) and not math.isfinite(poll_interval)): |
| 545 |
msg = f"poll_interval must be finite and non-negative, not {poll_interval!r}" |
| 546 |
raise ValueError(msg) |
| 547 |
return float(poll_interval) |
| 548 |
|
| 549 |
|
| 550 |
def _resolve_context_error_policy(policy: str) -> ContextErrorPolicy: |
| 551 |
if policy not in _CONTEXT_ERROR_POLICIES: |
| 552 |
msg = f"context_error_policy must be 'chain' or 'group', got {policy!r}" |
| 553 |
raise ValueError(msg) |
| 554 |
if policy == "group": # fail fast at construction rather than only when a dual failure happens to occur |
| 555 |
try: |
| 556 |
_exception_group_cls() |
| 557 |
except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport |
| 558 |
msg = "context_error_policy='group' requires Python 3.11+ or the 'exceptiongroup' backport installed" |
| 559 |
raise ValueError(msg) from exc |
| 560 |
return cast("ContextErrorPolicy", policy) |
| 561 |
|
| 562 |
|
| 563 |
def _resolve_close_error_policy(policy: str) -> CloseErrorPolicy: |
| 564 |
if policy not in _CLOSE_ERROR_POLICIES: |
| 565 |
msg = f"close_error_policy must be 'default', 'raise', or 'suppress', got {policy!r}" |
| 566 |
raise ValueError(msg) |
| 567 |
return cast("CloseErrorPolicy", policy) |
| 568 |
|
| 569 |
|
| 570 |
def _resolve_preserve_lock_file(*, preserve: bool, supported: bool, cls_name: str) -> bool: |
| 571 |
# An existence lock unlinks its marker to release, so preserving the pathname would defeat unlocking. Reject the |
| 572 |
# request rather than silently ignore it, since a caller asking for a stable identity must know it cannot be kept. |
| 573 |
if preserve and not supported: |
| 574 |
msg = f"preserve_lock_file=True is not supported by {cls_name}: unlinking its marker is how it releases" |
| 575 |
raise ValueError(msg) |
| 576 |
return preserve |
| 577 |
|
| 578 |
|
| 579 |
def _resolve_on_acquired( |
| 580 |
on_acquired: Callable[[int], None] | None, *, supported: bool, cls_name: str |
| 581 |
) -> Callable[[int], None] | None: |
| 582 |
if on_acquired is None: |
| 583 |
return None |
| 584 |
# An existence lock stores protocol state in its marker, so a caller writing through the descriptor would corrupt |
| 585 |
# stale detection and ownership metadata; only native locks lend out the descriptor. |
| 586 |
if not supported: |
| 587 |
msg = f"on_acquired is not supported by {cls_name}: only native locks expose the lock descriptor" |
| 588 |
raise ValueError(msg) |
| 589 |
# A hook that fails and then also fails to release surfaces both errors as a BaseExceptionGroup. Require that class |
| 590 |
# at construction rather than at the rare moment both fail, matching how context_error_policy='group' validates. |
| 591 |
try: |
| 592 |
_exception_group_cls() |
| 593 |
except ImportError as exc: # pragma: no cover # only on 3.10 without the exceptiongroup backport |
| 594 |
msg = "on_acquired requires Python 3.11+ or the 'exceptiongroup' backport for its rollback error path" |
| 595 |
raise ValueError(msg) from exc |
| 596 |
return on_acquired |
| 597 |
|
| 598 |
|
| 599 |
class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta): # ruff:ignore[too-many-public-methods] # public config properties |
| 600 |
""" |
| 601 |
Abstract base class for a file lock object. |
| 602 |
|
| 603 |
Provides the common reentrant API and state management. Subclasses implement the locking mechanism |
| 604 |
(:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock <filelock.WindowsFileLock>`, |
| 605 |
:class:`SoftFileLock <filelock.SoftFileLock>`). |
| 606 |
|
| 607 |
""" |
| 608 |
|
| 609 |
_instances: WeakValueDictionary[str, BaseFileLock] |
| 610 |
_instances_lock: RLock |
| 611 |
_instances_under_construction: set[str] |
| 612 |
|
| 613 |
#: How the cross-instance deadlock message names the conflicting holder; the async subclass says "task". |
| 614 |
_deadlock_holder_desc: str = "FileLock instance in this thread" |
| 615 |
|
| 616 |
#: Whether an age-based :attr:`lifetime` lease may break this lock. Only existence locks set it (they reclaim by |
| 617 |
#: unlinking a pathname); native OS locks leave it ``False`` since a kernel lock cannot be revoked by file age. |
| 618 |
_lifetime_supported: bool = False |
| 619 |
|
| 620 |
#: Strict-lock and lease replacements for a backend with legacy age-based expiry. |
| 621 |
_lifetime_replacements: tuple[str, str] | None = None |
| 622 |
|
| 623 |
#: Why a backend that refuses ``lifetime`` cannot honor it, named in the warning that drops the value. |
| 624 |
_lifetime_unsupported_reason: str = "a native OS lock cannot be broken safely by file age" |
| 625 |
|
| 626 |
#: Async construction adds one metaclass frame before lifetime validation. |
| 627 |
_constructor_lifetime_warning_stacklevel: int = 3 |
| 628 |
|
| 629 |
#: Whether :attr:`preserve_lock_file` may be ``True``. Native locks keep the pathname on release, so they support |
| 630 |
#: it; existence locks unlink their marker to release and reject it. |
| 631 |
_preserve_lock_file_supported: bool = True |
| 632 |
|
| 633 |
#: Whether an :attr:`on_acquired` hook may be set. Native locks lend the descriptor out; existence locks keep |
| 634 |
#: protocol state in the marker and reject it. |
| 635 |
_on_acquired_supported: bool = True |
| 636 |
|
| 637 |
#: Whether a shared instance serializes its physical acquire and release behind one gate. A backend that publishes |
| 638 |
#: several files per owner needs it; a single-file backend is atomic and leaves it off to skip the gate entirely. |
| 639 |
_serialize_transitions: bool = False |
| 640 |
|
| 641 |
#: Ceiling in seconds on the jittered backoff between contended acquisition retries. ``0`` keeps the fixed |
| 642 |
#: poll cadence; a multi-file backend sets it so contending processes desynchronize instead of livelocking. |
| 643 |
_poll_backoff_cap: float = 0.0 |
| 644 |
|
| 645 |
def __init_subclass__(cls, **kwargs: _SubclassValue) -> None: |
| 646 |
"""Give each lock subclass its own singleton registry and lock.""" |
| 647 |
super().__init_subclass__(**kwargs) |
| 648 |
cls._instances = WeakValueDictionary() |
| 649 |
cls._instances_lock = RLock() |
| 650 |
cls._instances_under_construction = set() |
| 651 |
_register_fork_class(cls) |
| 652 |
|
| 653 |
@classmethod |
| 654 |
def _reset_class_after_fork(cls) -> None: # pragma: forked child |
| 655 |
cls._instances = WeakValueDictionary() |
| 656 |
cls._instances_lock = RLock() |
| 657 |
cls._instances_under_construction = set() |
| 658 |
|
| 659 |
def __init__( # ruff:ignore[too-many-arguments] # public constructor: one parameter per documented lock option |
| 660 |
self, |
| 661 |
lock_file: str | os.PathLike[str], |
| 662 |
timeout: float = -1, |
| 663 |
mode: int = _UNSET_FILE_MODE, |
| 664 |
thread_local: bool = True, # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility |
| 665 |
*, |
| 666 |
blocking: bool = True, |
| 667 |
is_singleton: bool = False, |
| 668 |
poll_interval: float = 0.05, |
| 669 |
lifetime: float | None = None, |
| 670 |
context_error_policy: ContextErrorPolicy = "chain", |
| 671 |
close_error_policy: CloseErrorPolicy = "default", |
| 672 |
fallback_to_soft: bool = True, |
| 673 |
preserve_lock_file: bool = False, |
| 674 |
on_acquired: Callable[[int], None] | None = None, |
| 675 |
) -> None: |
| 676 |
""" |
| 677 |
Create a new lock object. |
| 678 |
|
| 679 |
:param lock_file: path to the file |
| 680 |
:param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the |
| 681 |
acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a |
| 682 |
negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock. |
| 683 |
:param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and |
| 684 |
default ACLs, preserving POSIX default ACL inheritance in shared directories. |
| 685 |
:param thread_local: Whether this object's internal context should be thread local or not. If this is set to |
| 686 |
``False`` then the lock will be reentrant across threads. When ``True`` (the default), **all fields of the |
| 687 |
lock's internal context are per-thread**, including the configuration values ``poll_interval``, ``timeout``, |
| 688 |
``blocking``, ``mode``, and ``lifetime``. Setting one of these properties from one thread does not change |
| 689 |
the value seen by another thread; threads that did not perform the write continue to see the value supplied |
| 690 |
at construction time. ``mode`` has no setter, so construction is the only place it is ever set. If you need |
| 691 |
configuration values to be visible across threads, construct the lock with ``thread_local=False``. |
| 692 |
:param blocking: whether the lock should be blocking or not |
| 693 |
:param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock |
| 694 |
file. This is useful if you want to use the lock object for reentrant locking without needing to pass the |
| 695 |
same object around. |
| 696 |
:param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value |
| 697 |
in the acquire method, if no poll_interval value (``None``) is given. |
| 698 |
:param lifetime: for :class:`SoftFileLock`, the age in seconds after which a waiting process may delete the |
| 699 |
marker, even while its holder remains alive. This legacy expiry mode does not provide strict mutual |
| 700 |
exclusion. ``None`` (the default) disables age-based expiry. Native OS locks (:class:`FileLock`) cannot be |
| 701 |
revoked by file age and ignore a non-``None`` ``lifetime`` with a warning. |
| 702 |
:param context_error_policy: how a context manager reconciles a failure in its body with a failure while |
| 703 |
releasing on exit. ``"chain"`` (the default) keeps Python's behavior: the release error propagates with the |
| 704 |
body error in its ``__context__``. ``"group"`` raises a :class:`BaseExceptionGroup` holding the body error |
| 705 |
first and the release error second, so neither hides the other. |
| 706 |
:param close_error_policy: what to do with an ``os.close`` failure after relinquishing descriptor ownership. |
| 707 |
``"default"`` keeps each backend's historical behavior (Unix native locks drop a FUSE/Docker ``EIO``; |
| 708 |
Windows native locks and :class:`SoftFileLock` propagate); ``"raise"`` always propagates the ``OSError``; |
| 709 |
``"suppress"`` always ignores it. Held state is released either way. It does not affect unlock failures or |
| 710 |
lock-file deletion. |
| 711 |
:param fallback_to_soft: for :class:`UnixFileLock`, whether to switch to :class:`SoftFileLock` when the |
| 712 |
filesystem's ``flock`` returns ``ENOSYS``. ``True`` (the default) keeps the historical fallback; |
| 713 |
``False`` fails closed, letting the ``ENOSYS`` propagate so a caller that needs kernel-enforced |
| 714 |
locking is never silently downgraded. It has no effect on Windows or :class:`SoftFileLock`. |
| 715 |
:param preserve_lock_file: for native locks (:class:`FileLock`), whether filelock promises not to unlink the |
| 716 |
lock pathname on release. ``False`` (the default) keeps each backend's cleanup: Windows removes the lock |
| 717 |
file, Unix already leaves it. ``True`` keeps a stable file identity for ACLs, auditing, and holder metadata: |
| 718 |
Windows skips its post-release unlink and Unix refuses to enter the ``ENOSYS`` soft fallback (which releases |
| 719 |
by unlinking). :class:`SoftFileLock` rejects ``True``. The promise covers filelock's own release path only; |
| 720 |
it cannot stop another process or the filesystem from removing the pathname. |
| 721 |
:param on_acquired: for native locks (:class:`FileLock`), a callable invoked with the borrowed lock descriptor |
| 722 |
once per physical acquisition, after filelock holds the native lock and finished backend initialization but |
| 723 |
before :meth:`~BaseFileLock.acquire` returns. Recursive acquisitions do not call it again. The callback may |
| 724 |
read, write, seek, truncate, or set metadata through ``os`` on the descriptor, but must not close, unlock, |
| 725 |
or take ownership of it, and filelock does not fsync its writes. If it raises, filelock releases the lock |
| 726 |
and re-raises. :class:`SoftFileLock` rejects the hook. |
| 727 |
|
| 728 |
""" |
| 729 |
self._creator_pid = os.getpid() |
| 730 |
self._transition_lock = RLock() |
| 731 |
self._is_thread_local = thread_local |
| 732 |
self._is_singleton = is_singleton |
| 733 |
self._context_error_policy = context_error_policy # already validated by the metaclass |
| 734 |
self._close_error_policy = close_error_policy # already validated by the metaclass |
| 735 |
self._fallback_to_soft = fallback_to_soft |
| 736 |
self._preserve_lock_file = preserve_lock_file # already validated by the metaclass |
| 737 |
self._on_acquired = on_acquired # already validated by the metaclass |
| 738 |
|
| 739 |
self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)( |
| 740 |
lock_file=os.fspath(lock_file), |
| 741 |
timeout=timeout, |
| 742 |
mode=mode, |
| 743 |
blocking=blocking, |
| 744 |
poll_interval=poll_interval, |
| 745 |
lifetime=lifetime, |
| 746 |
) |
| 747 |
_register_fork_object(self) |
| 748 |
|
| 749 |
def is_thread_local(self) -> bool: |
| 750 |
""":returns: a flag indicating if this lock is thread local or not""" |
| 751 |
return self._is_thread_local |
| 752 |
|
| 753 |
@property |
| 754 |
def is_singleton(self) -> bool: |
| 755 |
""" |
| 756 |
A flag indicating if this lock is singleton or not. |
| 757 |
|
| 758 |
.. versionadded:: 3.13.0 |
| 759 |
|
| 760 |
""" |
| 761 |
return self._is_singleton |
| 762 |
|
| 763 |
@property |
| 764 |
def context_error_policy(self) -> ContextErrorPolicy: |
| 765 |
""" |
| 766 |
How a context manager reconciles a body failure with a release failure on exit. |
| 767 |
|
| 768 |
.. versionadded:: 3.30.0 |
| 769 |
|
| 770 |
""" |
| 771 |
return self._context_error_policy |
| 772 |
|
| 773 |
@property |
| 774 |
def close_error_policy(self) -> CloseErrorPolicy: |
| 775 |
""" |
| 776 |
What a lock does with an ``os.close`` failure after relinquishing descriptor ownership. |
| 777 |
|
| 778 |
.. versionadded:: 3.30.0 |
| 779 |
|
| 780 |
""" |
| 781 |
return self._close_error_policy |
| 782 |
|
| 783 |
def _close_released_fd(self, fd: int, *, default_suppresses: bool) -> None: |
| 784 |
# CPython never retries close() after EINTR because the descriptor number may already be reused, so neither does |
| 785 |
# this. close_error_policy decides the error's fate after the backend relinquishes descriptor ownership. |
| 786 |
try: |
| 787 |
os.close(fd) |
| 788 |
except OSError: |
| 789 |
if self._close_error_policy == "suppress" or (self._close_error_policy == "default" and default_suppresses): |
| 790 |
return |
| 791 |
raise |
| 792 |
|
| 793 |
@property |
| 794 |
def fallback_to_soft(self) -> bool: |
| 795 |
""" |
| 796 |
Whether a :class:`FileLock` falls back to :class:`SoftFileLock` when the filesystem lacks ``flock``. |
| 797 |
|
| 798 |
Only :class:`UnixFileLock` acts on it: when ``False`` an ``ENOSYS`` from ``flock`` propagates instead of |
| 799 |
switching to existence-lock semantics. |
| 800 |
|
| 801 |
.. versionadded:: 3.30.0 |
| 802 |
|
| 803 |
""" |
| 804 |
return self._fallback_to_soft |
| 805 |
|
| 806 |
@property |
| 807 |
def preserve_lock_file(self) -> bool: |
| 808 |
""" |
| 809 |
Whether filelock promises not to unlink the lock pathname on release. |
| 810 |
|
| 811 |
When ``True``, Windows skips its post-release unlink and Unix refuses the ``ENOSYS`` soft fallback. |
| 812 |
:class:`SoftFileLock` rejects ``True`` because unlinking its marker is how it releases. |
| 813 |
|
| 814 |
.. versionadded:: 3.30.0 |
| 815 |
|
| 816 |
""" |
| 817 |
return self._preserve_lock_file |
| 818 |
|
| 819 |
@property |
| 820 |
def on_acquired(self) -> Callable[[int], None] | None: |
| 821 |
""" |
| 822 |
The callback run with the borrowed lock descriptor once per physical acquisition, or ``None``. |
| 823 |
|
| 824 |
Native locks only. It runs after the native lock is held and backend initialization finished, before |
| 825 |
:meth:`~BaseFileLock.acquire` returns; a raise rolls back the acquisition. :class:`SoftFileLock` rejects it. |
| 826 |
|
| 827 |
.. versionadded:: 3.30.0 |
| 828 |
|
| 829 |
""" |
| 830 |
return self._on_acquired |
| 831 |
|
| 832 |
@property |
| 833 |
def lock_file(self) -> str: |
| 834 |
"""Path to the lock file.""" |
| 835 |
return self._context.lock_file |
| 836 |
|
| 837 |
@property |
| 838 |
def timeout(self) -> float: |
| 839 |
""" |
| 840 |
The default timeout value, in seconds. |
| 841 |
|
| 842 |
.. versionadded:: 2.0.0 |
| 843 |
|
| 844 |
""" |
| 845 |
return self._context.timeout |
| 846 |
|
| 847 |
@timeout.setter |
| 848 |
def timeout(self, value: float | str) -> None: |
| 849 |
""" |
| 850 |
Change the default timeout value. |
| 851 |
|
| 852 |
:param value: the new value, in seconds |
| 853 |
|
| 854 |
""" |
| 855 |
self._context.timeout = float(value) |
| 856 |
|
| 857 |
@property |
| 858 |
def blocking(self) -> bool: |
| 859 |
""" |
| 860 |
Whether the locking is blocking or not. |
| 861 |
|
| 862 |
.. versionadded:: 3.14.0 |
| 863 |
|
| 864 |
""" |
| 865 |
return self._context.blocking |
| 866 |
|
| 867 |
@blocking.setter |
| 868 |
def blocking(self, value: bool) -> None: |
| 869 |
""" |
| 870 |
Change the default blocking value. |
| 871 |
|
| 872 |
:param value: the new value as bool |
| 873 |
|
| 874 |
""" |
| 875 |
self._context.blocking = value |
| 876 |
|
| 877 |
@property |
| 878 |
def poll_interval(self) -> float: |
| 879 |
""" |
| 880 |
The default polling interval, in seconds. |
| 881 |
|
| 882 |
.. versionadded:: 3.24.0 |
| 883 |
|
| 884 |
""" |
| 885 |
return self._context.poll_interval |
| 886 |
|
| 887 |
@poll_interval.setter |
| 888 |
def poll_interval(self, value: float) -> None: |
| 889 |
""" |
| 890 |
Change the default polling interval. |
| 891 |
|
| 892 |
:param value: the new value, in seconds |
| 893 |
|
| 894 |
:raises ValueError: if *value* is negative or not finite |
| 895 |
:raises TypeError: if *value* is not a real number |
| 896 |
|
| 897 |
""" |
| 898 |
self._context.poll_interval = _resolve_poll_interval(value) |
| 899 |
|
| 900 |
@property |
| 901 |
def lifetime(self) -> float | None: |
| 902 |
""" |
| 903 |
The soft marker age in seconds that permits expiry, or ``None`` to disable age-based expiry. |
| 904 |
|
| 905 |
A non-``None`` value permits a waiter to enter while the previous holder remains active, so it does not provide |
| 906 |
strict mutual exclusion. Native locks ignore the value with a warning. |
| 907 |
|
| 908 |
.. versionadded:: 3.24.0 |
| 909 |
|
| 910 |
""" |
| 911 |
return self._context.lifetime |
| 912 |
|
| 913 |
@lifetime.setter |
| 914 |
def lifetime(self, value: float | None) -> None: |
| 915 |
""" |
| 916 |
Change the legacy age-based expiry threshold. |
| 917 |
|
| 918 |
:param value: the new value in seconds, or ``None`` to disable expiration |
| 919 |
|
| 920 |
:raises ValueError: if *value* is negative or not finite |
| 921 |
:raises TypeError: if *value* is not ``None`` and not a real number |
| 922 |
|
| 923 |
""" |
| 924 |
self._context.lifetime = _resolve_lifetime(value, type(self), stacklevel=3) |
| 925 |
|
| 926 |
@property |
| 927 |
def mode(self) -> int: |
| 928 |
"""The file permissions for the lockfile.""" |
| 929 |
return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode |
| 930 |
|
| 931 |
@property |
| 932 |
def has_explicit_mode(self) -> bool: |
| 933 |
"""Whether the file permissions were explicitly set.""" |
| 934 |
return self._context.mode != _UNSET_FILE_MODE |
| 935 |
|
| 936 |
def _open_mode(self) -> int: |
| 937 |
"""Mode for ``os.open``: 0o666 when unset so umask and ACLs decide, otherwise the explicit mode.""" |
| 938 |
return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode |
| 939 |
|
| 940 |
@property |
| 941 |
def is_locked(self) -> bool: |
| 942 |
""" |
| 943 |
A boolean indicating if the lock file is holding the lock currently. |
| 944 |
|
| 945 |
.. versionchanged:: 2.0.0 |
| 946 |
|
| 947 |
This was previously a method and is now a property. |
| 948 |
|
| 949 |
""" |
| 950 |
_ensure_current_process() |
| 951 |
return self._context.lock_file_fd is not None |
| 952 |
|
| 953 |
@property |
| 954 |
def lock_counter(self) -> int: |
| 955 |
"""The number of times this lock has been acquired (but not yet released).""" |
| 956 |
_ensure_current_process() |
| 957 |
return self._context.lock_counter |
| 958 |
|
| 959 |
def __enter__(self) -> Self: |
| 960 |
""" |
| 961 |
Acquire the lock. |
| 962 |
|
| 963 |
:returns: the lock object |
| 964 |
|
| 965 |
""" |
| 966 |
self.acquire() |
| 967 |
return self |
| 968 |
|
| 969 |
def __exit__( |
| 970 |
self, |
| 971 |
exc_type: type[BaseException] | None, |
| 972 |
exc_value: BaseException | None, |
| 973 |
traceback: TracebackType | None, |
| 974 |
) -> None: |
| 975 |
"""Release the lock, reconciling a release failure with any body failure per :attr:`context_error_policy`.""" |
| 976 |
self._release_in_context(exc_value) |
| 977 |
|
| 978 |
def _release_in_context(self, body_error: BaseException | None) -> None: |
| 979 |
# Release from a context-manager exit. "chain" lets a release failure propagate with the body error already in |
| 980 |
# its __context__ (Python's default); "group" raises both as sibling leaves so neither one hides the other. |
| 981 |
try: |
| 982 |
self.release() |
| 983 |
except BaseException as release_error: |
| 984 |
if body_error is None or self._context_error_policy == "chain": |
| 985 |
raise |
| 986 |
_raise_body_and_release(body_error, release_error) |
| 987 |
|
| 988 |
def __del__(self) -> None: |
| 989 |
"""Force-release so a dropped reference never leaks a held lock.""" |
| 990 |
if vars(self).get("_creator_pid") != os.getpid(): |
| 991 |
return # pragma: forked child |
| 992 |
# A finalizer must not raise. A release error during garbage collection would otherwise surface as an |
| 993 |
# unraisable-exception warning, attributed to whichever code triggered collection. The dropped lock still gets |
| 994 |
# best-effort cleanup; an explicit release() reports the same error to a caller who can act on it. |
| 995 |
with contextlib.suppress(Exception): |
| 996 |
self.release(force=True) |
| 997 |
|
| 998 |
def acquire( |
| 999 |
self, |
| 1000 |
timeout: float | None = None, |
| 1001 |
poll_interval: float | None = None, |
| 1002 |
*, |
| 1003 |
poll_intervall: float | None = None, |
| 1004 |
blocking: bool | None = None, |
| 1005 |
cancel_check: Callable[[], bool] | None = None, |
| 1006 |
) -> AcquireReturnProxy: |
| 1007 |
""" |
| 1008 |
Try to acquire the file lock. |
| 1009 |
|
| 1010 |
:param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and |
| 1011 |
if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired |
| 1012 |
:param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default |
| 1013 |
:attr:`~poll_interval` |
| 1014 |
:param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead |
| 1015 |
:param blocking: whether to retry until this call holds the lock or the timeout expires, ``None`` means use |
| 1016 |
the default :attr:`~blocking`. ``False`` makes one attempt and raises :class:`~Timeout` on failure. |
| 1017 |
:param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll |
| 1018 |
iteration. When triggered, raises :class:`~Timeout` just like an expired timeout. |
| 1019 |
|
| 1020 |
:returns: a context object that will unlock the file when the context is exited |
| 1021 |
|
| 1022 |
:raises Timeout: if fails to acquire lock within the timeout period |
| 1023 |
|
| 1024 |
.. code-block:: python |
| 1025 |
|
| 1026 |
# You can use this method in the context manager (recommended) |
| 1027 |
with lock.acquire(): |
| 1028 |
pass |
| 1029 |
|
| 1030 |
# Or use an equivalent try-finally construct: |
| 1031 |
lock.acquire() |
| 1032 |
try: |
| 1033 |
pass |
| 1034 |
finally: |
| 1035 |
lock.release() |
| 1036 |
|
| 1037 |
.. versionchanged:: 2.0.0 |
| 1038 |
|
| 1039 |
This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement |
| 1040 |
without side effects. |
| 1041 |
|
| 1042 |
""" |
| 1043 |
self._raise_if_inherited() |
| 1044 |
if timeout is None: |
| 1045 |
timeout = self._context.timeout |
| 1046 |
|
| 1047 |
if blocking is None: |
| 1048 |
blocking = self._context.blocking |
| 1049 |
|
| 1050 |
if poll_intervall is not None: |
| 1051 |
msg = "use poll_interval instead of poll_intervall" |
| 1052 |
warnings.warn(msg, DeprecationWarning, stacklevel=2) |
| 1053 |
poll_interval = poll_intervall |
| 1054 |
|
| 1055 |
poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval |
| 1056 |
poll_interval = _resolve_poll_interval(poll_interval) |
| 1057 |
|
| 1058 |
start_time = time.perf_counter() |
| 1059 |
# Wait for admission before touching any state: a caller refused entry must leave the counter, the registry and |
| 1060 |
# the descriptor exactly as it found them. |
| 1061 |
with self._transition_admission( |
| 1062 |
blocking=blocking, |
| 1063 |
cancel_check=cancel_check, |
| 1064 |
timeout=timeout, |
| 1065 |
poll_interval=poll_interval, |
| 1066 |
start_time=start_time, |
| 1067 |
): |
| 1068 |
# Bump the counter up front; _undo_acquire rolls it back if acquisition fails. |
| 1069 |
self._context.lock_counter += 1 |
| 1070 |
|
| 1071 |
canonical = _canonical(self.lock_file) |
| 1072 |
self._raise_if_would_deadlock(canonical, timeout=timeout, blocking=blocking) |
| 1073 |
|
| 1074 |
try: |
| 1075 |
self._poll_until_acquired( |
| 1076 |
blocking=blocking, |
| 1077 |
cancel_check=cancel_check, |
| 1078 |
timeout=timeout, |
| 1079 |
poll_interval=poll_interval, |
| 1080 |
start_time=start_time, |
| 1081 |
) |
| 1082 |
except BaseException: |
| 1083 |
self._reconcile_failed_acquire(canonical) |
| 1084 |
raise |
| 1085 |
self._commit_acquire(canonical) |
| 1086 |
return AcquireReturnProxy(lock=self) |
| 1087 |
|
| 1088 |
@contextlib.contextmanager |
| 1089 |
def _transition_admission( |
| 1090 |
self, |
| 1091 |
*, |
| 1092 |
blocking: bool, |
| 1093 |
cancel_check: Callable[[], bool] | None, |
| 1094 |
timeout: float, |
| 1095 |
poll_interval: float, |
| 1096 |
start_time: float, |
| 1097 |
) -> Generator[None]: |
| 1098 |
# One thread at a time drives the physical transition of a shared instance. A protocol that publishes several |
| 1099 |
# files per owner leaves a half-built claim visible otherwise, and a second thread would read it as a holder. |
| 1100 |
# Only such a backend opts in; a single-file backend and a thread-local context each need no gate. |
| 1101 |
if not self._serialize_transitions or self._is_thread_local: |
| 1102 |
yield |
| 1103 |
return |
| 1104 |
while not self._transition_lock.acquire(blocking=False): # pragma: needs hard-link |
| 1105 |
if not blocking or (cancel_check is not None and cancel_check()): |
| 1106 |
raise Timeout(self.lock_file) |
| 1107 |
if timeout >= 0 and time.perf_counter() - start_time >= timeout: |
| 1108 |
raise Timeout(self.lock_file) |
| 1109 |
time.sleep(poll_interval) |
| 1110 |
try: # pragma: needs hard-link |
| 1111 |
yield |
| 1112 |
finally: # pragma: needs hard-link |
| 1113 |
self._transition_lock.release() |
| 1114 |
|
| 1115 |
def release(self, force: bool = False) -> None: # ruff:ignore[boolean-type-hint-positional-argument, boolean-default-value-positional-argument] # public API: positional bool kept for backwards compatibility |
| 1116 |
""" |
| 1117 |
Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file |
| 1118 |
itself may be deleted automatically, the behavior is platform-specific. |
| 1119 |
|
| 1120 |
:param force: If true, the lock counter is ignored and the lock is released in every case. |
| 1121 |
|
| 1122 |
""" |
| 1123 |
# A shared instance releases under the same gate its acquisition ran through, so a thread entering the lock |
| 1124 |
# never observes a partially torn-down owner. |
| 1125 |
serialize = self._serialize_transitions and not self._is_thread_local |
| 1126 |
with self._transition_lock if serialize else contextlib.nullcontext(): |
| 1127 |
if self._creator_pid != os.getpid() or not self.is_locked: |
| 1128 |
return |
| 1129 |
if not force and self._context.lock_counter > 1: |
| 1130 |
self._context.lock_counter -= 1 |
| 1131 |
return |
| 1132 |
|
| 1133 |
lock_id, lock_filename = id(self), self.lock_file |
| 1134 |
_LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) |
| 1135 |
try: |
| 1136 |
self._release_with_fork_tracking() |
| 1137 |
except BaseException: |
| 1138 |
# A failure after the OS unlock (during close or unlink) still released the lock: the backend cleared |
| 1139 |
# its descriptor, so commit the counter and registry to released even as the cleanup error propagates. |
| 1140 |
# A failure that left the lock held keeps the counter so a later release can retry the OS unlock. |
| 1141 |
if not self.is_locked: |
| 1142 |
self._commit_release() |
| 1143 |
raise |
| 1144 |
self._commit_release() |
| 1145 |
_LOGGER.debug("Lock %s released on %s", lock_id, lock_filename) |
| 1146 |
|
| 1147 |
def _raise_if_inherited(self) -> None: |
| 1148 |
if self._creator_pid != os.getpid(): # pragma: forked child |
| 1149 |
msg = f"{type(self).__name__} on {self.lock_file} was inherited across fork; construct a new instance" |
| 1150 |
raise RuntimeError(msg) |
| 1151 |
|
| 1152 |
def _mark_descriptor_owned(self, fd: int, identity: tuple[int, int] | None = None) -> None: |
| 1153 |
self._context.pending_lock_file_fd = None |
| 1154 |
self._context.pending_lock_file_fd_identity = None |
| 1155 |
self._context.lock_file_fd = fd |
| 1156 |
self._context.lock_file_fd_identity = identity |
| 1157 |
|
| 1158 |
def _mark_descriptor_pending(self, fd: int, identity: tuple[int, int] | None = None) -> None: |
| 1159 |
self._context.pending_lock_file_fd = fd |
| 1160 |
self._context.pending_lock_file_fd_identity = identity |
| 1161 |
|
| 1162 |
def _mark_descriptor_released(self) -> None: |
| 1163 |
self._context.pending_lock_file_fd = None |
| 1164 |
self._context.pending_lock_file_fd_identity = None |
| 1165 |
self._context.lock_file_fd = None |
| 1166 |
self._context.lock_file_fd_identity = None |
| 1167 |
|
| 1168 |
def _reset_after_fork_in_child(self) -> None: # pragma: forked child |
| 1169 |
# fork copies the lock in whatever state the parent's threads left it, so give the child an unheld one. |
| 1170 |
self._transition_lock = RLock() |
| 1171 |
self._context.owner_claim_paths = () |
| 1172 |
self._context.claim_root = None |
| 1173 |
self._context.lock_file_fd = None |
| 1174 |
self._context.lock_file_fd_token = None |
| 1175 |
self._context.lock_file_fd_identity = None |
| 1176 |
self._context.pending_lock_file_fd = None |
| 1177 |
self._context.pending_lock_file_fd_identity = None |
| 1178 |
self._context.lock_counter = 0 |
| 1179 |
self._context.lock_file_key = None |
| 1180 |
|
| 1181 |
def _descriptors_for_fork(self) -> tuple[tuple[int, tuple[int, int] | None], ...]: # pragma: needs fork |
| 1182 |
descriptors: list[tuple[int, tuple[int, int] | None]] = [] |
| 1183 |
if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: |
| 1184 |
descriptors.append((self._context.lock_file_fd, self._context.lock_file_fd_identity)) |
| 1185 |
if self._context.pending_lock_file_fd is not None: |
| 1186 |
descriptors.append((self._context.pending_lock_file_fd, self._context.pending_lock_file_fd_identity)) |
| 1187 |
return tuple(descriptors) |
| 1188 |
|
| 1189 |
def _raise_if_would_deadlock(self, canonical: str, *, timeout: float, blocking: bool) -> None: |
| 1190 |
""" |
| 1191 |
Fail fast when a *different* live instance already holds this path in the current deadlock scope. |
| 1192 |
|
| 1193 |
Only the first, indefinitely-blocking acquire can self-deadlock this way: waiting in the OS primitive would |
| 1194 |
block on a lock this flow already owns. A finite timeout or ``blocking=False`` keeps the normal Timeout path. |
| 1195 |
""" |
| 1196 |
would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking |
| 1197 |
if would_block and _registry.held.get(self._registry_key(canonical)) not in {None, id(self)}: |
| 1198 |
self._context.lock_counter -= 1 |
| 1199 |
msg = ( |
| 1200 |
f"Deadlock: lock '{self.lock_file}' is already held by a different {self._deadlock_holder_desc}. " |
| 1201 |
f"Use is_singleton=True to enable reentrant locking across instances." |
| 1202 |
) |
| 1203 |
raise RuntimeError(msg) |
| 1204 |
|
| 1205 |
def _registry_key(self, canonical: str) -> Hashable: |
| 1206 |
return canonical if (scope := self._deadlock_scope()) is None else (scope, canonical) |
| 1207 |
|
| 1208 |
@staticmethod |
| 1209 |
def _deadlock_scope() -> Hashable | None: |
| 1210 |
""" |
| 1211 |
Execution unit whose own hold would deadlock a new acquire. |
| 1212 |
|
| 1213 |
``None`` scopes holders to the thread, which the thread-local registry already separates. Async locks |
| 1214 |
override it with the running task, since one event loop thread runs many tasks and only a reacquire from |
| 1215 |
the *same* task can self-deadlock. |
| 1216 |
""" |
| 1217 |
return None |
| 1218 |
|
| 1219 |
def _poll_until_acquired( |
| 1220 |
self, |
| 1221 |
*, |
| 1222 |
blocking: bool, |
| 1223 |
cancel_check: Callable[[], bool] | None, |
| 1224 |
timeout: float, |
| 1225 |
poll_interval: float, |
| 1226 |
start_time: float, |
| 1227 |
) -> None: |
| 1228 |
lock_id = id(self) |
| 1229 |
lock_filename = self.lock_file |
| 1230 |
attempt = 0 |
| 1231 |
while True: |
| 1232 |
self._raise_if_inherited() |
| 1233 |
if not self.is_locked: |
| 1234 |
self._try_break_expired_lock() |
| 1235 |
_LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) |
| 1236 |
self._acquire_with_fork_tracking() |
| 1237 |
self._raise_if_inherited() |
| 1238 |
if self.is_locked: |
| 1239 |
_LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) |
| 1240 |
return |
| 1241 |
if self._check_give_up( |
| 1242 |
blocking=blocking, |
| 1243 |
cancel_check=cancel_check, |
| 1244 |
timeout=timeout, |
| 1245 |
start_time=start_time, |
| 1246 |
): |
| 1247 |
raise Timeout(lock_filename) |
| 1248 |
attempt += 1 |
| 1249 |
delay = self._poll_delay(poll_interval, attempt) |
| 1250 |
msg = "Lock %s not acquired on %s, waiting %s seconds ..." |
| 1251 |
_LOGGER.debug(msg, lock_id, lock_filename, delay) |
| 1252 |
time.sleep(delay) |
| 1253 |
|
| 1254 |
def _poll_delay(self, poll_interval: float, attempt: int) -> float: |
| 1255 |
# A single-file lock retries on a fixed cadence. A backend that publishes several files per acquisition sets a |
| 1256 |
# cap, and then contending processes back off across a jittered, exponentially widening window instead of |
| 1257 |
# colliding on every poll; poll_interval stays the floor so a lone waiter is still responsive. |
| 1258 |
if not self._poll_backoff_cap: |
| 1259 |
return poll_interval |
| 1260 |
# Cap the exponent before doubling: under heavy contention attempt reaches the thousands, and 2**attempt would |
| 1261 |
# overflow the float multiply long before the window itself stops growing past the cap. |
| 1262 |
window = min( |
| 1263 |
self._poll_backoff_cap, poll_interval * 2 ** min(attempt, _MAX_BACKOFF_EXPONENT) |
| 1264 |
) # pragma: needs hard-link |
| 1265 |
return max(poll_interval, secrets.randbelow(int(window * 1_000_000) + 1) / 1_000_000) # pragma: needs hard-link |
| 1266 |
|
| 1267 |
def _reconcile_failed_acquire(self, canonical: str) -> None: |
| 1268 |
# An acquire that raised while still holding the native lock (a hook that failed and whose rollback could not |
| 1269 |
# release) must keep the registry entry so a later release can retry the OS unlock; otherwise roll the counter |
| 1270 |
# back. is_locked was already reconciled by whichever release ran. |
| 1271 |
if self.is_locked: |
| 1272 |
self._commit_acquire(canonical) |
| 1273 |
else: |
| 1274 |
self._undo_acquire() |
| 1275 |
|
| 1276 |
def _invoke_on_acquired(self) -> None: |
| 1277 |
# The wrapper runs in the backend executor for async locks, preserving the callback's documented thread. |
| 1278 |
if self._on_acquired is None or self._context.lock_counter != 1: |
| 1279 |
return |
| 1280 |
try: |
| 1281 |
self._on_acquired(cast("int", self._context.lock_file_fd)) |
| 1282 |
except BaseException as callback_error: # arbitrary caller code; roll back on any failure |
| 1283 |
callback_context = callback_error.__context__ |
| 1284 |
try: |
| 1285 |
self._release_with_fork_tracking() |
| 1286 |
except BaseException as release_error: # ruff:ignore[blind-except] # both errors surface via the group below |
| 1287 |
_raise_body_and_release(callback_error, release_error) |
| 1288 |
callback_error.__context__ = callback_context |
| 1289 |
raise |
| 1290 |
|
| 1291 |
def _acquire_with_fork_tracking(self) -> None: |
| 1292 |
with _fork_transition(self): |
| 1293 |
try: |
| 1294 |
self._acquire() |
| 1295 |
except BaseException as acquisition_error: |
| 1296 |
self._rollback_failed_acquire(acquisition_error) |
| 1297 |
raise |
| 1298 |
try: |
| 1299 |
self._register_context_descriptor() |
| 1300 |
except BaseException as registration_error: # pragma: needs fork |
| 1301 |
self._rollback_failed_registration(registration_error) |
| 1302 |
raise |
| 1303 |
if self.is_locked: |
| 1304 |
self._invoke_on_acquired() |
| 1305 |
|
| 1306 |
def _rollback_failed_acquire(self, acquisition_error: BaseException) -> None: |
| 1307 |
if not self.is_locked: |
| 1308 |
return |
| 1309 |
registration_error: BaseException | None = None |
| 1310 |
tracking_error: BaseException | None = None |
| 1311 |
try: |
| 1312 |
self._register_context_descriptor() |
| 1313 |
except BaseException as error: # ruff:ignore[blind-except] # preserve registration and acquisition failures |
| 1314 |
registration_error = error |
| 1315 |
try: |
| 1316 |
# Rollback may fail too; retain the fd so a child can close it without another identity probe. |
| 1317 |
self._register_unverified_context_descriptor() |
| 1318 |
except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback |
| 1319 |
tracking_error = error |
| 1320 |
try: |
| 1321 |
self._release_with_fork_tracking() |
| 1322 |
except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and acquisition failures |
| 1323 |
_raise_cleanup_errors( |
| 1324 |
"lock acquisition cleanup failed", |
| 1325 |
acquisition_error, |
| 1326 |
registration_error, |
| 1327 |
tracking_error, |
| 1328 |
rollback_error, |
| 1329 |
) |
| 1330 |
if registration_error is not None: # pragma: needs fork |
| 1331 |
_raise_cleanup_errors( |
| 1332 |
"lock acquisition cleanup failed", acquisition_error, registration_error, tracking_error |
| 1333 |
) |
| 1334 |
|
| 1335 |
def _rollback_failed_registration(self, registration_error: BaseException) -> None: # pragma: needs fork |
| 1336 |
tracking_error: BaseException | None = None |
| 1337 |
try: |
| 1338 |
# Rollback may fail too; retain the fd so a child can close it without another identity probe. |
| 1339 |
self._register_unverified_context_descriptor() |
| 1340 |
except BaseException as error: # ruff:ignore[blind-except] # pragma: no cover - allocation/control-flow during fallback |
| 1341 |
tracking_error = error |
| 1342 |
try: |
| 1343 |
self._release_with_fork_tracking() |
| 1344 |
except BaseException as rollback_error: # ruff:ignore[blind-except] # preserve rollback and registration failures |
| 1345 |
_raise_cleanup_errors( |
| 1346 |
"descriptor registration cleanup failed", registration_error, tracking_error, rollback_error |
| 1347 |
) |
| 1348 |
if tracking_error is not None: # pragma: no cover - requires failed in-memory fallback |
| 1349 |
_raise_cleanup_errors("descriptor registration cleanup failed", registration_error, tracking_error) |
| 1350 |
|
| 1351 |
def _release_with_fork_tracking(self) -> None: |
| 1352 |
with _fork_transition(self): |
| 1353 |
try: |
| 1354 |
self._release() |
| 1355 |
finally: |
| 1356 |
self._unregister_released_descriptor() |
| 1357 |
|
| 1358 |
def _register_context_descriptor(self) -> None: |
| 1359 |
if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: |
| 1360 |
self._context.lock_file_fd_token = _register_owned_descriptor( |
| 1361 |
self._context.lock_file_fd, |
| 1362 |
self._context.lock_file_fd_identity, |
| 1363 |
) |
| 1364 |
|
| 1365 |
def _register_unverified_context_descriptor(self) -> None: |
| 1366 |
# The rollback only reaches here still holding a descriptor it never managed to register. |
| 1367 |
if self._context.lock_file_fd is not None and self._context.lock_file_fd_token is None: # pragma: no branch |
| 1368 |
self._context.lock_file_fd_token = _register_unverified_owned_descriptor(self._context.lock_file_fd) |
| 1369 |
|
| 1370 |
def _unregister_released_descriptor(self) -> None: |
| 1371 |
if self._context.lock_file_fd is None: |
| 1372 |
if (token := self._context.lock_file_fd_token) is not None: # pragma: needs fork |
| 1373 |
_unregister_owned_descriptor(token) |
| 1374 |
self._context.lock_file_fd_token = None |
| 1375 |
self._context.lock_file_fd_identity = None |
| 1376 |
|
| 1377 |
def _undo_acquire(self) -> None: |
| 1378 |
"""Roll back the counter after a failed acquire, dropping the registry entry once nothing holds the path.""" |
| 1379 |
self._context.lock_counter = max(0, self._context.lock_counter - 1) |
| 1380 |
if self._context.lock_counter == 0: |
| 1381 |
self._drop_registry_entry() |
| 1382 |
|
| 1383 |
def _commit_acquire(self, canonical: str) -> None: |
| 1384 |
"""Record this instance as the holder once the first acquire succeeds, so peers can detect the deadlock.""" |
| 1385 |
if self._context.lock_counter == 1: |
| 1386 |
key = self._registry_key(canonical) |
| 1387 |
# The holder scope is resolved once at commit so a later release from another flow drops the right entry. |
| 1388 |
self._context.lock_file_key = key |
| 1389 |
_registry.held[key] = id(self) |
| 1390 |
|
| 1391 |
def _drop_registry_entry(self) -> None: |
| 1392 |
"""Forget the key owned by this hold without resolving a mutable path again.""" |
| 1393 |
key = self._context.lock_file_key |
| 1394 |
self._context.lock_file_key = None |
| 1395 |
if key is not None: |
| 1396 |
_registry.held.pop(key, None) |
| 1397 |
|
| 1398 |
def _commit_release(self) -> None: |
| 1399 |
"""Record the lock as fully released: reset the recursion counter and drop the deadlock-registry entry.""" |
| 1400 |
self._context.lock_counter = 0 |
| 1401 |
self._drop_registry_entry() |
| 1402 |
|
| 1403 |
def _try_break_expired_lock(self) -> None: |
| 1404 |
"""Remove the lock file if its modification time exceeds the configured :attr:`lifetime`.""" |
| 1405 |
if (lifetime := self._context.lifetime) is None: |
| 1406 |
return |
| 1407 |
with contextlib.suppress(OSError): |
| 1408 |
# lstat, not stat: an attacker with write access to the lock directory can replace a held |
| 1409 |
# lock file with a symlink pointing at an old file, making stat() report the target's stale |
| 1410 |
# mtime so a waiter breaks a live lock and two processes hold it at once. lstat reads the |
| 1411 |
# symlink's own mtime, matching the O_NOFOLLOW reads elsewhere. |
| 1412 |
st = os.lstat(self.lock_file) |
| 1413 |
if time.time() - st.st_mtime < lifetime: |
| 1414 |
return |
| 1415 |
break_lock_file(self.lock_file, st.st_mtime, st.st_ino) |
| 1416 |
|
| 1417 |
def _check_give_up( |
| 1418 |
self, |
| 1419 |
*, |
| 1420 |
blocking: bool, |
| 1421 |
cancel_check: Callable[[], bool] | None, |
| 1422 |
timeout: float, |
| 1423 |
start_time: float, |
| 1424 |
) -> bool: |
| 1425 |
lock_id, lock_filename = id(self), self.lock_file |
| 1426 |
if blocking is False: |
| 1427 |
_LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename) |
| 1428 |
return True |
| 1429 |
if cancel_check is not None and cancel_check(): |
| 1430 |
_LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename) |
| 1431 |
return True |
| 1432 |
if 0 <= timeout < time.perf_counter() - start_time: |
| 1433 |
_LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename) |
| 1434 |
return True |
| 1435 |
return False |
| 1436 |
|
| 1437 |
@abstractmethod |
| 1438 |
def _acquire(self) -> None: |
| 1439 |
"""If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file.""" |
| 1440 |
raise NotImplementedError |
| 1441 |
|
| 1442 |
@abstractmethod |
| 1443 |
def _release(self) -> None: |
| 1444 |
"""Releases the lock and sets self._context.lock_file_fd to None.""" |
| 1445 |
raise NotImplementedError |
| 1446 |
|
| 1447 |
|
| 1448 |
# acquire() returns this wrapper instead of self so entering the with-statement does not call __enter__ a second |
| 1449 |
# time; returning self would re-acquire the lock in BaseFileLock.__enter__ without a matching release (issue #37). |
| 1450 |
class AcquireReturnProxy: |
| 1451 |
"""A context-aware object that will release the lock file when exiting.""" |
| 1452 |
|
| 1453 |
def __init__(self, lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock) -> None: |
| 1454 |
self.lock: BaseFileLock | ReadWriteLock | SoftReadWriteLock = lock |
| 1455 |
|
| 1456 |
def __enter__(self) -> BaseFileLock | ReadWriteLock | SoftReadWriteLock: |
| 1457 |
return self.lock |
| 1458 |
|
| 1459 |
def __exit__( |
| 1460 |
self, |
| 1461 |
exc_type: type[BaseException] | None, |
| 1462 |
exc_value: BaseException | None, |
| 1463 |
traceback: TracebackType | None, |
| 1464 |
) -> None: |
| 1465 |
if isinstance(self.lock, BaseFileLock): |
| 1466 |
self.lock._release_in_context(exc_value) # ruff:ignore[private-member-access] # forwards __exit__ to the owned lock's context release |
| 1467 |
else: # a reader/writer lock does not carry a context_error_policy |
| 1468 |
self.lock.release() |
| 1469 |
|
| 1470 |
|
| 1471 |
@dataclass |
| 1472 |
class FileLockContext: |
| 1473 |
"""Holds the context for a ``BaseFileLock`` object.""" |
| 1474 |
|
| 1475 |
# A separate class so ThreadLocalFileContext can make the whole context thread-local. |
| 1476 |
|
| 1477 |
lock_file: str |
| 1478 |
timeout: float |
| 1479 |
mode: int |
| 1480 |
blocking: bool |
| 1481 |
poll_interval: float |
| 1482 |
|
| 1483 |
#: The lock lifetime in seconds; ``None`` means the lock never expires. |
| 1484 |
lifetime: float | None = None |
| 1485 |
|
| 1486 |
#: File descriptor from os.open for the lock file; not None while the lock is held. |
| 1487 |
lock_file_fd: int | None = None |
| 1488 |
|
| 1489 |
#: Registry token for the descriptor owned by this thread's context. |
| 1490 |
lock_file_fd_token: int | None = None |
| 1491 |
|
| 1492 |
#: Identity captured by a backend that already inspected the descriptor. |
| 1493 |
lock_file_fd_identity: tuple[int, int] | None = None |
| 1494 |
|
| 1495 |
#: Descriptor opened by a backend but not yet committed as the held lock. |
| 1496 |
pending_lock_file_fd: int | None = None |
| 1497 |
|
| 1498 |
#: Identity captured for a descriptor whose acquisition has not committed. |
| 1499 |
pending_lock_file_fd_identity: tuple[int, int] | None = None |
| 1500 |
|
| 1501 |
#: Depth of nested acquisitions; the lock is released only when it returns to 0. |
| 1502 |
lock_counter: int = 0 |
| 1503 |
|
| 1504 |
#: Canonical registry key captured when the first physical acquisition commits. |
| 1505 |
lock_file_key: Hashable | None = None |
| 1506 |
|
| 1507 |
#: Claim pathnames this owner published, removed by name on release so no holder ever unlinks a peer's claim. |
| 1508 |
owner_claim_paths: tuple[str, ...] = () |
| 1509 |
|
| 1510 |
#: Canonical lock path resolved when an acquisition starts. A waiter polling a relative path must keep publishing |
| 1511 |
#: into the directory it started in, even when another thread changes the working directory mid-wait. |
| 1512 |
claim_root: str | None = None |
| 1513 |
|
| 1514 |
|
| 1515 |
class ThreadLocalFileContext(FileLockContext, local): |
| 1516 |
"""A thread local version of the ``FileLockContext`` class.""" |
| 1517 |
|
| 1518 |
|
| 1519 |
@dataclass(frozen=True) |
| 1520 |
class _OwnedDescriptor: |
| 1521 |
fd: int |
| 1522 |
creator_pid: int |
| 1523 |
device: int | None |
| 1524 |
inode: int | None |
| 1525 |
|
| 1526 |
|
| 1527 |
class _ForkTransitionContext(local): |
| 1528 |
depth: int = 0 |
| 1529 |
|
| 1530 |
|
| 1531 |
class _ForkState: |
| 1532 |
def __init__(self) -> None: |
| 1533 |
self.gate = Condition(RLock()) |
| 1534 |
self.registry_lock = RLock() |
| 1535 |
self.parameter_models_lock = RLock() |
| 1536 |
self.transition_context = _ForkTransitionContext() |
| 1537 |
self.transitions: dict[int, dict[int, _ForkDescriptorOwner | None]] = {} |
| 1538 |
self.active_transitions = 0 |
| 1539 |
self.admission_closed = False |
| 1540 |
self.fork_owner_depths: dict[int, int] = {} |
| 1541 |
self.pinned_objects: dict[int, list[tuple[_ForkResettable, ...]]] = {} |
| 1542 |
self.pinned_classes: dict[int, list[tuple[_ForkResettableClass, ...]]] = {} |
| 1543 |
self.provisional_descriptor_tokens: dict[int, list[tuple[int, ...]]] = {} |
| 1544 |
self.pid = os.getpid() |
| 1545 |
|
| 1546 |
def reset_synchronization(self) -> None: # pragma: forked child |
| 1547 |
self.gate = Condition(RLock()) |
| 1548 |
self.registry_lock = RLock() |
| 1549 |
self.parameter_models_lock = RLock() |
| 1550 |
self.transition_context = _ForkTransitionContext() |
| 1551 |
self.transitions = {} |
| 1552 |
self.active_transitions = 0 |
| 1553 |
self.admission_closed = False |
| 1554 |
self.fork_owner_depths = {} |
| 1555 |
self.pinned_objects = {} |
| 1556 |
self.pinned_classes = {} |
| 1557 |
self.provisional_descriptor_tokens = {} |
| 1558 |
|
| 1559 |
|
| 1560 |
_FORK_OBJECTS: Final[WeakValueDictionary[int, _ForkResettable]] = WeakValueDictionary() |
| 1561 |
_FORK_CLASSES: Final[WeakValueDictionary[int, _ForkResettableClass]] = WeakValueDictionary() |
| 1562 |
_OWNED_DESCRIPTORS: Final[dict[int, _OwnedDescriptor]] = {} |
| 1563 |
_DESCRIPTOR_TOKENS: Final[count[int]] = count() |
| 1564 |
_TRANSITION_TOKENS: Final[count[int]] = count() |
| 1565 |
_FORK_STATE: Final = _ForkState() |
| 1566 |
_FORK_AUDIT_EVENTS: Final[frozenset[str]] = frozenset({"os.fork", "os.forkpty"}) |
| 1567 |
|
| 1568 |
|
| 1569 |
def _register_fork_hooks() -> None: |
| 1570 |
if _REGISTER_AT_FORK is None: |
| 1571 |
return # pragma: lacks fork |
| 1572 |
sys.addaudithook(_audit_fork_safety) # pragma: needs fork |
| 1573 |
_REGISTER_AT_FORK( # pragma: needs fork |
| 1574 |
before=_pin_fork_objects, |
| 1575 |
after_in_parent=_resume_parent_after_fork, |
| 1576 |
after_in_child=_reset_child_after_fork, |
| 1577 |
) |
| 1578 |
|
| 1579 |
|
| 1580 |
@contextmanager |
| 1581 |
def _fork_transition(descriptor_owner: _ForkDescriptorOwner | None = None) -> Generator[None]: |
| 1582 |
if not _HAS_REGISTER_AT_FORK: |
| 1583 |
yield # pragma: lacks fork |
| 1584 |
return # pragma: lacks fork |
| 1585 |
_ensure_current_process() # pragma: needs fork |
| 1586 |
creator_pid = os.getpid() # pragma: needs fork |
| 1587 |
token = _enter_fork_transition(descriptor_owner) # pragma: needs fork |
| 1588 |
try: # pragma: needs fork |
| 1589 |
yield |
| 1590 |
finally: |
| 1591 |
if os.getpid() == creator_pid: # pragma: needs fork |
| 1592 |
_leave_fork_transition(token) |
| 1593 |
|
| 1594 |
|
| 1595 |
def _register_fork_object(instance: _ForkResettable) -> None: |
| 1596 |
if not _HAS_REGISTER_AT_FORK: |
| 1597 |
return # pragma: lacks fork |
| 1598 |
with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork |
| 1599 |
_FORK_OBJECTS[id(instance)] = instance |
| 1600 |
_refresh_owner_pins() |
| 1601 |
|
| 1602 |
|
| 1603 |
def _register_fork_class(cls: _ForkResettableClass) -> None: |
| 1604 |
if not _HAS_REGISTER_AT_FORK: |
| 1605 |
return # pragma: lacks fork |
| 1606 |
with _fork_transition(), _FORK_STATE.registry_lock: # pragma: needs fork |
| 1607 |
_FORK_CLASSES[id(cls)] = cls |
| 1608 |
_refresh_owner_pins() |
| 1609 |
|
| 1610 |
|
| 1611 |
def _register_owned_descriptor(fd: int, identity: tuple[int, int] | None = None) -> int | None: |
| 1612 |
if not _HAS_REGISTER_AT_FORK: |
| 1613 |
return None # pragma: lacks fork |
| 1614 |
with _fork_transition(): # pragma: needs fork |
| 1615 |
if identity is None: |
| 1616 |
stat_result = os.fstat(fd) |
| 1617 |
identity = stat_result.st_dev, stat_result.st_ino |
| 1618 |
return _record_owned_descriptor(fd, identity) |
| 1619 |
|
| 1620 |
|
| 1621 |
def _register_unverified_owned_descriptor(fd: int) -> int | None: |
| 1622 |
if not _HAS_REGISTER_AT_FORK: |
| 1623 |
return None # pragma: lacks fork |
| 1624 |
with _fork_transition(): # pragma: needs fork |
| 1625 |
return _record_owned_descriptor(fd, None) |
| 1626 |
|
| 1627 |
|
| 1628 |
def _record_owned_descriptor(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork |
| 1629 |
with _FORK_STATE.registry_lock: |
| 1630 |
token = next(_DESCRIPTOR_TOKENS) |
| 1631 |
_OWNED_DESCRIPTORS[token] = _OwnedDescriptor( |
| 1632 |
fd=fd, |
| 1633 |
creator_pid=os.getpid(), |
| 1634 |
device=None if identity is None else identity[0], |
| 1635 |
inode=None if identity is None else identity[1], |
| 1636 |
) |
| 1637 |
return token |
| 1638 |
|
| 1639 |
|
| 1640 |
def _unregister_owned_descriptor(token: int) -> None: # pragma: needs fork |
| 1641 |
with _fork_transition(), _FORK_STATE.registry_lock: |
| 1642 |
_OWNED_DESCRIPTORS.pop(token, None) |
| 1643 |
|
| 1644 |
|
| 1645 |
def _pin_fork_objects() -> None: # pragma: needs fork |
| 1646 |
_ensure_current_process() |
| 1647 |
thread_id = get_ident() |
| 1648 |
with _FORK_STATE.gate: |
| 1649 |
_FORK_STATE.fork_owner_depths[thread_id] = _FORK_STATE.fork_owner_depths.get(thread_id, 0) + 1 |
| 1650 |
_FORK_STATE.admission_closed = True |
| 1651 |
while _FORK_STATE.active_transitions > len(_FORK_STATE.transitions.get(thread_id, ())): |
| 1652 |
_FORK_STATE.gate.wait() |
| 1653 |
transition_owners = tuple(_FORK_STATE.transitions.get(thread_id, {}).values()) |
| 1654 |
_verify_unverified_descriptors() |
| 1655 |
owners = {id(owner): owner for owner in transition_owners if owner is not None} |
| 1656 |
provisional_descriptor_tokens = tuple( |
| 1657 |
starmap( |
| 1658 |
_snapshot_descriptor_for_fork, |
| 1659 |
(descriptor for owner in owners.values() for descriptor in owner._descriptors_for_fork()), # ruff:ignore[private-member-access] # snapshots each owner's own fork descriptors |
| 1660 |
) |
| 1661 |
) |
| 1662 |
with _FORK_STATE.registry_lock: |
| 1663 |
_FORK_STATE.provisional_descriptor_tokens.setdefault(thread_id, []).append(provisional_descriptor_tokens) |
| 1664 |
_FORK_STATE.pinned_objects.setdefault(thread_id, []).append(tuple(_FORK_OBJECTS.values())) |
| 1665 |
_FORK_STATE.pinned_classes.setdefault(thread_id, []).append(tuple(_FORK_CLASSES.values())) |
| 1666 |
|
| 1667 |
|
| 1668 |
def _resume_parent_after_fork() -> None: # pragma: needs fork |
| 1669 |
thread_id = get_ident() |
| 1670 |
with _FORK_STATE.registry_lock: |
| 1671 |
for token in _FORK_STATE.provisional_descriptor_tokens[thread_id].pop(): |
| 1672 |
_OWNED_DESCRIPTORS.pop(token, None) |
| 1673 |
_FORK_STATE.pinned_objects[thread_id].pop() |
| 1674 |
_FORK_STATE.pinned_classes[thread_id].pop() |
| 1675 |
if not _FORK_STATE.provisional_descriptor_tokens[thread_id]: # pragma: needs fork |
| 1676 |
del _FORK_STATE.provisional_descriptor_tokens[thread_id] |
| 1677 |
del _FORK_STATE.pinned_objects[thread_id] |
| 1678 |
del _FORK_STATE.pinned_classes[thread_id] |
| 1679 |
with _FORK_STATE.gate: |
| 1680 |
if _FORK_STATE.fork_owner_depths[thread_id] == 1: |
| 1681 |
del _FORK_STATE.fork_owner_depths[thread_id] |
| 1682 |
else: # pragma: no cover - earlier at-fork callbacks may deadlock first |
| 1683 |
_FORK_STATE.fork_owner_depths[thread_id] -= 1 |
| 1684 |
_FORK_STATE.admission_closed = bool(_FORK_STATE.fork_owner_depths) |
| 1685 |
_FORK_STATE.gate.notify_all() |
| 1686 |
|
| 1687 |
|
| 1688 |
def _ensure_current_process() -> None: |
| 1689 |
_reset_child_after_fork() |
| 1690 |
|
| 1691 |
|
| 1692 |
def _reset_child_after_fork() -> None: # pragma: forked child |
| 1693 |
if (pid := os.getpid()) == _FORK_STATE.pid: |
| 1694 |
return |
| 1695 |
thread_id = get_ident() |
| 1696 |
pinned_objects = _FORK_STATE.pinned_objects.get(thread_id, [()])[-1] |
| 1697 |
pinned_classes = _FORK_STATE.pinned_classes.get(thread_id, [()])[-1] |
| 1698 |
descriptors: list[_OwnedDescriptor] = [] |
| 1699 |
for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()): |
| 1700 |
if descriptor.creator_pid != pid: |
| 1701 |
descriptors.append(_OWNED_DESCRIPTORS.pop(token)) |
| 1702 |
_FORK_STATE.reset_synchronization() |
| 1703 |
_FORK_STATE.pid = pid |
| 1704 |
_INIT_PARAMETER_MODELS.clear() |
| 1705 |
_detach_child_state(descriptors, pinned_objects, pinned_classes) |
| 1706 |
|
| 1707 |
|
| 1708 |
def _enter_fork_transition(descriptor_owner: _ForkDescriptorOwner | None) -> int: # pragma: needs fork |
| 1709 |
thread_id = get_ident() |
| 1710 |
with _FORK_STATE.gate: |
| 1711 |
while ( |
| 1712 |
_FORK_STATE.admission_closed |
| 1713 |
and thread_id not in _FORK_STATE.fork_owner_depths |
| 1714 |
and thread_id not in _FORK_STATE.transitions |
| 1715 |
): |
| 1716 |
_FORK_STATE.gate.wait() # pragma: no cover - exercised in isolated interpreter |
| 1717 |
token = next(_TRANSITION_TOKENS) |
| 1718 |
_FORK_STATE.transitions.setdefault(thread_id, {})[token] = descriptor_owner |
| 1719 |
_FORK_STATE.active_transitions += 1 |
| 1720 |
_FORK_STATE.transition_context.depth += 1 |
| 1721 |
return token |
| 1722 |
|
| 1723 |
|
| 1724 |
def _leave_fork_transition(token: int) -> None: # pragma: needs fork |
| 1725 |
_FORK_STATE.transition_context.depth -= 1 |
| 1726 |
with _FORK_STATE.gate: |
| 1727 |
thread_id = get_ident() |
| 1728 |
del _FORK_STATE.transitions[thread_id][token] |
| 1729 |
if not _FORK_STATE.transitions[thread_id]: |
| 1730 |
del _FORK_STATE.transitions[thread_id] |
| 1731 |
_FORK_STATE.active_transitions -= 1 |
| 1732 |
_FORK_STATE.gate.notify_all() |
| 1733 |
|
| 1734 |
|
| 1735 |
def _verify_unverified_descriptors() -> None: # pragma: needs fork |
| 1736 |
with _FORK_STATE.registry_lock: |
| 1737 |
for token, descriptor in tuple(_OWNED_DESCRIPTORS.items()): |
| 1738 |
if descriptor.creator_pid != os.getpid() or descriptor.device is not None: |
| 1739 |
continue |
| 1740 |
try: |
| 1741 |
stat_result = os.fstat(descriptor.fd) |
| 1742 |
except OSError: |
| 1743 |
continue |
| 1744 |
_OWNED_DESCRIPTORS[token] = _OwnedDescriptor( |
| 1745 |
fd=descriptor.fd, |
| 1746 |
creator_pid=descriptor.creator_pid, |
| 1747 |
device=stat_result.st_dev, |
| 1748 |
inode=stat_result.st_ino, |
| 1749 |
) |
| 1750 |
|
| 1751 |
|
| 1752 |
def _snapshot_descriptor_for_fork(fd: int, identity: tuple[int, int] | None) -> int: # pragma: needs fork |
| 1753 |
if identity is None: # pragma: needs fork |
| 1754 |
try: |
| 1755 |
stat_result = os.fstat(fd) |
| 1756 |
except OSError: |
| 1757 |
pass |
| 1758 |
else: |
| 1759 |
identity = stat_result.st_dev, stat_result.st_ino |
| 1760 |
return _record_owned_descriptor(fd, identity) |
| 1761 |
|
| 1762 |
|
| 1763 |
def _detach_child_state( # pragma: forked child |
| 1764 |
descriptors: list[_OwnedDescriptor], |
| 1765 |
pinned_objects: tuple[_ForkResettable, ...], |
| 1766 |
pinned_classes: tuple[_ForkResettableClass, ...], |
| 1767 |
) -> None: |
| 1768 |
for descriptor in descriptors: |
| 1769 |
if descriptor.device is None: |
| 1770 |
continue |
| 1771 |
try: |
| 1772 |
stat_result = os.fstat(descriptor.fd) |
| 1773 |
except OSError: |
| 1774 |
continue |
| 1775 |
if (stat_result.st_dev, stat_result.st_ino) != (descriptor.device, descriptor.inode): |
| 1776 |
continue |
| 1777 |
with contextlib.suppress(OSError): |
| 1778 |
os.close(descriptor.fd) |
| 1779 |
for instance in pinned_objects: |
| 1780 |
instance._reset_after_fork_in_child() # ruff:ignore[private-member-access] # resets each pinned instance in the fork child |
| 1781 |
for cls in pinned_classes: |
| 1782 |
cls._reset_class_after_fork() |
| 1783 |
_registry.held.clear() |
| 1784 |
|
| 1785 |
|
| 1786 |
def _refresh_owner_pins() -> None: # pragma: needs fork |
| 1787 |
with _FORK_STATE.gate: |
| 1788 |
fork_owner_thread_ids = tuple(_FORK_STATE.fork_owner_depths) |
| 1789 |
if get_ident() not in fork_owner_thread_ids: # pragma: no cover - at-fork callbacks disable tracing |
| 1790 |
return |
| 1791 |
objects = tuple(_FORK_OBJECTS.values()) |
| 1792 |
classes = tuple(_FORK_CLASSES.values()) |
| 1793 |
for thread_id in fork_owner_thread_ids: |
| 1794 |
if object_snapshots := _FORK_STATE.pinned_objects.get(thread_id): # pragma: needs fork |
| 1795 |
object_snapshots[:] = [objects] * len(object_snapshots) |
| 1796 |
_FORK_STATE.pinned_classes[thread_id][:] = [classes] * len(object_snapshots) |
| 1797 |
|
| 1798 |
|
| 1799 |
# The defaults capture the module globals: the hook outlives them at interpreter shutdown, where CPython wipes the |
| 1800 |
# module dict to None before the final audit events fire. |
| 1801 |
def _audit_fork_safety( # pragma: no cover - CPython disables tracing while Python audit hooks run |
| 1802 |
event: str, |
| 1803 |
_args: Unused, |
| 1804 |
*, |
| 1805 |
_fork_events: frozenset[str] = _FORK_AUDIT_EVENTS, |
| 1806 |
_state: _ForkState = _FORK_STATE, |
| 1807 |
) -> None: |
| 1808 |
if event in _fork_events: |
| 1809 |
if _state.transition_context.depth or _state.fork_owner_depths: |
| 1810 |
msg = f"{event} is unsafe while filelock is changing descriptor ownership" |
| 1811 |
raise RuntimeError(msg) |
| 1812 |
elif event == "_posixsubprocess.fork_exec" and _state.transition_context.depth: |
| 1813 |
msg = "fork_exec is unsafe while filelock is changing descriptor ownership" |
| 1814 |
raise RuntimeError(msg) |
| 1815 |
|
| 1816 |
|
| 1817 |
_register_fork_hooks() |
| 1818 |
|
| 1819 |
|
| 1820 |
__all__ = [ |
| 1821 |
"_UNSET_FILE_MODE", |
| 1822 |
"AcquireReturnProxy", |
| 1823 |
"BaseFileLock", |
| 1824 |
"CloseErrorPolicy", |
| 1825 |
"ContextErrorPolicy", |
| 1826 |
"FileLockContext", |
| 1827 |
"FileLockMeta", |
| 1828 |
"LockOptions", |
| 1829 |
"_append_exception_context", |
| 1830 |
"_canonical", |
| 1831 |
"_ensure_current_process", |
| 1832 |
"_fork_transition", |
| 1833 |
"_grouped_errors", |
| 1834 |
"_raise_body_and_release", |
| 1835 |
"_raise_chained_errors", |
| 1836 |
"_raise_cleanup_errors", |
| 1837 |
"_raise_grouped_errors", |
| 1838 |
"_register_fork_class", |
| 1839 |
"_register_fork_object", |
| 1840 |
"_register_owned_descriptor", |
| 1841 |
"_unregister_owned_descriptor", |
| 1842 |
] |