asyncio.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. """An asyncio-based implementation of the file lock."""
  2. from __future__ import annotations
  3. import asyncio
  4. import contextlib
  5. import logging
  6. import os
  7. import time
  8. from dataclasses import dataclass
  9. from inspect import iscoroutinefunction
  10. from threading import local
  11. from typing import TYPE_CHECKING, Any, NoReturn, cast
  12. from ._api import BaseFileLock, FileLockContext, FileLockMeta
  13. from ._error import Timeout
  14. from ._soft import SoftFileLock
  15. from ._unix import UnixFileLock
  16. from ._windows import WindowsFileLock
  17. if TYPE_CHECKING:
  18. import sys
  19. from collections.abc import Callable
  20. from concurrent import futures
  21. from types import TracebackType
  22. if sys.version_info >= (3, 11): # pragma: no cover (py311+)
  23. from typing import Self
  24. else: # pragma: no cover (<py311)
  25. from typing_extensions import Self
  26. _LOGGER = logging.getLogger("filelock")
  27. @dataclass
  28. class AsyncFileLockContext(FileLockContext):
  29. """A dataclass which holds the context for a ``BaseAsyncFileLock`` object."""
  30. #: Whether run in executor
  31. run_in_executor: bool = True
  32. #: The executor
  33. executor: futures.Executor | None = None
  34. #: The loop
  35. loop: asyncio.AbstractEventLoop | None = None
  36. class AsyncThreadLocalFileContext(AsyncFileLockContext, local):
  37. """A thread local version of the ``FileLockContext`` class."""
  38. class AsyncAcquireReturnProxy:
  39. """A context-aware object that will release the lock file when exiting."""
  40. def __init__(self, lock: BaseAsyncFileLock) -> None: # noqa: D107
  41. self.lock = lock
  42. async def __aenter__(self) -> BaseAsyncFileLock: # noqa: D105
  43. return self.lock
  44. async def __aexit__( # noqa: D105
  45. self,
  46. exc_type: type[BaseException] | None,
  47. exc_value: BaseException | None,
  48. traceback: TracebackType | None,
  49. ) -> None:
  50. await self.lock.release()
  51. class AsyncFileLockMeta(FileLockMeta):
  52. def __call__( # type: ignore[override] # noqa: PLR0913
  53. cls, # noqa: N805
  54. lock_file: str | os.PathLike[str],
  55. timeout: float = -1,
  56. mode: int = 0o644,
  57. thread_local: bool = False, # noqa: FBT001, FBT002
  58. *,
  59. blocking: bool = True,
  60. is_singleton: bool = False,
  61. loop: asyncio.AbstractEventLoop | None = None,
  62. run_in_executor: bool = True,
  63. executor: futures.Executor | None = None,
  64. ) -> BaseAsyncFileLock:
  65. if thread_local and run_in_executor:
  66. msg = "run_in_executor is not supported when thread_local is True"
  67. raise ValueError(msg)
  68. instance = super().__call__(
  69. lock_file=lock_file,
  70. timeout=timeout,
  71. mode=mode,
  72. thread_local=thread_local,
  73. blocking=blocking,
  74. is_singleton=is_singleton,
  75. loop=loop,
  76. run_in_executor=run_in_executor,
  77. executor=executor,
  78. )
  79. return cast("BaseAsyncFileLock", instance)
  80. class BaseAsyncFileLock(BaseFileLock, metaclass=AsyncFileLockMeta):
  81. """Base class for asynchronous file locks."""
  82. def __init__( # noqa: PLR0913
  83. self,
  84. lock_file: str | os.PathLike[str],
  85. timeout: float = -1,
  86. mode: int = 0o644,
  87. thread_local: bool = False, # noqa: FBT001, FBT002
  88. *,
  89. blocking: bool = True,
  90. is_singleton: bool = False,
  91. loop: asyncio.AbstractEventLoop | None = None,
  92. run_in_executor: bool = True,
  93. executor: futures.Executor | None = None,
  94. ) -> None:
  95. """
  96. Create a new lock object.
  97. :param lock_file: path to the file
  98. :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in \
  99. the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it \
  100. to a negative value. A timeout of 0 means that there is exactly one attempt to acquire the file lock.
  101. :param mode: file permissions for the lockfile
  102. :param thread_local: Whether this object's internal context should be thread local or not. If this is set to \
  103. ``False`` then the lock will be reentrant across threads.
  104. :param blocking: whether the lock should be blocking or not
  105. :param is_singleton: If this is set to ``True`` then only one instance of this class will be created \
  106. per lock file. This is useful if you want to use the lock object for reentrant locking without needing \
  107. to pass the same object around.
  108. :param loop: The event loop to use. If not specified, the running event loop will be used.
  109. :param run_in_executor: If this is set to ``True`` then the lock will be acquired in an executor.
  110. :param executor: The executor to use. If not specified, the default executor will be used.
  111. """
  112. self._is_thread_local = thread_local
  113. self._is_singleton = is_singleton
  114. # Create the context. Note that external code should not work with the context directly and should instead use
  115. # properties of this class.
  116. kwargs: dict[str, Any] = {
  117. "lock_file": os.fspath(lock_file),
  118. "timeout": timeout,
  119. "mode": mode,
  120. "blocking": blocking,
  121. "loop": loop,
  122. "run_in_executor": run_in_executor,
  123. "executor": executor,
  124. }
  125. self._context: AsyncFileLockContext = (AsyncThreadLocalFileContext if thread_local else AsyncFileLockContext)(
  126. **kwargs
  127. )
  128. @property
  129. def run_in_executor(self) -> bool:
  130. """::return: whether run in executor."""
  131. return self._context.run_in_executor
  132. @property
  133. def executor(self) -> futures.Executor | None:
  134. """::return: the executor."""
  135. return self._context.executor
  136. @executor.setter
  137. def executor(self, value: futures.Executor | None) -> None: # pragma: no cover
  138. """
  139. Change the executor.
  140. :param value: the new executor or ``None``
  141. :type value: futures.Executor | None
  142. """
  143. self._context.executor = value
  144. @property
  145. def loop(self) -> asyncio.AbstractEventLoop | None:
  146. """::return: the event loop."""
  147. return self._context.loop
  148. async def acquire( # type: ignore[override]
  149. self,
  150. timeout: float | None = None,
  151. poll_interval: float = 0.05,
  152. *,
  153. blocking: bool | None = None,
  154. ) -> AsyncAcquireReturnProxy:
  155. """
  156. Try to acquire the file lock.
  157. :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default
  158. :attr:`~BaseFileLock.timeout` is and if ``timeout < 0``, there is no timeout and
  159. this method will block until the lock could be acquired
  160. :param poll_interval: interval of trying to acquire the lock file
  161. :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
  162. first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
  163. :raises Timeout: if fails to acquire lock within the timeout period
  164. :return: a context object that will unlock the file when the context is exited
  165. .. code-block:: python
  166. # You can use this method in the context manager (recommended)
  167. with lock.acquire():
  168. pass
  169. # Or use an equivalent try-finally construct:
  170. lock.acquire()
  171. try:
  172. pass
  173. finally:
  174. lock.release()
  175. """
  176. # Use the default timeout, if no timeout is provided.
  177. if timeout is None:
  178. timeout = self._context.timeout
  179. if blocking is None:
  180. blocking = self._context.blocking
  181. # Increment the number right at the beginning. We can still undo it, if something fails.
  182. self._context.lock_counter += 1
  183. lock_id = id(self)
  184. lock_filename = self.lock_file
  185. start_time = time.perf_counter()
  186. try:
  187. while True:
  188. if not self.is_locked:
  189. _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
  190. await self._run_internal_method(self._acquire)
  191. if self.is_locked:
  192. _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
  193. break
  194. if blocking is False:
  195. _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
  196. raise Timeout(lock_filename) # noqa: TRY301
  197. if 0 <= timeout < time.perf_counter() - start_time:
  198. _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
  199. raise Timeout(lock_filename) # noqa: TRY301
  200. msg = "Lock %s not acquired on %s, waiting %s seconds ..."
  201. _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
  202. await asyncio.sleep(poll_interval)
  203. except BaseException: # Something did go wrong, so decrement the counter.
  204. self._context.lock_counter = max(0, self._context.lock_counter - 1)
  205. raise
  206. return AsyncAcquireReturnProxy(lock=self)
  207. async def release(self, force: bool = False) -> None: # type: ignore[override] # noqa: FBT001, FBT002
  208. """
  209. Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0.
  210. Also note, that the lock file itself is not automatically deleted.
  211. :param force: If true, the lock counter is ignored and the lock is released in every case/
  212. """
  213. if self.is_locked:
  214. self._context.lock_counter -= 1
  215. if self._context.lock_counter == 0 or force:
  216. lock_id, lock_filename = id(self), self.lock_file
  217. _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
  218. await self._run_internal_method(self._release)
  219. self._context.lock_counter = 0
  220. _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
  221. async def _run_internal_method(self, method: Callable[[], Any]) -> None:
  222. if iscoroutinefunction(method):
  223. await method()
  224. elif self.run_in_executor:
  225. loop = self.loop or asyncio.get_running_loop()
  226. await loop.run_in_executor(self.executor, method)
  227. else:
  228. method()
  229. def __enter__(self) -> NoReturn:
  230. """
  231. Replace old __enter__ method to avoid using it.
  232. NOTE: DO NOT USE `with` FOR ASYNCIO LOCKS, USE `async with` INSTEAD.
  233. :return: none
  234. :rtype: NoReturn
  235. """
  236. msg = "Do not use `with` for asyncio locks, use `async with` instead."
  237. raise NotImplementedError(msg)
  238. async def __aenter__(self) -> Self:
  239. """
  240. Acquire the lock.
  241. :return: the lock object
  242. """
  243. await self.acquire()
  244. return self
  245. async def __aexit__(
  246. self,
  247. exc_type: type[BaseException] | None,
  248. exc_value: BaseException | None,
  249. traceback: TracebackType | None,
  250. ) -> None:
  251. """
  252. Release the lock.
  253. :param exc_type: the exception type if raised
  254. :param exc_value: the exception value if raised
  255. :param traceback: the exception traceback if raised
  256. """
  257. await self.release()
  258. def __del__(self) -> None:
  259. """Called when the lock object is deleted."""
  260. with contextlib.suppress(RuntimeError):
  261. loop = self.loop or asyncio.get_running_loop()
  262. if not loop.is_running(): # pragma: no cover
  263. loop.run_until_complete(self.release(force=True))
  264. else:
  265. loop.create_task(self.release(force=True))
  266. class AsyncSoftFileLock(SoftFileLock, BaseAsyncFileLock):
  267. """Simply watches the existence of the lock file."""
  268. class AsyncUnixFileLock(UnixFileLock, BaseAsyncFileLock):
  269. """Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems."""
  270. class AsyncWindowsFileLock(WindowsFileLock, BaseAsyncFileLock):
  271. """Uses the :func:`msvcrt.locking` to hard lock the lock file on windows systems."""
  272. __all__ = [
  273. "AsyncAcquireReturnProxy",
  274. "AsyncSoftFileLock",
  275. "AsyncUnixFileLock",
  276. "AsyncWindowsFileLock",
  277. "BaseAsyncFileLock",
  278. ]