Skip to content

Commit 9f0e566

Browse files
committed
Another file lock
1 parent 87a1e7c commit 9f0e566

File tree

3 files changed

+67
-2
lines changed

3 files changed

+67
-2
lines changed

tests/python_tests/requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ pytest==8.4.2
77
transformers==4.55.4
88
hf_transfer==0.1.9
99
gguf==0.17.1
10-
filelock==3.20.0
1110

1211
# rag requirements
1312
langchain_community==0.4

tests/python_tests/utils/constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
from importlib import metadata
1616
from datetime import datetime, timedelta, timezone
1717
from pathlib import Path
18-
from filelock import FileLock
1918
from contextlib import contextmanager
19+
from utils.file_lock import FileLock
2020

2121
ModelDownloaderCallable = Callable[[str], tuple[OVModel | None, AutoTokenizer | None, Path]]
2222

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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

Comments
 (0)