|
| 1 | +# Copyright (C) 2018-2025 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import os |
| 5 | +import time |
| 6 | +import errno |
| 7 | +from pathlib import Path |
| 8 | +from contextlib import contextmanager |
| 9 | + |
| 10 | +class FileLock: |
| 11 | + def __init__(self, lock_file: str, timeout: float = 300): |
| 12 | + self.lock_file = Path(lock_file) |
| 13 | + self.timeout = timeout |
| 14 | + self._lock_file_fd = None |
| 15 | + |
| 16 | + def acquire(self, poll_interval: float = 0.1): |
| 17 | + start_time = time.time() |
| 18 | + |
| 19 | + self.lock_file.parent.mkdir(parents=True, exist_ok=True) |
| 20 | + |
| 21 | + while True: |
| 22 | + try: |
| 23 | + self._lock_file_fd = os.open( |
| 24 | + str(self.lock_file), |
| 25 | + os.O_CREAT | os.O_EXCL | os.O_RDWR |
| 26 | + ) |
| 27 | + break |
| 28 | + except OSError as e: |
| 29 | + if e.errno != errno.EEXIST: |
| 30 | + raise |
| 31 | + |
| 32 | + if self.timeout is not None and (time.time() - start_time) >= self.timeout: |
| 33 | + raise TimeoutError(f"Timeout acquiring lock on {self.lock_file}") |
| 34 | + |
| 35 | + time.sleep(poll_interval) |
| 36 | + |
| 37 | + def release(self): |
| 38 | + if self._lock_file_fd is not None: |
| 39 | + os.close(self._lock_file_fd) |
| 40 | + self._lock_file_fd = None |
| 41 | + |
| 42 | + try: |
| 43 | + self.lock_file.unlink() |
| 44 | + except FileNotFoundError: |
| 45 | + pass |
| 46 | + |
| 47 | + def __enter__(self): |
| 48 | + self.acquire() |
| 49 | + return self |
| 50 | + |
| 51 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 52 | + self.release() |
| 53 | + return False |
| 54 | + |
| 55 | + def __del__(self): |
| 56 | + self.release() |
| 57 | + |
| 58 | +@contextmanager |
| 59 | +def file_lock(lock_file: str, timeout: float = 300): |
| 60 | + lock = FileLock(lock_file, timeout) |
| 61 | + lock.acquire() |
| 62 | + try: |
| 63 | + yield lock |
| 64 | + finally: |
| 65 | + lock.release() |
| 66 | + |
0 commit comments