_api.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. from __future__ import annotations
  2. import contextlib
  3. import inspect
  4. import logging
  5. import os
  6. import time
  7. import warnings
  8. from abc import ABCMeta, abstractmethod
  9. from dataclasses import dataclass
  10. from threading import local
  11. from typing import TYPE_CHECKING, Any, cast
  12. from weakref import WeakValueDictionary
  13. from ._error import Timeout
  14. if TYPE_CHECKING:
  15. import sys
  16. from types import TracebackType
  17. if sys.version_info >= (3, 11): # pragma: no cover (py311+)
  18. from typing import Self
  19. else: # pragma: no cover (<py311)
  20. from typing_extensions import Self
  21. _LOGGER = logging.getLogger("filelock")
  22. # This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__
  23. # is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired
  24. # again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak)
  25. class AcquireReturnProxy:
  26. """A context-aware object that will release the lock file when exiting."""
  27. def __init__(self, lock: BaseFileLock) -> None:
  28. self.lock = lock
  29. def __enter__(self) -> BaseFileLock:
  30. return self.lock
  31. def __exit__(
  32. self,
  33. exc_type: type[BaseException] | None,
  34. exc_value: BaseException | None,
  35. traceback: TracebackType | None,
  36. ) -> None:
  37. self.lock.release()
  38. @dataclass
  39. class FileLockContext:
  40. """A dataclass which holds the context for a ``BaseFileLock`` object."""
  41. # The context is held in a separate class to allow optional use of thread local storage via the
  42. # ThreadLocalFileContext class.
  43. #: The path to the lock file.
  44. lock_file: str
  45. #: The default timeout value.
  46. timeout: float
  47. #: The mode for the lock files
  48. mode: int
  49. #: Whether the lock should be blocking or not
  50. blocking: bool
  51. #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held
  52. lock_file_fd: int | None = None
  53. #: The lock counter is used for implementing the nested locking mechanism.
  54. lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
  55. class ThreadLocalFileContext(FileLockContext, local):
  56. """A thread local version of the ``FileLockContext`` class."""
  57. class FileLockMeta(ABCMeta):
  58. def __call__( # noqa: PLR0913
  59. cls,
  60. lock_file: str | os.PathLike[str],
  61. timeout: float = -1,
  62. mode: int = 0o644,
  63. thread_local: bool = True, # noqa: FBT001, FBT002
  64. *,
  65. blocking: bool = True,
  66. is_singleton: bool = False,
  67. **kwargs: Any, # capture remaining kwargs for subclasses # noqa: ANN401
  68. ) -> BaseFileLock:
  69. if is_singleton:
  70. instance = cls._instances.get(str(lock_file)) # type: ignore[attr-defined]
  71. if instance:
  72. params_to_check = {
  73. "thread_local": (thread_local, instance.is_thread_local()),
  74. "timeout": (timeout, instance.timeout),
  75. "mode": (mode, instance.mode),
  76. "blocking": (blocking, instance.blocking),
  77. }
  78. non_matching_params = {
  79. name: (passed_param, set_param)
  80. for name, (passed_param, set_param) in params_to_check.items()
  81. if passed_param != set_param
  82. }
  83. if not non_matching_params:
  84. return cast(BaseFileLock, instance)
  85. # parameters do not match; raise error
  86. msg = "Singleton lock instances cannot be initialized with differing arguments"
  87. msg += "\nNon-matching arguments: "
  88. for param_name, (passed_param, set_param) in non_matching_params.items():
  89. msg += f"\n\t{param_name} (existing lock has {set_param} but {passed_param} was passed)"
  90. raise ValueError(msg)
  91. # Workaround to make `__init__`'s params optional in subclasses
  92. # E.g. virtualenv changes the signature of the `__init__` method in the `BaseFileLock` class descendant
  93. # (https://github.com/tox-dev/filelock/pull/340)
  94. all_params = {
  95. "timeout": timeout,
  96. "mode": mode,
  97. "thread_local": thread_local,
  98. "blocking": blocking,
  99. "is_singleton": is_singleton,
  100. **kwargs,
  101. }
  102. present_params = inspect.signature(cls.__init__).parameters # type: ignore[misc]
  103. init_params = {key: value for key, value in all_params.items() if key in present_params}
  104. instance = super().__call__(lock_file, **init_params)
  105. if is_singleton:
  106. cls._instances[str(lock_file)] = instance # type: ignore[attr-defined]
  107. return cast(BaseFileLock, instance)
  108. class BaseFileLock(contextlib.ContextDecorator, metaclass=FileLockMeta):
  109. """Abstract base class for a file lock object."""
  110. _instances: WeakValueDictionary[str, BaseFileLock]
  111. def __init_subclass__(cls, **kwargs: dict[str, Any]) -> None:
  112. """Setup unique state for lock subclasses."""
  113. super().__init_subclass__(**kwargs)
  114. cls._instances = WeakValueDictionary()
  115. def __init__( # noqa: PLR0913
  116. self,
  117. lock_file: str | os.PathLike[str],
  118. timeout: float = -1,
  119. mode: int = 0o644,
  120. thread_local: bool = True, # noqa: FBT001, FBT002
  121. *,
  122. blocking: bool = True,
  123. is_singleton: bool = False,
  124. ) -> None:
  125. """
  126. Create a new lock object.
  127. :param lock_file: path to the file
  128. :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in \
  129. the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it \
  130. to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
  131. :param mode: file permissions for the lockfile
  132. :param thread_local: Whether this object's internal context should be thread local or not. If this is set to \
  133. ``False`` then the lock will be reentrant across threads.
  134. :param blocking: whether the lock should be blocking or not
  135. :param is_singleton: If this is set to ``True`` then only one instance of this class will be created \
  136. per lock file. This is useful if you want to use the lock object for reentrant locking without needing \
  137. to pass the same object around.
  138. """
  139. self._is_thread_local = thread_local
  140. self._is_singleton = is_singleton
  141. # Create the context. Note that external code should not work with the context directly and should instead use
  142. # properties of this class.
  143. kwargs: dict[str, Any] = {
  144. "lock_file": os.fspath(lock_file),
  145. "timeout": timeout,
  146. "mode": mode,
  147. "blocking": blocking,
  148. }
  149. self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
  150. def is_thread_local(self) -> bool:
  151. """:return: a flag indicating if this lock is thread local or not"""
  152. return self._is_thread_local
  153. @property
  154. def is_singleton(self) -> bool:
  155. """:return: a flag indicating if this lock is singleton or not"""
  156. return self._is_singleton
  157. @property
  158. def lock_file(self) -> str:
  159. """:return: path to the lock file"""
  160. return self._context.lock_file
  161. @property
  162. def timeout(self) -> float:
  163. """
  164. :return: the default timeout value, in seconds
  165. .. versionadded:: 2.0.0
  166. """
  167. return self._context.timeout
  168. @timeout.setter
  169. def timeout(self, value: float | str) -> None:
  170. """
  171. Change the default timeout value.
  172. :param value: the new value, in seconds
  173. """
  174. self._context.timeout = float(value)
  175. @property
  176. def blocking(self) -> bool:
  177. """:return: whether the locking is blocking or not"""
  178. return self._context.blocking
  179. @blocking.setter
  180. def blocking(self, value: bool) -> None:
  181. """
  182. Change the default blocking value.
  183. :param value: the new value as bool
  184. """
  185. self._context.blocking = value
  186. @property
  187. def mode(self) -> int:
  188. """:return: the file permissions for the lockfile"""
  189. return self._context.mode
  190. @abstractmethod
  191. def _acquire(self) -> None:
  192. """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
  193. raise NotImplementedError
  194. @abstractmethod
  195. def _release(self) -> None:
  196. """Releases the lock and sets self._context.lock_file_fd to None."""
  197. raise NotImplementedError
  198. @property
  199. def is_locked(self) -> bool:
  200. """
  201. :return: A boolean indicating if the lock file is holding the lock currently.
  202. .. versionchanged:: 2.0.0
  203. This was previously a method and is now a property.
  204. """
  205. return self._context.lock_file_fd is not None
  206. @property
  207. def lock_counter(self) -> int:
  208. """:return: The number of times this lock has been acquired (but not yet released)."""
  209. return self._context.lock_counter
  210. def acquire(
  211. self,
  212. timeout: float | None = None,
  213. poll_interval: float = 0.05,
  214. *,
  215. poll_intervall: float | None = None,
  216. blocking: bool | None = None,
  217. ) -> AcquireReturnProxy:
  218. """
  219. Try to acquire the file lock.
  220. :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
  221. if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
  222. :param poll_interval: interval of trying to acquire the lock file
  223. :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
  224. :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
  225. first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
  226. :raises Timeout: if fails to acquire lock within the timeout period
  227. :return: a context object that will unlock the file when the context is exited
  228. .. code-block:: python
  229. # You can use this method in the context manager (recommended)
  230. with lock.acquire():
  231. pass
  232. # Or use an equivalent try-finally construct:
  233. lock.acquire()
  234. try:
  235. pass
  236. finally:
  237. lock.release()
  238. .. versionchanged:: 2.0.0
  239. This method returns now a *proxy* object instead of *self*,
  240. so that it can be used in a with statement without side effects.
  241. """
  242. # Use the default timeout, if no timeout is provided.
  243. if timeout is None:
  244. timeout = self._context.timeout
  245. if blocking is None:
  246. blocking = self._context.blocking
  247. if poll_intervall is not None:
  248. msg = "use poll_interval instead of poll_intervall"
  249. warnings.warn(msg, DeprecationWarning, stacklevel=2)
  250. poll_interval = poll_intervall
  251. # Increment the number right at the beginning. We can still undo it, if something fails.
  252. self._context.lock_counter += 1
  253. lock_id = id(self)
  254. lock_filename = self.lock_file
  255. start_time = time.perf_counter()
  256. try:
  257. while True:
  258. if not self.is_locked:
  259. _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
  260. self._acquire()
  261. if self.is_locked:
  262. _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
  263. break
  264. if blocking is False:
  265. _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
  266. raise Timeout(lock_filename) # noqa: TRY301
  267. if 0 <= timeout < time.perf_counter() - start_time:
  268. _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
  269. raise Timeout(lock_filename) # noqa: TRY301
  270. msg = "Lock %s not acquired on %s, waiting %s seconds ..."
  271. _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
  272. time.sleep(poll_interval)
  273. except BaseException: # Something did go wrong, so decrement the counter.
  274. self._context.lock_counter = max(0, self._context.lock_counter - 1)
  275. raise
  276. return AcquireReturnProxy(lock=self)
  277. def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
  278. """
  279. Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0.
  280. Also note, that the lock file itself is not automatically deleted.
  281. :param force: If true, the lock counter is ignored and the lock is released in every case/
  282. """
  283. if self.is_locked:
  284. self._context.lock_counter -= 1
  285. if self._context.lock_counter == 0 or force:
  286. lock_id, lock_filename = id(self), self.lock_file
  287. _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
  288. self._release()
  289. self._context.lock_counter = 0
  290. _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
  291. def __enter__(self) -> Self:
  292. """
  293. Acquire the lock.
  294. :return: the lock object
  295. """
  296. self.acquire()
  297. return self
  298. def __exit__(
  299. self,
  300. exc_type: type[BaseException] | None,
  301. exc_value: BaseException | None,
  302. traceback: TracebackType | None,
  303. ) -> None:
  304. """
  305. Release the lock.
  306. :param exc_type: the exception type if raised
  307. :param exc_value: the exception value if raised
  308. :param traceback: the exception traceback if raised
  309. """
  310. self.release()
  311. def __del__(self) -> None:
  312. """Called when the lock object is deleted."""
  313. self.release(force=True)
  314. __all__ = [
  315. "AcquireReturnProxy",
  316. "BaseFileLock",
  317. ]