Zabbix5.0监控Zookeeper
1. 什么是Zookeeper
Zookeeper最早起源于雅虎研究院的一个研究小组。关于“ZooKeeper”这个项目的名字,其实也有一段趣闻。在立项初期,考虑到之前内部很多项目都是使用动物的名字来命名的(例如著名的Pig项目),雅虎的工程师希望给这个项目也取一个动物的名字。顾名思义 zookeeper 就是动物园管理员,他是用来管 hadoop(大象)、Hive(蜜蜂)、pig(小猪)的管理员。
ZooKeeper 是一个典型的分布式数据一致性解决方案,分布式应用程序可以基于 ZooKeeper 实现诸如数据发布/订阅、负载均衡、命名服务、分布式协调/通知、集群管理、Master 选举、分布式锁和分布式队列等功能。
Zookeeper 一个最常用的使用场景就是用于担任服务生产者和服务消费者的注册中心(提供发布订阅服务)。 服务生产者将自己提供的服务注册到Zookeeper中心,服务的消费者在进行服务调用的时候先到Zookeeper中查找服务,获取到服务生产者的详细信息之后,再去调用服务生产者的内容与数据。
2. ZooKeeper重要概念
2.1 重要概念总结
- ZooKeeper 本身就是一个分布式程序(只要半数以上节点存活,ZooKeeper 就能正常服务)。
2…为了保证高可用,最好是以集群形态来部署 ZooKeeper,这样只要集群中大部分机器是可用的(能够容忍一定的机器故障),那么 ZooKeeper 本身仍然是可用的。 - ZooKeeper 将数据保存在内存中,这也就保证了 高吞吐量和低延迟(但是内存限制了能够存储的容量不太大,此限制也是保持znode中存储的数据量较小的进一步原因)。
- ZooKeeper 是高性能的。 在“读”多于“写”的应用程序中尤其地高性能,因为“写”会导致所有的服务器间同步状态。(“读”多于“写”是协调服务的典型场景。)
- ZooKeeper有临时节点的概念。 当创建临时节点的客户端会话一直保持活动,瞬时节点就一直存在。而当会话终结时,瞬时节点被删除。持久节点是指一旦这个ZNode被创建了,除非主动进行ZNode的移除操作,否则这个ZNode将一直保存在Zookeeper上。
- ZooKeeper 底层其实只提供了两个功能:①管理(存储、读取)用户程序提交的数据;②为用户程序提供数据节点监听服务。
2.2 会话
Session 指的是 ZooKeeper 服务器与客户端会话。在 ZooKeeper 中,一个客户端连接是指客户端和服务器之间的一个 TCP 长连接。客户端启动的时候,首先会与服务器建立一个 TCP 连接,从第一次连接建立开始,客户端会话的生命周期也开始了。通过这个连接,客户端能够通过心跳检测与服务器保持有效的会话,也能够向Zookeeper服务器发送请求并接受响应,同时还能够通过该连接接收来自服务器的Watch事件通知。 Session的sessionTimeout值用来设置一个客户端会话的超时时间。当由于服务器压力太大、网络故障或是客户端主动断开连接等各种原因导致客户端连接断开时,只要在sessionTimeout规定的时间内能够重新连接上集群中任意一台服务器,那么之前创建的会话仍然有效。
在为客户端创建会话之前,服务端首先会为每个客户端都分配一个sessionID。由于 sessionID 是 Zookeeper 会话的一个重要标识,许多与会话相关的运行机制都是基于这个 sessionID 的,因此,无论是哪台服务器为客户端分配的 sessionID,都务必保证全局唯一。
2.3 Znode
在 Zookeeper 中,znode 是一个跟 Unix 文件系统路径相似的节点,可以往这个节点存储
或获取数据。
Zookeeper 底层是一套数据结构。这个存储结构是一个树形结构,其上的每一个节点,
我们称之为“znode”
zookeeper 中的数据是按照“树”结构进行存储的。而且 znode 节点还分为 4 中不同的类
型。
每一个 znode 默认能够存储 1MB 的数据(对于记录状态性质的数据来说,够了)
可以使用 zkCli 命令,登录到 zookeeper 上,并通过 ls、create、delete、get、set 等命令
操作这些 znode 节点.
2.4 Znode节点类型
(1)PERSISTENT 持久化节点: 所谓持久节点,是指在节点创建后,就一直存在,直到
有删除操作来主动清除这个节点。否则不会因为创建该节点的客户端会话失效而消失。
(2)PERSISTENT_SEQUENTIAL 持久顺序节点:这类节点的基本特性和上面的节点类
型是一致的。额外的特性是,在 ZK 中,每个父节点会为他的第一级子节点维护一份时序,
会记录每个子节点创建的先后顺序。基于这个特性,在创建子节点的时候,可以设置这个属
性,那么在创建节点过程中,ZK 会自动为给定节点名加上一个数字后缀,作为新的节点名。
这个数字后缀的范围是整型的最大值。在创建节点的时候只需要传入节点 “/test_”,这样
之后,zookeeper 自动会给”test_”后面补充数字。
(3)EPHEMERAL 临时节点:和持久节点不同的是,临时节点的生命周期和客户端会
话绑定。也就是说,如果客户端会话失效,那么这个节点就会自动被清除掉。注意,这里提
到的是会话失效,而非连接断开。另外,在临时节点下面不能创建子节点。
这里还要注意一件事,就是当你客户端会话失效后,所产生的节点也不是一下子就消失
了,也要过一段时间,大概是 10 秒以内,可以试一下,本机操作生成节点,在服务器端用
命令来查看当前的节点数目,你会发现客户端已经 stop,但是产生的节点还在。
(4) EPHEMERAL_SEQUENTIAL 临时自动编号节点:此节点是属于临时节点,不过带
有顺序,客户端会话结束节点就消失。
2.5 Watcher
Watcher,就是事件监听器,Zookeeper允许用户注册一些watcher,并且在一些事件特定触发时,ZooKeeper会将通知发给客户端。
2.6 ACL
Zookeeper采用ACL(AccessControlLists)策略来进行权限控制,类似于 UNIX 文件系统的权限控制。Zookeeper 定义了如下5种权限。
- create:创建子节点的权限
- read:获取节点数据和子节点列表的权限
- write:更新节点的权限
- delete:删除节点的权限
- admin:设置节点ACL的权限
3. ZooKeeper监控指标
3.1 系统监控指标
内存使用量 #ZooKeeper应当完全运行在内存中,不能使用到SWAP。Java Heap大小不能超过可用内存。
Swap使用量 #使用Swap会降低ZooKeeper的性能,设置vm.swappiness = 0
网络带宽占用 #如果发现ZooKeeper性能降低关注下网络带宽占用情况和丢包情况,通常情况下ZooKeeper是20%写入80%读入
磁盘使用量 #ZooKeeper数据目录使用情况需要注意
磁盘I/O #ZooKeeper的磁盘写入是异步的,所以不会存在很大的I/O请求,如果ZooKeeper和其他I/O密集型服务公用应该关注下磁盘I/O情况
3.2 ZooKeeper监控指标
zk_avg/min/max_latency #响应一个客户端请求的时间,建议这个时间大于10个Tick就报警
zk_outstanding_requests #排队请求的数量,当ZooKeeper超过了它的处理能力时,这个值会增大,建议设置报警阀值为10
zk_packets_received #接收到客户端请求的包数量
zk_packets_sent #发送给客户单的包数量,主要是响应和通知
zk_max_file_descriptor_count #最大允许打开的文件数,由ulimit控制
zk_open_file_descriptor_count #打开文件数量,当这个值大于允许值得85%时报警
Mode #运行的角色,如果没有加入集群就是standalone,加入集群式follower或者leader
zk_followers #leader角色才会有这个输出,集合中follower的个数。正常的值应该是集合成员的数量减1
zk_pending_syncs #leader角色才会有这个输出,pending syncs的数量
zk_znode_count #znodes的数量
zk_watch_count #watches的数量
Java Heap Size #ZooKeeper Java进程的
4. 如何监控Zookeeper
4.1 监控思路
zabbix任意版本都可以通过zookeeper的四字命令进行监控
zabbix3.5版本以上新出了adminserver功能,可以通过http访问8080端口获取监控数据
本案例主要是使用通用版本的四字命令监控方式实现
# echo ruok|nc 127.0.0.1 2181
imok
# echo mntr|nc 127.0.0.1 2181
zk_version 3.4.6-1569965, built on 03/16/2020 09:09 GMT
zk_avg_latency 0
zk_max_latency 6
zk_min_latency 0
zk_packets_received 93114
zk_packets_sent 93113
zk_num_alive_connections 4
zk_outstanding_requests 0
zk_server_state leader
zk_znode_count 29
zk_watch_count 0
zk_ephemerals_count 14
zk_approximate_data_size 1087
zk_open_file_descriptor_count 39
zk_max_file_descriptor_count 1000000
zk_followers 4
zk_synced_followers 4
zk_pending_syncs 0
# echo srvr|nc 127.0.0.1 2181
Zookeeper version: 3.4.6-1569965, built on 03/16/2020 09:09 GMT
Latency min/avg/max: 0/0/6
Received: 93121
Sent: 93120
Connections: 4
Outstanding: 0
Zxid: 0x900000020
Mode: leader
Node count: 29
我们决定采用zabbix_sender一次性发送全部监控数据给服务端,将监控项目汇集成一个字典,然后遍历这个字典,将字典中的key:value对通过zabbix_sender的-k和-o参数指定发送出去。
4.2 监控代码
zabbix_zookeeper.py监控代码如下:
#!/usr/bin/env python
""" Check Zookeeper Cluster
zookeeper version should be newer than 3.4.x
# echo mntr|nc 127.0.0.1 2181
zk_version 3.4.6-1569965, built on 02/20/2014 09:09 GMT
zk_avg_latency 0
zk_max_latency 4
zk_min_latency 0
zk_packets_received 84467
zk_packets_sent 84466
zk_num_alive_connections 3
zk_outstanding_requests 0
zk_server_state follower
zk_znode_count 17159
zk_watch_count 2
zk_ephemerals_count 1
zk_approximate_data_size 6666471
zk_open_file_descriptor_count 29
zk_max_file_descriptor_count 102400
# echo ruok|nc 127.0.0.1 2181
imok
"""
import sys
import socket
import re
import subprocess
from StringIO import StringIO
import os
zabbix_sender = '/usr/local/zabbix/bin/zabbix_sender'
zabbix_conf = '/usr/local/zabbix/etc/zabbix_agentd.conf'
send_to_zabbix = 1
############# get zookeeper server status
class ZooKeeperServer(object):
def __init__(self, host='localhost', port='2181', timeout=1):
self._address = (host, int(port))
self._timeout = timeout
self._result = {}
def _create_socket(self):
return socket.socket()
def _send_cmd(self, cmd):
""" Send a 4letter word command to the server """
s = self._create_socket()
s.settimeout(self._timeout)
s.connect(self._address)
s.send(cmd)
data = s.recv(2048)
s.close()
return data
def get_stats(self):
""" Get ZooKeeper server stats as a map """
data_mntr = self._send_cmd('mntr')
data_ruok = self._send_cmd('ruok')
if data_mntr:
result_mntr = self._parse(data_mntr)
if data_ruok:
result_ruok = self._parse_ruok(data_ruok)
self._result = dict(result_mntr.items() + result_ruok.items())
if not self._result.has_key('zk_followers') and not self._result.has_key(
'zk_synced_followers') and not self._result.has_key('zk_pending_syncs'):
##### the tree metrics only exposed on leader role zookeeper server, we just set the followers' to 0
leader_only = {'zk_followers': 0, 'zk_synced_followers': 0, 'zk_pending_syncs': 0}
self._result = dict(result_mntr.items() + result_ruok.items() + leader_only.items())
return self._result
def _parse(self, data):
""" Parse the output from the 'mntr' 4letter word command """
h = StringIO(data)
result = {}
for line in h.readlines():
try:
key, value = self._parse_line(line)
result[key] = value
except ValueError:
pass # ignore broken lines
return result
def _parse_ruok(self, data):
""" Parse the output from the 'ruok' 4letter word command """
h = StringIO(data)
result = {}
ruok = h.readline()
if ruok:
result['zk_server_ruok'] = ruok
return result
def _parse_line(self, line):
try:
key, value = map(str.strip, line.split('\t'))
except ValueError:
raise ValueError('Found invalid line: %s' % line)
if not key:
raise ValueError('The key is mandatory and should not be empty')
try:
value = int(value)
except (TypeError, ValueError):
pass
return key, value
def get_pid(self):
pidarg = '''ps -ef | grep zookeep+ | grep -v grep | awk '{print $2}' '''
pidout = subprocess.Popen(pidarg, shell=True, stdout=subprocess.PIPE)
pid = pidout.stdout.readline().strip('\n')
return pid
def send_to_zabbix(self, metric):
key = "zookeeper.status[" + metric + "]"
if send_to_zabbix > 0:
# print key + ":" + str(self._result[metric])
try:
subprocess.call([zabbix_sender, "-c", zabbix_conf, "-k", key, "-o", str(self._result[metric])],
stdout=FNULL, stderr=FNULL, shell=False)
except OSError, detail:
print "Something went wrong while exectuting zabbix_sender : ", detail
else:
print "Simulation: the following command would be execucted :\n", zabbix_sender, "-c", zabbix_conf, "-k", key, "-o", \
self._result[metric], "\n"
def usage():
"""Display program usage"""
print "\nUsage : ", sys.argv[0], " alive|all"
print "Modes : \n\talive : Return pid of running zookeeper\n\tall : Send zookeeper stats as well"
sys.exit(1)
accepted_modes = ['alive', 'all']
if len(sys.argv) == 2 and sys.argv[1] in accepted_modes:
mode = sys.argv[1]
else:
usage()
zk = ZooKeeperServer()
# print zk.get_stats()
pid = zk.get_pid()
if pid != "" and mode == 'alive':
zk.get_stats()
# print zk._result
FNULL = open(os.devnull, 'w')
for key in zk._result:
zk.send_to_zabbix(key)
FNULL.close()
print pid
else:
print 0
注意,有几个地方需要修改:
- zabbix_sender的目录
- zabbix_conf的目录
- jps的目录,在代码126行
4.3 上传脚本
将脚本上传到zabbix的scripts文件夹下,一般都是放在这个文件夹,没有就新建
#给脚本添加执行权限
chmod +x /etc/zabbix/scripts/zabbix_zookeeper.py
4.4 修改配置文件
vim /etc/zabbix/zabbix_agentd.d/zabbix_zookeeper.conf
UserParameter=zookeeper.status[*],/usr/bin/python /etc/zabbix/scripts/zabbix_zookeeper.py $1
chmod 755 /etc/zabbix/zabbix_agentd.d/zabbix_zookeeper.conf
4.5 重启zabbix_agent
service zabbix-agent2 restart
4.6 制作模板导入
zabbix_zookeeper.xml
<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
<version>5.0</version>
<date>2021-10-19T01:17:06Z</date>
<groups>
<group>
<name>Zabbix servers</name>
</group>
</groups>
<templates>
<template>
<template>Zookeeper</template>
<name>Zookeeper</name>
<groups>
<group>
<name>Zabbix servers</name>
</group>
</groups>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<items>
<item>
<name>zookeeper pid</name>
<key>zookeeper.status[alive]</key>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{last()}=0</expression>
<name>zookeeper is not running</name>
<priority>HIGH</priority>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper approximate data size</name>
<type>TRAP</type>
<key>zookeeper.status[zk_approximate_data_size]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper average latency</name>
<type>TRAP</type>
<key>zookeeper.status[zk_avg_latency]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{last()}>10</expression>
<name>large average latency</name>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper ephemerals count</name>
<type>TRAP</type>
<key>zookeeper.status[zk_ephemerals_count]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper leader's followers</name>
<type>TRAP</type>
<key>zookeeper.status[zk_followers]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper max file descriptor count</name>
<type>TRAP</type>
<key>zookeeper.status[zk_max_file_descriptor_count]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper max latency</name>
<type>TRAP</type>
<key>zookeeper.status[zk_max_latency]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper min latency</name>
<type>TRAP</type>
<key>zookeeper.status[zk_min_latency]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper alive connections</name>
<type>TRAP</type>
<key>zookeeper.status[zk_num_alive_connections]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper opened file descriptor count</name>
<type>TRAP</type>
<key>zookeeper.status[zk_open_file_descriptor_count]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper outstanding requests</name>
<type>TRAP</type>
<key>zookeeper.status[zk_outstanding_requests]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{last()}>10</expression>
<name>big outstanding requests number</name>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper packages received</name>
<type>TRAP</type>
<key>zookeeper.status[zk_packets_received]</key>
<delay>0</delay>
<description>收包数量</description>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper packages sent</name>
<type>TRAP</type>
<key>zookeeper.status[zk_packets_sent]</key>
<delay>0</delay>
<description>发包数据量</description>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper leader's pending syncs</name>
<type>TRAP</type>
<key>zookeeper.status[zk_pending_syncs]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{last()}>10</expression>
<name>big pending syncs</name>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper response checking</name>
<type>TRAP</type>
<key>zookeeper.status[zk_server_ruok]</key>
<delay>0</delay>
<trends>0</trends>
<value_type>CHAR</value_type>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{str(imok)}<>1</expression>
<name>zookeeper is abnormal</name>
<priority>HIGH</priority>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper state role</name>
<type>TRAP</type>
<key>zookeeper.status[zk_server_state]</key>
<delay>0</delay>
<trends>0</trends>
<value_type>CHAR</value_type>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
<triggers>
<trigger>
<expression>{abschange()}>0</expression>
<name>zookeeper state role has been changed</name>
<priority>INFO</priority>
</trigger>
</triggers>
</item>
<item>
<name>zookeeper leader's synced followers</name>
<type>TRAP</type>
<key>zookeeper.status[zk_synced_followers]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper version</name>
<type>TRAP</type>
<key>zookeeper.status[zk_version]</key>
<delay>0</delay>
<trends>0</trends>
<value_type>CHAR</value_type>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper watches count</name>
<type>TRAP</type>
<key>zookeeper.status[zk_watch_count]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
<item>
<name>zookeeper znodes count</name>
<type>TRAP</type>
<key>zookeeper.status[zk_znode_count]</key>
<delay>0</delay>
<applications>
<application>
<name>ZooKeeper Status</name>
</application>
</applications>
</item>
</items>
</template>
</templates>
<triggers>
<trigger>
<expression>{Zookeeper:zookeeper.status[zk_open_file_descriptor_count].last()} > {Zookeeper:zookeeper.status[zk_max_file_descriptor_count].last()}*0.85</expression>
<name>large file descriptor used</name>
</trigger>
</triggers>
<graphs>
<graph>
<name>ZooKeeper Alive Connections</name>
<graph_items>
<graph_item>
<color>1A7C11</color>
<item>
<host>Zookeeper</host>
<key>zookeeper.status[zk_num_alive_connections]</key>
</item>
</graph_item>
</graph_items>
</graph>
<graph>
<name>ZooKeeper Latency</name>
<graph_items>
<graph_item>
<color>1A7C11</color>
<item>
<host>Zookeeper</host>
<key>zookeeper.status[zk_avg_latency]</key>
</item>
</graph_item>
</graph_items>
</graph>
</graphs>
</zabbix_export>