Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/filelock/_api.py: 78%

104 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 07:11 +0000

1from __future__ import annotations 

2 

3import contextlib 

4import logging 

5import os 

6import time 

7import warnings 

8from abc import ABC, abstractmethod 

9from dataclasses import dataclass 

10from threading import local 

11from types import TracebackType 

12from typing import Any 

13 

14from ._error import Timeout 

15 

16_LOGGER = logging.getLogger("filelock") 

17 

18 

19# This is a helper class which is returned by :meth:`BaseFileLock.acquire` and wraps the lock to make sure __enter__ 

20# is not called twice when entering the with statement. If we would simply return *self*, the lock would be acquired 

21# again in the *__enter__* method of the BaseFileLock, but not released again automatically. issue #37 (memory leak) 

22class AcquireReturnProxy: 

23 """A context aware object that will release the lock file when exiting.""" 

24 

25 def __init__(self, lock: BaseFileLock) -> None: 

26 self.lock = lock 

27 

28 def __enter__(self) -> BaseFileLock: 

29 return self.lock 

30 

31 def __exit__( 

32 self, 

33 exc_type: type[BaseException] | None, # noqa: U100 

34 exc_value: BaseException | None, # noqa: U100 

35 traceback: TracebackType | None, # noqa: U100 

36 ) -> None: 

37 self.lock.release() 

38 

39 

40@dataclass 

41class FileLockContext: 

42 """ 

43 A dataclass which holds the context for a ``BaseFileLock`` object. 

44 """ 

45 

46 # The context is held in a separate class to allow optional use of thread local storage via the 

47 # ThreadLocalFileContext class. 

48 

49 #: The path to the lock file. 

50 lock_file: str 

51 

52 #: The default timeout value. 

53 timeout: float 

54 

55 #: The mode for the lock files 

56 mode: int 

57 

58 #: The file descriptor for the *_lock_file* as it is returned by the os.open() function, not None when lock held 

59 lock_file_fd: int | None = None 

60 

61 #: The lock counter is used for implementing the nested locking mechanism. 

62 lock_counter: int = 0 # When the lock is acquired is increased and the lock is only released, when this value is 0 

63 

64 

65class ThreadLocalFileContext(FileLockContext, local): 

66 """ 

67 A thread local version of the ``FileLockContext`` class. 

68 """ 

69 

70 

71class BaseFileLock(ABC, contextlib.ContextDecorator): 

72 """Abstract base class for a file lock object.""" 

73 

74 def __init__( 

75 self, 

76 lock_file: str | os.PathLike[Any], 

77 timeout: float = -1, 

78 mode: int = 0o644, 

79 thread_local: bool = True, 

80 ) -> None: 

81 """ 

82 Create a new lock object. 

83 

84 :param lock_file: path to the file 

85 :param timeout: default timeout when acquiring the lock, in seconds. It will be used as fallback value in 

86 the acquire method, if no timeout value (``None``) is given. If you want to disable the timeout, set it 

87 to a negative value. A timeout of 0 means, that there is exactly one attempt to acquire the file lock. 

88 :param mode: file permissions for the lockfile. 

89 :param thread_local: Whether this object's internal context should be thread local or not. 

90 If this is set to ``False`` then the lock will be reentrant across threads. 

91 """ 

92 self._is_thread_local = thread_local 

93 

94 # Create the context. Note that external code should not work with the context directly and should instead use 

95 # properties of this class. 

96 kwargs: dict[str, Any] = { 

97 "lock_file": os.fspath(lock_file), 

98 "timeout": timeout, 

99 "mode": mode, 

100 } 

101 self._context: FileLockContext = (ThreadLocalFileContext if thread_local else FileLockContext)(**kwargs) 

102 

103 def is_thread_local(self) -> bool: 

104 """:return: a flag indicating if this lock is thread local or not""" 

105 return self._is_thread_local 

106 

107 @property 

108 def lock_file(self) -> str: 

109 """:return: path to the lock file""" 

110 return self._context.lock_file 

111 

112 @property 

113 def timeout(self) -> float: 

114 """ 

115 :return: the default timeout value, in seconds 

116 

117 .. versionadded:: 2.0.0 

118 """ 

119 return self._context.timeout 

120 

121 @timeout.setter 

122 def timeout(self, value: float | str) -> None: 

123 """ 

124 Change the default timeout value. 

125 

126 :param value: the new value, in seconds 

127 """ 

128 self._context.timeout = float(value) 

129 

130 @abstractmethod 

131 def _acquire(self) -> None: 

132 """If the file lock could be acquired, self._context.lock_file_fd holds the file descriptor of the lock file.""" 

133 raise NotImplementedError 

134 

135 @abstractmethod 

136 def _release(self) -> None: 

137 """Releases the lock and sets self._context.lock_file_fd to None.""" 

138 raise NotImplementedError 

139 

140 @property 

141 def is_locked(self) -> bool: 

142 """ 

143 

144 :return: A boolean indicating if the lock file is holding the lock currently. 

145 

146 .. versionchanged:: 2.0.0 

147 

148 This was previously a method and is now a property. 

149 """ 

150 return self._context.lock_file_fd is not None 

