Total Complexity | 42 |
Total Lines | 178 |
Duplicated Lines | 0 % |
Complex classes like src.redis_lock.Lock often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | import threading |
||
96 | class Lock(object): |
||
97 | """ |
||
98 | A Lock context manager implemented via redis SETNX/BLPOP. |
||
99 | """ |
||
100 | |||
101 | def __init__(self, redis_client, name, expire=None, id=None, auto_renewal=False): |
||
102 | """ |
||
103 | :param redis_client: |
||
104 | An instance of :class:`~StrictRedis`. |
||
105 | :param name: |
||
106 | The name (redis key) the lock should have. |
||
107 | :param expire: |
||
108 | The lock expiry time in seconds. If left at the default (None) |
||
109 | the lock will not expire. |
||
110 | :param id: |
||
111 | The ID (redis value) the lock should have. A random value is |
||
112 | generated when left at the default. |
||
113 | :param auto_renewal: |
||
114 | If set to True, Lock will automatically renew the lock so that it |
||
115 | doesn't expire for as long as the lock is held (acquire() called |
||
116 | or running in a context manager). |
||
117 | |||
118 | Implementation note: Renewal will happen using a daemon thread with |
||
119 | an interval of expire*2/3. If wishing to use a different renewal |
||
120 | time, subclass Lock, call super().__init__() then set |
||
121 | self._lock_renewal_interval to your desired interval. |
||
122 | """ |
||
123 | assert isinstance(redis_client, StrictRedis) |
||
124 | if auto_renewal and expire is None: |
||
125 | raise ValueError("Expire may not be None when auto_renewal is set") |
||
126 | |||
127 | self._client = redis_client |
||
128 | self._expire = expire if expire is None else int(expire) |
||
129 | self._id = urandom(16) if id is None else id |
||
130 | self._held = False |
||
131 | self._name = 'lock:'+name |
||
132 | self._signal = 'lock-signal:'+name |
||
133 | self._lock_renewal_interval = expire*2/3 if auto_renewal else None |
||
134 | self._lock_renewal_thread = None |
||
135 | |||
136 | def reset(self): |
||
137 | """ |
||
138 | Forcibly deletes the lock. Use this with care. |
||
139 | """ |
||
140 | _eval_script(self._client, RESET, 2, self._name, self._signal) |
||
141 | |||
142 | @property |
||
143 | def id(self): |
||
144 | return self._id |
||
145 | |||
146 | def get_owner_id(self): |
||
147 | return self._client.get(self._name) |
||
148 | |||
149 | def acquire(self, blocking=True, timeout=None): |
||
150 | """ |
||
151 | :param blocking: |
||
152 | Boolean value specifying whether lock should be blocking or not. |
||
153 | :param timeout: |
||
154 | An integer value specifying the maximum number of seconds to block. |
||
155 | """ |
||
156 | logger.debug("Getting %r ...", self._name) |
||
157 | |||
158 | if self._held: |
||
159 | raise AlreadyAcquired("Already acquired from this Lock instance.") |
||
160 | |||
161 | if not blocking and timeout is not None: |
||
162 | raise TimeoutNotUsable("Timeout cannot be used if blocking=False") |
||
163 | |||
164 | timeout = timeout if timeout is None else int(timeout) |
||
165 | if timeout is not None and timeout <= 0: |
||
166 | raise InvalidTimeout("Timeout (%d) cannot be less than or equal to 0" % timeout) |
||
167 | |||
168 | if timeout and self._expire and timeout > self._expire: |
||
169 | raise TimeoutTooLarge("Timeout (%d) cannot be greater than expire (%d)" % (timeout, self._expire)) |
||
170 | |||
171 | busy = True |
||
172 | blpop_timeout = timeout or self._expire or 0 |
||
173 | timed_out = False |
||
174 | while busy: |
||
175 | busy = not self._client.set(self._name, self._id, nx=True, ex=self._expire) |
||
176 | if busy: |
||
177 | if timed_out: |
||
178 | return False |
||
179 | elif blocking: |
||
180 | timed_out = not self._client.blpop(self._signal, blpop_timeout) |
||
181 | else: |
||
182 | logger.debug("Failed to get %r.", self._name) |
||
183 | return False |
||
184 | |||
185 | logger.debug("Got lock for %r.", self._name) |
||
186 | self._held = True |
||
187 | if self._lock_renewal_interval is not None: |
||
188 | self._start_lock_renewer() |
||
189 | return True |
||
190 | |||
191 | def extend(self, expire=None): |
||
192 | """Extends expiration time of the lock. |
||
193 | |||
194 | :param expire: |
||
195 | New expiration time. If ``None`` - `expire` provided during |
||
196 | lock initialization will be taken. |
||
197 | """ |
||
198 | if self._expire is None: |
||
199 | raise NotExpirable('The lock has no expiry time, so extending it ' |
||
200 | 'makes no sense.') |
||
201 | if expire is None: |
||
202 | expire = self._expire |
||
203 | self._client.set(self._name, self._id, xx=True, ex=expire) |
||
204 | |||
205 | def _lock_renewer(self, interval): |
||
206 | """ |
||
207 | Renew the lock key in redis every `interval` seconds for as long |
||
208 | as `self._lock_renewal_thread.should_exit` is False. |
||
209 | """ |
||
210 | log = getLogger("%s.lock_refresher" % __name__) |
||
211 | while not self._lock_renewal_thread.wait_for_exit_request(timeout=interval): |
||
212 | log.debug("Refreshing lock") |
||
213 | self.extend(expire=self._expire) |
||
214 | log.debug("Exit requested, stopping lock refreshing") |
||
215 | |||
216 | def _start_lock_renewer(self): |
||
217 | """ |
||
218 | Starts the lock refresher thread. |
||
219 | """ |
||
220 | if self._lock_renewal_thread is not None: |
||
221 | raise AlreadyStarted("Lock refresh thread already started") |
||
222 | |||
223 | logger.debug( |
||
224 | "Starting thread to refresh lock every %s seconds", |
||
225 | self._lock_renewal_interval |
||
226 | ) |
||
227 | self._lock_renewal_thread = InterruptableThread( |
||
228 | group=None, |
||
229 | target=self._lock_renewer, |
||
230 | kwargs={'interval': self._lock_renewal_interval} |
||
231 | ) |
||
232 | self._lock_renewal_thread.setDaemon(True) |
||
233 | self._lock_renewal_thread.start() |
||
234 | |||
235 | def _stop_lock_renewer(self): |
||
236 | """ |
||
237 | Stop the lock renewer. |
||
238 | |||
239 | This signals the renewal thread and waits for its exit. |
||
240 | """ |
||
241 | if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive(): |
||
242 | return |
||
243 | logger.debug("Signalling the lock refresher to stop") |
||
244 | self._lock_renewal_thread.request_exit() |
||
245 | self._lock_renewal_thread.join() |
||
246 | self._lock_renewal_thread = None |
||
247 | logger.debug("Lock refresher has stopped") |
||
248 | |||
249 | def __enter__(self): |
||
250 | acquired = self.acquire(blocking=True) |
||
251 | assert acquired, "Lock wasn't acquired, but blocking=True" |
||
252 | return self |
||
253 | |||
254 | def __exit__(self, exc_type=None, exc_value=None, traceback=None, force=False): |
||
255 | if not (self._held or force): |
||
256 | raise NotAcquired("This Lock instance didn't acquire the lock.") |
||
257 | if self._lock_renewal_thread is not None: |
||
258 | self._stop_lock_renewer() |
||
259 | logger.debug("Releasing %r.", self._name) |
||
260 | _eval_script(self._client, UNLOCK, |
||
261 | 2, self._name, self._signal, self._id) |
||
262 | |||
263 | self._held = False |
||
264 | |||
265 | def release(self, force=False): |
||
266 | """Releases the lock, that was acquired in the same Python context. |
||
267 | |||
268 | :param force: |
||
269 | If ``False`` - fail with exception if this instance was not in |
||
270 | acquired state in the same Python context. |
||
271 | If ``True`` - fail silently. |
||
272 | """ |
||
273 | return self.__exit__(force=force) |
||
274 | |||
319 |