Skip to content

Commit

Permalink
fix lease test, ajust some ttl to make everthing right
Browse files Browse the repository at this point in the history
  • Loading branch information
revol.cai committed Mar 20, 2018
1 parent 5b56638 commit 8559273
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 8 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ etcdserverpbTxnResponse(header=etcdserverpbResponseHeader(cluster_id=11588568905
```python
>>> from etcd3 import Client
>>> client = Client()
>>> watcher=c.Watcher(all=True, progress_notify=True, prev_kv=True)
>>> watcher = c.Watcher(all=True, progress_notify=True, prev_kv=True)
>>> w.onEvent('f.*', lambda e: print(e.key, e.value))
>>> w.runDaemon()
>>> # etcdctl put foo bar
Expand Down
20 changes: 15 additions & 5 deletions etcd3/stateful/lease.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,24 @@ def grant(self):
self._ID = r.ID
return r
else:
r = self.client.lease_time_to_live(self.ID)
if r.TTL == -1:
r = self.time_to_live()
if 'TTL' not in r:
ttl = -1
else:
ttl = r.TTL
if ttl == -1:
raise ErrLeaseNotFound
self.last_grant = time.time() - r.TTL
self.last_grant = time.time() - ttl
return r

def time_to_live(self, keys=False):
return self.client.lease_time_to_live(self.ID, keys=keys)

def ttl(self):
return self.time_to_live().TTL
r = self.time_to_live()
if 'TTL' not in r:
return -1
return r.TTL

def alive(self):
return self.ttl() > 0
Expand Down Expand Up @@ -84,7 +91,10 @@ def keepalived():
keep_cb()
except Exception:
log.exception("stream_cb() raised an error")
time.sleep(self.grantedTTL / 4.0)
for i in range(int(self.grantedTTL / 2.0)): # keep per grantedTTL/4 seconds
if self.keeping:
break
time.sleep(0.5)
log.debug("canceled keeping lease %d" % self.ID)
if cancel_cb:
try:
Expand Down
5 changes: 3 additions & 2 deletions tests/test_lease_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_lease_util(client):
assert not lease.jammed()
assert lease._thread.is_alive()

time.sleep(TTL / 3.0)
time.sleep(TTL)
assert not lease.alive()
assert not lease.keeping
assert not lease._thread.is_alive()
Expand All @@ -54,10 +54,11 @@ def test_lease_util(client):
lease.grant()
lease.keepalive(keep_cb=keep_cb, cancel_cb=cancel_cb)
lease.cancel_keepalive()
time.sleep(TTL)
time.sleep(TTL * 0.8)
assert keep_cb.called
assert cancel_cb.called

lease.keepalive_once()
lease = client.Lease(ttl=TTL, ID=ID, new=False)
lease.grant()
assert lease.alive()
Expand Down

0 comments on commit 8559273

Please sign in to comment.