Skip to content
This repository has been archived by the owner on May 5, 2021. It is now read-only.

Commit

Permalink
Fix logic when calculating validity.
Browse files Browse the repository at this point in the history
By substracting twice, we accidentally *added* the drift to the final
validity value.

- wrong (before): validity = ttl - (elapsed_time - drift)
- correct (now):  validity = ttl - elapsed_time - drift
  • Loading branch information
hellp committed Feb 28, 2015
1 parent 169f291 commit 1ab1090
Showing 1 changed file with 9 additions and 7 deletions.
16 changes: 9 additions & 7 deletions redlock/__init__.py
@@ -1,5 +1,4 @@
import redis
from datetime import datetime, timedelta
import string
import random
import time
Expand Down Expand Up @@ -55,16 +54,20 @@ def get_unique_id(self):
def lock(self, resource, ttl):
retry = 0
val = self.get_unique_id()

# Add 2 milliseconds to the drift to account for Redis expires
# precision, which is 1 millisecond, plus 1 millisecond min
# drift for small TTLs.
drift = int(ttl * self.clock_drift_factor) + 2

while retry < self.retry_count:
n = 0
start_time = datetime.utcnow()
start_time = int(time.time() * 1000)
for server in self.servers:
if self.lock_instance(server, resource, val, ttl):
n += 1
drift = (ttl * self.clock_drift_factor) + 2
now_time = datetime.utcnow()
elapsed_time_minus_drift = ((now_time - start_time) - timedelta(milliseconds=drift)).total_seconds() * 1000
validity = ttl - elapsed_time_minus_drift
elapsed_time = int(time.time() * 1000) - start_time
validity = int(ttl - elapsed_time - drift)
if validity > 0 and n >= self.quorum:
return Lock(validity, resource, val)
else:
Expand All @@ -77,4 +80,3 @@ def lock(self, resource, ttl):
def unlock(self, lock):
for server in self.servers:
self.unlock_instance(server, lock.resource, lock.key)

0 comments on commit 1ab1090

Please sign in to comment.