151 

152 @property 

153 def lock_counter(self) -> int: 

154 """ 

155 :return: The number of times this lock has been acquired (but not yet released). 

156 """ 

157 return self._context.lock_counter 

158 

159 def acquire( 

160 self, 

161 timeout: float | None = None, 

162 poll_interval: float = 0.05, 

163 *, 

164 poll_intervall: float | None = None, 

165 blocking: bool = True, 

166 ) -> AcquireReturnProxy: 

167 """ 

168 Try to acquire the file lock. 

169 

170 :param timeout: maximum wait time for acquiring the lock, ``None`` means use the default :attr:`~timeout` is and 

171 if ``timeout < 0``, there is no timeout and this method will block until the lock could be acquired 

172 :param poll_interval: interval of trying to acquire the lock file 

173 :param poll_intervall: deprecated, kept for backwards compatibility, use ``poll_interval`` instead 

174 :param blocking: defaults to True. If False, function will return immediately if it cannot obtain a lock on the 

175 first attempt. Otherwise, this method will block until the timeout expires or the lock is acquired. 

176 :raises Timeout: if fails to acquire lock within the timeout period 

177 :return: a context object that will unlock the file when the context is exited 

178 

179 .. code-block:: python 

180 

181 # You can use this method in the context manager (recommended) 

182 with lock.acquire(): 

183 pass 

184 

185 # Or use an equivalent try-finally construct: 

186 lock.acquire() 

187 try: 

188 pass 

189 finally: 

190 lock.release() 

191 

192 .. versionchanged:: 2.0.0 

193 

194 This method returns now a *proxy* object instead of *self*, 

195 so that it can be used in a with statement without side effects. 

196 

197 """ 

198 # Use the default timeout, if no timeout is provided. 

199 if timeout is None: 

200 timeout = self._context.timeout 

201 

202 if poll_intervall is not None: 

203 msg = "use poll_interval instead of poll_intervall" 

204 warnings.warn(msg, DeprecationWarning, stacklevel=2) 

205 poll_interval = poll_intervall 

206 

207 # Increment the number right at the beginning. We can still undo it, if something fails. 

208 self._context.lock_counter += 1 

209 

210 lock_id = id(self) 

211 lock_filename = self.lock_file 

212 start_time = time.perf_counter() 

213 try: 

214 while True: 

215 if not self.is_locked: 

216 _LOGGER.debug("Attempting to acquire lock %s on %s", lock_id, lock_filename) 

217 self._acquire() 

218 if self.is_locked: 

219 _LOGGER.debug("Lock %s acquired on %s", lock_id, lock_filename) 

220 break 

221 elif blocking is False: 

222 _LOGGER.debug("Failed to immediately acquire lock %s on %s", lock_id, lock_filename) 

223 raise Timeout(lock_filename) 

224 elif 0 <= timeout < time.perf_counter() - start_time: 

225 _LOGGER.debug("Timeout on acquiring lock %s on %s", lock_id, lock_filename) 

226 raise Timeout(lock_filename) 

227 else: 

228 msg = "Lock %s not acquired on %s, waiting %s seconds ..." 

229 _LOGGER.debug(msg, lock_id, lock_filename, poll_interval) 

230 time.sleep(poll_interval) 

231 except BaseException: # Something did go wrong, so decrement the counter. 

232 self._context.lock_counter = max(0, self._context.lock_counter - 1) 

233 raise 

234 return AcquireReturnProxy(lock=self) 

235 

236 def release(self, force: bool = False) -> None: 

237 """ 

238 Releases the file lock. Please note, that the lock is only completely released, if the lock counter is 0. Also 

239 note, that the lock file itself is not automatically deleted. 

240 

241 :param force: If true, the lock counter is ignored and the lock is released in every case/ 

242 """ 

243 if self.is_locked: 

244 self._context.lock_counter -= 1 

245 

246 if self._context.lock_counter == 0 or force: 

247 lock_id, lock_filename = id(self), self.lock_file 

248 

249 _LOGGER.debug("Attempting to release lock %s on %s", lock_id, lock_filename) 

250 self._release() 

251 self._context.lock_counter = 0 

252 _LOGGER.debug("Lock %s released on %s", lock_id, lock_filename) 

253 

254 def __enter__(self) -> BaseFileLock: 

255 """ 

256 Acquire the lock. 

257 

258 :return: the lock object 

259 """ 

260 self.acquire() 

261 return self 

262 

263 def __exit__( 

264 self, 

265 exc_type: type[BaseException] | None, # noqa: U100 

266 exc_value: BaseException | None, # noqa: U100 

267 traceback: TracebackType | None, # noqa: U100 

268 ) -> None: 

269 """ 

270 Release the lock. 

271 

272 :param exc_type: the exception type if raised 

273 :param exc_value: the exception value if raised 

274 :param traceback: the exception traceback if raised 

275 """ 

276 self.release() 

277 

278 def __del__(self) -> None: 

279 """Called when the lock object is deleted.""" 

280 self.release(force=True) 

281 

282 

283__all__ = [ 

284 "BaseFileLock", 

285 "AcquireReturnProxy", 

286]