Platform independent file lock system. LockFile accepts a parameter, the path to a file acting as a lock. Once the LockFile, instance is created, the associated file is 'locked from the point of view of the OS, meaning that if another instance of Certbot try at the same time to acqu
| 20 | |
| 21 | |
| 22 | class LockFile: |
| 23 | """ |
| 24 | Platform independent file lock system. |
| 25 | LockFile accepts a parameter, the path to a file acting as a lock. Once the LockFile, |
| 26 | instance is created, the associated file is 'locked from the point of view of the OS, |
| 27 | meaning that if another instance of Certbot try at the same time to acquire the same lock, |
| 28 | it will raise an Exception. Calling release method will release the lock, and make it |
| 29 | available to every other instance. |
| 30 | Upon exit, Certbot will also release all the locks. |
| 31 | This allows us to protect a file or directory from being concurrently accessed |
| 32 | or modified by two Certbot instances. |
| 33 | LockFile is platform independent: it will proceed to the appropriate OS lock mechanism |
| 34 | depending on Linux or Windows. |
| 35 | """ |
| 36 | def __init__(self, path: str) -> None: |
| 37 | """ |
| 38 | Create a LockFile instance on the given file path, and acquire lock. |
| 39 | :param str path: the path to the file that will hold a lock |
| 40 | """ |
| 41 | self._path = path |
| 42 | mechanism = _UnixLockMechanism if POSIX_MODE else _WindowsLockMechanism |
| 43 | self._lock_mechanism = mechanism(path) |
| 44 | |
| 45 | self.acquire() |
| 46 | |
| 47 | def __repr__(self) -> str: |
| 48 | repr_str = '{0}({1}) <'.format(self.__class__.__name__, self._path) |
| 49 | if self.is_locked(): |
| 50 | repr_str += 'acquired>' |
| 51 | else: |
| 52 | repr_str += 'released>' |
| 53 | return repr_str |
| 54 | |
| 55 | def acquire(self) -> None: |
| 56 | """ |
| 57 | Acquire the lock on the file, forbidding any other Certbot instance to acquire it. |
| 58 | :raises errors.LockError: if unable to acquire the lock |
| 59 | """ |
| 60 | self._lock_mechanism.acquire() |
| 61 | |
| 62 | def release(self) -> None: |
| 63 | """ |
| 64 | Release the lock on the file, allowing any other Certbot instance to acquire it. |
| 65 | """ |
| 66 | self._lock_mechanism.release() |
| 67 | |
| 68 | def is_locked(self) -> bool: |
| 69 | """ |
| 70 | Check if the file is currently locked. |
| 71 | :return: True if the file is locked, False otherwise |
| 72 | """ |
| 73 | return self._lock_mechanism.is_locked() |
| 74 | |
| 75 | |
| 76 | class _BaseLockMechanism: |