Skip to content

Commit e7f5829

Browse files
author
Joshua Harlow
committed
Use a mini-watch helper to ensure timeout is decreased
After the initial lock is acquired the timeout can now be different (due to time used getting the lock) so add a little helper class to ensure that the timeout is changed due to the elapsed time.
1 parent 87fe12f commit e7f5829

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

kazoo/recipe/lock.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,10 @@
1616
"""
1717

1818
import sys
19+
try:
20+
from time import monotonic as now
21+
except ImportError:
22+
from time import time as now
1923
import uuid
2024

2125
import six
@@ -32,6 +36,22 @@
3236
from kazoo.protocol.states import KazooState
3337

3438

39+
class _Watch(object):
40+
def __init__(self, duration=None):
41+
self.duration = duration
42+
self.started_at = None
43+
44+
def start(self):
45+
self.started_at = now()
46+
47+
def leftover(self):
48+
if self.duration is None:
49+
return None
50+
else:
51+
elapsed = now() - self.started_at
52+
return max(0, self.duration - elapsed)
53+
54+
3555
class Lock(object):
3656
"""Kazoo Lock
3757
@@ -448,8 +468,10 @@ def _inner_acquire(self, blocking, timeout=None):
448468
if self.client.exists(self.create_path):
449469
return True
450470

471+
w = _Watch(duration=timeout)
472+
w.start()
451473
lock = self.client.Lock(self.lock_path, self.data)
452-
gotten = lock.acquire(blocking=blocking, timeout=timeout)
474+
gotten = lock.acquire(blocking=blocking, timeout=w.leftover())
453475
if not gotten:
454476
return False
455477
try:
@@ -463,7 +485,7 @@ def _inner_acquire(self, blocking, timeout=None):
463485
if blocking:
464486
# If blocking, wait until self._watch_lease_change() is
465487
# called before returning
466-
self.wake_event.wait(timeout)
488+
self.wake_event.wait(w.leftover())
467489
if not self.wake_event.isSet():
468490
raise LockTimeout(
469491
"Failed to acquire semaphore on %s "

0 commit comments

Comments
 (0)