Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/filelock/_api.py: 76%
106 statements
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:08 +0000
« prev ^ index » next coverage.py v7.3.1, created at 2023-09-25 06:08 +0000
1from __future__ import annotations
3import contextlib
4import logging
5import os
6import time
7import warnings
8from abc import ABC, abstractmethod
9from dataclasses import dataclass
10from threading import local
11from typing import TYPE_CHECKING, Any
13from ._error import Timeout
15if TYPE_CHECKING:
16 import sys
17 from types import TracebackType
19 if sys.version_info >= (3, 11): # pragma: no cover (py311+)
20 from typing import Self
21 else: # pragma: no cover (<py311)
22 from typing_extensions import Self
25_LOGGER = logging.getLogger("filelock")
28# This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__
29# is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired
30# again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak)
31class AcquireReturnProxy:
32 """A context aware object that will release the lock file when exiting."""
34 def __init__(self, lock: BaseFileLock) -> None:
35 self.lock = lock
37 def __enter__(self) -> BaseFileLock:
38 return self.lock
40 def __exit__(
41 self,
42 exc_type: type[BaseException] | None,
43 exc_value: BaseException | None,
44 traceback: TracebackType | None,
45 ) -> None:
46 self.lock.release()
49@dataclass
50class FileLockContext:
51 """A dataclass which holds the context for a ``BaseFileLock`` object."""
53 # The context is held in a separate class to allow optional use of thread local storage via the
54 # ThreadLocalFileContext class.
56 #: The path to the lock file.
57 lock_file: str
59 #: The default timeout value.
60 timeout: float
62 #: The mode for the lock files
63 mode: int
65 #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held
66 lock_file_fd: int | None = None
68 #: The lock counter is used for implementing the nested locking mechanism.
69 lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0
72class ThreadLocalFileContext(FileLockContext, local):
73 """A thread local version of the ``FileLockContext`` class."""
76class BaseFileLock(ABC, contextlib.ContextDecorator):
77 """Abstract base class for a file lock object."""
79 def __init__(
80 self,
81 lock_file: str | os.PathLike[str],
82 timeout: float = -1,
83 mode: int = 0o644,
84 thread_local: bool = True, # noqa: FBT001, FBT002
85 ) -> None:
86 """
87 Create a new lock object.
89 :param lock_file: path to the file
90 :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in
91 the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it
92 to a negative value. A timeout of 0 means, that there is exactly one attempt to acquire the file lock.
93 :param mode: file permissions for the lockfile.
94 :param thread_local: Whether this object's internal context should be thread local or not.
95 If this is set to ``False`` then the lock will be reentrant across threads.
96 """
97 self._is_thread_local = thread_local
99 # Create the context. Note that external code should not work with the context directly and should instead use
100 # properties of this class.
101 kwargs: dict[str, Any] = {
102 "lock_file": os.fspath(lock_file),
103 "timeout": timeout,
104 "mode": mode,
105 }
106 self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs)
108 def is_thread_local(self) -> bool:
109 """:return: a flag indicating if this lock is thread local or not"""
110 return self._is_thread_local
112 @property
113 def lock_file(self) -> str:
114 """:return: path to the lock file"""
115 return self._context.lock_file
117 @property
118 def timeout(self) -> float:
119 """
120 :return: the default timeout value, in seconds
122 .. versionadded:: 2.0.0
123 """
124 return self._context.timeout
126 @timeout.setter
127 def timeout(self, value: float | str) -> None:
128 """
129 Change the default timeout value.
131 :param value: the new value, in seconds
132 """
133 self._context.timeout = float(value)
135 @abstractmethod
136 def _acquire(self) -> None:
137 """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file."""
138 raise NotImplementedError
140 @abstractmethod
141 def _release(self) -> None:
142 """Releases the lock and sets self._context.lock_file_fd to None."""
143 raise NotImplementedError
145 @property
146 def is_locked(self) -> bool:
147 """
149 :return: A boolean indicating if the lock file is holding the lock currently.
151 .. versionchanged:: 2.0.0
153 This was previously a method and is now a property.
154 """
155 return self._context.lock_file_fd is not None
157 @property
158 def lock_counter(self) -> int:
159 """:return: The number of times this lock has been acquired (but not yet released)."""
160 return self._context.lock_counter
162 def acquire(
163 self,
164 timeout: float | None = None,
165 poll_interval: float = 0.05,
166 *,
167 poll_intervall: float | None = None,
168 blocking: bool = True,
169 ) -> AcquireReturnProxy:
170 """
171 Try to acquire the file lock.
173 :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and
174 if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired
175 :param poll_interval: interval of trying to acquire the lock file
176 :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead
177 :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the
178 first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired.
179 :raises Timeout: if fails to acquire lock within the timeout period
180 :return: a context object that will unlock the file when the context is exited
182 .. code-block:: python
184 # You can use this method in the context manager (recommended)
185 with lock.acquire():
186 pass
188 # Or use an equivalent try-finally construct:
189 lock.acquire()
190 try:
191 pass
192 finally:
193 lock.release()
195 .. versionchanged:: 2.0.0
197 This method returns now a *proxy* object instead of *self*,
198 so that it can be used in a with statement without side effects.
200 """
201 # Use the default timeout, if no timeout is provided.
202 if timeout is None:
203 timeout = self._context.timeout
205 if poll_intervall is not None:
206 msg = "use poll_interval instead of poll_intervall"
207 warnings.warn(msg, DeprecationWarning, stacklevel=2)
208 poll_interval = poll_intervall
210 # Increment the number right at the beginning. We can still undo it, if something fails.
211 self._context.lock_counter += 1
213 lock_id = id(self)
214 lock_filename = self.lock_file
215 start_time = time.perf_counter()
216 try:
217 while True:
218 if not self.is_locked:
219 _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename)
220 self._acquire()
221 if self.is_locked:
222 _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename)
223 break
224 if blocking is False:
225 _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename)
226 raise Timeout(lock_filename) # noqa: TRY301
227 if 0 <= timeout < time.perf_counter() - start_time:
228 _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename)
229 raise Timeout(lock_filename) # noqa: TRY301
230 msg = "Lock %s not acquired on %s, waiting %s seconds ..."
231 _LOGGER.debug(msg, lock_id, lock_filename, poll_interval)
232 time.sleep(poll_interval)
233 except BaseException: # Something did go wrong, so decrement the counter.
234 self._context.lock_counter = max(0, self._context.lock_counter - 1)
235 raise
236 return AcquireReturnProxy(lock=self)
238 def release(self, force: bool = False) -> None: # noqa: FBT001, FBT002
239 """
240 Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0. Also
241 note, that the lock file itself is not automatically deleted.
243 :param force: If true, the lock counter is ignored and the lock is released in every case/
244 """
245 if self.is_locked:
246 self._context.lock_counter -= 1
248 if self._context.lock_counter == 0 or force:
249 lock_id, lock_filename = id(self), self.lock_file
251 _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename)
252 self._release()
253 self._context.lock_counter = 0
254 _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename)
256 def __enter__(self) -> Self:
257 """
258 Acquire the lock.
260 :return: the lock object
261 """
262 self.acquire()
263 return self
265 def __exit__(
266 self,
267 exc_type: type[BaseException] | None,
268 exc_value: BaseException | None,
269 traceback: TracebackType | None,
270 ) -> None:
271 """
272 Release the lock.
274 :param exc_type: the exception type if raised
275 :param exc_value: the exception value if raised
276 :param traceback: the exception traceback if raised
277 """
278 self.release()
280 def __del__(self) -> None:
281 """Called when the lock object is deleted."""
282 self.release(force=True)
285__all__ = [
286 "BaseFileLock",
287 "AcquireReturnProxy",
288]