File: lock.py

package info (click to toggle)
python-etcd3gw 2.4.2-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 312 kB
  • sloc: python: 1,209; sh: 38; makefile: 22
file content (113 lines) | stat: -rw-r--r-- 3,244 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import uuid

from etcd3gw.utils import _encode
from etcd3gw.utils import DEFAULT_TIMEOUT
from etcd3gw.utils import LOCK_PREFIX


class Lock(object):
    def __init__(self, name, ttl=DEFAULT_TIMEOUT, client=None):
        """Create a lock using the given name with specified timeout

        :param name:
        :param ttl:
        :param client:
        """
        self.name = name
        self.ttl = ttl
        self.client = client
        self.key = LOCK_PREFIX + self.name
        self.lease = None
        self._uuid = str(uuid.uuid1())

    @property
    def uuid(self):
        """The unique id of the lock"""
        return self._uuid

    def acquire(self):
        """Acquire the lock."""
        self.lease = self.client.lease(self.ttl)

        base64_key = _encode(self.key)
        base64_value = _encode(self._uuid)
        txn = {
            'compare': [{
                'key': base64_key,
                'result': 'EQUAL',
                'target': 'CREATE',
                'create_revision': 0
            }],
            'success': [{
                'request_put': {
                    'key': base64_key,
                    'value': base64_value,
                    'lease': self.lease.id
                }
            }],
            'failure': [{
                'request_range': {
                    'key': base64_key
                }
            }]
        }
        result = self.client.transaction(txn)
        if 'succeeded' in result:
            return result['succeeded']
        return False

    def release(self):
        """Release the lock"""
        base64_key = _encode(self.key)
        base64_value = _encode(self._uuid)

        txn = {
            'compare': [{
                'key': base64_key,
                'result': 'EQUAL',
                'target': 'VALUE',
                'value': base64_value
            }],
            'success': [{
                'request_delete_range': {
                    'key': base64_key
                }
            }]
        }

        result = self.client.transaction(txn)
        if 'succeeded' in result:
            return result['succeeded']
        return False

    def refresh(self):
        """Refresh the lease on the lock

        :return:
        """
        return self.lease.refresh()

    def is_acquired(self):
        """Check if the lock is acquired"""
        values = self.client.get(self.key)
        return self._uuid.encode("latin-1") in values

    def __enter__(self):
        """Use the lock as a contextmanager"""
        self.acquire()
        return self

    def __exit__(self, exception_type, exception_value, traceback):
        self.release()