| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
import uuid |
| 14 |
|
| 15 |
from etcd3gw.utils import _encode |
| 16 |
from etcd3gw.utils import DEFAULT_TIMEOUT |
| 17 |
from etcd3gw.utils import LOCK_PREFIX |
| 18 |
|
| 19 |
|
| 20 |
class Lock: |
| 21 |
def __init__(self, name, ttl=DEFAULT_TIMEOUT, client=None): |
| 22 |
"""Create a lock using the given name with specified timeout |
| 23 |
|
| 24 |
:param name: |
| 25 |
:param ttl: |
| 26 |
:param client: |
| 27 |
""" |
| 28 |
self.name = name |
| 29 |
self.ttl = ttl |
| 30 |
self.client = client |
| 31 |
self.key = LOCK_PREFIX + self.name |
| 32 |
self.lease = None |
| 33 |
self._uuid = str(uuid.uuid1()) |
| 34 |
|
| 35 |
@property |
| 36 |
def uuid(self): |
| 37 |
"""The unique id of the lock""" |
| 38 |
return self._uuid |
| 39 |
|
| 40 |
def acquire(self): |
| 41 |
"""Acquire the lock.""" |
| 42 |
self.lease = self.client.lease(self.ttl) |
| 43 |
|
| 44 |
base64_key = _encode(self.key) |
| 45 |
base64_value = _encode(self._uuid) |
| 46 |
txn = { |
| 47 |
'compare': [{ |
| 48 |
'key': base64_key, |
| 49 |
'result': 'EQUAL', |
| 50 |
'target': 'CREATE', |
| 51 |
'create_revision': 0 |
| 52 |
}], |
| 53 |
'success': [{ |
| 54 |
'request_put': { |
| 55 |
'key': base64_key, |
| 56 |
'value': base64_value, |
| 57 |
'lease': self.lease.id |
| 58 |
} |
| 59 |
}], |
| 60 |
'failure': [{ |
| 61 |
'request_range': { |
| 62 |
'key': base64_key |
| 63 |
} |
| 64 |
}] |
| 65 |
} |
| 66 |
result = self.client.transaction(txn) |
| 67 |
if 'succeeded' in result: |
| 68 |
return result['succeeded'] |
| 69 |
return False |
| 70 |
|
| 71 |
def release(self): |
| 72 |
"""Release the lock""" |
| 73 |
base64_key = _encode(self.key) |
| 74 |
base64_value = _encode(self._uuid) |
| 75 |
|
| 76 |
txn = { |
| 77 |
'compare': [{ |
| 78 |
'key': base64_key, |
| 79 |
'result': 'EQUAL', |
| 80 |
'target': 'VALUE', |
| 81 |
'value': base64_value |
| 82 |
}], |
| 83 |
'success': [{ |
| 84 |
'request_delete_range': { |
| 85 |
'key': base64_key |
| 86 |
} |
| 87 |
}] |
| 88 |
} |
| 89 |
|
| 90 |
result = self.client.transaction(txn) |
| 91 |
if 'succeeded' in result: |
| 92 |
return result['succeeded'] |
| 93 |
return False |
| 94 |
|
| 95 |
def refresh(self): |
| 96 |
"""Refresh the lease on the lock |
| 97 |
|
| 98 |
:return: |
| 99 |
""" |
| 100 |
return self.lease.refresh() |
| 101 |
|
| 102 |
def is_acquired(self): |
| 103 |
"""Check if the lock is acquired""" |
| 104 |
values = self.client.get(self.key) |
| 105 |
return self._uuid.encode("latin-1") in values |
| 106 |
|
| 107 |
def __enter__(self): |
| 108 |
"""Use the lock as a contextmanager""" |
| 109 |
self.acquire() |
| 110 |
return self |
| 111 |
|
| 112 |
def __exit__(self, exception_type, exception_value, traceback): |
| 113 |
self.release() |