| 1 |
# This is free and unencumbered software released into the public domain. |
| 2 |
# |
| 3 |
# Anyone is free to copy, modify, publish, use, compile, sell, or |
| 4 |
# distribute this software, either in source code form or as a compiled |
| 5 |
# binary, for any purpose, commercial or non-commercial, and by any |
| 6 |
# means. |
| 7 |
# |
| 8 |
# In jurisdictions that recognize copyright laws, the author or authors |
| 9 |
# of this software dedicate any and all copyright interest in the |
| 10 |
# software to the public domain. We make this dedication for the benefit |
| 11 |
# of the public at large and to the detriment of our heirs and |
| 12 |
# successors. We intend this dedication to be an overt act of |
| 13 |
# relinquishment in perpetuity of all present and future rights to this |
| 14 |
# software under copyright law. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 17 |
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 18 |
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 19 |
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR |
| 20 |
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, |
| 21 |
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR |
| 22 |
# OTHER DEALINGS IN THE SOFTWARE. |
| 23 |
# |
| 24 |
# For more information, please refer to <http://unlicense.org> |
| 25 |
|
| 26 |
""" |
| 27 |
A platform independent file lock that supports the with-statement. |
| 28 |
""" |
| 29 |
|
| 30 |
# Modules |
| 31 |
# ------------------------------------------------ |
| 32 |
import logging |
| 33 |
import os |
| 34 |
import threading |
| 35 |
import time |
| 36 |
|
| 37 |
try: |
| 38 |
import warnings |
| 39 |
except ImportError: |
| 40 |
warnings = None |
| 41 |
|
| 42 |
try: |
| 43 |
import msvcrt |
| 44 |
except ImportError: |
| 45 |
msvcrt = None |
| 46 |
|
| 47 |
try: |
| 48 |
import fcntl |
| 49 |
except ImportError: |
| 50 |
fcntl = None |
| 51 |
|
| 52 |
|
| 53 |
# Backward compatibility |
| 54 |
# ------------------------------------------------ |
| 55 |
try: |
| 56 |
TimeoutError |
| 57 |
except NameError: |
| 58 |
TimeoutError = OSError |
| 59 |
|
| 60 |
|
| 61 |
# Data |
| 62 |
# ------------------------------------------------ |
| 63 |
__all__ = [ |
| 64 |
"Timeout", |
| 65 |
"BaseFileLock", |
| 66 |
"WindowsFileLock", |
| 67 |
"UnixFileLock", |
| 68 |
"SoftFileLock", |
| 69 |
"FileLock", |
| 70 |
] |
| 71 |
|
| 72 |
__version__ = "3.0.12" |
| 73 |
|
| 74 |
|
| 75 |
_logger = None |
| 76 |
|
| 77 |
|
| 78 |
def logger(): |
| 79 |
"""Returns the logger instance used in this module.""" |
| 80 |
global _logger |
| 81 |
_logger = _logger or logging.getLogger(__name__) |
| 82 |
return _logger |
| 83 |
|
| 84 |
|
| 85 |
# Exceptions |
| 86 |
# ------------------------------------------------ |
| 87 |
class Timeout(TimeoutError): |
| 88 |
""" |
| 89 |
Raised when the lock could not be acquired in *timeout* |
| 90 |
seconds. |
| 91 |
""" |
| 92 |
|
| 93 |
def __init__(self, lock_file): |
| 94 |
""" """ |
| 95 |
#: The path of the file lock. |
| 96 |
self.lock_file = lock_file |
| 97 |
|
| 98 |
def __str__(self): |
| 99 |
temp = f"The file lock '{self.lock_file}' could not be acquired." |
| 100 |
return temp |
| 101 |
|
| 102 |
|
| 103 |
# Classes |
| 104 |
# ------------------------------------------------ |
| 105 |
|
| 106 |
|
| 107 |
# This is a helper class which is returned by :meth:`BaseFileLock.acquire` |
| 108 |
# and wraps the lock to make sure __enter__ is not called twice when entering |
| 109 |
# the with statement. |
| 110 |
# If we would simply return *self*, the lock would be acquired again |
| 111 |
# in the *__enter__* method of the BaseFileLock, but not released again |
| 112 |
# automatically. |
| 113 |
# |
| 114 |
# :seealso: issue #37 (memory leak) |
| 115 |
class _Acquire_ReturnProxy: |
| 116 |
def __init__(self, lock): |
| 117 |
self.lock = lock |
| 118 |
|
| 119 |
def __enter__(self): |
| 120 |
return self.lock |
| 121 |
|
| 122 |
def __exit__(self, exc_type, exc_value, traceback): |
| 123 |
self.lock.release() |
| 124 |
return None |
| 125 |
|
| 126 |
|
| 127 |
class BaseFileLock: |
| 128 |
""" |
| 129 |
Implements the base class of a file lock. |
| 130 |
""" |
| 131 |
|
| 132 |
def __init__(self, lock_file, timeout=-1): |
| 133 |
""" """ |
| 134 |
# The path to the lock file. |
| 135 |
self._lock_file = lock_file |
| 136 |
|
| 137 |
# The file descriptor for the *_lock_file* as it is returned by the |
| 138 |
# os.open() function. |
| 139 |
# This file lock is only NOT None, if the object currently holds the |
| 140 |
# lock. |
| 141 |
self._lock_file_fd = None |
| 142 |
|
| 143 |
# The default timeout value. |
| 144 |
self.timeout = timeout |
| 145 |
|
| 146 |
# We use this lock primarily for the lock counter. |
| 147 |
self._thread_lock = threading.Lock() |
| 148 |
|
| 149 |
# The lock counter is used for implementing the nested locking |
| 150 |
# mechanism. Whenever the lock is acquired, the counter is increased and |
| 151 |
# the lock is only released, when this value is 0 again. |
| 152 |
self._lock_counter = 0 |
| 153 |
|
| 154 |
@property |
| 155 |
def lock_file(self): |
| 156 |
""" |
| 157 |
The path to the lock file. |
| 158 |
""" |
| 159 |
return self._lock_file |
| 160 |
|
| 161 |
@property |
| 162 |
def timeout(self): |
| 163 |
""" |
| 164 |
You can set a default timeout for the filelock. It will be used as |
| 165 |
fallback value in the acquire method, if no timeout value (*None*) is |
| 166 |
given. |
| 167 |
|
| 168 |
If you want to disable the timeout, set it to a negative value. |
| 169 |
|
| 170 |
A timeout of 0 means, that there is exactly one attempt to acquire the |
| 171 |
file lock. |
| 172 |
|
| 173 |
.. versionadded:: 2.0.0 |
| 174 |
""" |
| 175 |
return self._timeout |
| 176 |
|
| 177 |
@timeout.setter |
| 178 |
def timeout(self, value): |
| 179 |
""" """ |
| 180 |
self._timeout = float(value) |
| 181 |
return None |
| 182 |
|
| 183 |
# Platform dependent locking |
| 184 |
# -------------------------------------------- |
| 185 |
|
| 186 |
def _acquire(self): |
| 187 |
""" |
| 188 |
Platform dependent. If the file lock could be |
| 189 |
acquired, self._lock_file_fd holds the file descriptor |
| 190 |
of the lock file. |
| 191 |
""" |
| 192 |
raise NotImplementedError() |
| 193 |
|
| 194 |
def _release(self): |
| 195 |
""" |
| 196 |
Releases the lock and sets self._lock_file_fd to None. |
| 197 |
""" |
| 198 |
raise NotImplementedError() |
| 199 |
|
| 200 |
# Platform independent methods |
| 201 |
# -------------------------------------------- |
| 202 |
|
| 203 |
@property |
| 204 |
def is_locked(self): |
| 205 |
""" |
| 206 |
True, if the object holds the file lock. |
| 207 |
|
| 208 |
.. versionchanged:: 2.0.0 |
| 209 |
|
| 210 |
This was previously a method and is now a property. |
| 211 |
""" |
| 212 |
return self._lock_file_fd is not None |
| 213 |
|
| 214 |
def acquire(self, timeout=None, poll_intervall=0.05): |
| 215 |
""" |
| 216 |
Acquires the file lock or fails with a :exc:`Timeout` error. |
| 217 |
|
| 218 |
.. code-block:: python |
| 219 |
|
| 220 |
# You can use this method in the context manager (recommended) |
| 221 |
with lock.acquire(): |
| 222 |
pass |
| 223 |
|
| 224 |
# Or use an equivalent try-finally construct: |
| 225 |
lock.acquire() |
| 226 |
try: |
| 227 |
pass |
| 228 |
finally: |
| 229 |
lock.release() |
| 230 |
|
| 231 |
:arg float timeout: |
| 232 |
The maximum time waited for the file lock. |
| 233 |
If ``timeout < 0``, there is no timeout and this method will |
| 234 |
block until the lock could be acquired. |
| 235 |
If ``timeout`` is None, the default :attr:`~timeout` is used. |
| 236 |
|
| 237 |
:arg float poll_intervall: |
| 238 |
We check once in *poll_intervall* seconds if we can acquire the |
| 239 |
file lock. |
| 240 |
|
| 241 |
:raises Timeout: |
| 242 |
if the lock could not be acquired in *timeout* seconds. |
| 243 |
|
| 244 |
.. versionchanged:: 2.0.0 |
| 245 |
|
| 246 |
This method returns now a *proxy* object instead of *self*, |
| 247 |
so that it can be used in a with statement without side effects. |
| 248 |
""" |
| 249 |
# Use the default timeout, if no timeout is provided. |
| 250 |
if timeout is None: |
| 251 |
timeout = self.timeout |
| 252 |
|
| 253 |
# Increment the number right at the beginning. |
| 254 |
# We can still undo it, if something fails. |
| 255 |
with self._thread_lock: |
| 256 |
self._lock_counter += 1 |
| 257 |
|
| 258 |
lock_id = id(self) |
| 259 |
lock_filename = self._lock_file |
| 260 |
start_time = time.time() |
| 261 |
try: |
| 262 |
while True: |
| 263 |
with self._thread_lock: |
| 264 |
if not self.is_locked: |
| 265 |
# Level 5 = DIAGNOSTIC |
| 266 |
logger().log( |
| 267 |
5, |
| 268 |
"Attempting to acquire lock %s on %s", |
| 269 |
lock_id, |
| 270 |
lock_filename, |
| 271 |
) |
| 272 |
self._acquire() |
| 273 |
|
| 274 |
if self.is_locked: |
| 275 |
logger().debug("Lock %s acquired on %s", lock_id, lock_filename) |
| 276 |
break |
| 277 |
elif timeout >= 0 and time.time() - start_time > timeout: |
| 278 |
logger().debug( |
| 279 |
"Timeout on acquiring lock %s on %s", lock_id, lock_filename |
| 280 |
) |
| 281 |
raise Timeout(self._lock_file) |
| 282 |
else: |
| 283 |
logger().log( |
| 284 |
5, |
| 285 |
"Lock %s not acquired on %s, waiting %s seconds ...", |
| 286 |
lock_id, |
| 287 |
lock_filename, |
| 288 |
poll_intervall, |
| 289 |
) |
| 290 |
time.sleep(poll_intervall) |
| 291 |
except BaseException: |
| 292 |
# Something did go wrong, so decrement the counter. |
| 293 |
with self._thread_lock: |
| 294 |
self._lock_counter = max(0, self._lock_counter - 1) |
| 295 |
|
| 296 |
raise |
| 297 |
return _Acquire_ReturnProxy(lock=self) |
| 298 |
|
| 299 |
def release(self, force=False): |
| 300 |
""" |
| 301 |
Releases the file lock. |
| 302 |
|
| 303 |
Please note, that the lock is only completly released, if the lock |
| 304 |
counter is 0. |
| 305 |
|
| 306 |
Also note, that the lock file itself is not automatically deleted. |
| 307 |
|
| 308 |
:arg bool force: |
| 309 |
If true, the lock counter is ignored and the lock is released in |
| 310 |
every case. |
| 311 |
""" |
| 312 |
with self._thread_lock: |
| 313 |
if self.is_locked: |
| 314 |
self._lock_counter -= 1 |
| 315 |
|
| 316 |
if self._lock_counter == 0 or force: |
| 317 |
lock_id = id(self) |
| 318 |
lock_filename = self._lock_file |
| 319 |
|
| 320 |
logger().log( |
| 321 |
5, "Attempting to release lock %s on %s", lock_id, lock_filename |
| 322 |
) |
| 323 |
self._release() |
| 324 |
self._lock_counter = 0 |
| 325 |
logger().debug("Lock %s released on %s", lock_id, lock_filename) |
| 326 |
|
| 327 |
return None |
| 328 |
|
| 329 |
def __enter__(self): |
| 330 |
self.acquire() |
| 331 |
return self |
| 332 |
|
| 333 |
def __exit__(self, exc_type, exc_value, traceback): |
| 334 |
self.release() |
| 335 |
return None |
| 336 |
|
| 337 |
def __del__(self): |
| 338 |
self.release(force=True) |
| 339 |
return None |
| 340 |
|
| 341 |
|
| 342 |
# Windows locking mechanism |
| 343 |
# ~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 344 |
|
| 345 |
|
| 346 |
class WindowsFileLock(BaseFileLock): |
| 347 |
""" |
| 348 |
Uses the :func:`msvcrt.locking` function to hard lock the lock file on |
| 349 |
windows systems. |
| 350 |
""" |
| 351 |
|
| 352 |
def _acquire(self): |
| 353 |
open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC |
| 354 |
|
| 355 |
try: |
| 356 |
fd = os.open(self._lock_file, open_mode) |
| 357 |
except OSError: |
| 358 |
pass |
| 359 |
else: |
| 360 |
try: |
| 361 |
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) |
| 362 |
except OSError: |
| 363 |
os.close(fd) |
| 364 |
else: |
| 365 |
self._lock_file_fd = fd |
| 366 |
return None |
| 367 |
|
| 368 |
def _release(self): |
| 369 |
fd = self._lock_file_fd |
| 370 |
self._lock_file_fd = None |
| 371 |
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1) |
| 372 |
os.close(fd) |
| 373 |
|
| 374 |
try: |
| 375 |
os.remove(self._lock_file) |
| 376 |
# Probably another instance of the application |
| 377 |
# that acquired the file lock. |
| 378 |
except OSError: |
| 379 |
pass |
| 380 |
return None |
| 381 |
|
| 382 |
|
| 383 |
# Unix locking mechanism |
| 384 |
# ~~~~~~~~~~~~~~~~~~~~~~ |
| 385 |
|
| 386 |
|
| 387 |
class UnixFileLock(BaseFileLock): |
| 388 |
""" |
| 389 |
Uses the :func:`fcntl.flock` to hard lock the lock file on unix systems. |
| 390 |
""" |
| 391 |
|
| 392 |
def _acquire(self): |
| 393 |
open_mode = os.O_RDWR | os.O_CREAT | os.O_TRUNC |
| 394 |
fd = os.open(self._lock_file, open_mode) |
| 395 |
|
| 396 |
try: |
| 397 |
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 398 |
except OSError: |
| 399 |
os.close(fd) |
| 400 |
else: |
| 401 |
self._lock_file_fd = fd |
| 402 |
return None |
| 403 |
|
| 404 |
def _release(self): |
| 405 |
# Do not remove the lockfile: |
| 406 |
# |
| 407 |
# https://github.com/benediktschmitt/py-filelock/issues/31 |
| 408 |
# https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition |
| 409 |
fd = self._lock_file_fd |
| 410 |
self._lock_file_fd = None |
| 411 |
fcntl.flock(fd, fcntl.LOCK_UN) |
| 412 |
os.close(fd) |
| 413 |
return None |
| 414 |
|
| 415 |
|
| 416 |
# Soft lock |
| 417 |
# ~~~~~~~~~ |
| 418 |
|
| 419 |
|
| 420 |
class SoftFileLock(BaseFileLock): |
| 421 |
""" |
| 422 |
Simply watches the existence of the lock file. |
| 423 |
""" |
| 424 |
|
| 425 |
def _acquire(self): |
| 426 |
open_mode = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC |
| 427 |
try: |
| 428 |
fd = os.open(self._lock_file, open_mode) |
| 429 |
except OSError: |
| 430 |
pass |
| 431 |
else: |
| 432 |
self._lock_file_fd = fd |
| 433 |
return None |
| 434 |
|
| 435 |
def _release(self): |
| 436 |
os.close(self._lock_file_fd) |
| 437 |
self._lock_file_fd = None |
| 438 |
|
| 439 |
try: |
| 440 |
os.remove(self._lock_file) |
| 441 |
# The file is already deleted and that's what we want. |
| 442 |
except OSError: |
| 443 |
pass |
| 444 |
return None |
| 445 |
|
| 446 |
|
| 447 |
# Platform filelock |
| 448 |
# ~~~~~~~~~~~~~~~~~ |
| 449 |
|
| 450 |
#: Alias for the lock, which should be used for the current platform. On |
| 451 |
#: Windows, this is an alias for :class:`WindowsFileLock`, on Unix for |
| 452 |
#: :class:`UnixFileLock` and otherwise for :class:`SoftFileLock`. |
| 453 |
FileLock = None |
| 454 |
|
| 455 |
if msvcrt: |
| 456 |
FileLock = WindowsFileLock |
| 457 |
elif fcntl: |
| 458 |
FileLock = UnixFileLock |
| 459 |
else: |
| 460 |
FileLock = SoftFileLock |
| 461 |
|
| 462 |
if warnings is not None: |
| 463 |
warnings.warn("only soft file lock is available", stacklevel=1) |