Kitxuuu commited on
Commit
ea8198f
·
verified ·
1 Parent(s): f34fa51

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/setup.py +46 -0
  2. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/__init__.py +16 -0
  3. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/rest.py +230 -0
  4. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/settings.py +30 -0
  5. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/static/bootstrap.js +32 -0
  6. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/static/js/package.yml +19 -0
  7. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/stats.py +170 -0
  8. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/clients.mako +51 -0
  9. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/index.mako +54 -0
  10. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/view.mako +128 -0
  11. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/urls.py +28 -0
  12. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/utils.py +33 -0
  13. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/views.py +165 -0
  14. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/windmilltests.py +23 -0
  15. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-rest/src/python/zk_dump_tree.py +108 -0
  16. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/examples/watch_znode_for_changes.py +202 -0
  17. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/setup.py +45 -0
  18. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/python/zk.py +76 -0
  19. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/acl_test.py +109 -0
  20. local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/get_set_test.py +211 -0
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/setup.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from setuptools import setup, find_packages
17
+ import os
18
+
19
+ def expand_package_data(src_dirs, strip=""):
20
+ ret = []
21
+ for src_dir in src_dirs:
22
+ for path, dnames, fnames in os.walk(src_dir):
23
+ for fname in fnames:
24
+ ret.append(os.path.join(path, fname).replace(strip, ""))
25
+ return ret
26
+
27
+ os.chdir(os.path.dirname(os.path.abspath(__file__)))
28
+ setup(
29
+ name = "zkui",
30
+ version = "0.1",
31
+ url = 'http://zookeeper.apache.org/',
32
+ description = 'ZooKeeper Browser',
33
+ packages = find_packages('src'),
34
+ package_dir = {'': 'src'},
35
+ install_requires = ['setuptools', 'desktop'],
36
+ entry_points = { 'desktop.sdk.application': 'zkui=zkui' },
37
+ zip_safe = False,
38
+ package_data = {
39
+ # Include static resources. Package_data doesn't
40
+ # deal well with directory globs, so we enumerate
41
+ # the files manually.
42
+ 'zkui': expand_package_data(
43
+ ["src/zkui/templates", "src/zkui/static"],
44
+ "src/zkui/")
45
+ }
46
+ )
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
local-test-zookeeper-delta-02/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-02/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-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/static/bootstrap.js ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ CCS.Desktop.register({
17
+ Zkui : {
18
+ name : 'ZooKeeper Browser',
19
+ css : '/zkui/static/css/zkui.css',
20
+ require: [ 'Zkui' ],
21
+ launch: function(path, options){
22
+ return new Zkui(path || '/zkui/', options);
23
+ },
24
+ menu: {
25
+ id: 'ccs-zkui-menu',
26
+ img: {
27
+ src: '/zkui/static/art/zkui.png'
28
+ }
29
+ },
30
+ help: '/help/zkui/'
31
+ }
32
+ });
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/static/js/package.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed to the Apache Software Foundation (ASF) under one or more
2
+ # contributor license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright ownership.
4
+ # The ASF licenses this file to You under the Apache License, Version 2.0
5
+ # (the "License"); you may not use this file except in compliance with
6
+ # the License. You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ copyright: Apache License v2.0
16
+ version: 0.1
17
+ description: ZooKeeper Browser
18
+ name: ZooKeeper Browser
19
+ sources: [Source/Zkui/Zkui.js]
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/stats.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 socket
18
+ import re
19
+
20
+ from StringIO import StringIO
21
+
22
+ class Session(object):
23
+
24
+ class BrokenLine(Exception): pass
25
+
26
+ def __init__(self, session):
27
+ m = re.search('/(\d+\.\d+\.\d+\.\d+):(\d+)\[(\d+)\]\((.*)\)', session)
28
+ if m:
29
+ self.host = m.group(1)
30
+ self.port = m.group(2)
31
+ self.interest_ops = m.group(3)
32
+ for d in m.group(4).split(","):
33
+ k,v = d.split("=")
34
+ self.__dict__[k] = v
35
+ else:
36
+ raise Session.BrokenLine()
37
+
38
+ class ZooKeeperStats(object):
39
+
40
+ def __init__(self, host='localhost', port='2181', timeout=1):
41
+ self._address = (host, int(port))
42
+ self._timeout = timeout
43
+
44
+ def get_stats(self):
45
+ """ Get ZooKeeper server stats as a map """
46
+ data = self._send_cmd('mntr')
47
+ if data:
48
+ return self._parse(data)
49
+ else:
50
+ data = self._send_cmd('stat')
51
+ return self._parse_stat(data)
52
+
53
+ def get_clients(self):
54
+ """ Get ZooKeeper server clients """
55
+ clients = []
56
+
57
+ stat = self._send_cmd('stat')
58
+ if not stat:
59
+ return clients
60
+
61
+ sio = StringIO(stat)
62
+
63
+ #skip two lines
64
+ sio.readline()
65
+ sio.readline()
66
+
67
+ for line in sio:
68
+ if not line.strip():
69
+ break
70
+ try:
71
+ clients.append(Session(line.strip()))
72
+ except Session.BrokenLine:
73
+ continue
74
+
75
+ return clients
76
+
77
+ def _create_socket(self):
78
+ return socket.socket()
79
+
80
+ def _send_cmd(self, cmd):
81
+ """ Send a 4letter word command to the server """
82
+ s = self._create_socket()
83
+ s.settimeout(self._timeout)
84
+
85
+ s.connect(self._address)
86
+ s.send(cmd)
87
+
88
+ data = s.recv(2048)
89
+ s.close()
90
+
91
+ return data
92
+
93
+ def _parse(self, data):
94
+ """ Parse the output from the 'mntr' 4letter word command """
95
+ h = StringIO(data)
96
+
97
+ result = {}
98
+ for line in h.readlines():
99
+ try:
100
+ key, value = self._parse_line(line)
101
+ result[key] = value
102
+ except ValueError:
103
+ pass # ignore broken lines
104
+
105
+ return result
106
+
107
+ def _parse_stat(self, data):
108
+ """ Parse the output from the 'stat' 4letter word command """
109
+ h = StringIO(data)
110
+
111
+ result = {}
112
+
113
+ version = h.readline()
114
+ if version:
115
+ result['zk_version'] = version[version.index(':')+1:].strip()
116
+
117
+ # skip all lines until we find the empty one
118
+ while h.readline().strip(): pass
119
+
120
+ for line in h.readlines():
121
+ m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line)
122
+ if m is not None:
123
+ result['zk_min_latency'] = int(m.group(1))
124
+ result['zk_avg_latency'] = int(m.group(2))
125
+ result['zk_max_latency'] = int(m.group(3))
126
+ continue
127
+
128
+ m = re.match('Received: (\d+)', line)
129
+ if m is not None:
130
+ result['zk_packets_received'] = int(m.group(1))
131
+ continue
132
+
133
+ m = re.match('Sent: (\d+)', line)
134
+ if m is not None:
135
+ result['zk_packets_sent'] = int(m.group(1))
136
+ continue
137
+
138
+ m = re.match('Outstanding: (\d+)', line)
139
+ if m is not None:
140
+ result['zk_outstanding_requests'] = int(m.group(1))
141
+ continue
142
+
143
+ m = re.match('Mode: (.*)', line)
144
+ if m is not None:
145
+ result['zk_server_state'] = m.group(1)
146
+ continue
147
+
148
+ m = re.match('Node count: (\d+)', line)
149
+ if m is not None:
150
+ result['zk_znode_count'] = int(m.group(1))
151
+ continue
152
+
153
+ return result
154
+
155
+ def _parse_line(self, line):
156
+ try:
157
+ key, value = map(str.strip, line.split('\t'))
158
+ except ValueError:
159
+ raise ValueError('Found invalid line: %s' % line)
160
+
161
+ if not key:
162
+ raise ValueError('The key is mandatory and should not be empty')
163
+
164
+ try:
165
+ value = int(value)
166
+ except (TypeError, ValueError):
167
+ pass
168
+
169
+ return key, value
170
+
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/clients.mako ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ <%namespace name="shared" file="shared_components.mako" />
20
+
21
+ ${shared.header("ZooKeeper Browser > Clients > %s:%s" % (host, port))}
22
+
23
+ <h1>${host}:${port} :: client connections</h1>
24
+ <br />
25
+
26
+ % if clients:
27
+ <table data-filters="HtmlTable">
28
+ <thead>
29
+ <tr>
30
+ <th>Host</th>
31
+ <th>Port</th>
32
+ <th>Interest Ops</th>
33
+ <th>Queued</th>
34
+ <th>Received</th>
35
+ <th>Sent</th>
36
+ </thead>
37
+ % for client in clients:
38
+ <tr>
39
+ <td>${client.host}</td>
40
+ <td>${client.port}</td>
41
+ <td>${client.interest_ops}</td>
42
+ <td>${client.queued}</td>
43
+ <td>${client.recved}</td>
44
+ <td>${client.sent}</td>
45
+ </tr>
46
+ % endfor
47
+ </table>
48
+ % endif
49
+
50
+ ${shared.footer()}
51
+
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/index.mako ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ <%namespace name="shared" file="shared_components.mako" />
19
+
20
+ ${shared.header("ZooKeeper Browser")}
21
+
22
+ <h2>Overview</h2>
23
+
24
+ <br />
25
+
26
+ % for i, c in enumerate(overview):
27
+ <h3> ${i+1}. <a href="${url('zkui.views.view', id=i)}">${c['nice_name']} Cluster Overview</a></h3><br />
28
+
29
+ <table data-filters="HtmlTable">
30
+ <thead>
31
+ <tr>
32
+ <th>Node</th>
33
+ <th>Role</th>
34
+ <th>Avg Latency</th>
35
+ <th>Watch Count</th>
36
+ <th>Version</th>
37
+ </tr>
38
+ </thead>
39
+ % for host, stats in c['stats'].items():
40
+ <tr>
41
+ <td>${host}</td>
42
+ <td>${stats.get('zk_server_state', '')}</td>
43
+ <td>${stats.get('zk_avg_latency', '')}</td>
44
+ <td>${stats.get('zk_watch_count', '')}</td>
45
+ <td>${stats.get('zk_version', '')}</td>
46
+ </tr>
47
+ % endfor
48
+ </table>
49
+
50
+ <br /><br />
51
+ % endfor
52
+
53
+ ${shared.footer()}
54
+
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/templates/view.mako ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ <%namespace name="shared" file="shared_components.mako" />
19
+
20
+ ${shared.header("ZooKeeper Browser > %s" % cluster['nice_name'])}
21
+
22
+ <%def name="show_stats(stats)">
23
+ <thead>
24
+ <tr><th>Key</th>
25
+ <th width="100%">Value</th></tr>
26
+ </thead>
27
+
28
+ <tr><td>Version</td>
29
+ <td>${stats.get('zk_version')}</td>
30
+ </tr>
31
+
32
+ <tr><td>Latency</td><td>
33
+ Min: ${stats.get('zk_min_latency', '')}
34
+ Avg: ${stats.get('zk_avg_latency', '')}
35
+ Max: ${stats.get('zk_max_latency', '')}
36
+ </td></tr>
37
+
38
+ <tr><td>Packets</td>
39
+ <td>Sent: ${stats.get('zk_packets_sent', '')}
40
+ Received: ${stats.get('zk_packets_received', '')}
41
+ </td>
42
+ </tr>
43
+
44
+ <tr><td>Outstanding Requests</td>
45
+ <td>${stats.get('zk_outstanding_requests', '')}</td>
46
+ </tr>
47
+
48
+ <tr><td>Watch Count</td>
49
+ <td>${stats.get('zk_watch_count', '')}</td>
50
+ </tr>
51
+
52
+ <tr><td>Open FD Count</td>
53
+ <td>${stats.get('zk_open_file_descriptor_count', '')}</td>
54
+ </tr>
55
+
56
+ <tr><td>Max FD Count</td>
57
+ <td>${stats.get('zk_max_file_descriptor_count', '')}</td>
58
+ </tr>
59
+
60
+ </%def>
61
+
62
+ <h2> ${cluster['nice_name']} Cluster Overview </h2>
63
+
64
+ ${shared.info_button(url('zkui.views.tree', id=cluster['id'], path='/'), 'View Znode Hierarchy')}
65
+
66
+ <br /><br />
67
+
68
+ % if leader:
69
+ <h2>General</h2>
70
+
71
+ <table data-filters="HtmlTable">
72
+ <thead>
73
+ <tr><th>Key</th><th width="100%">Value</th></tr>
74
+ </thead>
75
+
76
+ <tr><td>ZNode Count</td>
77
+ <td>${leader.get('zk_znode_count', '')}</td></tr>
78
+
79
+ <tr><td>Ephemerals Count</td>
80
+ <td>${leader.get('zk_ephemerals_count', '')}</td></tr>
81
+
82
+ <tr><td>Approximate Data Size</td>
83
+ <td>${leader.get('zk_approximate_data_size', '')} bytes</td></tr>
84
+
85
+ </table>
86
+ <br /><br />
87
+ % endif
88
+
89
+ % if leader:
90
+ <h2>node :: ${leader['host']} :: leader</h2>
91
+
92
+ ${shared.info_button(url('zkui.views.clients', host=leader['host']), 'View Client Connections')}
93
+
94
+ <br /><br />
95
+ <table data-filters="HtmlTable">
96
+ ${show_stats(leader)}
97
+
98
+ <tr><td>Followers</td>
99
+ <td>${leader.get('zk_learners', '')}</td>
100
+ </tr>
101
+
102
+ <tr><td>Synced Followers</td>
103
+ <td>${leader.get('zk_synced_followers', '')}</td>
104
+ </tr>
105
+
106
+ <tr><td>Pending Syncs</td>
107
+ <td>${leader.get('zk_pending_syncs', '')}</td>
108
+ </tr>
109
+
110
+ </table>
111
+ <br /><br />
112
+ % endif
113
+
114
+ % for stats in followers:
115
+ <h2>node :: ${stats['host']} :: follower</h2>
116
+ <br />
117
+
118
+ ${shared.info_button(url('zkui.views.clients', host=stats['host']), 'View Client Connections')}
119
+
120
+ <br /><br />
121
+ <table data-filters="HtmlTable">
122
+ ${show_stats(stats)}
123
+ </table>
124
+ <br /><br />
125
+ % endfor
126
+
127
+ ${shared.footer()}
128
+
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/urls.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 django.conf.urls.defaults import patterns, url
18
+
19
+ urlpatterns = patterns('zkui',
20
+ url(r'^$', 'views.index'),
21
+ url(r'view/(?P<id>\d+)$', 'views.view'),
22
+ url(r'clients/(?P<host>.+)$', 'views.clients'),
23
+ url(r'tree/(?P<id>\d+)(?P<path>.+)$', 'views.tree'),
24
+ url(r'create/(?P<id>\d+)(?P<path>.*)$', 'views.create'),
25
+ url(r'delete/(?P<id>\d+)(?P<path>.*)$', 'views.delete'),
26
+ url(r'edit/base64/(?P<id>\d+)(?P<path>.*)$', 'views.edit_as_base64'),
27
+ url(r'edit/text/(?P<id>\d+)(?P<path>.*)$', 'views.edit_as_text')
28
+ )
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 zkui import settings
18
+
19
+ from django.http import Http404
20
+
21
+ def get_cluster_or_404(id):
22
+ try:
23
+ id = int(id)
24
+ if not (0 <= id < len(settings.CLUSTERS)):
25
+ raise ValueError, 'Undefined cluster id.'
26
+ except (TypeError, ValueError):
27
+ raise Http404()
28
+
29
+ cluster = settings.CLUSTERS[id]
30
+ cluster['id'] = id
31
+
32
+ return cluster
33
+
local-test-zookeeper-delta-02/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-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-huebrowser/zkui/src/zkui/windmilltests.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.windmill_util import logged_in_client
18
+
19
+ def test_zkui():
20
+ """ launches the default view for zkui """
21
+ client = logged_in_client()
22
+ client.click(id='ccs-zkui-menu')
23
+ client.waits.forElement(classname='CCS-ZKUI', timeout='2000')
local-test-zookeeper-delta-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-rest/src/python/zk_dump_tree.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 getopt
20
+ import sys
21
+ import simplejson
22
+ import urllib2
23
+ from base64 import b64decode
24
+
25
+ printdata = False
26
+ fullpath = False
27
+
28
+ def dump_node(url, depth):
29
+ """Dump the node, then dump children recursively
30
+
31
+ Arguments:
32
+ - `url`:
33
+ - `depth`:
34
+ """
35
+ req = urllib2.urlopen(url)
36
+ resp = simplejson.load(req)
37
+ if 'Error' in resp:
38
+ raise resp['Error']
39
+
40
+ if fullpath:
41
+ name = resp['path']
42
+ else:
43
+ name = '/' + resp['path'].split('/')[-1]
44
+
45
+ data64 = resp.get('data64')
46
+ dataUtf8 = resp.get('dataUtf8')
47
+ if data64 and printdata:
48
+ data = b64decode(data64)
49
+ print '%(indent)s%(name)s = b64(%(data64)s) str(%(data)s)' % \
50
+ {'indent':' '*2*depth, 'name':name, 'data64':data64, 'data':data}
51
+ elif dataUtf8 and printdata:
52
+ print '%(indent)s%(name)s = %(data)s' % \
53
+ {'indent':' '*2*depth, 'name':name, 'data':dataUtf8}
54
+ else:
55
+ print '%(indent)s%(name)s' % {'indent':' '*2*depth, 'name':name}
56
+
57
+ req = urllib2.urlopen(resp['uri'] + '?view=children')
58
+ resp = simplejson.load(req)
59
+
60
+ for child in resp.get('children', []):
61
+ dump_node(resp['child_uri_template']
62
+ .replace("{child}", urllib2.quote(child)),
63
+ depth + 1)
64
+
65
+ def zk_dump_tree(url, root):
66
+ """Dump the tree starting at the roota
67
+
68
+ Arguments:
69
+ - `root`:
70
+ """
71
+ dump_node(url + '/znodes/v1' + root, 0)
72
+
73
+ def usage():
74
+ """Usage
75
+ """
76
+ print 'Usage: zk_dump_tree.py [-h|--help -u|--url=url -d|--data -f|--fullpath -r|--root=root]'
77
+ print ' where url is the url of the rest server, data is whether to'
78
+ print ' to include node data on output, root is the znode root'
79
+ print ' fullpath prints the full node path (useful for copy/paste)'
80
+
81
+ if __name__ == '__main__':
82
+ try:
83
+ opts, args = getopt.getopt(sys.argv[1:],
84
+ "hu:dfr:", ["help", "url=", "data", "fullpath", "root="])
85
+ except getopt.GetoptError, err:
86
+ # print help information and exit:
87
+ print str(err) # will print something like "option -a not recognized"
88
+ usage()
89
+ sys.exit(2)
90
+ url ='http://localhost:9998'
91
+ root = '/'
92
+ for o, a in opts:
93
+ if o in ("-d", "--data"):
94
+ printdata = True
95
+ elif o in ("-h", "--help"):
96
+ usage()
97
+ sys.exit()
98
+ elif o in ("-u", "--url"):
99
+ url = a
100
+ elif o in ("-r", "--root"):
101
+ root = a
102
+ elif o in ("-f", "--fullpath"):
103
+ fullpath = True
104
+ else:
105
+ assert False, "unhandled option"
106
+
107
+ print 'Accessing REST server at ' + url
108
+ zk_dump_tree(url, root)
local-test-zookeeper-delta-02/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-02/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-02/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-02/afc-zookeeper/zookeeper-contrib/zookeeper-contrib-zkpython/src/test/acl_test.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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":zookeeper.PERM_ALL, "scheme":"world", "id" :"anyone"}
22
+ ZOO_ACL_READ = {"perms":zookeeper.PERM_READ, "scheme": "world",
23
+ "id":"anyone"}
24
+ class ACLTest(zktestbase.TestBase):
25
+ """Test whether basic ACL setting and getting work correctly"""
26
+ # to do: startup and teardown via scripts?
27
+ def setUp(self):
28
+ zktestbase.TestBase.setUp(self)
29
+ try:
30
+ zookeeper.delete(self.handle, "/zk-python-acltest")
31
+ zookeeper.delete(self.handle, "/zk-python-aacltest")
32
+ except:
33
+ pass
34
+
35
+ def test_sync_acl(self):
36
+ self.assertEqual(self.connected, True)
37
+ ret = zookeeper.create(self.handle, "/zk-python-acltest", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
38
+ acls = zookeeper.get_acl(self.handle, "/zk-python-acltest")
39
+ self.assertEqual(acls[1], [ZOO_OPEN_ACL_UNSAFE])
40
+ self.assertRaises(zookeeper.InvalidACLException,zookeeper.set_acl,self.handle, "/zk-python-acltest", -1, ZOO_ACL_READ)
41
+ zookeeper.set_acl(self.handle, "/zk-python-acltest", -1, [ZOO_ACL_READ])
42
+ acls = zookeeper.get_acl(self.handle, "/zk-python-acltest")
43
+ self.assertEqual(acls[1], [ZOO_ACL_READ])
44
+
45
+
46
+ def test_async_acl(self):
47
+ self.cv = threading.Condition()
48
+ self.cv = threading.Condition()
49
+ def aget_callback(handle, rc, acl, stat):
50
+ self.cv.acquire()
51
+ self.callback_flag = True
52
+ self.rc = rc
53
+ self.acl = acl
54
+ self.stat = stat
55
+ self.cv.notify()
56
+ self.cv.release()
57
+
58
+ def aset_callback(handle, rc):
59
+ self.cv.acquire()
60
+ self.callback_flag = True
61
+ self.rc = rc
62
+ self.cv.notify()
63
+ self.cv.release()
64
+
65
+ self.assertEqual(self.connected, True, "Not connected!")
66
+ ret = zookeeper.create(self.handle, "/zk-python-aacltest", "nodecontents", [ZOO_OPEN_ACL_UNSAFE], zookeeper.EPHEMERAL)
67
+
68
+ self.cv.acquire()
69
+ zookeeper.aget_acl(self.handle, "/zk-python-aacltest", aget_callback)
70
+ self.cv.wait(15)
71
+ self.cv.release()
72
+
73
+ self.assertEqual(self.callback_flag, True, "aget_acl timed out")
74
+ self.assertEqual(self.rc, zookeeper.OK, "aget failed")
75
+ self.assertEqual(self.acl, [ZOO_OPEN_ACL_UNSAFE], "Wrong ACL returned from aget")
76
+
77
+ self.cv.acquire()
78
+ self.callback_flag = False
79
+ zookeeper.aset_acl(self.handle, "/zk-python-aacltest", -1, [ZOO_ACL_READ], aset_callback)
80
+ self.cv.wait(15)
81
+ self.cv.release()
82
+
83
+ self.assertEqual(self.callback_flag, True, "aset_acl timed out")
84
+ self.assertEqual(self.rc, zookeeper.OK, "aset failed")
85
+ acls = zookeeper.get_acl(self.handle, "/zk-python-aacltest")
86
+ self.assertEqual(acls[1], [ZOO_ACL_READ], "Wrong ACL returned from get when aset")
87
+
88
+ def test_invalid_acl(self):
89
+ self.assertRaises(zookeeper.InvalidACLException,
90
+ zookeeper.create,
91
+ self.handle,
92
+ "/zk-python-aclverifytest",
93
+ "",
94
+ None,
95
+ zookeeper.EPHEMERAL)
96
+
97
+ def test_invalid_acl2(self):
98
+ """Verify all required keys are present in the ACL."""
99
+ invalid_acl = [{"schema": "digest", "id": "zebra"}]
100
+ self.assertRaises(zookeeper.InvalidACLException,
101
+ zookeeper.create,
102
+ self.handle,
103
+ "/zk-python-aclverifytest",
104
+ "",
105
+ invalid_acl,
106
+ zookeeper.EPHEMERAL)
107
+
108
+ if __name__ == '__main__':
109
+ unittest.main()
local-test-zookeeper-delta-02/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()