Kitxuuu commited on
Commit
b63c816
·
verified ·
1 Parent(s): e1028bb

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-fatjar/src/main/resources/mainClasses +9 -0
  2. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/models.py +17 -0
  3. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/rest.py +230 -0
  4. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/settings.py +30 -0
  5. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/views.py +165 -0
  6. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/c/zookeeper.c +1702 -0
  7. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/examples/README +8 -0
  8. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/examples/watch_znode_for_changes.py +202 -0
  9. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/setup.py +45 -0
  10. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/zk.py +76 -0
  11. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/async_test.py +33 -0
  12. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/close_deadlock_test.py +50 -0
  13. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/connection_test.py +163 -0
  14. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/create_test.py +104 -0
  15. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/delete_test.py +68 -0
  16. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/exists_test.py +64 -0
  17. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/get_set_test.py +211 -0
  18. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/run_tests.sh +43 -0
  19. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/zkServer.sh +102 -0
  20. local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/zktestbase.py +104 -0
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-fatjar/src/main/resources/mainClasses ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ ::Client Commands
2
+ client:org.apache.zookeeper.ZooKeeperMain:Client shell to ZooKeeper
3
+ ::Server Commands
4
+ server:org.apache.zookeeper.server.quorum.QuorumPeerMain:Start ZooKeeper server
5
+ ::Test Commands
6
+ generateLoad:org.apache.zookeeper.test.system.GenerateLoad:A distributed load generator for testing
7
+ ic:org.apache.zookeeper.test.system.InstanceContainer:A container that will instantiate classes as directed by an instance manager
8
+ systest:org.apache.zookeeper.test.system.BaseSysTest:Start system test
9
+ jmh:org.apache.zookeeper.BenchMain:Run jmh micro benchmarks
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/models.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/rest.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Licensed to the Apache Software Foundation (ASF) under one
3
+ # or more contributor license agreements. See the NOTICE file
4
+ # distributed with this work for additional information
5
+ # regarding copyright ownership. The ASF licenses this file
6
+ # to you under the Apache License, Version 2.0 (the
7
+ # "License"); you may not use this file except in compliance
8
+ # with the License. You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import urllib2
19
+ import urllib
20
+ import simplejson
21
+
22
+ from contextlib import contextmanager
23
+
24
+ class RequestWithMethod(urllib2.Request):
25
+ """ Request class that know how to set the method name """
26
+ def __init__(self, *args, **kwargs):
27
+ urllib2.Request.__init__(self, *args, **kwargs)
28
+ self._method = None
29
+
30
+ def get_method(self):
31
+ return self._method or \
32
+ urllib2.Request.get_method(self)
33
+
34
+ def set_method(self, method):
35
+ self._method = method
36
+
37
+ class ZooKeeper(object):
38
+
39
+ class Error(Exception): pass
40
+
41
+ class NotFound(Error): pass
42
+
43
+ class ZNodeExists(Error): pass
44
+
45
+ class InvalidSession(Error): pass
46
+
47
+ class WrongVersion(Error): pass
48
+
49
+ def __init__(self, uri = 'http://localhost:9998'):
50
+ self._base = uri
51
+ self._session = None
52
+
53
+ def start_session(self, expire=5, id=None):
54
+ """ Create a session and return the ID """
55
+ if id is None:
56
+ url = "%s/sessions/v1/?op=create&expire=%d" % (self._base, expire)
57
+ self._session = self._do_post(url)['id']
58
+ else:
59
+ self._session = id
60
+ return self._session
61
+
62
+ def close_session(self):
63
+ """ Close the session on the server """
64
+ if self._session is not None:
65
+ url = '%s/sessions/v1/%s' % (self._base, self._session)
66
+ self._do_delete(url)
67
+ self._session = None
68
+
69
+ def heartbeat(self):
70
+ """ Send a heartbeat request. This is needed in order to keep a session alive """
71
+ if self._session is not None:
72
+ url = '%s/sessions/v1/%s' % (self._base, self._session)
73
+ self._do_put(url, '')
74
+
75
+ @contextmanager
76
+ def session(self, *args, **kwargs):
77
+ """ Session handling using a context manager """
78
+ yield self.start_session(*args, **kwargs)
79
+ self.close_session()
80
+
81
+ def get(self, path):
82
+ """ Get a node """
83
+ url = "%s/znodes/v1%s" % (self._base, path)
84
+ return self._do_get(url)
85
+
86
+ def get_children(self, path):
87
+ """ Get all the children for a given path. This function creates a generator """
88
+ for child_path in self.get_children_paths(path, uris=True):
89
+ try:
90
+ yield self._do_get(child_path)
91
+ except ZooKeeper.NotFound:
92
+ continue
93
+
94
+ def get_children_paths(self, path, uris=False):
95
+ """ Get the paths for children nodes """
96
+ url = "%s/znodes/v1%s?view=children" % (self._base, path)
97
+ resp = self._do_get(url)
98
+ for child in resp.get('children', []):
99
+ yield child if not uris else resp['child_uri_template']\
100
+ .replace('{child}', urllib2.quote(child))
101
+
102
+ def create(self, path, data=None, sequence=False, ephemeral=False):
103
+ """ Create a new node. By default this call creates a persistent znode.
104
+
105
+ You can also create an ephemeral or a sequential znode.
106
+ """
107
+ ri = path.rindex('/')
108
+ head, name = path[:ri+1], path[ri+1:]
109
+ if head != '/': head = head[:-1]
110
+
111
+ flags = {
112
+ 'null': 'true' if data is None else 'false',
113
+ 'ephemeral': 'true' if ephemeral else 'false',
114
+ 'sequence': 'true' if sequence else 'false'
115
+ }
116
+ if ephemeral:
117
+ if self._session:
118
+ flags['session'] = self._session
119
+ else:
120
+ raise ZooKeeper.Error, 'You need a session '\
121
+ 'to create an ephemeral node'
122
+ flags = urllib.urlencode(flags)
123
+
124
+ url = "%s/znodes/v1%s?op=create&name=%s&%s" % \
125
+ (self._base, head, name, flags)
126
+
127
+ return self._do_post(url, data)
128
+
129
+ def set(self, path, data=None, version=-1, null=False):
130
+ """ Set the value of node """
131
+ url = "%s/znodes/v1%s?%s" % (self._base, path, \
132
+ urllib.urlencode({
133
+ 'version': version,
134
+ 'null': 'true' if null else 'false'
135
+ }))
136
+ return self._do_put(url, data)
137
+
138
+ def delete(self, path, version=-1):
139
+ """ Delete a znode """
140
+ if type(path) is list:
141
+ map(lambda el: self.delete(el, version), path)
142
+ return
143
+
144
+ url = '%s/znodes/v1%s?%s' % (self._base, path, \
145
+ urllib.urlencode({
146
+ 'version':version
147
+ }))
148
+ try:
149
+ return self._do_delete(url)
150
+ except urllib2.HTTPError, e:
151
+ if e.code == 412:
152
+ raise ZooKeeper.WrongVersion(path)
153
+ elif e.code == 404:
154
+ raise ZooKeeper.NotFound(path)
155
+ raise
156
+
157
+ def recursive_delete(self, path):
158
+ """ Delete all the nodes from the tree """
159
+ for child in self.get_children_paths(path):
160
+ fp = ("%s/%s" % (path, child)).replace('//', '/')
161
+ self.recursive_delete(fp)
162
+ self.delete(path)
163
+
164
+ def exists(self, path):
165
+ """ Do a znode exists """
166
+ try:
167
+ self.get(path)
168
+ return True
169
+ except ZooKeeper.NotFound:
170
+ return False
171
+
172
+ def _do_get(self, uri):
173
+ """ Send a GET request and convert errors to exceptions """
174
+ try:
175
+ req = urllib2.urlopen(uri)
176
+ resp = simplejson.load(req)
177
+
178
+ if 'Error' in resp:
179
+ raise ZooKeeper.Error(resp['Error'])
180
+
181
+ return resp
182
+ except urllib2.HTTPError, e:
183
+ if e.code == 404:
184
+ raise ZooKeeper.NotFound(uri)
185
+ raise
186
+
187
+ def _do_post(self, uri, data=None):
188
+ """ Send a POST request and convert errors to exceptions """
189
+ try:
190
+ req = urllib2.Request(uri, {})
191
+ req.add_header('Content-Type', 'application/octet-stream')
192
+ if data is not None:
193
+ req.add_data(data)
194
+
195
+ resp = simplejson.load(urllib2.urlopen(req))
196
+ if 'Error' in resp:
197
+ raise ZooKeeper.Error(resp['Error'])
198
+ return resp
199
+
200
+ except urllib2.HTTPError, e:
201
+ if e.code == 201:
202
+ return True
203
+ elif e.code == 409:
204
+ raise ZooKeeper.ZNodeExists(uri)
205
+ elif e.code == 401:
206
+ raise ZooKeeper.InvalidSession(uri)
207
+ raise
208
+
209
+ def _do_delete(self, uri):
210
+ """ Send a DELETE request """
211
+ req = RequestWithMethod(uri)
212
+ req.set_method('DELETE')
213
+ req.add_header('Content-Type', 'application/octet-stream')
214
+ return urllib2.urlopen(req).read()
215
+
216
+ def _do_put(self, uri, data):
217
+ """ Send a PUT request """
218
+ try:
219
+ req = RequestWithMethod(uri)
220
+ req.set_method('PUT')
221
+ req.add_header('Content-Type', 'application/octet-stream')
222
+ if data is not None:
223
+ req.add_data(data)
224
+
225
+ return urllib2.urlopen(req).read()
226
+ except urllib2.HTTPError, e:
227
+ if e.code == 412: # precondition failed
228
+ raise ZooKeeper.WrongVersion(uri)
229
+ raise
230
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/settings.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ DJANGO_APPS = [ "zkui" ]
18
+ NICE_NAME = "ZooKeeper Browser"
19
+ REQUIRES_HADOOP = False
20
+
21
+ CLUSTERS = [{
22
+ 'nice_name': 'Default',
23
+ 'hostport': 'localhost:2181,localhost:2182,localhost:2183',
24
+ 'rest_gateway': 'http://localhost:9998'
25
+ }
26
+ ]
27
+
28
+ DEPENDER_PACKAGE_YMLS = [
29
+ "src/zkui/static/js/package.yml",
30
+ ]
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/views.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from desktop.lib.django_util import render
18
+ from django.http import Http404
19
+
20
+ from zkui import settings
21
+ from zkui.stats import ZooKeeperStats
22
+ from zkui.rest import ZooKeeper
23
+ from zkui.utils import get_cluster_or_404
24
+ from zkui.forms import CreateZNodeForm, EditZNodeForm
25
+
26
+ def _get_global_overview():
27
+ overview = []
28
+ for c in settings.CLUSTERS:
29
+ overview.append(_get_overview(c))
30
+ return overview
31
+
32
+ def _get_overview(cluster):
33
+ stats = {}
34
+ for s in cluster['hostport'].split(','):
35
+ host, port = map(str.strip, s.split(':'))
36
+
37
+ zks = ZooKeeperStats(host, port)
38
+ stats[s] = zks.get_stats() or {}
39
+
40
+ cluster['stats'] = stats
41
+ return cluster
42
+
43
+ def _group_stats_by_role(cluster):
44
+ leader, followers = None, []
45
+ for host, stats in cluster['stats'].items():
46
+ stats['host'] = host
47
+
48
+ if stats.get('zk_server_state') == 'leader':
49
+ leader = stats
50
+
51
+ elif stats.get('zk_server_state') == 'follower':
52
+ followers.append(stats)
53
+
54
+ return leader, followers
55
+
56
+ def index(request):
57
+ overview = _get_global_overview()
58
+ return render('index.mako', request,
59
+ dict(overview=overview))
60
+
61
+ def view(request, id):
62
+ cluster = get_cluster_or_404(id)
63
+
64
+ cluster = _get_overview(cluster)
65
+ leader, followers = _group_stats_by_role(cluster)
66
+
67
+ return render('view.mako', request,
68
+ dict(cluster=cluster, leader=leader, followers=followers))
69
+
70
+ def clients(request, host):
71
+ parts = host.split(':')
72
+ if len(parts) != 2:
73
+ raise Http404
74
+
75
+ host, port = parts
76
+ zks = ZooKeeperStats(host, port)
77
+ clients = zks.get_clients()
78
+
79
+ return render('clients.mako', request,
80
+ dict(host=host, port=port, clients=clients))
81
+
82
+ def tree(request, id, path):
83
+ cluster = get_cluster_or_404(id)
84
+ zk = ZooKeeper(cluster['rest_gateway'])
85
+
86
+ znode = zk.get(path)
87
+ children = sorted(zk.get_children_paths(path))
88
+
89
+ return render('tree.mako', request,
90
+ dict(cluster=cluster, path=path, \
91
+ znode=znode, children=children))
92
+
93
+ def delete(request, id, path):
94
+ cluster = get_cluster_or_404(id)
95
+ if request.method == 'POST':
96
+ zk = ZooKeeper(cluster['rest_gateway'])
97
+ try:
98
+ zk.recursive_delete(path)
99
+ except ZooKeeper.NotFound:
100
+ pass
101
+
102
+ return tree(request, id, path[:path.rindex('/')] or '/')
103
+
104
+ def create(request, id, path):
105
+ cluster = get_cluster_or_404(id)
106
+
107
+ if request.method == 'POST':
108
+ form = CreateZNodeForm(request.POST)
109
+ if form.is_valid():
110
+ zk = ZooKeeper(cluster['rest_gateway'])
111
+
112
+ full_path = ("%s/%s" % (path, form.cleaned_data['name']))\
113
+ .replace('//', '/')
114
+
115
+ zk.create(full_path, \
116
+ form.cleaned_data['data'], \
117
+ sequence = form.cleaned_data['sequence'])
118
+ return tree(request, id, path)
119
+ else:
120
+ form = CreateZNodeForm()
121
+
122
+ return render('create.mako', request,
123
+ dict(path=path, form=form))
124
+
125
+ def edit_as_base64(request, id, path):
126
+ cluster = get_cluster_or_404(id)
127
+ zk = ZooKeeper(cluster['rest_gateway'])
128
+ node = zk.get(path)
129
+
130
+ if request.method == 'POST':
131
+ form = EditZNodeForm(request.POST)
132
+ if form.is_valid():
133
+ # TODO is valid base64 string?
134
+ data = form.cleaned_data['data'].decode('base64')
135
+ zk.set(path, data, form.cleaned_data['version'])
136
+
137
+ return tree(request, id, path)
138
+ else:
139
+ form = EditZNodeForm(dict(\
140
+ data=node.get('data64', ''),
141
+ version=node.get('version', '-1')))
142
+
143
+ return render('edit.mako', request,
144
+ dict(path=path, form=form))
145
+
146
+ def edit_as_text(request, id, path):
147
+ cluster = get_cluster_or_404(id)
148
+ zk = ZooKeeper(cluster['rest_gateway'])
149
+ node = zk.get(path)
150
+
151
+ if request.method == 'POST':
152
+ form = EditZNodeForm(request.POST)
153
+ if form.is_valid():
154
+ zk.set(path, form.cleaned_data['data'])
155
+
156
+ return tree(request, id, path)
157
+ else:
158
+ form = EditZNodeForm(dict(data=node.get('data64', '')\
159
+ .decode('base64').strip(),
160
+ version=node.get('version', '-1')))
161
+
162
+ return render('edit.mako', request,
163
+ dict(path=path, form=form))
164
+
165
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/c/zookeeper.c ADDED
@@ -0,0 +1,1702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ #include <Python.h>
20
+ #include <zookeeper.h>
21
+ #include <assert.h>
22
+
23
+ //////////////////////////////////////////////
24
+ // EXCEPTIONS
25
+ PyObject *ZooKeeperException = NULL;
26
+ PyObject *SystemErrorException;
27
+ PyObject *RuntimeInconsistencyException;
28
+ PyObject *DataInconsistencyException;
29
+ PyObject *ConnectionLossException;
30
+ PyObject *MarshallingErrorException;
31
+ PyObject *UnimplementedException;
32
+ PyObject *OperationTimeoutException;
33
+ PyObject *BadArgumentsException;
34
+ PyObject *InvalidStateException;
35
+
36
+ PyObject *ApiErrorException;
37
+ PyObject *NoNodeException;
38
+ PyObject *NoAuthException;
39
+ PyObject *NodeExistsException;
40
+ PyObject *BadVersionException;
41
+ PyObject *NoChildrenForEphemeralsException;
42
+ PyObject *NotEmptyException;
43
+ PyObject *SessionExpiredException;
44
+ PyObject *SessionMovedException;
45
+ PyObject *InvalidCallbackException;
46
+ PyObject *InvalidACLException;
47
+ PyObject *AuthFailedException;
48
+ PyObject *ClosingException;
49
+ PyObject *NothingException;
50
+
51
+ PyObject *err_to_exception(int errcode) {
52
+ switch (errcode) {
53
+ case ZSYSTEMERROR:
54
+ return SystemErrorException;
55
+ case ZINVALIDSTATE:
56
+ return InvalidStateException;
57
+ case ZRUNTIMEINCONSISTENCY:
58
+ return RuntimeInconsistencyException;
59
+ case ZDATAINCONSISTENCY:
60
+ return DataInconsistencyException;
61
+ case ZCONNECTIONLOSS:
62
+ return ConnectionLossException;
63
+ case ZMARSHALLINGERROR:
64
+ return MarshallingErrorException;
65
+ case ZUNIMPLEMENTED:
66
+ return UnimplementedException;
67
+ case ZOPERATIONTIMEOUT:
68
+ return OperationTimeoutException;
69
+ case ZBADARGUMENTS:
70
+ return BadArgumentsException;
71
+ case ZAPIERROR:
72
+ return ApiErrorException;
73
+ case ZNONODE:
74
+ return NoNodeException;
75
+ case ZNOAUTH:
76
+ return NoAuthException;
77
+ case ZBADVERSION:
78
+ return BadVersionException;
79
+ case ZNOCHILDRENFOREPHEMERALS:
80
+ return NoChildrenForEphemeralsException;
81
+ case ZNODEEXISTS:
82
+ return NodeExistsException;
83
+ case ZINVALIDACL:
84
+ return InvalidACLException;
85
+ case ZAUTHFAILED:
86
+ return AuthFailedException;
87
+ case ZNOTEMPTY:
88
+ return NotEmptyException;
89
+ case ZSESSIONEXPIRED:
90
+ return SessionExpiredException;
91
+ case ZINVALIDCALLBACK:
92
+ return InvalidCallbackException;
93
+ case ZSESSIONMOVED:
94
+ return SessionMovedException;
95
+ case ZCLOSING:
96
+ return ClosingException;
97
+ case ZNOTHING:
98
+ return NothingException;
99
+ case ZOK:
100
+ default:
101
+ return NULL;
102
+ }
103
+ }
104
+
105
+
106
+ #define CHECK_ZHANDLE(z) if ( (z) < 0 || (z) >= num_zhandles) { \
107
+ PyErr_SetString( ZooKeeperException, "zhandle out of range" ); \
108
+ return NULL; \
109
+ } else if ( zhandles[(z)] == NULL ) { \
110
+ PyErr_SetString(ZooKeeperException, "zhandle already freed"); \
111
+ return NULL; \
112
+ }
113
+
114
+ /* Contains all the state required for a watcher callback - these are
115
+ passed to the *dispatch functions as void*, cast to pywatcher_t and
116
+ then their callback member is invoked if not NULL */
117
+ typedef struct {
118
+ int zhandle;
119
+ PyObject *callback;
120
+ int permanent;
121
+ }pywatcher_t;
122
+
123
+ /* This array exists because we need to ref. count the global watchers
124
+ for each connection - but they're inaccessible without pulling in
125
+ zk_adaptor.h, which I'm trying to avoid. */
126
+ static pywatcher_t **watchers;
127
+
128
+ /* We keep an array of zhandles available for use. When a zhandle is
129
+ correctly closed, the C client frees the memory so we set the
130
+ zhandles[i] entry to NULL. This entry can then be re-used. */
131
+ static zhandle_t** zhandles = NULL;
132
+ static int num_zhandles = 0;
133
+ static int max_zhandles = 0;
134
+ #define REAL_MAX_ZHANDLES 32768
135
+
136
+ /* -------------------------------------------------------------------------- */
137
+ /* zhandles - unique connection ids - tracking */
138
+ /* -------------------------------------------------------------------------- */
139
+
140
+
141
+ /* Allocates an initial zhandle and watcher array */
142
+ int init_zhandles(int num) {
143
+ zhandles = malloc(sizeof(zhandle_t*)*num);
144
+ watchers = malloc(sizeof(pywatcher_t*)*num);
145
+ if (zhandles == NULL || watchers == NULL) {
146
+ return 0;
147
+ }
148
+ max_zhandles = num;
149
+ num_zhandles = 0;
150
+ memset(zhandles, 0, sizeof(zhandle_t*)*max_zhandles);
151
+ return 1;
152
+ }
153
+
154
+ /* Note that the following zhandle functions are not thread-safe. The
155
+ C-Python runtime does not seem to pre-empt a thread that is in a C
156
+ module, so there's no need for synchronisation. */
157
+
158
+ /* Doubles the size of the zhandle / watcher array Returns 0 if the
159
+ new array would be >= REAL_MAX_ZHANDLES in size. Called when zhandles
160
+ is full. Returns 0 if allocation failed or if max num zhandles
161
+ exceeded. */
162
+ int resize_zhandles(void) {
163
+ zhandle_t **tmp = zhandles;
164
+ pywatcher_t ** wtmp = watchers;
165
+ if (max_zhandles >= REAL_MAX_ZHANDLES >> 1) {
166
+ return 0;
167
+ }
168
+ max_zhandles *= 2;
169
+ zhandles = malloc(sizeof(zhandle_t*)*max_zhandles);
170
+ if (zhandles == NULL) {
171
+ PyErr_SetString(PyExc_MemoryError, "malloc for new zhandles failed");
172
+ return 0;
173
+ }
174
+ memset(zhandles, 0, sizeof(zhandle_t*)*max_zhandles);
175
+ memcpy(zhandles, tmp, sizeof(zhandle_t*)*max_zhandles/2);
176
+
177
+ watchers = malloc(sizeof(pywatcher_t*)*max_zhandles);
178
+ if (watchers == NULL) {
179
+ PyErr_SetString(PyExc_MemoryError, "malloc for new watchers failed");
180
+ return 0;
181
+ }
182
+ memset(watchers, 0, sizeof(pywatcher_t*)*max_zhandles);
183
+ memcpy(watchers, wtmp, sizeof(pywatcher_t*)*max_zhandles/2);
184
+
185
+ free(wtmp);
186
+ free(tmp);
187
+ return 1;
188
+ }
189
+
190
+ /* Find a free zhandle - this iterates through the list of open
191
+ zhandles, but we expect it to be infrequently called. There are
192
+ optimisations that can be made if this turns out to be problematic.
193
+ Returns -1 if no free handle is found - resize_handles() can be
194
+ called in that case. */
195
+ unsigned int next_zhandle(void) {
196
+ int i = 0;
197
+ for (i=0;i<max_zhandles;++i) {
198
+ if (zhandles[i] == NULL) {
199
+ num_zhandles++;
200
+ return i;
201
+ }
202
+ }
203
+
204
+ return -1;
205
+ }
206
+
207
+ /* -------------------------------------------------------------------------- */
208
+ /* Utility functions to construct and deallocate data structures */
209
+ /* -------------------------------------------------------------------------- */
210
+
211
+
212
+ /* Creates a new pywatcher_t to hold connection state, a callback
213
+ object and a flag to say if the watcher is permanent. Takes a new
214
+ reference to the callback object. */
215
+ pywatcher_t *create_pywatcher(int zh, PyObject* cb, int permanent)
216
+ {
217
+ pywatcher_t *ret = (pywatcher_t*)calloc(sizeof(pywatcher_t),1);
218
+ if (ret == NULL) {
219
+ PyErr_SetString(PyExc_MemoryError, "calloc failed in create_pywatcher");
220
+ return NULL;
221
+ }
222
+ Py_INCREF(cb);
223
+ ret->zhandle = zh; ret->callback = cb; ret->permanent = permanent;
224
+ return ret;
225
+ }
226
+
227
+ /* Releases the reference taken in create_pywatcher to the callback,
228
+ then frees the allocated pywatcher_t* */
229
+ void free_pywatcher(pywatcher_t *pw)
230
+ {
231
+ if (pw == NULL) {
232
+ return;
233
+ }
234
+ Py_DECREF(pw->callback);
235
+
236
+ free(pw);
237
+ }
238
+
239
+ /* Constructs a new stat object. Returns Py_None if stat == NULL or a
240
+ dictionary containing all the stat information otherwise. In either
241
+ case, takes a reference to the returned object. */
242
+ PyObject *build_stat( const struct Stat *stat )
243
+ {
244
+ if (stat == NULL) {
245
+ Py_INCREF(Py_None);
246
+ return Py_None;
247
+ }
248
+ return Py_BuildValue( "{s:K, s:K, s:K, s:K,"
249
+ "s:i, s:i, s:i, s:K,"
250
+ "s:i, s:i, s:K}",
251
+ "czxid", stat->czxid,
252
+ "mzxid", stat->mzxid,
253
+ "ctime", stat->ctime,
254
+ "mtime", stat->mtime,
255
+ "version", stat->version,
256
+ "cversion", stat->cversion,
257
+ "aversion", stat->aversion,
258
+ "ephemeralOwner", stat->ephemeralOwner,
259
+ "dataLength", stat->dataLength,
260
+ "numChildren", stat->numChildren,
261
+ "pzxid", stat->pzxid );
262
+ }
263
+
264
+ /* Creates a new list of strings from a String_vector. Returns the
265
+ empty list if the String_vector is NULL. Takes a reference to the
266
+ returned PyObject and gives that reference to the caller. */
267
+ PyObject *build_string_vector(const struct String_vector *sv)
268
+ {
269
+ PyObject *ret;
270
+ if (!sv) {
271
+ return PyList_New(0);
272
+ }
273
+
274
+ ret = PyList_New(sv->count);
275
+ if (ret) {
276
+ int i;
277
+ for (i=0;i<sv->count;++i) {
278
+ #if PY_MAJOR_VERSION >= 3
279
+ PyObject *s = PyUnicode_FromString(sv->data[i]);
280
+ #else
281
+ PyObject *s = PyString_FromString(sv->data[i]);
282
+ #endif
283
+ if (!s) {
284
+ if (ret != Py_None) {
285
+ Py_DECREF(ret);
286
+ }
287
+ ret = NULL;
288
+ break;
289
+ }
290
+ PyList_SetItem(ret, i, s);
291
+ }
292
+ }
293
+ return ret;
294
+ }
295
+
296
+ /* Returns 1 if the PyObject is a valid representation of an ACL, and
297
+ 0 otherwise. */
298
+ int check_is_acl(PyObject *o) {
299
+ int i;
300
+ PyObject *entry;
301
+ if (o == NULL) {
302
+ return 0;
303
+ }
304
+ if (!PyList_Check(o)) {
305
+ return 0;
306
+ }
307
+ for (i=0;i<PyList_Size(o);++i) {
308
+ PyObject *element = PyList_GetItem(o,i);
309
+ if (!PyDict_Check(element)) {
310
+ return 0;
311
+ }
312
+ entry = PyDict_GetItemString( element, "perms" );
313
+ if (entry == NULL) {
314
+ return 0;
315
+ }
316
+
317
+ entry = PyDict_GetItemString( element, "scheme" );
318
+ if (entry == NULL) {
319
+ return 0;
320
+ }
321
+
322
+ entry = PyDict_GetItemString( element, "id" );
323
+ if (entry == NULL) {
324
+ return 0;
325
+ }
326
+ }
327
+
328
+ return 1;
329
+ }
330
+
331
+ /* Macro form to throw exception if o is not an ACL */
332
+ #define CHECK_ACLS(o) if (check_is_acl(o) == 0) { \
333
+ PyErr_SetString(err_to_exception(ZINVALIDACL), zerror(ZINVALIDACL)); \
334
+ return NULL; \
335
+ }
336
+
337
+
338
+ /* Creates a new list of ACL dictionaries from an ACL_vector. Returns
339
+ the empty list if the ACL_vector is NULL. Takes a reference to the
340
+ returned PyObject and gives that reference to the caller. */
341
+ PyObject *build_acls( const struct ACL_vector *acls )
342
+ {
343
+ if (acls == NULL) {
344
+ return PyList_New(0);
345
+ }
346
+
347
+ PyObject *ret = PyList_New(acls->count);
348
+ int i;
349
+ for (i=0;i<acls->count;++i) {
350
+ PyObject *acl = Py_BuildValue( "{s:i, s:s, s:s}",
351
+ "perms", acls->data[i].perms,
352
+ "scheme", acls->data[i].id.scheme,
353
+ "id", acls->data[i].id.id );
354
+ PyList_SetItem(ret, i, acl);
355
+ }
356
+ return ret;
357
+ }
358
+
359
+ /* Parse the Python representation of an ACL list into an ACL_vector
360
+ (which needs subsequent freeing) */
361
+ int parse_acls(struct ACL_vector *acls, PyObject *pyacls)
362
+ {
363
+ PyObject *a;
364
+ int i;
365
+ if (acls == NULL || pyacls == NULL) {
366
+ PyErr_SetString(PyExc_ValueError, "acls or pyacls NULL in parse_acls");
367
+ return 0;
368
+ }
369
+
370
+ acls->count = PyList_Size( pyacls );
371
+
372
+ // Is this a list? If not, we can't do anything
373
+ if (PyList_Check(pyacls) == 0) {
374
+ PyErr_SetString(InvalidACLException, "List of ACLs required in parse_acls");
375
+ return 0;
376
+ }
377
+
378
+ acls->data = (struct ACL *)calloc(acls->count, sizeof(struct ACL));
379
+ if (acls->data == NULL) {
380
+ PyErr_SetString(PyExc_MemoryError, "calloc failed in parse_acls");
381
+ return 0;
382
+ }
383
+
384
+ for (i=0;i<acls->count;++i) {
385
+ a = PyList_GetItem(pyacls, i);
386
+ // a is now a dictionary
387
+ PyObject *perms = PyDict_GetItemString( a, "perms" );
388
+ #if PY_MAJOR_VERSION >= 3
389
+ acls->data[i].perms = (int32_t)(PyLong_AsLong(perms));
390
+ PyObject *tem_utfstring;
391
+ tem_utfstring = PyUnicode_AsEncodedString(PyDict_GetItemString( a, "id" ), "utf-8", NULL );
392
+ acls->data[i].id.id = strdup( PyBytes_AS_STRING(tem_utfstring));
393
+ Py_DECREF(tem_utfstring);
394
+ tem_utfstring = PyUnicode_AsEncodedString(PyDict_GetItemString( a, "scheme" ), "utf-8", NULL );
395
+ acls->data[i].id.scheme = strdup( PyBytes_AS_STRING(tem_utfstring) );
396
+ Py_DECREF(tem_utfstring);
397
+ #else
398
+ acls->data[i].perms = (int32_t)(PyInt_AsLong(perms));
399
+ acls->data[i].id.id = strdup( PyString_AsString( PyDict_GetItemString( a, "id" ) ) );
400
+ acls->data[i].id.scheme = strdup( PyString_AsString( PyDict_GetItemString( a, "scheme" ) ) );
401
+ #endif
402
+ }
403
+ return 1;
404
+ }
405
+
406
+ /* Deallocates the memory allocated inside an ACL_vector, but not the
407
+ ACL_vector itself */
408
+ void free_acls( struct ACL_vector *acls )
409
+ {
410
+ if (acls == NULL) {
411
+ return;
412
+ }
413
+ int i;
414
+ for (i=0;i<acls->count;++i) {
415
+ free(acls->data[i].id.id);
416
+ free(acls->data[i].id.scheme);
417
+ }
418
+ free(acls->data);
419
+ }
420
+
421
+ /* -------------------------------------------------------------------------- */
422
+ /* Watcher and callback implementation */
423
+ /* -------------------------------------------------------------------------- */
424
+
425
+ /* Every watcher invocation goes through this dispatch point, which
426
+ a) acquires the global interpreter lock
427
+
428
+ b) unpacks the PyObject to call from the passed context pointer,
429
+ which handily includes the index of the relevant zookeeper handle
430
+ to pass back to Python.
431
+
432
+ c) Makes the call into Python, checking for error conditions which
433
+ we are responsible for detecting and doing something about (we just
434
+ print the error and plough right on)
435
+
436
+ d) releases the lock after freeing up the context object, which is
437
+ only used for one watch invocation (watches are one-shot, unless
438
+ 'permanent' != 0)
439
+ */
440
+ void watcher_dispatch(zhandle_t *zzh, int type, int state,
441
+ const char *path, void *context)
442
+ {
443
+ PyGILState_STATE gstate;
444
+ pywatcher_t *pyw = (pywatcher_t*)context;
445
+ PyObject *callback = pyw->callback;
446
+ if (callback == NULL) {
447
+ // This is unexpected
448
+ char msg[256];
449
+ sprintf(msg, "pywatcher: %d %p %d", pyw->zhandle, pyw->callback, pyw->permanent);
450
+ PyErr_SetString(PyExc_ValueError, msg);
451
+ return;
452
+ }
453
+
454
+ gstate = PyGILState_Ensure();
455
+ PyObject *arglist = Py_BuildValue("(i,i,i,s)", pyw->zhandle,type, state, path);
456
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL) {
457
+ PyErr_Print();
458
+ }
459
+ Py_DECREF(arglist);
460
+ if (pyw->permanent == 0 && (type != ZOO_SESSION_EVENT || state < 0)) {
461
+ free_pywatcher(pyw);
462
+ }
463
+ PyGILState_Release(gstate);
464
+ }
465
+
466
+ /* The completion callbacks (from asynchronous calls) are implemented similarly */
467
+
468
+ /* Called when an asynchronous call that returns void completes and
469
+ dispatches user provided callback */
470
+ void void_completion_dispatch(int rc, const void *data)
471
+ {
472
+ PyGILState_STATE gstate;
473
+ pywatcher_t *pyw = (pywatcher_t*)data;
474
+ if (pyw == NULL)
475
+ return;
476
+ PyObject *callback = pyw->callback;
477
+ gstate = PyGILState_Ensure();
478
+ PyObject *arglist = Py_BuildValue("(i,i)", pyw->zhandle, rc);
479
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL)
480
+ PyErr_Print();
481
+ Py_DECREF(arglist);
482
+ free_pywatcher(pyw);
483
+ PyGILState_Release(gstate);
484
+ }
485
+
486
+ /* Called when an asynchronous call that returns a stat structure
487
+ completes and dispatches user provided callback */
488
+ void stat_completion_dispatch(int rc, const struct Stat *stat, const void *data)
489
+ {
490
+ PyGILState_STATE gstate;
491
+ pywatcher_t *pyw = (pywatcher_t*)data;
492
+ if (pyw == NULL)
493
+ return;
494
+ PyObject *callback = pyw->callback;
495
+ gstate = PyGILState_Ensure();
496
+ PyObject *pystat = build_stat(stat);
497
+ PyObject *arglist = Py_BuildValue("(i,i,O)", pyw->zhandle,rc, pystat);
498
+ Py_DECREF(pystat);
499
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL)
500
+ PyErr_Print();
501
+ Py_DECREF(arglist);
502
+ free_pywatcher(pyw);
503
+ PyGILState_Release(gstate);
504
+ }
505
+
506
+ /* Called when an asynchronous call that returns a stat structure and
507
+ some untyped data completes and dispatches user provided
508
+ callback (used by aget) */
509
+ void data_completion_dispatch(int rc, const char *value, int value_len, const struct Stat *stat, const void *data)
510
+ {
511
+ PyGILState_STATE gstate;
512
+ pywatcher_t *pyw = (pywatcher_t*)data;
513
+ if (pyw == NULL)
514
+ return;
515
+ PyObject *callback = pyw->callback;
516
+ gstate = PyGILState_Ensure();
517
+ PyObject *pystat = build_stat(stat);
518
+ PyObject *arglist = Py_BuildValue("(i,i,s#,O)", pyw->zhandle,rc, value,value_len, pystat);
519
+ Py_DECREF(pystat);
520
+
521
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL)
522
+ PyErr_Print();
523
+ Py_DECREF(arglist);
524
+ free_pywatcher(pyw);
525
+ PyGILState_Release(gstate);
526
+ }
527
+
528
+ /* Called when an asynchronous call that returns a list of strings
529
+ completes and dispatches user provided callback */
530
+ void strings_completion_dispatch(int rc, const struct String_vector *strings, const void *data)
531
+ {
532
+ PyGILState_STATE gstate;
533
+ pywatcher_t *pyw = (pywatcher_t*)data;
534
+ if (pyw == NULL)
535
+ return;
536
+ PyObject *callback = pyw->callback;
537
+ gstate = PyGILState_Ensure();
538
+ PyObject *pystrings = build_string_vector(strings);
539
+ if (pystrings)
540
+ {
541
+ PyObject *arglist = Py_BuildValue("(i,i,O)", pyw->zhandle, rc, pystrings);
542
+ if (arglist == NULL || PyObject_CallObject((PyObject*)callback, arglist) == NULL)
543
+ PyErr_Print();
544
+ Py_DECREF(arglist);
545
+ }
546
+ else
547
+ PyErr_Print();
548
+ Py_DECREF(pystrings);
549
+ free_pywatcher(pyw);
550
+ PyGILState_Release(gstate);
551
+ }
552
+
553
+ /* Called when an asynchronous call that returns a single string
554
+ completes and dispatches user provided callback */
555
+ void string_completion_dispatch(int rc, const char *value, const void *data)
556
+ {
557
+ PyGILState_STATE gstate;
558
+ pywatcher_t *pyw = (pywatcher_t*)data;
559
+ if (pyw == NULL) {
560
+ return;
561
+ }
562
+ PyObject *callback = pyw->callback;
563
+ gstate = PyGILState_Ensure();
564
+ PyObject *arglist = Py_BuildValue("(i,i,s)", pyw->zhandle,rc, value);
565
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL)
566
+ PyErr_Print();
567
+ Py_DECREF(arglist);
568
+ free_pywatcher(pyw);
569
+ PyGILState_Release(gstate);
570
+ }
571
+
572
+ /* Called when an asynchronous call that returns a list of ACLs
573
+ completes and dispatches user provided callback */
574
+ void acl_completion_dispatch(int rc, struct ACL_vector *acl, struct Stat *stat, const void *data)
575
+ {
576
+ PyGILState_STATE gstate;
577
+ pywatcher_t *pyw = (pywatcher_t*)data;
578
+ if (pyw == NULL) {
579
+ return;
580
+ }
581
+ PyObject *callback = pyw->callback;
582
+ gstate = PyGILState_Ensure();
583
+ PyObject *pystat = build_stat(stat);
584
+ PyObject *pyacls = build_acls(acl);
585
+ PyObject *arglist = Py_BuildValue("(i,i,O,O)", pyw->zhandle,rc, pyacls, pystat);
586
+
587
+ Py_DECREF(pystat);
588
+ Py_DECREF(pyacls);
589
+
590
+ if (PyObject_CallObject((PyObject*)callback, arglist) == NULL) {
591
+ PyErr_Print();
592
+ }
593
+ Py_DECREF(arglist);
594
+ free_pywatcher(pyw);
595
+ PyGILState_Release(gstate);
596
+ }
597
+
598
+ /* -------------------------------------------------------------------------- */
599
+ /* ZOOKEEPER API IMPLEMENTATION */
600
+ /* -------------------------------------------------------------------------- */
601
+
602
+
603
+ static PyObject *pyzookeeper_init_common(PyObject *self, PyObject *args, int ssl) {
604
+ const char *host;
605
+ const char *cert_str;
606
+ PyObject *watcherfn = Py_None;
607
+ zhandle_t *zh = NULL;
608
+ int recv_timeout = 10000;
609
+ clientid_t cid;
610
+ cid.client_id = -1;
611
+ const char *passwd;
612
+ int handle = next_zhandle();
613
+ if (handle == -1) {
614
+ if (resize_zhandles() == 0) {
615
+ return NULL;
616
+ }
617
+ handle = next_zhandle();
618
+ }
619
+
620
+ if (handle == -1) {
621
+ PyErr_SetString(ZooKeeperException,"Couldn't find a free zhandle, something is very wrong");
622
+ return NULL;
623
+ }
624
+
625
+ if (ssl) {
626
+ if (!PyArg_ParseTuple(args, "ss|Oi(Ls)", &host, &cert_str, &watcherfn, &recv_timeout, &cid.client_id, &passwd))
627
+ return NULL;
628
+ } else {
629
+ if (!PyArg_ParseTuple(args, "s|Oi(Ls)", &host, &watcherfn, &recv_timeout, &cid.client_id, &passwd))
630
+ return NULL;
631
+ }
632
+
633
+ if (cid.client_id != -1) {
634
+ strncpy(cid.passwd, passwd, 16*sizeof(char));
635
+ }
636
+ pywatcher_t *pyw = NULL;
637
+ if (watcherfn != Py_None) {
638
+ pyw = create_pywatcher(handle, watcherfn,1);
639
+ if (pyw == NULL) {
640
+ return NULL;
641
+ }
642
+ }
643
+ watchers[handle] = pyw;
644
+
645
+ if (ssl) {
646
+ #ifdef HAVE_OPENSSL_H
647
+ zh = zookeeper_init_ssl( host, cert_str, watcherfn != Py_None ? watcher_dispatch : NULL,
648
+ recv_timeout, cid.client_id == -1 ? 0 : &cid, pyw, 0 );
649
+ #else
650
+ fprintf(stderr, "SSL support not compiled in (called with ssl=%d).\n", ssl);
651
+ abort();
652
+ #endif
653
+ } else {
654
+ zh = zookeeper_init( host, watcherfn != Py_None ? watcher_dispatch : NULL,
655
+ recv_timeout, cid.client_id == -1 ? 0 : &cid, pyw, 0 );
656
+ }
657
+
658
+ if (zh == NULL)
659
+ {
660
+ PyErr_Format( ZooKeeperException, "Could not internally obtain%s zookeeper handle", ssl ? " SSL" : "" );
661
+ return NULL;
662
+ }
663
+
664
+ zhandles[handle] = zh;
665
+ return Py_BuildValue( "i", handle);
666
+ }
667
+
668
+ static PyObject *pyzookeeper_init(PyObject *self, PyObject *args)
669
+ {
670
+ return pyzookeeper_init_common(self, args, /*ssl*/0);
671
+ }
672
+
673
+
674
+ #ifdef HAVE_OPENSSL_H
675
+ static PyObject *pyzookeeper_init_ssl(PyObject *self, PyObject *args)
676
+ {
677
+ return pyzookeeper_init_common(self, args, /*ssl*/1);
678
+ }
679
+ #endif
680
+
681
+
682
+ /* -------------------------------------------------------------------------- */
683
+ /* Asynchronous API implementation */
684
+ /* -------------------------------------------------------------------------- */
685
+
686
+ /* Asynchronous node creation, returns integer error code */
687
+ PyObject *pyzoo_acreate(PyObject *self, PyObject *args)
688
+ {
689
+ int zkhid; char *path; char *value; int valuelen;
690
+ struct ACL_vector acl; int flags = 0;
691
+ PyObject *completion_callback = Py_None;
692
+ PyObject *pyacls = Py_None;
693
+ if (!PyArg_ParseTuple(args, "iss#O|iO", &zkhid, &path,
694
+ &value, &valuelen, &pyacls, &flags,
695
+ &completion_callback)) {
696
+ return NULL;
697
+ }
698
+ CHECK_ZHANDLE(zkhid);
699
+ CHECK_ACLS(pyacls);
700
+ if (parse_acls(&acl, pyacls) == 0) {
701
+ return NULL;
702
+ }
703
+ void *pyw = NULL;
704
+ if (completion_callback != Py_None) {
705
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
706
+ if (pyw == NULL) {
707
+ return NULL;
708
+ }
709
+ }
710
+ int err = zoo_acreate( zhandles[zkhid],
711
+ path,
712
+ value,
713
+ valuelen,
714
+ pyacls == Py_None ? NULL : &acl,
715
+ flags,
716
+ string_completion_dispatch,
717
+ pyw);
718
+ free_acls(&acl);
719
+ if (err != ZOK)
720
+ {
721
+ PyErr_SetString(err_to_exception(err), zerror(err));
722
+ return NULL;
723
+ }
724
+ return Py_BuildValue("i", err);
725
+ }
726
+
727
+ /* Asynchronous node deletion, returns integer error code */
728
+ PyObject *pyzoo_adelete(PyObject *self, PyObject *args)
729
+ {
730
+ int zkhid; char *path; int version = -1;
731
+ PyObject *completion_callback = Py_None;
732
+ if (!PyArg_ParseTuple(args, "is|iO", &zkhid, &path, &version, &completion_callback))
733
+ return NULL;
734
+ CHECK_ZHANDLE(zkhid);
735
+
736
+ void *pyw = NULL;
737
+ if (completion_callback != Py_None) {
738
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
739
+ if (pyw == NULL) {
740
+ return NULL;
741
+ }
742
+ }
743
+
744
+ int err = zoo_adelete( zhandles[zkhid],
745
+ path,
746
+ version,
747
+ void_completion_dispatch,
748
+ pyw);
749
+
750
+ if (err != ZOK) {
751
+ PyErr_SetString(err_to_exception(err), zerror(err));
752
+ return NULL;
753
+ }
754
+ return Py_BuildValue("i", err);
755
+ }
756
+
757
+ /* Asynchronous node existence check, returns integer error code */
758
+ PyObject *pyzoo_aexists(PyObject *self, PyObject *args)
759
+ {
760
+ int zkhid; char *path;
761
+ PyObject *completion_callback = Py_None;
762
+ PyObject *exists_watch = Py_None;
763
+ if (!PyArg_ParseTuple(args, "is|OO", &zkhid, &path,
764
+ &exists_watch, &completion_callback))
765
+ return NULL;
766
+ CHECK_ZHANDLE(zkhid);
767
+ void *comp_pyw = NULL;
768
+ if (completion_callback != Py_None) {
769
+ comp_pyw = create_pywatcher(zkhid, completion_callback, 0);
770
+ if (comp_pyw == NULL) {
771
+ return NULL;
772
+ }
773
+ }
774
+ void *exist_pyw = NULL;
775
+ if (exists_watch != Py_None) {
776
+ exist_pyw = create_pywatcher(zkhid, exists_watch, 0);
777
+ if (exist_pyw == NULL) {
778
+ return NULL;
779
+ }
780
+ }
781
+
782
+ int err = zoo_awexists( zhandles[zkhid],
783
+ path,
784
+ exists_watch != Py_None ? watcher_dispatch : NULL,
785
+ exist_pyw,
786
+ stat_completion_dispatch,
787
+ comp_pyw);
788
+
789
+ if (err != ZOK)
790
+ {
791
+ PyErr_SetString(err_to_exception(err), zerror(err));
792
+ return NULL;
793
+ }
794
+ return Py_BuildValue("i", err);;
795
+ }
796
+
797
+ /* Asynchronous node data retrieval, returns integer error code */
798
+ PyObject *pyzoo_aget(PyObject *self, PyObject *args)
799
+ {
800
+ int zkhid; char *path;
801
+ PyObject *completion_callback = Py_None;
802
+ PyObject *get_watch = Py_None;
803
+ void *comp_pw = NULL;
804
+ void *watch_pw = NULL;
805
+
806
+ if (!PyArg_ParseTuple(args, "is|OO", &zkhid, &path,
807
+ &get_watch, &completion_callback)) {
808
+ return NULL;
809
+ }
810
+
811
+ CHECK_ZHANDLE(zkhid);
812
+
813
+ if (get_watch != Py_None) {
814
+ if ((watch_pw = create_pywatcher(zkhid, get_watch, 0)) == NULL) {
815
+ return NULL;
816
+ }
817
+ }
818
+
819
+ if (completion_callback != Py_None) {
820
+ if ((comp_pw = create_pywatcher(zkhid, completion_callback, 0)) == NULL) {
821
+ return NULL;
822
+ }
823
+ }
824
+
825
+ int err = zoo_awget( zhandles[zkhid],
826
+ path,
827
+ get_watch != Py_None ? watcher_dispatch : NULL,
828
+ watch_pw,
829
+ data_completion_dispatch,
830
+ comp_pw);
831
+
832
+ if (err != ZOK) {
833
+ PyErr_SetString(err_to_exception(err), zerror(err));
834
+ return NULL;
835
+ }
836
+ return Py_BuildValue("i", err);
837
+ }
838
+
839
+ /* Asynchronous node contents update, returns integer error code */
840
+ PyObject *pyzoo_aset(PyObject *self, PyObject *args)
841
+ {
842
+ int zkhid; char *path; char *buffer; int buflen; int version=-1;
843
+ PyObject *completion_callback = Py_None;
844
+ if (!PyArg_ParseTuple(args, "iss#|iO", &zkhid, &path, &buffer, &buflen, &version, &completion_callback))
845
+ return NULL;
846
+ CHECK_ZHANDLE(zkhid);
847
+ void *pyw = NULL;
848
+ if (completion_callback != Py_None) {
849
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
850
+ if (pyw == NULL) {
851
+ return NULL;
852
+ }
853
+ }
854
+ int err = zoo_aset( zhandles[zkhid],
855
+ path,
856
+ buffer,
857
+ buflen,
858
+ version,
859
+ stat_completion_dispatch,
860
+ pyw);
861
+
862
+ if (err != ZOK) {
863
+ PyErr_SetString(err_to_exception(err), zerror(err));
864
+ return NULL;
865
+ }
866
+ return Py_BuildValue("i", err);
867
+ }
868
+
869
+ /* Asynchronous node child retrieval, returns integer error code */
870
+ PyObject *pyzoo_aget_children(PyObject *self, PyObject *args)
871
+ {
872
+ int zkhid; char *path;
873
+ PyObject *completion_callback = Py_None;
874
+ PyObject *get_watch;
875
+ if (!PyArg_ParseTuple(args, "is|OO", &zkhid, &path,
876
+ &get_watch, &completion_callback))
877
+ return NULL;
878
+ CHECK_ZHANDLE(zkhid);
879
+
880
+ void *get_pyw = NULL;
881
+ if (get_watch != Py_None) {
882
+ get_pyw = create_pywatcher(zkhid, get_watch, 0);
883
+ if (get_pyw == NULL) {
884
+ return NULL;
885
+ }
886
+ }
887
+
888
+ void *pyw = NULL;
889
+ if (completion_callback != Py_None) {
890
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
891
+ if (pyw == NULL) {
892
+ return NULL;
893
+ }
894
+ }
895
+
896
+ int err = zoo_awget_children( zhandles[zkhid],
897
+ path,
898
+ get_watch != Py_None ? watcher_dispatch : NULL,
899
+ get_pyw,
900
+ strings_completion_dispatch,
901
+ pyw);
902
+ if (err != ZOK) {
903
+ PyErr_SetString(err_to_exception(err), zerror(err));
904
+ return NULL;
905
+ }
906
+ return Py_BuildValue("i", err);;
907
+ }
908
+
909
+ /* Asynchronous sync, returns integer error code */
910
+ PyObject *pyzoo_async(PyObject *self, PyObject *args)
911
+ {
912
+ int zkhid; char *path;
913
+ PyObject *completion_callback = Py_None;
914
+ if (!PyArg_ParseTuple(args, "is|O", &zkhid, &path,
915
+ &completion_callback)) {
916
+ return NULL;
917
+ }
918
+ CHECK_ZHANDLE(zkhid);
919
+
920
+ void *pyw = NULL;
921
+ if (completion_callback != Py_None) {
922
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
923
+ if (pyw == NULL) {
924
+ return NULL;
925
+ }
926
+ }
927
+
928
+ int err = zoo_async( zhandles[zkhid],
929
+ path,
930
+ string_completion_dispatch,
931
+ pyw);
932
+
933
+ if (err != ZOK) {
934
+ PyErr_SetString(err_to_exception(err), zerror(err));
935
+ return NULL;
936
+ }
937
+ return Py_BuildValue("i", err);;
938
+ }
939
+
940
+ /* Asynchronous node ACL retrieval, returns integer error code */
941
+ PyObject *pyzoo_aget_acl(PyObject *self, PyObject *args)
942
+ {
943
+ int zkhid; char *path;
944
+ PyObject *completion_callback = Py_None;
945
+ if (!PyArg_ParseTuple(args, "is|O", &zkhid, &path,
946
+ &completion_callback)) {
947
+ return NULL;
948
+ }
949
+ CHECK_ZHANDLE(zkhid);
950
+
951
+ void *pyw = NULL;
952
+ if (completion_callback != Py_None) {
953
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
954
+ if (pyw == NULL) {
955
+ return NULL;
956
+ }
957
+ }
958
+
959
+ int err = zoo_aget_acl( zhandles[zkhid],
960
+ path,
961
+ acl_completion_dispatch,
962
+ pyw);
963
+ if (err != ZOK) {
964
+ PyErr_SetString(err_to_exception(err), zerror(err));
965
+ return NULL;
966
+ }
967
+ return Py_BuildValue("i", err);;
968
+ }
969
+
970
+ /* Asynchronous node ACL update, returns integer error code */
971
+ PyObject *pyzoo_aset_acl(PyObject *self, PyObject *args)
972
+ {
973
+ int zkhid; char *path; int version;
974
+ PyObject *completion_callback = Py_None, *pyacl;
975
+ struct ACL_vector aclv;
976
+ if (!PyArg_ParseTuple(args, "isiO|O", &zkhid, &path, &version,
977
+ &pyacl, &completion_callback)) {
978
+ return NULL;
979
+ }
980
+ CHECK_ZHANDLE(zkhid);
981
+ CHECK_ACLS(pyacl);
982
+ if (parse_acls(&aclv, pyacl) == 0) {
983
+ return NULL;
984
+ }
985
+
986
+ void *pyw = NULL;
987
+ if (completion_callback != Py_None) {
988
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
989
+ if (pyw == NULL) {
990
+ return NULL;
991
+ }
992
+ }
993
+
994
+ int err = zoo_aset_acl( zhandles[zkhid],
995
+ path,
996
+ version,
997
+ &aclv,
998
+ void_completion_dispatch,
999
+ pyw);
1000
+ free_acls(&aclv);
1001
+ if (err != ZOK) {
1002
+ PyErr_SetString(err_to_exception(err), zerror(err));
1003
+ return NULL;
1004
+ }
1005
+ return Py_BuildValue("i", err);;
1006
+ }
1007
+
1008
+ /* Asynchronous authorization addition, returns integer error code */
1009
+ PyObject *pyzoo_add_auth(PyObject *self, PyObject *args)
1010
+ {
1011
+ int zkhid;
1012
+ char *scheme, *cert;
1013
+ int certLen;
1014
+ PyObject *completion_callback;
1015
+
1016
+ if (!PyArg_ParseTuple(args, "iss#O", &zkhid, &scheme, &cert, &certLen,
1017
+ &completion_callback)) {
1018
+ return NULL;
1019
+ }
1020
+ CHECK_ZHANDLE(zkhid);
1021
+
1022
+ void *pyw = NULL;
1023
+ if (completion_callback != Py_None) {
1024
+ pyw = create_pywatcher(zkhid, completion_callback, 0);
1025
+ if (pyw == NULL) {
1026
+ return NULL;
1027
+ }
1028
+ }
1029
+
1030
+ int err = zoo_add_auth( zhandles[zkhid],
1031
+ scheme,
1032
+ cert,
1033
+ certLen,
1034
+ void_completion_dispatch,
1035
+ pyw);
1036
+ if (err != ZOK) {
1037
+ PyErr_SetString(err_to_exception(err), zerror(err));
1038
+ return NULL;
1039
+ }
1040
+ return Py_BuildValue("i", err);
1041
+ }
1042
+
1043
+ /* -------------------------------------------------------------------------- */
1044
+ /* Synchronous API implementation */
1045
+ /* -------------------------------------------------------------------------- */
1046
+
1047
+ /* Synchronous node creation, returns node path string */
1048
+ static PyObject *pyzoo_create(PyObject *self, PyObject *args)
1049
+ {
1050
+ char *path;
1051
+ int zkhid;
1052
+ char* values;
1053
+ int valuelen;
1054
+ PyObject *acl = NULL;
1055
+ int flags = 0;
1056
+ char realbuf[256];
1057
+ const int maxbuf_len = 256;
1058
+ if (!PyArg_ParseTuple(args, "iss#O|i",&zkhid, &path, &values, &valuelen,&acl,&flags))
1059
+ return NULL;
1060
+ CHECK_ZHANDLE(zkhid);
1061
+ struct ACL_vector aclv;
1062
+ CHECK_ACLS(acl);
1063
+ if (parse_acls(&aclv,acl) == 0) {
1064
+ return NULL;
1065
+ }
1066
+ zhandle_t *zh = zhandles[zkhid];
1067
+ int err = zoo_create(zh, path, values, valuelen, &aclv, flags, realbuf, maxbuf_len);
1068
+ free_acls(&aclv);
1069
+ if (err != ZOK) {
1070
+ PyErr_SetString(err_to_exception(err), zerror(err));
1071
+ return NULL;
1072
+ }
1073
+
1074
+ return Py_BuildValue("s", realbuf);
1075
+ }
1076
+
1077
+ /* Synchronous node deletion, returns integer error code */
1078
+ static PyObject *pyzoo_delete(PyObject *self, PyObject *args)
1079
+ {
1080
+ int zkhid;
1081
+ char *path;
1082
+ int version = -1;
1083
+ if (!PyArg_ParseTuple(args, "is|i",&zkhid,&path,&version))
1084
+ return NULL;
1085
+ CHECK_ZHANDLE(zkhid);
1086
+ zhandle_t *zh = zhandles[zkhid];
1087
+ int err = zoo_delete(zh, path, version);
1088
+ if (err != ZOK) {
1089
+ PyErr_SetString(err_to_exception(err), zerror(err));
1090
+ return NULL;
1091
+ }
1092
+ return Py_BuildValue("i", err);
1093
+ }
1094
+
1095
+ /* Synchronous node existence check, returns stat if exists, None if
1096
+ absent */
1097
+ static PyObject *pyzoo_exists(PyObject *self, PyObject *args)
1098
+ {
1099
+ int zkhid; char *path; PyObject *watcherfn = Py_None;
1100
+ struct Stat stat;
1101
+ if (!PyArg_ParseTuple(args, "is|O", &zkhid, &path, &watcherfn)) {
1102
+ return NULL;
1103
+ }
1104
+ CHECK_ZHANDLE(zkhid);
1105
+ zhandle_t *zh = zhandles[zkhid];
1106
+ pywatcher_t *pw = NULL;
1107
+ void *callback = NULL;
1108
+ if (watcherfn != Py_None) {
1109
+ pw = create_pywatcher(zkhid, watcherfn,0);
1110
+ callback = watcher_dispatch;
1111
+ if (pw == NULL) {
1112
+ return NULL;
1113
+ }
1114
+ }
1115
+ int err = zoo_wexists(zh, path, callback, pw, &stat);
1116
+ if (err != ZOK && err != ZNONODE) {
1117
+ PyErr_SetString(err_to_exception(err), zerror(err));
1118
+ free_pywatcher(pw);
1119
+ return NULL;
1120
+ }
1121
+ if (err == ZNONODE) {
1122
+ Py_INCREF(Py_None);
1123
+ return Py_None; // This isn't exceptional
1124
+ }
1125
+ return build_stat(&stat);
1126
+ }
1127
+
1128
+ /* Synchronous node child retrieval, returns list of children's path
1129
+ as strings */
1130
+ static PyObject *pyzoo_get_children(PyObject *self, PyObject *args)
1131
+ {
1132
+ int zkhid;
1133
+ char *path;
1134
+ PyObject *watcherfn = Py_None;
1135
+ struct String_vector strings;
1136
+ if (!PyArg_ParseTuple(args, "is|O", &zkhid, &path, &watcherfn)) {
1137
+ return NULL;
1138
+ }
1139
+ CHECK_ZHANDLE(zkhid);
1140
+ pywatcher_t *pw = NULL;
1141
+ void *callback = NULL;
1142
+ if (watcherfn != Py_None) {
1143
+ pw = create_pywatcher( zkhid, watcherfn, 0 );
1144
+ callback = watcher_dispatch;
1145
+ if (pw == NULL) {
1146
+ return NULL;
1147
+ }
1148
+ }
1149
+ int err = zoo_wget_children(zhandles[zkhid], path,
1150
+ callback,
1151
+ pw, &strings );
1152
+
1153
+ if (err != ZOK) {
1154
+ PyErr_SetString(err_to_exception(err), zerror(err));
1155
+ free_pywatcher(pw);
1156
+ return NULL;
1157
+ }
1158
+
1159
+ PyObject *ret = build_string_vector(&strings);
1160
+ deallocate_String_vector(&strings);
1161
+ return ret;
1162
+ }
1163
+
1164
+ /* Synchronous node data update, returns integer error code */
1165
+ static PyObject *pyzoo_set(PyObject *self, PyObject *args)
1166
+ {
1167
+ int zkhid;
1168
+ char *path;
1169
+ char *buffer;
1170
+ int buflen;
1171
+ int version = -1;
1172
+ if (!PyArg_ParseTuple(args, "iss#|i", &zkhid, &path, &buffer, &buflen,
1173
+ &version)) {
1174
+ return NULL;
1175
+ }
1176
+ CHECK_ZHANDLE(zkhid);
1177
+
1178
+ int err = zoo_set(zhandles[zkhid], path, buffer, buflen, version);
1179
+ if (err != ZOK) {
1180
+ PyErr_SetString(err_to_exception(err), zerror(err));
1181
+ return NULL;
1182
+ }
1183
+
1184
+ return Py_BuildValue("i", err);
1185
+ }
1186
+
1187
+ /* Synchronous node data update, returns node's stat data structure */
1188
+ static PyObject *pyzoo_set2(PyObject *self, PyObject *args)
1189
+ {
1190
+ int zkhid;
1191
+ char *path;
1192
+ char *buffer;
1193
+ int buflen;
1194
+ int version = -1;
1195
+ if (!PyArg_ParseTuple(args, "iss#|i", &zkhid, &path, &buffer, &buflen,
1196
+ &version)) {
1197
+ return NULL;
1198
+ }
1199
+ CHECK_ZHANDLE(zkhid);
1200
+ struct Stat stat;
1201
+ int err = zoo_set2(zhandles[zkhid], path, buffer, buflen, version, &stat);
1202
+ if (err != ZOK) {
1203
+ PyErr_SetString(err_to_exception(err), zerror(err));
1204
+ return NULL;
1205
+ }
1206
+
1207
+ return build_stat(&stat);
1208
+ }
1209
+
1210
+ /* As per ZK documentation, datanodes are limited to 1Mb. Why not do a
1211
+ stat followed by a get, to determine how big the buffer should be?
1212
+ Because the znode may get updated between calls, so we can't
1213
+ guarantee a complete get anyhow. */
1214
+ #define GET_BUFFER_SIZE 1024*1024
1215
+
1216
+ /* pyzoo_get has an extra parameter over the java/C equivalents. If
1217
+ you set the fourth integer parameter buffer_len, we return
1218
+ min(buffer_len, datalength) bytes. This is set by default to
1219
+ GET_BUFFER_SIZE */
1220
+ static PyObject *pyzoo_get(PyObject *self, PyObject *args)
1221
+ {
1222
+ int zkhid;
1223
+ char *path;
1224
+ char *buffer;
1225
+ int buffer_len=GET_BUFFER_SIZE;
1226
+ struct Stat stat;
1227
+ PyObject *watcherfn = Py_None;
1228
+ pywatcher_t *pw = NULL;
1229
+ if (!PyArg_ParseTuple(args, "is|Oi", &zkhid, &path, &watcherfn, &buffer_len)) {
1230
+ return NULL;
1231
+ }
1232
+ CHECK_ZHANDLE(zkhid);
1233
+ if (watcherfn != Py_None) {
1234
+ pw = create_pywatcher( zkhid, watcherfn,0 );
1235
+ if (pw == NULL) {
1236
+ return NULL;
1237
+ }
1238
+ }
1239
+ buffer = malloc(sizeof(char)*buffer_len);
1240
+ if (buffer == NULL) {
1241
+ free_pywatcher(pw);
1242
+ PyErr_SetString(PyExc_MemoryError, "buffer could not be allocated in pyzoo_get");
1243
+ return NULL;
1244
+ }
1245
+
1246
+ int err = zoo_wget(zhandles[zkhid], path,
1247
+ watcherfn != Py_None ? watcher_dispatch : NULL,
1248
+ pw, buffer,
1249
+ &buffer_len, &stat);
1250
+
1251
+ if (err != ZOK) {
1252
+ PyErr_SetString(err_to_exception(err), zerror(err));
1253
+ free_pywatcher(pw);
1254
+ free(buffer);
1255
+ return NULL;
1256
+ }
1257
+
1258
+ PyObject *stat_dict = build_stat( &stat );
1259
+ PyObject *ret = Py_BuildValue( "(s#,N)", buffer,buffer_len < 0 ? 0 : buffer_len, stat_dict );
1260
+ free(buffer);
1261
+
1262
+ return ret;
1263
+ }
1264
+
1265
+ /* Synchronous node ACL retrieval, returns list of ACLs */
1266
+ PyObject *pyzoo_get_acl(PyObject *self, PyObject *args)
1267
+ {
1268
+ int zkhid;
1269
+ char *path;
1270
+ struct ACL_vector acl;
1271
+ struct Stat stat;
1272
+ if (!PyArg_ParseTuple(args, "is", &zkhid, &path))
1273
+ return NULL;
1274
+ CHECK_ZHANDLE(zkhid);
1275
+ int err = zoo_get_acl( zhandles[zkhid], path, &acl, &stat );
1276
+ if (err != ZOK) {
1277
+ PyErr_SetString(err_to_exception(err), zerror(err));
1278
+ return NULL;
1279
+ }
1280
+ PyObject *pystat = build_stat( &stat );
1281
+ PyObject *acls = build_acls( &acl );
1282
+ PyObject *ret = Py_BuildValue( "(O,O)", pystat, acls );
1283
+ Py_DECREF(pystat);
1284
+ Py_DECREF(acls);
1285
+ return ret;
1286
+ }
1287
+
1288
+ /* Synchronous node ACL update, returns integer error code */
1289
+ PyObject *pyzoo_set_acl(PyObject *self, PyObject *args)
1290
+ {
1291
+ int zkhid;
1292
+ char *path;
1293
+ int version;
1294
+ PyObject *pyacls;
1295
+ struct ACL_vector acl;
1296
+ if (!PyArg_ParseTuple(args, "isiO", &zkhid, &path, &version, &pyacls)) {
1297
+ return NULL;
1298
+ }
1299
+ CHECK_ZHANDLE(zkhid);
1300
+ if (parse_acls(&acl, pyacls) == 0) {
1301
+ return NULL;
1302
+ }
1303
+ int err = zoo_set_acl(zhandles[zkhid], path, version, &acl );
1304
+ free_acls(&acl);
1305
+ if (err != ZOK) {
1306
+ PyErr_SetString(err_to_exception(err), zerror(err));
1307
+ return NULL;
1308
+ }
1309
+ return Py_BuildValue("i", err);;
1310
+ }
1311
+
1312
+ /* -------------------------------------------------------------------------- */
1313
+ /* Session and context methods */
1314
+ /* -------------------------------------------------------------------------- */
1315
+
1316
+ /* Closes a connection, returns integer error code */
1317
+ PyObject *pyzoo_close(PyObject *self, PyObject *args)
1318
+ {
1319
+ int zkhid, ret;
1320
+ if (!PyArg_ParseTuple(args, "i", &zkhid)) {
1321
+ return NULL;
1322
+ }
1323
+ CHECK_ZHANDLE(zkhid);
1324
+ zhandle_t *handle = zhandles[zkhid];
1325
+ Py_BEGIN_ALLOW_THREADS
1326
+ ret = zookeeper_close(handle);
1327
+ Py_END_ALLOW_THREADS
1328
+ zhandles[zkhid] = NULL; // The zk C client frees the zhandle
1329
+ return Py_BuildValue("i", ret);
1330
+ }
1331
+
1332
+ /* Returns the ID of current client as a tuple (client_id, passwd) */
1333
+ PyObject *pyzoo_client_id(PyObject *self, PyObject *args)
1334
+ {
1335
+ int zkhid;
1336
+ if (!PyArg_ParseTuple(args, "i", &zkhid)) {
1337
+ return NULL;
1338
+ }
1339
+ CHECK_ZHANDLE(zkhid);
1340
+ const clientid_t *cid = zoo_client_id(zhandles[zkhid]);
1341
+ return Py_BuildValue("(L,s)", cid->client_id, cid->passwd);
1342
+ }
1343
+
1344
+ /* DO NOT USE - context is used internally. This method is not exposed
1345
+ in the Python module */
1346
+ PyObject *pyzoo_get_context(PyObject *self, PyObject *args)
1347
+ {
1348
+ int zkhid;
1349
+ if (!PyArg_ParseTuple(args, "i", &zkhid))
1350
+ return NULL;
1351
+ CHECK_ZHANDLE(zkhid);
1352
+ PyObject *context = NULL;
1353
+ context = (PyObject*)zoo_get_context(zhandles[zkhid]);
1354
+ if (context) return context;
1355
+ Py_INCREF(Py_None);
1356
+ return Py_None;
1357
+ }
1358
+
1359
+ /* DO NOT USE - context is used internally. This method is not exposed
1360
+ in the Python module */
1361
+ PyObject *pyzoo_set_context(PyObject *self, PyObject *args)
1362
+ {
1363
+ int zkhid;
1364
+ PyObject *context;
1365
+ if (!PyArg_ParseTuple(args, "iO", &zkhid, &context)) {
1366
+ return NULL;
1367
+ }
1368
+ CHECK_ZHANDLE(zkhid);
1369
+ PyObject *py_context = (PyObject*)zoo_get_context(zhandles[zkhid]);
1370
+ if (py_context != NULL && py_context != Py_None) {
1371
+ Py_DECREF(py_context);
1372
+ }
1373
+ Py_INCREF(context);
1374
+ zoo_set_context(zhandles[zkhid], (void*)context);
1375
+ Py_INCREF(Py_None);
1376
+ return Py_None;
1377
+ }
1378
+
1379
+
1380
+ /* -------------------------------------------------------------------------- */
1381
+ /* Miscellaneous methods */
1382
+ /* -------------------------------------------------------------------------- */
1383
+
1384
+ /* Sets the global watcher. Returns None */
1385
+ PyObject *pyzoo_set_watcher(PyObject *self, PyObject *args)
1386
+ {
1387
+ int zkhid;
1388
+ PyObject *watcherfn;
1389
+ if (!PyArg_ParseTuple(args, "iO", &zkhid, &watcherfn)) {
1390
+ return NULL;
1391
+ }
1392
+ CHECK_ZHANDLE(zkhid);
1393
+ pywatcher_t *pyw = watchers[zkhid];
1394
+ if (pyw != NULL) {
1395
+ free_pywatcher( pyw );
1396
+ }
1397
+
1398
+ // Create a *permanent* watcher object, not deallocated when called
1399
+ pyw = create_pywatcher(zkhid, watcherfn,1);
1400
+ if (pyw == NULL) {
1401
+ return NULL;
1402
+ }
1403
+ watchers[zkhid] = pyw;
1404
+ zoo_set_watcher(zhandles[zkhid], watcher_dispatch);
1405
+ zoo_set_context(zhandles[zkhid], pyw);
1406
+ Py_INCREF(Py_None);
1407
+ return Py_None;
1408
+ }
1409
+
1410
+ /* Returns an integer code representing the current connection
1411
+ state */
1412
+ PyObject *pyzoo_state(PyObject *self, PyObject *args)
1413
+ {
1414
+ int zkhid;
1415
+ if (!PyArg_ParseTuple(args,"i",&zkhid)) {
1416
+ return NULL;
1417
+ }
1418
+ CHECK_ZHANDLE(zkhid);
1419
+ int state = zoo_state(zhandles[zkhid]);
1420
+ return Py_BuildValue("i",state);
1421
+ }
1422
+
1423
+
1424
+ /* Convert an integer error code into a string */
1425
+ PyObject *pyzerror(PyObject *self, PyObject *args)
1426
+ {
1427
+ int rc;
1428
+ if (!PyArg_ParseTuple(args,"i", &rc))
1429
+ return NULL;
1430
+ return Py_BuildValue("s", zerror(rc));
1431
+ }
1432
+
1433
+ /* Returns the integer receive timeout for a connection */
1434
+ PyObject *pyzoo_recv_timeout(PyObject *self, PyObject *args)
1435
+ {
1436
+ int zkhid;
1437
+ if (!PyArg_ParseTuple(args,"i",&zkhid))
1438
+ return NULL;
1439
+ CHECK_ZHANDLE(zkhid);
1440
+ int recv_timeout = zoo_recv_timeout(zhandles[zkhid]);
1441
+ return Py_BuildValue("i",recv_timeout);
1442
+ }
1443
+
1444
+ /* Returns True if connection is unrecoverable, False otherwise */
1445
+ PyObject *pyis_unrecoverable(PyObject *self, PyObject *args)
1446
+ {
1447
+ int zkhid;
1448
+ if (!PyArg_ParseTuple(args,"i",&zkhid))
1449
+ return NULL;
1450
+ CHECK_ZHANDLE(zkhid);
1451
+ int ret = is_unrecoverable(zhandles[zkhid]);
1452
+ if (ret == ZINVALIDSTATE)
1453
+ Py_RETURN_TRUE;
1454
+ Py_RETURN_FALSE;
1455
+ }
1456
+
1457
+ /* Set the debug level for logging, returns None */
1458
+ PyObject *pyzoo_set_debug_level(PyObject *self, PyObject *args)
1459
+ {
1460
+ int loglevel;
1461
+ if (!PyArg_ParseTuple(args, "i", &loglevel))
1462
+ return NULL;
1463
+ zoo_set_debug_level((ZooLogLevel)loglevel);
1464
+ Py_INCREF(Py_None);
1465
+ return Py_None;
1466
+ }
1467
+
1468
+ static PyObject *log_stream = NULL;
1469
+
1470
+ /* Set the output file-like object for logging output. Returns Py_None */
1471
+ PyObject *pyzoo_set_log_stream(PyObject *self, PyObject *args)
1472
+ {
1473
+ PyObject *pystream = NULL;
1474
+ if (!PyArg_ParseTuple(args,"O",&pystream)) {
1475
+ PyErr_SetString(PyExc_ValueError, "Must supply a Python object to set_log_stream");
1476
+ return NULL;
1477
+ }
1478
+
1479
+ #if PY_MAJOR_VERSION >= 3
1480
+ extern PyTypeObject PyIOBase_Type;
1481
+ if (!PyObject_IsInstance(pystream, (PyObject *)&PyIOBase_Type)) {
1482
+ #else
1483
+ if(!PyFile_Check(pystream)) {
1484
+ #endif
1485
+
1486
+ PyErr_SetString(PyExc_ValueError, "Must supply a file object to set_log_stream");
1487
+ return NULL;
1488
+ }
1489
+ /* Release the previous reference to log_stream that we took */
1490
+ if (log_stream != NULL) {
1491
+ Py_DECREF(log_stream);
1492
+ }
1493
+
1494
+ log_stream = pystream;
1495
+ Py_INCREF(log_stream);
1496
+
1497
+ #if PY_MAJOR_VERSION >= 3
1498
+ int fd = PyObject_AsFileDescriptor(log_stream);
1499
+ FILE *fp = fdopen(fd, "w");
1500
+ #else
1501
+ FILE *fp = PyFile_AsFile(log_stream);
1502
+ #endif
1503
+ zoo_set_log_stream(fp);
1504
+
1505
+ Py_INCREF(Py_None);
1506
+ return Py_None;
1507
+ }
1508
+
1509
+ /* Set the connection order - randomized or in-order. Returns None. */
1510
+ PyObject *pyzoo_deterministic_conn_order(PyObject *self, PyObject *args)
1511
+ {
1512
+ int yesOrNo;
1513
+ if (!PyArg_ParseTuple(args, "i",&yesOrNo))
1514
+ return NULL;
1515
+ zoo_deterministic_conn_order( yesOrNo );
1516
+ Py_INCREF(Py_None);
1517
+ return Py_None;
1518
+ }
1519
+
1520
+ /* -------------------------------------------------------------------------- */
1521
+ /* Module setup */
1522
+ /* -------------------------------------------------------------------------- */
1523
+
1524
+ #include "pyzk_docstrings.h"
1525
+
1526
+ static PyMethodDef ZooKeeperMethods[] = {
1527
+ {"init", pyzookeeper_init, METH_VARARGS, pyzk_init_doc },
1528
+ #ifdef HAVE_OPENSSL_H
1529
+ {"init_ssl", pyzookeeper_init_ssl, METH_VARARGS, pyzk_init_ssl_doc },
1530
+ #endif
1531
+ {"create",pyzoo_create, METH_VARARGS, pyzk_create_doc },
1532
+ {"delete",pyzoo_delete, METH_VARARGS, pyzk_delete_doc },
1533
+ {"get_children", pyzoo_get_children, METH_VARARGS, pyzk_get_children_doc },
1534
+ {"set", pyzoo_set, METH_VARARGS, pyzk_set_doc },
1535
+ {"set2", pyzoo_set2, METH_VARARGS, pyzk_set2_doc },
1536
+ {"get",pyzoo_get, METH_VARARGS, pyzk_get_doc },
1537
+ {"exists",pyzoo_exists, METH_VARARGS, pyzk_exists_doc },
1538
+ {"get_acl", pyzoo_get_acl, METH_VARARGS, pyzk_get_acl_doc },
1539
+ {"set_acl", pyzoo_set_acl, METH_VARARGS, pyzk_set_acl_doc },
1540
+ {"close", pyzoo_close, METH_VARARGS, pyzk_close_doc },
1541
+ {"client_id", pyzoo_client_id, METH_VARARGS, pyzk_client_id_doc },
1542
+ {"set_watcher", pyzoo_set_watcher, METH_VARARGS },
1543
+ {"state", pyzoo_state, METH_VARARGS, pyzk_state_doc },
1544
+ {"recv_timeout",pyzoo_recv_timeout, METH_VARARGS },
1545
+ {"is_unrecoverable",pyis_unrecoverable, METH_VARARGS, pyzk_is_unrecoverable_doc },
1546
+ {"set_debug_level",pyzoo_set_debug_level, METH_VARARGS, pyzk_set_debug_level_doc },
1547
+ {"set_log_stream",pyzoo_set_log_stream, METH_VARARGS, pyzk_set_log_stream_doc },
1548
+ {"deterministic_conn_order",pyzoo_deterministic_conn_order, METH_VARARGS, pyzk_deterministic_conn_order_doc },
1549
+ {"acreate", pyzoo_acreate, METH_VARARGS, pyzk_acreate_doc },
1550
+ {"adelete", pyzoo_adelete, METH_VARARGS,pyzk_adelete_doc },
1551
+ {"aexists", pyzoo_aexists, METH_VARARGS,pyzk_aexists_doc },
1552
+ {"aget", pyzoo_aget, METH_VARARGS, pyzk_aget_doc },
1553
+ {"aset", pyzoo_aset, METH_VARARGS, pyzk_aset_doc },
1554
+ {"aget_children", pyzoo_aget_children, METH_VARARGS, pyzk_aget_children_doc },
1555
+ {"async", pyzoo_async, METH_VARARGS, pyzk_async_doc },
1556
+ {"aget_acl", pyzoo_aget_acl, METH_VARARGS, pyzk_aget_acl_doc },
1557
+ {"aset_acl", pyzoo_aset_acl, METH_VARARGS, pyzk_aset_acl_doc },
1558
+ {"zerror", pyzerror, METH_VARARGS, pyzk_zerror_doc },
1559
+ {"add_auth", pyzoo_add_auth, METH_VARARGS, pyzk_add_auth_doc },
1560
+ /* DO NOT USE get / set_context. Context is used internally to pass
1561
+ the python watcher to a dispatch function. If you want context, set
1562
+ it through set_watcher. */
1563
+ // {"get_context", pyzoo_get_context, METH_VARARGS, "" },
1564
+ // {"set_context", pyzoo_set_context, METH_VARARGS, "" },
1565
+ {NULL, NULL}
1566
+ };
1567
+
1568
+ #if PY_MAJOR_VERSION >= 3
1569
+ static struct PyModuleDef zookeeper_moddef = {
1570
+ PyModuleDef_HEAD_INIT,
1571
+ "zookeeper",
1572
+ NULL,
1573
+ 0,
1574
+ ZooKeeperMethods,
1575
+ 0,
1576
+ 0,
1577
+ 0,
1578
+ 0
1579
+ };
1580
+ #endif
1581
+
1582
+ #define ADD_INTCONSTANT(x) PyModule_AddIntConstant(module, #x, ZOO_##x)
1583
+ #define ADD_INTCONSTANTZ(x) PyModule_AddIntConstant(module, #x, Z##x)
1584
+
1585
+ #define ADD_EXCEPTION(x) x = PyErr_NewException("zookeeper."#x, ZooKeeperException, NULL); \
1586
+ Py_INCREF(x); \
1587
+ PyModule_AddObject(module, #x, x);
1588
+
1589
+ #if PY_MAJOR_VERSION >= 3
1590
+ PyMODINIT_FUNC PyInit_zookeeper(void) {
1591
+ #else
1592
+ PyMODINIT_FUNC initzookeeper(void) {
1593
+ #endif
1594
+ PyEval_InitThreads();
1595
+
1596
+ #if PY_MAJOR_VERSION >= 3
1597
+ PyObject *module = PyModule_Create(&zookeeper_moddef);
1598
+ #else
1599
+ PyObject *module = Py_InitModule("zookeeper", ZooKeeperMethods);
1600
+ #endif
1601
+
1602
+ if (init_zhandles(32) == 0) {
1603
+ #if PY_MAJOR_VERSION >= 3
1604
+ Py_DECREF(module);
1605
+ return PyErr_NoMemory();
1606
+ #else
1607
+ return;
1608
+ #endif
1609
+ }
1610
+
1611
+ ZooKeeperException = PyErr_NewException("zookeeper.ZooKeeperException",
1612
+ PyExc_Exception,
1613
+ NULL);
1614
+
1615
+ PyModule_AddObject(module, "ZooKeeperException", ZooKeeperException);
1616
+ Py_INCREF(ZooKeeperException);
1617
+
1618
+ PyModule_AddStringConstant(module, "__version__", ZOO_VERSION);
1619
+
1620
+ ADD_INTCONSTANT(PERM_READ);
1621
+ ADD_INTCONSTANT(PERM_WRITE);
1622
+ ADD_INTCONSTANT(PERM_CREATE);
1623
+ ADD_INTCONSTANT(PERM_DELETE);
1624
+ ADD_INTCONSTANT(PERM_ALL);
1625
+ ADD_INTCONSTANT(PERM_ADMIN);
1626
+
1627
+ ADD_INTCONSTANT(EPHEMERAL);
1628
+ ADD_INTCONSTANT(SEQUENCE);
1629
+
1630
+ ADD_INTCONSTANT(EXPIRED_SESSION_STATE);
1631
+ ADD_INTCONSTANT(AUTH_FAILED_STATE);
1632
+ ADD_INTCONSTANT(CONNECTING_STATE);
1633
+ ADD_INTCONSTANT(ASSOCIATING_STATE);
1634
+ ADD_INTCONSTANT(CONNECTED_STATE);
1635
+
1636
+ ADD_INTCONSTANT(CREATED_EVENT);
1637
+ ADD_INTCONSTANT(DELETED_EVENT);
1638
+ ADD_INTCONSTANT(CHANGED_EVENT);
1639
+ ADD_INTCONSTANT(CHILD_EVENT);
1640
+ ADD_INTCONSTANT(SESSION_EVENT);
1641
+ ADD_INTCONSTANT(NOTWATCHING_EVENT);
1642
+
1643
+ ADD_INTCONSTANT(LOG_LEVEL_ERROR);
1644
+ ADD_INTCONSTANT(LOG_LEVEL_WARN);
1645
+ ADD_INTCONSTANT(LOG_LEVEL_INFO);
1646
+ ADD_INTCONSTANT(LOG_LEVEL_DEBUG);
1647
+
1648
+ ADD_INTCONSTANTZ(SYSTEMERROR);
1649
+ ADD_INTCONSTANTZ(RUNTIMEINCONSISTENCY);
1650
+ ADD_INTCONSTANTZ(DATAINCONSISTENCY);
1651
+ ADD_INTCONSTANTZ(CONNECTIONLOSS);
1652
+ ADD_INTCONSTANTZ(MARSHALLINGERROR);
1653
+ ADD_INTCONSTANTZ(UNIMPLEMENTED);
1654
+ ADD_INTCONSTANTZ(OPERATIONTIMEOUT);
1655
+ ADD_INTCONSTANTZ(BADARGUMENTS);
1656
+ ADD_INTCONSTANTZ(INVALIDSTATE);
1657
+
1658
+ ADD_EXCEPTION(SystemErrorException);
1659
+ ADD_EXCEPTION(RuntimeInconsistencyException);
1660
+ ADD_EXCEPTION(DataInconsistencyException);
1661
+ ADD_EXCEPTION(ConnectionLossException);
1662
+ ADD_EXCEPTION(MarshallingErrorException);
1663
+ ADD_EXCEPTION(UnimplementedException);
1664
+ ADD_EXCEPTION(OperationTimeoutException);
1665
+ ADD_EXCEPTION(BadArgumentsException);
1666
+ ADD_EXCEPTION(InvalidStateException);
1667
+
1668
+ ADD_INTCONSTANTZ(OK);
1669
+ ADD_INTCONSTANTZ(APIERROR);
1670
+ ADD_INTCONSTANTZ(NONODE);
1671
+ ADD_INTCONSTANTZ(NOAUTH);
1672
+ ADD_INTCONSTANTZ(BADVERSION);
1673
+ ADD_INTCONSTANTZ(NOCHILDRENFOREPHEMERALS);
1674
+ ADD_INTCONSTANTZ(NODEEXISTS);
1675
+ ADD_INTCONSTANTZ(NOTEMPTY);
1676
+ ADD_INTCONSTANTZ(SESSIONEXPIRED);
1677
+ ADD_INTCONSTANTZ(INVALIDCALLBACK);
1678
+ ADD_INTCONSTANTZ(INVALIDACL);
1679
+ ADD_INTCONSTANTZ(AUTHFAILED);
1680
+ ADD_INTCONSTANTZ(CLOSING);
1681
+ ADD_INTCONSTANTZ(NOTHING);
1682
+ ADD_INTCONSTANTZ(SESSIONMOVED);
1683
+
1684
+ ADD_EXCEPTION(ApiErrorException);
1685
+ ADD_EXCEPTION(NoNodeException);
1686
+ ADD_EXCEPTION(NoAuthException);
1687
+ ADD_EXCEPTION(BadVersionException);
1688
+ ADD_EXCEPTION(NoChildrenForEphemeralsException);
1689
+ ADD_EXCEPTION(NodeExistsException);
1690
+ ADD_EXCEPTION(NotEmptyException);
1691
+ ADD_EXCEPTION(SessionExpiredException);
1692
+ ADD_EXCEPTION(InvalidCallbackException);
1693
+ ADD_EXCEPTION(InvalidACLException);
1694
+ ADD_EXCEPTION(AuthFailedException);
1695
+ ADD_EXCEPTION(ClosingException);
1696
+ ADD_EXCEPTION(NothingException);
1697
+ ADD_EXCEPTION(SessionMovedException);
1698
+
1699
+ #if PY_MAJOR_VERSION >= 3
1700
+ return module;
1701
+ #endif
1702
+ }
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/examples/README ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+
2
+ This folder contains sample showing how you can use ZooKeeper from Python.
3
+
4
+ You should also check the following projects:
5
+
6
+ * http://github.com/phunt/zk-smoketest
7
+ * http://github.com/henryr/pyzk-recipes
8
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/examples/watch_znode_for_changes.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python2.6
2
+ # Licensed to the Apache Software Foundation (ASF) under one
3
+ # or more contributor license agreements. See the NOTICE file
4
+ # distributed with this work for additional information
5
+ # regarding copyright ownership. The ASF licenses this file
6
+ # to you under the Apache License, Version 2.0 (the
7
+ # "License"); you may not use this file except in compliance
8
+ # with the License. You may obtain a copy of the License at
9
+
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """ ZNode Change Watcher Skeleton Script
18
+
19
+ This script shows you how to write a python program that watches a specific
20
+ znode for changes and reacts to them.
21
+
22
+ Steps to understand how this script works:
23
+
24
+ 1. start a standalone ZooKeeper server (by default it listens on localhost:2181)
25
+
26
+ Did you know you can deploy "local clusters" by using zkconf[1]?
27
+ [1] http://github.com/phunt/zkconf
28
+
29
+ 2. enter the command line console
30
+
31
+ 3. create the test node:
32
+ [zk: (CONNECTED) 1] create /watch-test dummy-data
33
+ Created /watch-test
34
+
35
+ 4. in another shell start this script in verbose mode
36
+ $ python watch_znode_for_changes.py -v
37
+
38
+ # you should see a lot of log messages. have a look over them because
39
+ # you can easily understand how zookeeper works
40
+
41
+ 5. update the node data:
42
+
43
+ [zk: (CONNECTED) 2] set /watch-test new-data
44
+ cZxid = 0xa0000001a
45
+ ctime = Fri Jul 09 19:14:45 EEST 2010
46
+ mZxid = 0xa0000001e
47
+ mtime = Fri Jul 09 19:18:18 EEST 2010
48
+ pZxid = 0xa0000001a
49
+ cversion = 0
50
+ dataVersion = 1
51
+ aclVersion = 0
52
+ ephemeralOwner = 0x0
53
+ dataLength = 8
54
+ numChildren = 0
55
+
56
+ ... and you should see similar log messages:
57
+
58
+ 2010-07-09 19:18:18,537:11542(0xb6ea5b70):ZOO_DEBUG@process_completions@1765: Calling a watcher for node [/watch-test], type = -1 event=ZOO_CHANGED_EVENT
59
+ 2010-07-09 19:18:18,537 watch_znode_for_changes.py:83 - Running watcher: zh=0 event=3 state=3 path=/watch-test
60
+ 2010-07-09 19:18:18,537:11542(0xb6ea5b70):ZOO_DEBUG@zoo_awget@2400: Sending request xid=0x4c374b33 for path [/watch-test] to 127.0.0.1:2181
61
+ 2010-07-09 19:18:18,545:11542(0xb76a6b70):ZOO_DEBUG@zookeeper_process@1980: Queueing asynchronous response
62
+ 2010-07-09 19:18:18,545:11542(0xb6ea5b70):ZOO_DEBUG@process_completions@1772: Calling COMPLETION_DATA for xid=0x4c374b33 rc=0
63
+ 2010-07-09 19:18:18,545 watch_znode_for_changes.py:54 - This is where your application does work.
64
+
65
+ You can repeat this step multiple times.
66
+
67
+ 6. that's all. in the end you can delete the node and you should see a ZOO_DELETED_EVENT
68
+
69
+ """
70
+
71
+ import logging
72
+ import logging.handlers
73
+ import signal
74
+ import sys
75
+ import time
76
+ import threading
77
+ import zookeeper
78
+
79
+ from optparse import OptionParser
80
+
81
+ logger = logging.getLogger()
82
+
83
+ class MyClass(threading.Thread):
84
+ znode = '/watch-test'
85
+
86
+ def __init__(self, options, args):
87
+ threading.Thread.__init__(self)
88
+
89
+ logger.debug('Initializing MyClass thread.')
90
+ if options.verbose:
91
+ zookeeper.set_debug_level(zookeeper.LOG_LEVEL_DEBUG)
92
+
93
+ self.zh = zookeeper.init(options.servers)
94
+ if zookeeper.OK != zookeeper.aget(self.zh, self.znode,
95
+ self.watcher, self.handler):
96
+ logger.critical('Unable to get znode! Exiting.')
97
+ sys.exit(1)
98
+
99
+ def __del__(self):
100
+ zookeeper.close(self.zh)
101
+
102
+ def aget(self):
103
+ return zookeeper.aget(self.zh, self.znode, self.watcher, self.handler)
104
+
105
+ def handler(self, zh, rc, data, stat):
106
+ """Handle zookeeper.aget() responses.
107
+
108
+ This code handles the zookeeper.aget callback. It does not handle watches.
109
+
110
+ Numeric arguments map to constants. See ``DATA`` in ``help(zookeeper)``
111
+ for more information.
112
+
113
+ Args:
114
+ zh Zookeeper handle that made this request.
115
+ rc Return code.
116
+ data Data stored in the znode.
117
+
118
+ Does not provide a return value.
119
+ """
120
+ if zookeeper.OK == rc:
121
+ logger.debug('This is where your application does work.')
122
+ else:
123
+ if zookeeper.NONODE == rc:
124
+ # avoid sending too many requests if the node does not yet exists
125
+ logger.info('Node not found. Trying again to set the watch.')
126
+ time.sleep(1)
127
+
128
+ if zookeeper.OK != self.aget():
129
+ logger.critical('Unable to get znode! Exiting.')
130
+ sys.exit(1)
131
+
132
+ def watcher(self, zh, event, state, path):
133
+ """Handle zookeeper.aget() watches.
134
+
135
+ This code is called when a znode changes and triggers a data watch.
136
+ It is not called to handle the zookeeper.aget call itself.
137
+
138
+ Numeric arguments map to constants. See ``DATA`` in ``help(zookeeper)``
139
+ for more information.
140
+
141
+ Args:
142
+ zh Zookeeper handle that set this watch.
143
+ event Event that caused the watch (often called ``type`` elsewhere).
144
+ state Connection state.
145
+ path Znode that triggered this watch.
146
+
147
+ Does not provide a return value.
148
+ """
149
+ out = ['Running watcher:',
150
+ 'zh=%d' % zh,
151
+ 'event=%d' % event,
152
+ 'state=%d' % state,
153
+ 'path=%s' % path]
154
+ logger.debug(' '.join(out))
155
+ if event == zookeeper.CHANGED_EVENT and \
156
+ state == zookeeper.CONNECTED_STATE and \
157
+ self.znode == path:
158
+ if zookeeper.OK != self.aget():
159
+ logger.critical('Unable to get znode! Exiting.')
160
+ sys.exit(1)
161
+
162
+ def run(self):
163
+ while True:
164
+ time.sleep(86400)
165
+
166
+
167
+ def main(argv=None):
168
+ # Allow Ctrl-C
169
+ signal.signal(signal.SIGINT, signal.SIG_DFL)
170
+
171
+ parser = OptionParser()
172
+ parser.add_option('-v', '--verbose',
173
+ dest='verbose',
174
+ default=False,
175
+ action='store_true',
176
+ help='Verbose logging. (default: %default)')
177
+ parser.add_option('-s', '--servers',
178
+ dest='servers',
179
+ default='localhost:2181',
180
+ help='Comma-separated list of host:port pairs. (default: %default)')
181
+
182
+ (options, args) = parser.parse_args()
183
+
184
+ if options.verbose:
185
+ logger.setLevel(logging.DEBUG)
186
+ else:
187
+ logger.setLevel(logging.INFO)
188
+
189
+ formatter = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d - %(message)s")
190
+ stream_handler = logging.StreamHandler()
191
+ stream_handler.setFormatter(formatter)
192
+ logger.addHandler(stream_handler)
193
+
194
+ logger.info('Starting Zookeeper python example: %s' % ' '.join(sys.argv))
195
+
196
+ mc = MyClass(options, args)
197
+ mc.start()
198
+ mc.join()
199
+
200
+
201
+ if __name__ == '__main__':
202
+ main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/setup.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ from distutils.core import setup, Extension
18
+ import os
19
+
20
+ zookeeper_basedir = "../../"
21
+
22
+ zookeeper_macros = [("THREADED", None)]
23
+
24
+ # Assume the C extension includes OpenSSL support unless told
25
+ # otherwise.
26
+ if not os.environ.get("ZKPYTHON_NO_SSL"):
27
+ zookeeper_macros.append(("HAVE_OPENSSL_H", True))
28
+
29
+ zookeepermodule = Extension("zookeeper",
30
+ sources=["src/c/zookeeper.c"],
31
+ define_macros=zookeeper_macros,
32
+ include_dirs=[zookeeper_basedir + "/zookeeper-client/zookeeper-client-c/include",
33
+ zookeeper_basedir + "/zookeeper-client/zookeeper-client-c/target/c",
34
+ zookeeper_basedir + "/zookeeper-client/zookeeper-client-c/generated"],
35
+ libraries=["zookeeper_mt"],
36
+ library_dirs=[zookeeper_basedir + "/zookeeper-client/zookeeper-client-c/.libs/",
37
+ zookeeper_basedir + "/zookeeper-client/zookeeper-client-c/target/c/.libs/",
38
+ zookeeper_basedir + "/build/test/test-cppunit/.libs",
39
+ "/usr/local/lib"
40
+ ])
41
+
42
+ setup( name="ZooKeeper",
43
+ version = "0.4",
44
+ description = "ZooKeeper Python bindings",
45
+ ext_modules=[zookeepermodule] )
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/zk.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import zookeeper, time, threading
18
+
19
+ f = open("out.log","w")
20
+ zookeeper.set_log_stream(f)
21
+
22
+ connected = False
23
+ conn_cv = threading.Condition( )
24
+
25
+ def my_connection_watcher(handle,type,state,path):
26
+ global connected, conn_cv
27
+ print("Connected, handle is ", handle)
28
+ conn_cv.acquire()
29
+ connected = True
30
+ conn_cv.notifyAll()
31
+ conn_cv.release()
32
+
33
+ conn_cv.acquire()
34
+ print("Connecting to localhost:2181 -- ")
35
+ handle = zookeeper.init("localhost:2181", my_connection_watcher, 10000, 0)
36
+ while not connected:
37
+ conn_cv.wait()
38
+ conn_cv.release()
39
+
40
+ def my_getc_watch( handle, type, state, path ):
41
+ print("Watch fired -- ")
42
+ print(type, state, path)
43
+
44
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"};
45
+
46
+ try:
47
+ zookeeper.create(handle, "/zk-python", "data", [ZOO_OPEN_ACL_UNSAFE], 0)
48
+ zookeeper.get_children(handle, "/zk-python", my_getc_watch)
49
+ for i in xrange(5):
50
+ print("Creating sequence node ", i, " ", zookeeper.create(handle, "/zk-python/sequencenode", "data", [ZOO_OPEN_ACL_UNSAFE], zookeeper.SEQUENCE ))
51
+ except:
52
+ pass
53
+
54
+ def pp_zk(handle,root, indent = 0):
55
+ """Pretty print(a zookeeper tree, starting at root)"""
56
+ def make_path(child):
57
+ if root == "/":
58
+ return "/" + child
59
+ return root + "/" + child
60
+ children = zookeeper.get_children(handle, root, None)
61
+ out = ""
62
+ for i in xrange(indent):
63
+ out += "\t"
64
+ out += "|---"+root + " :: " + zookeeper.get(handle, root, None)[0]
65
+ print(out)
66
+ for child in children:
67
+ pp_zk(handle,make_path(child),indent+1)
68
+
69
+ print("ZNode tree -- ")
70
+ pp_zk(handle,"/")
71
+
72
+ print("Getting ACL / Stat for /zk-python --")
73
+ (stat, acl) = zookeeper.get_acl(handle, "/zk-python")
74
+ print("Stat:: ", stat)
75
+ print("Acl:: ", acl)
76
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/async_test.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading
20
+
21
+ class AsyncTest(zktestbase.TestBase):
22
+ """Test whether async works"""
23
+ # to do: startup and teardown via scripts?
24
+ def setUp( self ):
25
+ zktestbase.TestBase.setUp(self)
26
+
27
+ def test_async(self):
28
+ self.assertEqual(self.connected, True)
29
+ ret = getattr(zookeeper, 'async')(self.handle, "/")
30
+ self.assertEqual(ret, zookeeper.OK, "async failed")
31
+
32
+ if __name__ == '__main__':
33
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/close_deadlock_test.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading
20
+ import time
21
+
22
+
23
+ class CloseDeadlockTest(zktestbase.TestBase):
24
+ """
25
+ This tests for the issue found in
26
+ https://issues.apache.org/jira/browse/ZOOKEEPER-763
27
+
28
+ zookeeper.close blocks on waiting for all completions to
29
+ finish. Previously it was doing so while holding the GIL, stopping
30
+ any completions from actually continuing.
31
+
32
+ This test is a failure if it does not exit within a few seconds.
33
+ """
34
+ def deadlock():
35
+ cv = threading.Condition()
36
+
37
+ def callback(*args):
38
+ cv.acquire()
39
+ cv.notifyAll()
40
+ cv.release()
41
+ time.sleep(1)
42
+
43
+ cv.acquire()
44
+ zookeeper.aget(handle, "/", None, callback)
45
+ cv.wait()
46
+ zookeeper.close(handle)
47
+
48
+
49
+ if __name__ == '__main__':
50
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/connection_test.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import unittest, threading, re, sys
20
+ if sys.version_info < (3,):
21
+ range = xrange
22
+
23
+ import zookeeper, zktestbase
24
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
25
+
26
+ class ConnectionTest(zktestbase.TestBase):
27
+ """Test whether we can make a connection"""
28
+ def setUp(self):
29
+ pass
30
+
31
+ def testconnection(self):
32
+ cv = threading.Condition()
33
+ self.connected = False
34
+ def connection_watcher(handle, type, state, path):
35
+ cv.acquire()
36
+ self.connected = True
37
+ self.assertEqual(zookeeper.CONNECTED_STATE, state)
38
+ self.handle = handle
39
+ cv.notify()
40
+ cv.release()
41
+
42
+ cv.acquire()
43
+ ret = zookeeper.init(self.host, connection_watcher)
44
+ cv.wait(15.0)
45
+ cv.release()
46
+ self.assertEqual(self.connected, True, "Connection timed out to " + self.host)
47
+ self.assertEqual(zookeeper.CONNECTED_STATE, zookeeper.state(self.handle))
48
+
49
+ self.assertEqual(zookeeper.close(self.handle), zookeeper.OK)
50
+ # Trying to close the same handle twice is an error, and the C library will segfault on it
51
+ # so make sure this is caught at the Python module layer
52
+ self.assertRaises(zookeeper.ZooKeeperException,
53
+ zookeeper.close,
54
+ self.handle)
55
+
56
+ self.assertRaises(zookeeper.ZooKeeperException,
57
+ zookeeper.get,
58
+ self.handle,
59
+ "/")
60
+
61
+ @unittest.skipUnless(hasattr(zookeeper, 'init_ssl'),
62
+ "SSL support not compiled in.")
63
+ def testsslconnection(self):
64
+ cv = threading.Condition()
65
+ self.connected = False
66
+ def connection_watcher(handle, type, state, path):
67
+ cv.acquire()
68
+ self.connected = True
69
+ self.assertEqual(zookeeper.CONNECTED_STATE, state)
70
+ self.handle = handle
71
+ cv.notify()
72
+ cv.release()
73
+
74
+ cv.acquire()
75
+ ret = zookeeper.init_ssl(self.sslhost, self.sslcert, connection_watcher)
76
+ cv.wait(15.0)
77
+ cv.release()
78
+ self.assertEqual(self.connected, True, "SSL Connection timed out to " + self.host)
79
+ self.assertEqual(zookeeper.CONNECTED_STATE, zookeeper.state(self.handle))
80
+
81
+ self.assertEqual(zookeeper.close(self.handle), zookeeper.OK)
82
+ # Trying to close the same handle twice is an error, and the C library will segfault on it
83
+ # so make sure this is caught at the Python module layer
84
+ self.assertRaises(zookeeper.ZooKeeperException,
85
+ zookeeper.close,
86
+ self.handle)
87
+
88
+ self.assertRaises(zookeeper.ZooKeeperException,
89
+ zookeeper.get,
90
+ self.handle,
91
+ "/")
92
+
93
+ def testhandlereuse(self):
94
+ """
95
+ Test a) multiple concurrent connections b) reuse of closed handles
96
+ """
97
+ cv = threading.Condition()
98
+ self.connected = False
99
+ def connection_watcher(handle, type, state, path):
100
+ cv.acquire()
101
+ self.connected = True
102
+ self.assertEqual(zookeeper.CONNECTED_STATE, state)
103
+ self.handle = handle
104
+ cv.notify()
105
+ cv.release()
106
+
107
+ cv.acquire()
108
+ handles = [ zookeeper.init(self.host) for i in range(10) ]
109
+ ret = zookeeper.init(self.host, connection_watcher)
110
+ cv.wait(15.0)
111
+ cv.release()
112
+ self.assertEqual(self.connected, True, "Connection timed out to " + self.host)
113
+ self.assertEqual(True, self.all( [ zookeeper.state(handle) == zookeeper.CONNECTED_STATE for handle in handles ] ),
114
+ "Not all connections succeeded")
115
+ oldhandle = handles[3]
116
+ zookeeper.close(oldhandle)
117
+ newhandle = zookeeper.init(self.host)
118
+
119
+ # This assertion tests *internal* behaviour; i.e. that the module
120
+ # correctly reuses closed handles. This is therefore implementation
121
+ # dependent.
122
+ self.assertEqual(newhandle, oldhandle, "Didn't get reused handle")
123
+
124
+ def testmanyhandles(self):
125
+ """
126
+ Test the ability of the module to support many handles.
127
+ """
128
+ # We'd like to do more, but currently the C client doesn't
129
+ # work with > 83 handles (fails to create a pipe) on MacOS 10.5.8
130
+ handles = [ zookeeper.init(self.host) for i in range(9) ]
131
+
132
+ cv = threading.Condition()
133
+ self.connected = False
134
+ def connection_watcher(handle, type, state, path):
135
+ cv.acquire()
136
+ self.connected = True
137
+ self.assertEqual(zookeeper.CONNECTED_STATE, state)
138
+ self.handle = handle
139
+ cv.notify()
140
+ cv.release()
141
+
142
+ cv.acquire()
143
+ ret = zookeeper.init(self.host, connection_watcher)
144
+ cv.wait(15.0)
145
+ cv.release()
146
+ self.assertEqual(self.connected, True, "Connection timed out to " + self.host)
147
+
148
+ for i,h in enumerate(handles):
149
+ path = "/zkpython-test-handles-%s" % str(i)
150
+ self.assertEqual(path, zookeeper.create(h, path, "", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL))
151
+
152
+ self.assertEqual(True, self.all( zookeeper.close(h) == zookeeper.OK for h in handles ))
153
+
154
+ def testversionstringexists(self):
155
+ self.assertTrue(hasattr(zookeeper, '__version__'))
156
+ self.assertTrue(re.match("\d.\d.\d", zookeeper.__version__))
157
+
158
+
159
+ def tearDown(self):
160
+ pass
161
+
162
+ if __name__ == '__main__':
163
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/create_test.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading
20
+
21
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
22
+
23
+ class CreationTest(zktestbase.TestBase):
24
+ """Test whether we can create znodes"""
25
+ # to do: startup and teardown via scripts?
26
+ def setUp(self):
27
+ zktestbase.TestBase.setUp(self)
28
+ try:
29
+ zookeeper.delete(self.handle, "/zk-python-createtest")
30
+ zookeeper.delete(self.handle, "/zk-python-acreatetest")
31
+ except:
32
+ pass
33
+
34
+ def test_sync_create(self):
35
+ self.assertEqual(self.connected, True)
36
+ ret = zookeeper.create(self.handle, "/zk-python-createtest", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
37
+ self.assertEqual(ret, "/zk-python-createtest")
38
+ self.assertRaises(zookeeper.NoChildrenForEphemeralsException,
39
+ zookeeper.create,
40
+ self.handle,
41
+ "/zk-python-createtest/invalid-child",
42
+ "",
43
+ [ZOO_OPEN_ACL_UNSAFE],
44
+ zookeeper.EPHEMERAL)
45
+
46
+ def test_sync_create_existing(self):
47
+ self.assertEqual(self.connected, True)
48
+ ret = zookeeper.create(self.handle, "/zk-python-createtest-existing", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
49
+ self.assertEqual(ret, "/zk-python-createtest-existing")
50
+
51
+ self.assertRaises(zookeeper.NodeExistsException,
52
+ zookeeper.create,
53
+ self.handle,
54
+ "/zk-python-createtest-existing",
55
+ "nodecontents",
56
+ [ZOO_OPEN_ACL_UNSAFE],
57
+ zookeeper.EPHEMERAL)
58
+
59
+
60
+ def test_exception_paths(self):
61
+ """
62
+ Make sure common exceptions due to API misuse are correctly propagated
63
+ """
64
+ self.assertRaises(zookeeper.BadArgumentsException,
65
+ zookeeper.create,
66
+ self.handle,
67
+ "/zk-python-badargs-test",
68
+ "",
69
+ [ZOO_OPEN_ACL_UNSAFE],
70
+ -1)
71
+ self.assertRaises(zookeeper.InvalidACLException,
72
+ zookeeper.create,
73
+ self.handle,
74
+ "/zk-python-invalidacl-test",
75
+ "",
76
+ ZOO_OPEN_ACL_UNSAFE) # Error - not a list
77
+
78
+
79
+ def test_async_create(self):
80
+ self.cv = threading.Condition()
81
+ def callback(handle, rc, value):
82
+ self.cv.acquire()
83
+ self.callback_flag = True
84
+ self.rc = rc
85
+ self.cv.notify()
86
+ self.cv.release()
87
+
88
+ self.assertEqual(self.connected, True, "Not connected!")
89
+ self.cv.acquire()
90
+
91
+ ret = zookeeper.acreate(self.handle, "/zk-python-acreatetest", "nodecontents",
92
+ [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL,
93
+ callback )
94
+ self.assertEqual(ret, zookeeper.OK, "acreate failed")
95
+ while not self.callback_flag:
96
+ self.cv.wait(15)
97
+ self.cv.release()
98
+
99
+ self.assertEqual(self.callback_flag, True, "acreate timed out")
100
+ self.assertEqual(self.rc, zookeeper.OK)
101
+
102
+
103
+ if __name__ == '__main__':
104
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/delete_test.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading
20
+
21
+ class DeletionTest(zktestbase.TestBase):
22
+ """Test whether we can delete znodes"""
23
+
24
+ def test_sync_delete(self):
25
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
26
+ self.assertEqual(self.connected, True)
27
+ ret = zookeeper.create(self.handle, "/zk-python-deletetest", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
28
+ self.assertEqual(ret, "/zk-python-deletetest")
29
+ ret = zookeeper.delete(self.handle,"/zk-python-deletetest")
30
+ self.assertEqual(ret, zookeeper.OK)
31
+ children = zookeeper.get_children(self.handle, "/")
32
+ self.assertEqual(False, "zk-python-deletetest" in children)
33
+
34
+ # test exception
35
+ self.assertRaises(zookeeper.NoNodeException,
36
+ zookeeper.delete,
37
+ self.handle,
38
+ "/zk-python-deletetest")
39
+
40
+ def test_async_delete(self):
41
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
42
+ self.assertEqual(self.connected, True)
43
+ ret = zookeeper.create(self.handle, "/zk-python-adeletetest", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
44
+ self.assertEqual(ret, "/zk-python-adeletetest")
45
+
46
+ self.cv = threading.Condition()
47
+ self.callback_flag = False
48
+ self.rc = -1
49
+ def callback(handle, rc):
50
+ self.cv.acquire()
51
+ self.callback_flag = True
52
+ self.cv.notify()
53
+ self.rc = rc # don't assert this here, as if the assertion fails, the test will block
54
+ self.cv.release()
55
+
56
+ self.cv.acquire()
57
+ ret = zookeeper.adelete(self.handle,"/zk-python-adeletetest",-1,callback)
58
+ self.assertEqual(ret, zookeeper.OK, "adelete failed")
59
+ while not self.callback_flag:
60
+ self.cv.wait(15)
61
+ self.cv.release()
62
+
63
+ self.assertEqual(self.callback_flag, True, "adelete timed out")
64
+ self.assertEqual(self.rc, zookeeper.OK)
65
+
66
+
67
+ if __name__ == '__main__':
68
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/exists_test.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading
20
+
21
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
22
+ class ExistsTest(zktestbase.TestBase):
23
+ def setUp( self ):
24
+ zktestbase.TestBase.setUp(self)
25
+ try:
26
+ zookeeper.create(self.handle, "/zk-python-existstest","existstest", [ZOO_OPEN_ACL_UNSAFE],zookeeper.EPHEMERAL)
27
+ zookeeper.create(self.handle, "/zk-python-aexiststest","existstest",[ZOO_OPEN_ACL_UNSAFE],zookeeper.EPHEMERAL)
28
+ except:
29
+ pass
30
+
31
+ def test_sync_exists(self):
32
+ self.assertEqual(self.connected, True)
33
+ ret = zookeeper.exists(self.handle, "/zk-python-existstest", None)
34
+ self.assertNotEqual(ret, None, "/zk-python-existstest does not exist (possibly means creation failure)")
35
+
36
+ def test_sync_nexists(self):
37
+ self.assertEqual(None, zookeeper.exists(self.handle, "/i-dont-exist", None))
38
+
39
+
40
+ def test_async_exists(self):
41
+ self.cv = threading.Condition()
42
+ def callback(handle, rc, stat):
43
+ self.cv.acquire()
44
+ self.callback_flag = True
45
+ self.cv.notify()
46
+ self.cv.release()
47
+ self.rc = rc
48
+
49
+ self.assertEqual(self.connected, True)
50
+
51
+ self.cv.acquire()
52
+ ret = zookeeper.aexists(self.handle, "/zk-python-aexiststest", None,
53
+ callback )
54
+ self.assertEqual(ret, zookeeper.OK)
55
+ while not self.callback_flag:
56
+ self.cv.wait(15)
57
+ self.cv.release()
58
+
59
+ self.assertEqual(self.callback_flag, True, "aexists timed out")
60
+ self.assertEqual(self.rc, zookeeper.OK, "Return code not ok:" + zookeeper.zerror(self.rc))
61
+
62
+
63
+ if __name__ == '__main__':
64
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/get_set_test.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import zookeeper, zktestbase, unittest, threading, sys
20
+ if sys.version_info < (3,):
21
+ range = xrange
22
+
23
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
24
+
25
+ class GetSetTest(zktestbase.TestBase):
26
+ def setUp( self ):
27
+ zktestbase.TestBase.setUp(self)
28
+ try:
29
+ zookeeper.create(self.handle, "/zk-python-getsettest", "on",[ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
30
+ zookeeper.create(self.handle, "/zk-python-agetsettest",
31
+ "on",[ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
32
+ except:
33
+ pass
34
+
35
+ def test_empty_node(self):
36
+ """
37
+ Test for a bug when instead of empty string we can get
38
+ random data from buffer malloc'ed to hold node contents.
39
+ See ZOOKEEPER-1906 for details
40
+ """
41
+ NODE_PATH = "/zk-python-test-empty-node"
42
+ self.ensureDeleted(NODE_PATH)
43
+ zookeeper.create(self.handle, NODE_PATH, "",
44
+ [{"perms":0x1f, "scheme":"world", "id" :"anyone"}])
45
+ (data,stat) = zookeeper.get(self.handle, NODE_PATH, None)
46
+ self.assertEqual(data, "", "Data is not empty as expected: " + data)
47
+
48
+ def test_sync_getset(self):
49
+ self.assertEqual(self.connected, True, "Not connected!")
50
+ (data,stat) = zookeeper.get(self.handle, "/zk-python-getsettest", None)
51
+ self.assertEqual(data, "on", "Data is not 'on' as expected: " + data)
52
+ ret = zookeeper.set(self.handle, "/zk-python-getsettest",
53
+ "off", stat["version"])
54
+ (data,stat) = zookeeper.get(self.handle, "/zk-python-getsettest", None)
55
+ self.assertEqual(data, "off", "Data is not 'off' as expected: " + data)
56
+ self.assertRaises(zookeeper.BadVersionException,
57
+ zookeeper.set,
58
+ self.handle,
59
+ "/zk-python-getsettest",
60
+ "test",
61
+ stat["version"]+1)
62
+ stat2 = zookeeper.set2(self.handle, "/zk-python-getsettest",
63
+ "set2", stat["version"])
64
+ self.assertNotEqual(stat2, None, "set2 call failed, return should not be None")
65
+ self.assertEqual(stat2["numChildren"], 0,
66
+ "set2 call failed, numChildren not 0 in set2 call")
67
+ (data,stat) = zookeeper.get(self.handle, "/zk-python-getsettest", None)
68
+ self.assertEqual(data, "set2", "Data is not 'set2' as expected: " + data)
69
+
70
+ def test_stat_deleted_node(self):
71
+ """
72
+ Test for a bug that surfaced when trying to build a
73
+ stat object from a non-existent node.
74
+
75
+ """
76
+ self.ensureDeleted("/zk-python-test-deleteme")
77
+ self.assertRaises(zookeeper.NoNodeException,
78
+ zookeeper.get,
79
+ self.handle,
80
+ "/zk-python-test-deleteme")
81
+ self.cv = threading.Condition()
82
+ def callback(handle, rc, value, stat):
83
+ self.cv.acquire()
84
+ self.stat = stat
85
+ self.rc = rc
86
+ self.value = value
87
+ self.callback_flag = True
88
+ self.cv.notify()
89
+ self.cv.release()
90
+ self.cv.acquire()
91
+ zookeeper.aget(self.handle, "/zk-python-test-deleteme", None, callback)
92
+ self.cv.wait(15)
93
+ self.assertEqual(self.callback_flag, True, "aget timed out!")
94
+ self.assertEqual(self.stat, None, "Stat should be none!")
95
+ self.assertEqual(self.value, None, "Value should be none!")
96
+
97
+ def test_sync_get_large_datanode(self):
98
+ """
99
+ Test that we can retrieve datanode sizes up to
100
+ 1Mb with default parameters (depends on ZooKeeper server).
101
+ """
102
+
103
+ data = ''.join(["A" for x in range(1024*1023)])
104
+ self.ensureDeleted("/zk-python-test-large-datanode")
105
+ zookeeper.create(self.handle, "/zk-python-test-large-datanode", data,
106
+ [{"perms":0x1f, "scheme":"world", "id" :"anyone"}])
107
+ (ret,stat) = zookeeper.get(self.handle, "/zk-python-test-large-datanode")
108
+ self.assertEqual(len(ret), 1024*1023,
109
+ "Should have got 1Mb returned, instead got %s" % len(ret))
110
+ (ret,stat) = zookeeper.get(self.handle, "/zk-python-test-large-datanode",None,500)
111
+ self.assertEqual(len(ret), 500,
112
+ "Should have got 500 bytes returned, instead got %s" % len(ret))
113
+
114
+
115
+
116
+ def test_async_getset(self):
117
+ self.cv = threading.Condition()
118
+ def get_callback(handle, rc, value, stat):
119
+ self.cv.acquire()
120
+ self.callback_flag = True
121
+ self.rc = rc
122
+ self.value = (value,stat)
123
+ self.cv.notify()
124
+ self.cv.release()
125
+
126
+ def set_callback(handle, rc, stat):
127
+ self.cv.acquire()
128
+ self.callback_flag = True
129
+ self.rc = rc
130
+ self.value = stat
131
+ self.cv.notify()
132
+ self.cv.release()
133
+
134
+ self.assertEqual(self.connected, True, "Not connected!")
135
+
136
+ self.cv.acquire()
137
+ self.callback_flag = False
138
+ ret = zookeeper.aset(self.handle, "/zk-python-agetsettest", "off", -1, set_callback)
139
+ self.assertEqual(ret, zookeeper.OK, "aset failed")
140
+ while not self.callback_flag:
141
+ self.cv.wait(15)
142
+ self.cv.release()
143
+ self.assertEqual(self.callback_flag, True, "aset timed out")
144
+
145
+ self.cv.acquire()
146
+ self.callback_flag = False
147
+ ret = zookeeper.aget(self.handle, "/zk-python-agetsettest", None, get_callback)
148
+ self.assertEqual(ret, zookeeper.OK, "aget failed")
149
+ self.cv.wait(15)
150
+ self.cv.release()
151
+ self.assertEqual(self.callback_flag, True, "aget timed out")
152
+ self.assertEqual(self.value[0], "off", "Data is not 'off' as expected: " + self.value[0])
153
+
154
+ def test_sync_getchildren(self):
155
+ self.ensureCreated("/zk-python-getchildrentest", flags=0)
156
+ self.ensureCreated("/zk-python-getchildrentest/child")
157
+ children = zookeeper.get_children(self.handle, "/zk-python-getchildrentest")
158
+ self.assertEqual(len(children), 1, "Expected to find 1 child, got " + str(len(children)))
159
+
160
+ def test_async_getchildren(self):
161
+ self.ensureCreated("/zk-python-getchildrentest", flags=0)
162
+ self.ensureCreated("/zk-python-getchildrentest/child")
163
+
164
+ def gc_callback(handle, rc, children):
165
+ self.cv.acquire()
166
+ self.rc = rc
167
+ self.children = children
168
+ self.callback_flag = True
169
+ self.cv.notify()
170
+ self.cv.release()
171
+
172
+ self.cv.acquire()
173
+ self.callback_flag = False
174
+ zookeeper.aget_children(self.handle, "/zk-python-getchildrentest", None, gc_callback)
175
+ self.cv.wait(15)
176
+ self.assertEqual(self.callback_flag, True, "aget_children timed out")
177
+ self.assertEqual(self.rc, zookeeper.OK, "Return code for aget_children was not OK - %s" % zookeeper.zerror(self.rc))
178
+ self.assertEqual(len(self.children), 1, "Expected to find 1 child, got " + str(len(self.children)))
179
+
180
+
181
+ def test_async_getchildren_with_watcher(self):
182
+ self.ensureCreated("/zk-python-getchildrentest", flags=0)
183
+ self.ensureCreated("/zk-python-getchildrentest/child")
184
+
185
+ watched = []
186
+
187
+ def watcher(*args):
188
+ self.cv.acquire()
189
+ watched.append(args)
190
+ self.cv.notify()
191
+ self.cv.release()
192
+
193
+ def children_callback(*args):
194
+ self.cv.acquire()
195
+ self.cv.notify()
196
+ self.cv.release()
197
+
198
+ zookeeper.aget_children(
199
+ self.handle, "/zk-python-getchildrentest", watcher, children_callback)
200
+
201
+ self.cv.acquire()
202
+ self.cv.wait()
203
+ self.cv.release()
204
+
205
+ self.cv.acquire()
206
+ self.ensureCreated("/zk-python-getchildrentest/child2")
207
+ self.cv.wait(15)
208
+ self.assertTrue(watched)
209
+
210
+ if __name__ == '__main__':
211
+ unittest.main()
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/run_tests.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/sh
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ # Usage: run_tests.sh testdir [logdir]
20
+ # logdir is optional, defaults to cwd
21
+
22
+ set -e
23
+
24
+ # get the number of command-line arguments given
25
+ ARGC=$#
26
+
27
+ # check to make sure enough arguments were given or exit
28
+ if [ $ARGC -lt 2 ]; then
29
+ export ZKPY_LOG_DIR="."
30
+ else
31
+ export ZKPY_LOG_DIR=$2
32
+ fi
33
+
34
+ # Find the build directory containing zookeeper.so
35
+ SO_PATH=`find ./target/ -name 'zookeeper*.so' | head -1`
36
+ PYTHONPATH=`dirname $SO_PATH`
37
+ LIB_PATH=../../zookeeper-client/zookeeper-client-c/target/c/.libs
38
+ for test in `ls $1/*_test.py`;
39
+ do
40
+ echo "Running $test"
41
+ echo "Running LD_LIBRARY_PATH=$LIB_PATH:$LD_LIBRARY_PATH DYLD_LIBRARY_PATH=$LIB_PATH:$DYLD_LIBRARY_PATH PYTHONPATH=$PYTHONPATH python $test"
42
+ LD_LIBRARY_PATH=$LIB_PATH:$LD_LIBRARY_PATH DYLD_LIBRARY_PATH=$LIB_PATH:$DYLD_LIBRARY_PATH PYTHONPATH=$PYTHONPATH python $test
43
+ done
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/zkServer.sh ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ if [ "x$1" == "x" ]
20
+ then
21
+ echo "USAGE: $0 startClean|start|stop"
22
+ exit 2
23
+ fi
24
+
25
+ if [ "x${base_dir}" == "x" ]
26
+ then
27
+ PROJECT_ROOT="../../"
28
+ else
29
+ PROJECT_ROOT=${base_dir}
30
+ fi
31
+ WORK_DIR=${PROJECT_ROOT}/zookeeper-contrib/zookeeper-contrib-zkpython/target/zkpython_tests
32
+ TEST_DIR=${PROJECT_ROOT}/zookeeper-contrib/zookeeper-contrib-zkpython/src/test
33
+
34
+
35
+ if [ -r "${WORK_DIR}/../zk.pid" ]
36
+ then
37
+ pid=`cat "${WORK_DIR}/../zk.pid"`
38
+ kill -9 $pid
39
+ rm -f "${WORK_DIR}/../zk.pid"
40
+ fi
41
+
42
+ which lsof &> /dev/null
43
+ if [ $? -eq 0 ]
44
+ then
45
+ pid=`lsof -i :22182 | grep LISTEN | awk '{print $2}'`
46
+ if [ -n "$pid" ]
47
+ then
48
+ kill -9 $pid
49
+ fi
50
+ fi
51
+
52
+
53
+
54
+
55
+ if [ "x$1" == "xstartClean" ]
56
+ then
57
+ rm -rf ${WORK_DIR}
58
+ fi
59
+
60
+
61
+
62
+ CLASSPATH="$CLASSPATH:${PROJECT_ROOT}/zookeeper-server/target/classes"
63
+ CLASSPATH="$CLASSPATH:${zk_base}/conf"
64
+
65
+ for i in "${PROJECT_ROOT}"/zookeeper-server/target/lib/*.jar
66
+ do
67
+ CLASSPATH="$CLASSPATH:$i"
68
+ done
69
+
70
+ for i in "${PROJECT_ROOT}"/zookeeper-server/src/main/resource/lib/*.jar
71
+ do
72
+ CLASSPATH="$CLASSPATH:$i"
73
+ done
74
+
75
+ # Make sure nothing is left over from before
76
+ #fuser -skn tcp 22182/tcp
77
+
78
+ case $1 in
79
+ start|startClean)
80
+ mkdir -p ${WORK_DIR}/zkdata
81
+
82
+ rm -rf ${WORK_DIR}/ssl
83
+ mkdir -p ${WORK_DIR}/ssl
84
+ cp ${PROJECT_ROOT}/zookeeper-client/zookeeper-client-c/ssl/gencerts.sh ${WORK_DIR}/ssl/
85
+ cd ${WORK_DIR}/ssl/
86
+ ./gencerts.sh
87
+ cd -
88
+
89
+ sed "s#WORKDIR#${WORK_DIR}#g" ${TEST_DIR}/zoo.cfg > "${WORK_DIR}/zoo.cfg"
90
+ java -Dzookeeper.extendedTypesEnabled=true -Dznode.container.checkIntervalMs=100 -cp $CLASSPATH org.apache.zookeeper.server.ZooKeeperServerMain "${WORK_DIR}/zoo.cfg" &> "${WORK_DIR}/zoo.log" &
91
+ pid=$!
92
+ echo -n $! > ${WORK_DIR}/../zk.pid
93
+ sleep 5
94
+ ;;
95
+ stop)
96
+ # Already killed above
97
+ ;;
98
+ *)
99
+ echo "Unknown command " + $1
100
+ exit 2
101
+ esac
102
+
local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/zktestbase.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python
2
+ #
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import os
20
+ import unittest, threading, zookeeper
21
+ ZOO_OPEN_ACL_UNSAFE = {"perms":0x1f, "scheme":"world", "id" :"anyone"}
22
+
23
+ class TestBase(unittest.TestCase):
24
+ SERVER_PORT = 22182
25
+ SERVER_SSL_PORT = 22183
26
+
27
+ def __init__(self,methodName='runTest'):
28
+ unittest.TestCase.__init__(self,methodName)
29
+ self.host = "localhost:%d" % self.SERVER_PORT
30
+ self.sslhost = "localhost:%d" % self.SERVER_SSL_PORT
31
+ self.sslcert = "./target/zkpython_tests/ssl/server.crt,./target/zkpython_tests/ssl/client.crt,./target/zkpython_tests/ssl/clientkey.pem,password"
32
+ self.connected = False
33
+ self.handle = -1
34
+ logdir = os.environ.get("ZKPY_LOG_DIR")
35
+ logfile = os.path.join(logdir, self.__class__.__name__ + ".log")
36
+ try:
37
+ f = open(logfile,"w")
38
+ zookeeper.set_log_stream(f)
39
+ except IOError:
40
+ print("Couldn't open " + logfile + " for writing")
41
+
42
+
43
+ def setUp(self):
44
+ self.callback_flag = False
45
+ self.cv = threading.Condition()
46
+ self.connected = False
47
+ def connection_watcher(handle, type, state, path):
48
+ self.cv.acquire()
49
+ self.connected = True
50
+ self.cv.notify()
51
+ self.cv.release()
52
+
53
+ self.cv.acquire()
54
+ self.handle = zookeeper.init(self.host, connection_watcher)
55
+ self.cv.wait(15.0)
56
+ self.cv.release()
57
+
58
+ if not self.connected:
59
+ raise Exception("Couldn't connect to host -", self.host)
60
+
61
+ def newConnection(self):
62
+ cv = threading.Condition()
63
+ self.pending_connection = False
64
+ def connection_watcher(handle, type, state, path):
65
+ cv.acquire()
66
+ self.pending_connection = True
67
+ cv.notify()
68
+ cv.release()
69
+
70
+ cv.acquire()
71
+ handle = zookeeper.init(self.host, connection_watcher)
72
+ cv.wait(15.0)
73
+ cv.release()
74
+
75
+ if not self.pending_connection:
76
+ raise Exception("Couldn't connect to host -", self.host)
77
+ return handle
78
+
79
+ def ensureDeleted(self,path):
80
+ self.assertEqual(zookeeper.CONNECTED_STATE, zookeeper.state(self.handle), "Not connected!")
81
+ try:
82
+ self.assertEqual(zookeeper.OK, zookeeper.delete(self.handle, path))
83
+ except zookeeper.NoNodeException:
84
+ pass
85
+
86
+ def ensureCreated(self,path,data="",flags=zookeeper.EPHEMERAL):
87
+ """
88
+ It's possible not to get the flags you want here if the node already exists
89
+ """
90
+ self.assertEqual(zookeeper.CONNECTED_STATE, zookeeper.state(self.handle), "Not connected!")
91
+ try:
92
+ self.assertEqual(path, zookeeper.create(self.handle, path, data, [ZOO_OPEN_ACL_UNSAFE], flags))
93
+ except zookeeper.NodeExistsException:
94
+ pass
95
+
96
+ def tearDown(self):
97
+ if self.connected:
98
+ zookeeper.close(self.handle)
99
+
100
+ def all(self, iterable):
101
+ for element in iterable:
102
+ if not element:
103
+ return False
104
+ return True