通过python脚本和zabbix配合监控zookeeper的节点数

通过python脚本和zabbix配合监控zookeeper的节点数

需求描述:
在日常zabbix监控zookeeper的时候,无法通过shell来获取zookeeper的具体节点信息,没有开放具体的接口,只能通过交互式的shell获取
python提供了操作zookeeper的api,我们可以使用python脚本结合zabbix来监控zookeeper的服务端是否上线


1.安装相关的依赖
由于python客户端依赖c的客户端所以要先安装c版本的客户端
cd /usr/local/src
wget http://archive.apache.org/dist/zookeeper/zookeeper-3.4.6/zookeeper-3.4.6.tar.gz
tar -zxvf zookeeper-3.4.6.tar.gz
cd /usr/local/src/zookeeper-3.4.6/src/c
./configure  
make   
make install  

# 验证是否成功,测试是否能够连上zookeeper
[root@localhost c]# ./cli_mt 1.1.1.1:9181
Watcher SESSION_EVENT state = CONNECTED_STATE
Got a new session id: 0x35f2e9cf58103e6

2.下载安装zkpython
wget https://pypi.python.org/packages/source/z/zkpython/zkpython-0.4.2.tar.gz  
tar -zxf zkpython-0.4.2.tar.gz
cd zkpython-0.4.2
python setup.py build
python setup.py install

# 加入环境变量
# vim /etc/profile
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib

source /etc/profile
或者

# echo "/usr/local/lib" >> /etc/ld.so.conf  
# /sbin/ldconfig  

3.测试
使用ipython访问zookeeper

[root@localhost zkpython-0.4.2]# ipython
Python 2.7.5 (default, Aug  4 2017, 00:39:18) 
Type "copyright", "credits" or "license" for more information.

IPython 5.5.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

import zookeeper as zoo
# 初始化连接到集群  
zk = zoo.init("1.1.1.1:2181")
  
# 获取所有节点
zoo.get_children(zk, "/", None)
# 获取voice-server所有节点
nodes = zoo.get_children(zk, "/sdk/voice/server/info", None)
# 获取zookeeper节点中voice-server的个数
print len(nodes)


# 具体代码

#!/usr/bin/python
#encoding:utf-8

import zookeeper as zoo
import sys

# 设置zookeeper的日志等级,避免python输出大量无用信息
zoo.set_debug_level(zoo.LOG_LEVEL_ERROR) 

DEFAULT_TIMEOUT = 30000

class zookServer():
    def __init__(self, timeout=DEFAULT_TIMEOUT):
        # 初始化连接到集群
        self.timeout = timeout
        self.zk = zoo.init("ip1:2181,ip2:2181,ip3:2181")

    # 获取zookeeper所有的节点长度
    def get_children_len(self, _path, watcher = None):
        self.connected = True
        # 获取voice-server所有节点
        nodes = zoo.get_children(self.zk, _path, watcher)
        # 获取zookeeper节点中voice-server的个数
        return len(nodes)

if __name__ == "__main__":
    z = zookServer()
    print z.get_children_len('/sdk/voice/server/info')

 

posted @ 2017-12-20 17:51  reblue520  阅读(608)  评论(0编辑  收藏  举报