Total Complexity | 47 |
Total Lines | 208 |
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 |
||
120 | """ |
||
121 | args = kwargs.pop('args', ()) |
||
122 | if kwargs: |
||
123 | raise TypeError("Unexpected keyword arguments %s" % kwargs.keys()) |
||
124 | try: |
||
125 | return redis.evalsha(SCRIPTS[script_id], len(keys), *keys + args) |
||
126 | except NoScriptError: |
||
127 | logger.warn("%s not cached.", SCRIPTS[script_id + 2]) |
||
128 | return redis.eval(SCRIPTS[script_id + 1], len(keys), *keys + args) |
||
129 | |||
130 | |||
131 | class Lock(object): |
||
132 | """ |
||
133 | A Lock context manager implemented via redis SETNX/BLPOP. |
||
134 | """ |
||
135 | |||
136 | def __init__(self, redis_client, name, expire=None, id=None, auto_renewal=False): |
||
137 | """ |
||
138 | :param redis_client: |
||
139 | An instance of :class:`~StrictRedis`. |
||
140 | :param name: |
||
141 | The name (redis key) the lock should have. |
||
142 | :param expire: |
||
143 | The lock expiry time in seconds. If left at the default (None) |
||
144 | the lock will not expire. |
||
145 | :param id: |
||
146 | The ID (redis value) the lock should have. A random value is |
||
147 | generated when left at the default. |
||
148 | |||
149 | Note that if you specify this then the lock is marked as "held". Acquires |
||
150 | won't be possible. |
||
151 | :param auto_renewal: |
||
152 | If set to True, Lock will automatically renew the lock so that it |
||
153 | doesn't expire for as long as the lock is held (acquire() called |
||
154 | or running in a context manager). |
||
155 | |||
156 | Implementation note: Renewal will happen using a daemon thread with |
||
157 | an interval of expire*2/3. If wishing to use a different renewal |
||
158 | time, subclass Lock, call super().__init__() then set |
||
159 | self._lock_renewal_interval to your desired interval. |
||
160 | """ |
||
161 | assert isinstance(redis_client, StrictRedis) |
||
162 | if auto_renewal and expire is None: |
||
163 | raise ValueError("Expire may not be None when auto_renewal is set") |
||
164 | |||
165 | self._client = redis_client |
||
166 | self._expire = expire if expire is None else int(expire) |
||
167 | self._id = urandom(16) if id is None else id |
||
168 | self._held = id is not None |
||
169 | self._name = 'lock:'+name |
||
170 | self._signal = 'lock-signal:'+name |
||
171 | self._lock_renewal_interval = (float(expire)*2/3 |
||
172 | if auto_renewal |
||
173 | else None) |
||
174 | self._lock_renewal_thread = None |
||
175 | |||
176 | def reset(self): |
||
177 | """ |
||
178 | Forcibly deletes the lock. Use this with care. |
||
179 | """ |
||
180 | _eval_script(self._client, RESET, self._name, self._signal) |
||
181 | self._delete_signal() |
||
182 | |||
183 | @property |
||
184 | def id(self): |
||
185 | return self._id |
||
186 | |||
187 | def get_owner_id(self): |
||
188 | return self._client.get(self._name) |
||
189 | |||
190 | def acquire(self, blocking=True, timeout=None): |
||
191 | """ |
||
192 | :param blocking: |
||
193 | Boolean value specifying whether lock should be blocking or not. |
||
194 | :param timeout: |
||
195 | An integer value specifying the maximum number of seconds to block. |
||
196 | """ |
||
197 | logger.debug("Getting %r ...", self._name) |
||
198 | |||
199 | if self._held: |
||
200 | raise AlreadyAcquired("Already acquired from this Lock instance.") |
||
201 | |||
202 | if not blocking and timeout is not None: |
||
203 | raise TimeoutNotUsable("Timeout cannot be used if blocking=False") |
||
204 | |||
205 | timeout = timeout if timeout is None else int(timeout) |
||
206 | if timeout is not None and timeout <= 0: |
||
207 | raise InvalidTimeout("Timeout (%d) cannot be less than or equal to 0" % timeout) |
||
208 | |||
209 | if timeout and self._expire and timeout > self._expire: |
||
210 | raise TimeoutTooLarge("Timeout (%d) cannot be greater than expire (%d)" % (timeout, self._expire)) |
||
211 | |||
212 | busy = True |
||
213 | blpop_timeout = timeout or self._expire or 0 |
||
214 | timed_out = False |
||
215 | while busy: |
||
216 | busy = not self._client.set(self._name, self._id, nx=True, ex=self._expire) |
||
217 | if busy: |
||
218 | if timed_out: |
||
219 | return False |
||
220 | elif blocking: |
||
221 | timed_out = not self._client.blpop(self._signal, blpop_timeout) and timeout |
||
222 | else: |
||
223 | logger.debug("Failed to get %r.", self._name) |
||
224 | return False |
||
225 | |||
226 | logger.debug("Got lock for %r.", self._name) |
||
227 | self._held = True |
||
228 | if self._lock_renewal_interval is not None: |
||
229 | self._start_lock_renewer() |
||
230 | return True |
||
231 | |||
232 | def extend(self, expire=None): |
||
233 | """Extends expiration time of the lock. |
||
234 | |||
235 | :param expire: |
||
236 | New expiration time. If ``None`` - `expire` provided during |
||
237 | lock initialization will be taken. |
||
238 | """ |
||
239 | if expire is None: |
||
240 | if self._expire is not None: |
||
241 | expire = self._expire |
||
242 | else: |
||
243 | raise TypeError( |
||
244 | "To extend a lock 'expire' must be provided as an " |
||
245 | "argument to extend() method or at initialization time." |
||
246 | ) |
||
247 | error = _eval_script(self._client, EXTEND, self._name, args=(expire, self._id)) |
||
248 | if error == 1: |
||
249 | raise NotAcquired("Lock %s is not acquired or it already expired." % self._name) |
||
250 | elif error == 2: |
||
251 | raise NotExpirable("Lock %s has no assigned expiration time" % |
||
252 | self._name) |
||
253 | elif error: |
||
254 | raise RuntimeError("Unsupported error code %s from EXTEND script" % error) |
||
255 | |||
256 | @staticmethod |
||
257 | def _lock_renewer(lockref, interval, stop): |
||
258 | """ |
||
259 | Renew the lock key in redis every `interval` seconds for as long |
||
260 | as `self._lock_renewal_thread.should_exit` is False. |
||
261 | """ |
||
262 | log = getLogger("%s.lock_refresher" % __name__) |
||
263 | while not stop.wait(timeout=interval): |
||
264 | log.debug("Refreshing lock") |
||
265 | lock = lockref() |
||
266 | if lock is None: |
||
267 | log.debug("The lock no longer exists, " |
||
268 | "stopping lock refreshing") |
||
269 | break |
||
270 | lock.extend(expire=lock._expire) |
||
271 | del lock |
||
272 | log.debug("Exit requested, stopping lock refreshing") |
||
273 | |||
274 | def _start_lock_renewer(self): |
||
275 | """ |
||
276 | Starts the lock refresher thread. |
||
277 | """ |
||
278 | if self._lock_renewal_thread is not None: |
||
279 | raise AlreadyStarted("Lock refresh thread already started") |
||
280 | |||
281 | logger.debug( |
||
282 | "Starting thread to refresh lock every %s seconds", |
||
283 | self._lock_renewal_interval |
||
284 | ) |
||
285 | self._lock_renewal_stop = threading.Event() |
||
286 | self._lock_renewal_thread = threading.Thread( |
||
287 | group=None, |
||
288 | target=self._lock_renewer, |
||
289 | kwargs={'lockref': weakref.ref(self), |
||
290 | 'interval': self._lock_renewal_interval, |
||
291 | 'stop': self._lock_renewal_stop} |
||
292 | ) |
||
293 | self._lock_renewal_thread.setDaemon(True) |
||
294 | self._lock_renewal_thread.start() |
||
295 | |||
296 | def _stop_lock_renewer(self): |
||
297 | """ |
||
298 | Stop the lock renewer. |
||
299 | |||
300 | This signals the renewal thread and waits for its exit. |
||
301 | """ |
||
302 | if self._lock_renewal_thread is None or not self._lock_renewal_thread.is_alive(): |
||
303 | return |
||
304 | logger.debug("Signalling the lock refresher to stop") |
||
305 | self._lock_renewal_stop.set() |
||
306 | self._lock_renewal_thread.join() |
||
307 | self._lock_renewal_thread = None |
||
308 | logger.debug("Lock refresher has stopped") |
||
309 | |||
310 | def __enter__(self): |
||
311 | acquired = self.acquire(blocking=True) |
||
312 | assert acquired, "Lock wasn't acquired, but blocking=True" |
||
313 | return self |
||
314 | |||
315 | def __exit__(self, exc_type=None, exc_value=None, traceback=None): |
||
316 | self.release() |
||
317 | |||
318 | def release(self): |
||
319 | """Releases the lock, that was acquired with the same object. |
||
320 | |||
321 | .. note:: |
||
322 | |||
323 | If you want to release a lock that you acquired in a different place you have two choices: |
||
324 | |||
325 | * Use ``Lock("name", id=id_from_other_place).release()`` |
||
326 | * Use ``Lock("name").reset()`` |
||
327 | """ |
||
328 | if not self._held: |
||
352 |