forked from z3rone-org/dirlock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
173 lines (142 loc) · 4.78 KB
/
Copy path__init__.py
File metadata and controls
173 lines (142 loc) · 4.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import os
import signal
import time
import atexit
from datetime import datetime
"""
This module provides a directory-based locking mechanism.
It allows for acquiring and releasing locks using directories,
which can be useful in scenarios where file-based based
operations can not be done atomically (e.g.
distributed or cluster filesystem)
The DirLock class provides methods to acquire and release locks,
and it supports context management for easy usage.
It also handles cleanup of locks on program exit or signal interrupts.
"""
# keep a list of currently acquired locks
# so these can be cleaned up on exit
_allActiveLocks = set()
# we don't want to miss the original handler
try:
original_sigint_handler = signal.getsignal(signal.SIGINT)
except Exception:
pass
try:
original_sigterm_handler = signal.getsignal(signal.SIGTERM)
except Exception:
pass
# function to clean up all active locks
def _clean_locks():
global _allActiveLocks
# Create a copy to avoid "Set changed size during iteration" error
locks_to_release = list(_allActiveLocks)
for dl in locks_to_release:
dl.release()
def handle_sigint_cleanup(signum, frame):
"""
Handle SIGINT (Ctrl+C) cleanup.
This function is called when a SIGINT signal is received.
It cleans up all active locks and calls the original signal handler if it exists.
"""
global original_sigint_handler
_clean_locks()
if original_sigint_handler is not None:
# restore the original handler
if callable(original_sigint_handler):
original_sigint_handler(signum, frame)
else:
signal.signal(signal.SIGINT, original_sigint_handler)
# and re-raise the signal
os.kill(os.getpid(), signal.SIGINT)
def handle_sigterm_cleanup(signum, frame):
"""
Handle SIGTERM cleanup.
This function is called when a SIGTERM signal is received.
It cleans up all active locks and calls the original signal handler if it exists.
"""
global original_sigterm_handler
_clean_locks()
if original_sigterm_handler is not None:
# restore the original handler
if callable(original_sigterm_handler):
original_sigterm_handler(signum, frame)
else:
signal.signal(signal.SIGTERM, original_sigterm_handler)
# and re-raise the signal
os.kill(os.getpid(), signal.SIGTERM)
# normal exit clean up
atexit.register(_clean_locks)
try:
# ctrl+c cleanup
signal.signal(signal.SIGINT, handle_sigint_cleanup)
except Exception:
pass
try:
# sigterm cleanup
signal.signal(signal.SIGTERM, handle_sigterm_cleanup)
except Exception:
pass
class DirLock:
default_retry_interval: float = 0.1
def __init__(self,
lock_dir: str,
retry_interval: float = None,
timeout_interval: float = -1):
"""
Initialize the DirLock.
Args:
lock_dir (str): Path to the lock directory.
retry_interval (float): Time to wait before retrying (in seconds).
timeout_interval (float): Timeout
"""
self.lock_dir = str(lock_dir)
self.timeout_interval = timeout_interval
if retry_interval is None:
self.retry_interval = DirLock.default_retry_interval
else:
self.retry_interval = retry_interval
self.acquired = False
def acquire(self):
"""
Acquire the lock by following the directory-based lock mechanism.
"""
global _allActiveLocks
start_time = datetime.now()
while True:
try:
os.mkdir(self.lock_dir)
self.acquired = True
_allActiveLocks.add(self)
break
except FileExistsError:
pass
if self.timeout_interval >= 0.0:
if (datetime.now() - start_time).total_seconds() > self.timeout_interval:
raise LockTimeoutException()
# If the lock directory exists, retry
time.sleep(self.retry_interval)
def release(self):
"""
Release the lock if it is held by this instance.
"""
if self.acquired:
try:
os.rmdir(self.lock_dir)
_allActiveLocks.remove(self)
except FileNotFoundError:
pass
self.acquired = False
def __enter__(self):
"""
Context management entry point.
"""
self.acquire()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""
Context management exit point.
"""
self.release()
class LockTimeoutException(Exception):
def __init__(self, message="acquiring lock timed out"):
super().__init__(message)