forked from tinyogre/zklock
/
zklock.py
194 lines (165 loc) · 6.13 KB
/
zklock.py
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# Copyright (c) 2011 Joe Rumsey (joe@rumsey.org)
#
# This file is part of zklock (http://github.com/tinyogre/zklock)
#
# zklock is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import zookeeper, threading
import sys
connected=False
conn_cv = threading.Condition( )
reconnect_host = ''
ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"};
ROOT="/ZkLock"
# locks is a hash by lock name, each value being a list of locks that are waiting for that name.
locks = {}
def my_connection_watcher(handle,type,state,path):
global connected, conn_cv
conn_cv.acquire()
connected = True
conn_cv.notifyAll()
conn_cv.release()
def my_lock_watcher(handle,type,state,path):
global locks
if not path in locks:
return
# Notify everyone that's blocked on this lock that should wake up and see if they acquired the lock
# (Which happens when they have the oldest entry in the list of waiters)
locklist = locks[path]
for lock in locklist:
lock.cv.acquire()
lock.cv.notifyAll()
lock.cv.release()
def connect(host=None):
global conn_cv, connected, handle
global reconnect_host
if host is None:
host = "localhost:2181"
reconnect_host = host
conn_cv.acquire()
handle = zookeeper.init(host, my_connection_watcher, 10000)
while not connected:
conn_cv.wait()
conn_cv.release()
connected = False
while not connected:
try:
zookeeper.create(handle, ROOT, "1", [ZOO_OPEN_ACL_UNSAFE], 0)
connected = True
except zookeeper.NodeExistsException as e:
# No worries
connected = True
except zookeeper.ConnectionLossException:
continue
except:
raise
def reconnect():
connect(reconnect_host)
class Lock:
def __init__(self, name):
self.name = ROOT + '/' + name
self.cv = threading.Condition()
created = False
while not created:
try:
zookeeper.create(handle, self.name, "0", [ZOO_OPEN_ACL_UNSAFE], 0)
created=True
except zookeeper.NodeExistsException:
# S'ok.
created = True
except zookeeper.ConnectionLossException:
continue
self.znode = None
def createNode(self):
# the EPHEMERAL flag creates a new unique node name with an increasing sequence
created = False
while not created:
try:
self.znode = zookeeper.create(handle, self.name + '/lock', "0", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL | zookeeper.SEQUENCE)
created = True
except zookeeper.ConnectionLossException:
reconnect()
continue
def acquire(self, block = True):
# Here's what this does:
# Creates a child node of the named node with a unique ID
# Gets all the children of the named node
# Looks to see if the node it just created is the lowest in sequence
# If it is, the lock is ours! Done!
# If not, wait for the children callback to signal that there has been a change to children, then start over at step 2
#
# So it's not polling, but it will wake up any time another client starts waiting, in addition to any time a client goes away
global handle
global locks
if not self.name in locks:
locks[self.name] = []
locks[self.name] += [self]
exists = False
self.createNode()
self.keyname = self.znode[self.znode.rfind('/') + 1:]
acquired = False
self.cv.acquire()
while not acquired:
try:
children = zookeeper.get_children(handle, self.name, my_lock_watcher)
except zookeeper.ConnectionLossException:
reconnect()
continue
children.sort()
if len(children) == 0 or not self.keyname in children:
# Disconnects or other errors can cause this
self.createNode()
continue
if self.keyname == children[0]:
# The lock is ours!
acquired = True
else:
if block:
# Wait for a notification from get_children
self.cv.wait()
else:
#lock could not be acquired
break
self.cv.release()
locks[self.name].remove(self)
return acquired
def release(self):
# All release has to do, if you follow the logic in acquire, is delete the unique ID that this lock created. That will wake
# up all the other waiters and whoever is first in line can then have the lock.
global handle
released = False
while not released:
try:
zookeeper.delete(handle, self.znode)
released = True
except zookeeper.ConnectionLossException:
reconnect()
self.znode = None
self.keyname = None
class ScopedLock:
def __init__(self, name, block=True):
self.name = name
self.lock = None
self.acquired = None
self.block = block
def __enter__(self):
if not self.lock:
self.lock = Lock(self.name)
self.acquired = self.lock.acquire(block=self.block)
return self
def __exit__(self, type, value, traceback):
if self.acquired:
self.lock.release()
self.lock = None
self.acquired = False