_api.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. from __future__ import annotations
  2. import contextlib
  3. import inspect
  4. import logging
  5. import os
  6. import pathlib
  7. import sys
  8. import time
  9. import warnings
  10. from abc import ABCMeta, abstractmethod
  11. from dataclasses import dataclass
  12. from threading import local
  13. from typing import TYPE_CHECKING, Any, cast
  14. from weakref import WeakValueDictionary
  15. from ._error import Timeout
  16. #: Sentinel indicating that no explicit file permission mode was passed.
  17. #: When used, lock files are created with 0o666 (letting umask and default ACLs control the final permissions)
  18. #: and fchmod is skipped so that POSIX default ACL inheritance is preserved.
  19. _UNSET_FILE_MODE: int = -1
  20. if TYPE_CHECKING:
  21. from collections.abc import Callable
  22. from types import TracebackType
  23. from ._read_write import ReadWriteLock
  24. if sys.version_info >= (3, 11): # pragma: no cover (py311+)
  25. from typing import Self
  26. else: # pragma: no cover (<py311)
  27. from typing_extensions import Self
  28. _LOGGER = logging.getLogger("filelock")
  29. # On Windows os.path.realpath calls CreateFileW with share_mode=0, which blocks concurrent DeleteFileW and causes
  30. # livelocks under threaded contention with SoftFileLock. os.path.abspath is purely string-based and avoids this.
  31. _canonical = os.path.abspath if sys.platform == "win32" else os.path.realpath
  32. class _ThreadLocalRegistry(local):
  33. def __init__(self) -> None:
  34. super().__init__()
  35. self.held: dict[str, int] = {}
  36. _registry = _ThreadLocalRegistry()
  37. # This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__
  38. # is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired
  39. # again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak)
  40. class AcquireReturnProxy:
  41. """A context-aware object that will release the lock file when exiting."""
  42. def __init__(self, lock: BaseFileLock | ReadWriteLock) -> None:
  43. self.lock: BaseFileLock | ReadWriteLock = lock
  44. def __enter__(self) -> BaseFileLock | ReadWriteLock:
  45. return self.lock
  46. def __exit__(
  47. self,
  48. exc_type: type[BaseException] | None,
  49. exc_value: BaseException | None,
  50. traceback: TracebackType | None,
  51. ) -> None:
  52. self.lock.release()
  53. @dataclass
  54. class FileLockContext:
  55. """A dataclass which holds the context for a ``BaseFileLock`` object."""
  56. # The context is held in a separate class to allow optional use of thread local storage via the
  57. # ThreadLocalFileContext class.
  58. #: The path to the lock file.
  59. lock_file: str
  60. #: The default timeout value.
  61. timeout: float
  62. #: The mode for the lock files
  63. mode: int
  64. #: Whether the lock should be blocking or not
  65. blocking: bool
  66. #: The default polling interval value.
  67. poll_interval: float
  68. #: The lock lifetime in seconds; ``None`` means the lock never expires.
  69. lifetime: float | None = None
  70. #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held
  71. lock_file_fd: int | None = None
  72. #: The lock counter is used for implementing the nested locking mechanism.
  73. lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
  74. class ThreadLocalFileContext(FileLockContext, local):
  75. """A thread local version of the ``FileLockContext`` class."""
  76. class FileLockMeta(ABCMeta):
  77. _instances: WeakValueDictionary[str, BaseFileLock]
  78. def __call__( # noqa: PLR0913
  79. cls,
  80. lock_file: str | os.PathLike[str],
  81. timeout: float = -1,
  82. mode: int = _UNSET_FILE_MODE,
  83. thread_local: bool = True, # noqa: FBT001, FBT002
  84. *,
  85. blocking: bool = True,
  86. is_singleton: bool = False,
  87. poll_interval: float = 0.05,
  88. lifetime: float | None = None,
  89. **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ANN401
  90. ) -> BaseFileLock:
  91. if is_singleton:
  92. instance = cls._instances.get(str(lock_file))
  93. if instance:
  94. params_to_check = {
  95. "thread_local": (thread_local, instance.is_thread_local()),
  96. "timeout": (timeout, instance.timeout),
  97. "mode": (mode, instance._context.mode), # noqa: SLF001
  98. "blocking": (blocking, instance.blocking),
  99. "poll_interval": (poll_interval, instance.poll_interval),
  100. "lifetime": (lifetime, instance.lifetime),
  101. }
  102. non_matching_params = {
  103. name: (passed_param, set_param)
  104. for name, (passed_param, set_param) in params_to_check.items()
  105. if passed_param != set_param
  106. }
  107. if not non_matching_params:
  108. return cast("BaseFileLock", instance)
  109. # parameters do not match; raise error
  110. msg = "Singleton lock instances cannot be initialized with differing arguments"
  111. msg += "\nNon-matching arguments: "
  112. for param_name, (passed_param, set_param) in non_matching_params.items():
  113. msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)"
  114. raise ValueError(msg)
  115. # Workaround to make `__init__`'s params optional in subclasses
  116. # E.g. virtualenv changes the signature of the `__init__` method in the `BaseFileLock` class descendant
  117. # (https://github.com/tox-dev/filelock/pull/340)
  118. all_params = {
  119. "timeout": timeout,
  120. "mode": mode,
  121. "thread_local": thread_local,
  122. "blocking": blocking,
  123. "is_singleton": is_singleton,
  124. "poll_interval": poll_interval,
  125. "lifetime": lifetime,
  126. **kwargs,
  127. }
  128. present_params = inspect.signature(cls.__init__).parameters
  129. init_params = {key: value for key, value in all_params.items() if key in present_params}
  130. instance = super().__call__(lock_file, **init_params)
  131. if is_singleton:
  132. cls._instances[str(lock_file)] = instance
  133. return cast("BaseFileLock", instance)
  134. class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta):
  135. """
  136. Abstract base class for a file lock object.
  137. Provides a reentrant, cross-process exclusive lock backed by OS-level primitives. Subclasses implement the actual
  138. locking mechanism (:class:`UnixFileLock <filelock.UnixFileLock>`, :class:`WindowsFileLock
  139. <filelock.WindowsFileLock>`, :class:`SoftFileLock <filelock.SoftFileLock>`).
  140. """
  141. _instances: WeakValueDictionary[str, BaseFileLock]
  142. def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
  143. """Setup unique state for lock subclasses."""
  144. super().__init_subclass__(**kwargs)
  145. cls._instances = WeakValueDictionary()
  146. def __init__( # noqa: PLR0913
  147. self,
  148. lock_file: str | os.PathLike[str],
  149. timeout: float = -1,
  150. mode: int = _UNSET_FILE_MODE,
  151. thread_local: bool = True, # noqa: FBT001, FBT002
  152. *,
  153. blocking: bool = True,
  154. is_singleton: bool = False,
  155. poll_interval: float = 0.05,
  156. lifetime: float | None = None,
  157. ) -> None:
  158. """
  159. Create a new lock object.
  160. :param lock_file: path to the file
  161. :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in the
  162. acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it to a
  163. negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
  164. :param mode: file permissions for the lockfile. When not specified, the OS controls permissions via umask and
  165. default ACLs, preserving POSIX default ACL inheritance in shared directories.
  166. :param thread_local: Whether this object's internal context should be thread local or not. If this is set to
  167. ``False`` then the lock will be reentrant across threads.
  168. :param blocking: whether the lock should be blocking or not
  169. :param is_singleton: If this is set to ``True`` then only one instance of this class will be created per lock
  170. file. This is useful if you want to use the lock object for reentrant locking without needing to pass the
  171. same object around.
  172. :param poll_interval: default interval for polling the lock file, in seconds. It will be used as fallback value
  173. in the acquire method, if no poll_interval value (``None``) is given.
  174. :param lifetime: maximum time in seconds a lock can be held before it is considered expired. When set, a waiting
  175. process will break a lock whose file modification time is older than ``lifetime`` seconds. ``None`` (the
  176. default) means locks never expire.
  177. """
  178. self._is_thread_local = thread_local
  179. self._is_singleton = is_singleton
  180. # Create the context. Note that external code should not work with the context directly and should instead use
  181. # properties of this class.
  182. kwargs: dict[str, Any] = {
  183. "lock_file": os.fspath(lock_file),
  184. "timeout": timeout,
  185. "mode": mode,
  186. "blocking": blocking,
  187. "poll_interval": poll_interval,
  188. "lifetime": lifetime,
  189. }
  190. self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
  191. def is_thread_local(self) -> bool:
  192. """:returns: a flag indicating if this lock is thread local or not"""
  193. return self._is_thread_local
  194. @property
  195. def is_singleton(self) -> bool:
  196. """
  197. :returns: a flag indicating if this lock is singleton or not
  198. .. versionadded:: 3.13.0
  199. """
  200. return self._is_singleton
  201. @property
  202. def lock_file(self) -> str:
  203. """:returns: path to the lock file"""
  204. return self._context.lock_file
  205. @property
  206. def timeout(self) -> float:
  207. """
  208. :returns: the default timeout value, in seconds
  209. .. versionadded:: 2.0.0
  210. """
  211. return self._context.timeout
  212. @timeout.setter
  213. def timeout(self, value: float | str) -> None:
  214. """
  215. Change the default timeout value.
  216. :param value: the new value, in seconds
  217. """
  218. self._context.timeout = float(value)
  219. @property
  220. def blocking(self) -> bool:
  221. """
  222. :returns: whether the locking is blocking or not
  223. .. versionadded:: 3.14.0
  224. """
  225. return self._context.blocking
  226. @blocking.setter
  227. def blocking(self, value: bool) -> None:
  228. """
  229. Change the default blocking value.
  230. :param value: the new value as bool
  231. """
  232. self._context.blocking = value
  233. @property
  234. def poll_interval(self) -> float:
  235. """
  236. :returns: the default polling interval, in seconds
  237. .. versionadded:: 3.24.0
  238. """
  239. return self._context.poll_interval
  240. @poll_interval.setter
  241. def poll_interval(self, value: float) -> None:
  242. """
  243. Change the default polling interval.
  244. :param value: the new value, in seconds
  245. """
  246. self._context.poll_interval = value
  247. @property
  248. def lifetime(self) -> float | None:
  249. """
  250. :returns: the lock lifetime in seconds, or ``None`` if the lock never expires
  251. .. versionadded:: 3.24.0
  252. """
  253. return self._context.lifetime
  254. @lifetime.setter
  255. def lifetime(self, value: float | None) -> None:
  256. """
  257. Change the lock lifetime.
  258. :param value: the new value in seconds, or ``None`` to disable expiration
  259. """
  260. self._context.lifetime = value
  261. @property
  262. def mode(self) -> int:
  263. """:returns: the file permissions for the lockfile"""
  264. return 0o644 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
  265. @property
  266. def has_explicit_mode(self) -> bool:
  267. """:returns: whether the file permissions were explicitly set"""
  268. return self._context.mode != _UNSET_FILE_MODE
  269. def _open_mode(self) -> int:
  270. """:returns: the mode for os.open() — 0o666 when unset (let umask/ACLs decide), else the explicit mode"""
  271. return 0o666 if self._context.mode == _UNSET_FILE_MODE else self._context.mode
  272. def _try_break_expired_lock(self) -> None:
  273. """Remove the lock file if its modification time exceeds the configured :attr:`lifetime`."""
  274. if (lifetime := self._context.lifetime) is None:
  275. return
  276. with contextlib.suppress(OSError):
  277. if time.time() - pathlib.Path(self.lock_file).stat().st_mtime < lifetime:
  278. return
  279. break_path = f"{self.lock_file}.break.{os.getpid()}"
  280. pathlib.Path(self.lock_file).rename(break_path)
  281. pathlib.Path(break_path).unlink()
  282. @abstractmethod
  283. def _acquire(self) -> None:
  284. """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
  285. raise NotImplementedError
  286. @abstractmethod
  287. def _release(self) -> None:
  288. """Releases the lock and sets self._context.lock_file_fd to None."""
  289. raise NotImplementedError
  290. @property
  291. def is_locked(self) -> bool:
  292. """
  293. :returns: A boolean indicating if the lock file is holding the lock currently.
  294. .. versionchanged:: 2.0.0
  295. This was previously a method and is now a property.
  296. """
  297. return self._context.lock_file_fd is not None
  298. @property
  299. def lock_counter(self) -> int:
  300. """:returns: The number of times this lock has been acquired (but not yet released)."""
  301. return self._context.lock_counter
  302. @staticmethod
  303. def _check_give_up( # noqa: PLR0913
  304. lock_id: int,
  305. lock_filename: str,
  306. *,
  307. blocking: bool,
  308. cancel_check: Callable[[], bool] | None,
  309. timeout: float,
  310. start_time: float,
  311. ) -> bool:
  312. if blocking is False:
  313. _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
  314. return True
  315. if cancel_check is not None and cancel_check():
  316. _LOGGER.debug("Cancellation requested for lock %s on %s", lock_id, lock_filename)
  317. return True
  318. if 0 <= timeout < time.perf_counter() - start_time:
  319. _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
  320. return True
  321. return False
  322. def acquire( # noqa: C901
  323. self,
  324. timeout: float | None = None,
  325. poll_interval: float | None = None,
  326. *,
  327. poll_intervall: float | None = None,
  328. blocking: bool | None = None,
  329. cancel_check: Callable[[], bool] | None = None,
  330. ) -> AcquireReturnProxy:
  331. """
  332. Try to acquire the file lock.
  333. :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
  334. if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
  335. :param poll_interval: interval of trying to acquire the lock file, ``None`` means use the default
  336. :attr:`~poll_interval`
  337. :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
  338. :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
  339. first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
  340. :param cancel_check: a callable returning ``True`` when the acquisition should be canceled. Checked on each poll
  341. iteration. When triggered, raises :class:`~Timeout` just like an expired timeout.
  342. :returns: a context object that will unlock the file when the context is exited
  343. :raises Timeout: if fails to acquire lock within the timeout period
  344. .. code-block:: python
  345. # You can use this method in the context manager (recommended)
  346. with lock.acquire():
  347. pass
  348. # Or use an equivalent try-finally construct:
  349. lock.acquire()
  350. try:
  351. pass
  352. finally:
  353. lock.release()
  354. .. versionchanged:: 2.0.0
  355. This method returns now a *proxy* object instead of *self*, so that it can be used in a with statement
  356. without side effects.
  357. """
  358. # Use the default timeout, if no timeout is provided.
  359. if timeout is None:
  360. timeout = self._context.timeout
  361. if blocking is None:
  362. blocking = self._context.blocking
  363. if poll_intervall is not None:
  364. msg = "use poll_interval instead of poll_intervall"
  365. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  366. poll_interval = poll_intervall
  367. poll_interval = poll_interval if poll_interval is not None else self._context.poll_interval
  368. # Increment the number right at the beginning. We can still undo it, if something fails.
  369. self._context.lock_counter += 1
  370. lock_id = id(self)
  371. lock_filename = self.lock_file
  372. canonical = _canonical(lock_filename)
  373. would_block = self._context.lock_counter == 1 and not self.is_locked and timeout < 0 and blocking
  374. if would_block and (existing := _registry.held.get(canonical)) is not None and existing != lock_id:
  375. self._context.lock_counter -= 1
  376. msg = (
  377. f"Deadlock: lock '{lock_filename}' is already held by a different "
  378. f"FileLock instance in this thread. Use is_singleton=True to "
  379. f"enable reentrant locking across instances."
  380. )
  381. raise RuntimeError(msg)
  382. start_time = time.perf_counter()
  383. try:
  384. while True:
  385. if not self.is_locked:
  386. self._try_break_expired_lock()
  387. _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
  388. self._acquire()
  389. if self.is_locked:
  390. _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
  391. break
  392. if self._check_give_up(
  393. lock_id,
  394. lock_filename,
  395. blocking=blocking,
  396. cancel_check=cancel_check,
  397. timeout=timeout,
  398. start_time=start_time,
  399. ):
  400. raise Timeout(lock_filename) # noqa: TRY301
  401. msg = "Lock %s not acquired on %s, waiting %s seconds ..."
  402. _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
  403. time.sleep(poll_interval)
  404. except BaseException:
  405. self._context.lock_counter = max(0, self._context.lock_counter - 1)
  406. if self._context.lock_counter == 0:
  407. _registry.held.pop(canonical, None)
  408. raise
  409. if self._context.lock_counter == 1:
  410. _registry.held[canonical] = lock_id
  411. return AcquireReturnProxy(lock=self)
  412. def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
  413. """
  414. Release the file lock. The lock is only completely released when the lock counter reaches 0. The lock file
  415. itself is not automatically deleted.
  416. :param force: If true, the lock counter is ignored and the lock is released in every case.
  417. """
  418. if self.is_locked:
  419. self._context.lock_counter -= 1
  420. if self._context.lock_counter == 0 or force:
  421. lock_id, lock_filename = id(self), self.lock_file
  422. _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
  423. self._release()
  424. self._context.lock_counter = 0
  425. _registry.held.pop(_canonical(lock_filename), None)
  426. _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
  427. def __enter__(self) -> Self:
  428. """
  429. Acquire the lock.
  430. :returns: the lock object
  431. """
  432. self.acquire()
  433. return self
  434. def __exit__(
  435. self,
  436. exc_type: type[BaseException] | None,
  437. exc_value: BaseException | None,
  438. traceback: TracebackType | None,
  439. ) -> None:
  440. """
  441. Release the lock.
  442. :param exc_type: the exception type if raised
  443. :param exc_value: the exception value if raised
  444. :param traceback: the exception traceback if raised
  445. """
  446. self.release()
  447. def __del__(self) -> None:
  448. """Called when the lock object is deleted."""
  449. self.release(force=True)
  450. __all__ = [
  451. "_UNSET_FILE_MODE",
  452. "AcquireReturnProxy",
  453. "BaseFileLock",
  454. ]