烹茶细论

Kazoo zookeeper python模块的使用

kazoo是zookeeper的python模块,使用python编写的。使用python写运维平台的就可以用上

##1、安装
安装简单,不需要其他依赖

1
Pip install kazoo

##2、使用

1
2
3
4
5
from kazoo.client import KazooClient
zk = KazooClient(hosts='127.0.0.1:2181')
zk.start() //没有异常的话就意味着连接上zookeeper
children = zk.get_children('/')
zk.stop()

###2.1、连接状态 zk.state

有三个值,LOST、CONNECTED、SUSPENDED
QQ图片20150408141901

###2.2、zk.connected
已连接上返回True
没有连接上返回False

###2.3、zk.get(path, watch=None)
获取指定节点的值,节点不存在触发NoNodeError异常

###2.4、zk.get_children(path, watch=None)
获取指定节点子节点信息
QQ图片20150408141922

###3、web展示结果
zookeeper7

###4、后台逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def base(basedir, id, pid):
'''
id:当前节点的id,ID的组成是 深度 + 兄弟节点序号 + 父节点ID
pid: 父节点id
name: 节点名称
children: 子节点个数
deep: 深度
url: 节点的路径
'''
deep = ''
try:
if not zk.connected:
zk.start()
item = {}
if basedir == '/':
children = ['redis','game','uc']
else:
children = zk.get_children(basedir)
cut = basedir.split('/')
deep = len(cut)-1
name = cut[deep]
if len(children) == 0:
childrenlen = 0
else:
childrenlen = len(children)
item = {'id': id, 'pid': pid, 'name': name, 'children':childrenlen, 'deep':deep, 'url': basedir}
datas.append(item)
for i in xrange(len(children)):
path = os.path.join(basedir, children[i])
cut = path.split('/')
n_id = str(len(cut)-1) + str(i) + str(id)
base(path, n_id, id)
except Exception, e:
data = str(e)
return datas
def get_children(req):
status = 0
message = ''
data = []
global datas
datas = []
basedir = '/'
try:
data = base(basedir, '10', '0')
except Exception, e:
status = -1
message = str(e)
zk.stop()
result = stringify(status, message, data)
return HttpResponse(result)

参考资料:
https://kazoo.readthedocs.org/en/latest/install.html
http://sapser.github.io/python/zookeeper/2014/07/24/zookeeper-kazoo/