check_zookeeper.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. #! /usr/bin/env python
  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. # http://www.apache.org/licenses/LICENSE-2.0
  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. """ Check Zookeeper Cluster
  16. Generic monitoring script that could be used with multiple platforms (Ganglia, Nagios, Cacti).
  17. It requires ZooKeeper 3.4.0 or greater. The script needs the 'mntr' 4letter word
  18. command (patch ZOOKEEPER-744) that was now committed to the trunk.
  19. The script also works with ZooKeeper 3.3.x but in a limited way.
  20. """
  21. import sys
  22. import socket
  23. import logging
  24. import re
  25. import subprocess
  26. from StringIO import StringIO
  27. from optparse import OptionParser, OptionGroup
  28. __version__ = (0, 1, 0)
  29. log = logging.getLogger()
  30. logging.basicConfig(level=logging.ERROR)
  31. class NagiosHandler(object):
  32. @classmethod
  33. def register_options(cls, parser):
  34. group = OptionGroup(parser, 'Nagios specific options')
  35. group.add_option('-w', '--warning', dest='warning')
  36. group.add_option('-c', '--critical', dest='critical')
  37. parser.add_option_group(group)
  38. def analyze(self, opts, cluster_stats):
  39. try:
  40. warning = int(opts.warning)
  41. critical = int(opts.critical)
  42. except (TypeError, ValueError):
  43. print >>sys.stderr, 'Invalid values for "warning" and "critical".'
  44. return 2
  45. if opts.key is None:
  46. print >>sys.stderr, 'You should specify a key name.'
  47. return 2
  48. warning_state, critical_state, values = [], [], []
  49. for host, stats in cluster_stats.items():
  50. if opts.key in stats:
  51. value = stats[opts.key]
  52. values.append('%s=%s;%s;%s' % (host, value, warning, critical))
  53. if warning >= value > critical or warning <= value < critical:
  54. warning_state.append(host)
  55. elif (warning < critical and critical <= value) or (warning > critical and critical >= value):
  56. critical_state.append(host)
  57. if not values:
  58. # Zookeeper may be down, not serving requests or we may have a bad configuration
  59. print 'Critical, %s not found' % opts.key
  60. return 2
  61. values = ' '.join(values)
  62. if critical_state:
  63. print 'Critical "%s" %s!|%s' % (opts.key, ', '.join(critical_state), values)
  64. return 2
  65. elif warning_state:
  66. print 'Warning "%s" %s!|%s' % (opts.key, ', '.join(warning_state), values)
  67. return 1
  68. else:
  69. print 'Ok "%s"!|%s' % (opts.key, values)
  70. return 0
  71. class CactiHandler(object):
  72. @classmethod
  73. def register_options(cls, parser):
  74. group = OptionGroup(parser, 'Cacti specific options')
  75. group.add_option('-l', '--leader', dest='leader',
  76. action="store_true", help="only query the cluster leader")
  77. parser.add_option_group(group)
  78. def analyze(self, opts, cluster_stats):
  79. if opts.key is None:
  80. print >>sys.stderr, 'The key name is mandatory.'
  81. return 1
  82. if opts.leader is True:
  83. try:
  84. leader = [x for x in cluster_stats.values() \
  85. if x.get('zk_server_state', '') == 'leader'][0]
  86. except IndexError:
  87. print >>sys.stderr, 'No leader found.'
  88. return 3
  89. if opts.key in leader:
  90. print leader[opts.key]
  91. return 0
  92. else:
  93. print >>sys.stderr, 'Unknown key: "%s"' % opts.key
  94. return 2
  95. else:
  96. for host, stats in cluster_stats.items():
  97. if opts.key not in stats:
  98. continue
  99. host = host.replace(':', '_')
  100. print '%s:%s' % (host, stats[opts.key]),
  101. class GangliaHandler(object):
  102. @classmethod
  103. def register_options(cls, parser):
  104. group = OptionGroup(parser, 'Ganglia specific options')
  105. group.add_option('-g', '--gmetric', dest='gmetric',
  106. default='/usr/bin/gmetric', help='ganglia gmetric binary '\
  107. 'location: /usr/bin/gmetric')
  108. parser.add_option_group(group)
  109. def call(self, *args, **kwargs):
  110. subprocess.call(*args, **kwargs)
  111. def analyze(self, opts, cluster_stats):
  112. if len(cluster_stats) != 1:
  113. print >>sys.stderr, 'Only allowed to monitor a single node.'
  114. return 1
  115. for host, stats in cluster_stats.items():
  116. for k, v in stats.items():
  117. try:
  118. self.call([opts.gmetric, '-n', k, '-v', str(int(v)), '-t', 'uint32'])
  119. except (TypeError, ValueError):
  120. pass
  121. class ZooKeeperServer(object):
  122. def __init__(self, host='localhost', port='2181', timeout=1):
  123. self._address = (host, int(port))
  124. self._timeout = timeout
  125. def get_stats(self):
  126. """ Get ZooKeeper server stats as a map """
  127. data = self._send_cmd('mntr')
  128. stat = self._parse_stat(self._send_cmd('stat'))
  129. if data:
  130. mntr = self._parse(data)
  131. missing = ['zk_zxid', 'zk_zxid_counter', 'zk_zxid_epoch']
  132. for m in missing:
  133. if m in stat:
  134. mntr[m] = stat[m]
  135. return mntr
  136. else:
  137. return stat
  138. def _create_socket(self):
  139. return socket.socket()
  140. def _send_cmd(self, cmd):
  141. """ Send a 4letter word command to the server """
  142. s = self._create_socket()
  143. s.settimeout(self._timeout)
  144. s.connect(self._address)
  145. s.send(cmd)
  146. data = s.recv(2048)
  147. s.close()
  148. return data
  149. def _parse(self, data):
  150. """ Parse the output from the 'mntr' 4letter word command """
  151. h = StringIO(data)
  152. result = {}
  153. for line in h.readlines():
  154. try:
  155. key, value = self._parse_line(line)
  156. result[key] = value
  157. except ValueError:
  158. pass # ignore broken lines
  159. return result
  160. def _parse_stat(self, data):
  161. """ Parse the output from the 'stat' 4letter word command """
  162. h = StringIO(data)
  163. result = {}
  164. version = h.readline()
  165. if version:
  166. result['zk_version'] = version[version.index(':')+1:].strip()
  167. # skip all lines until we find the empty one
  168. while h.readline().strip(): pass
  169. for line in h.readlines():
  170. m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line)
  171. if m is not None:
  172. result['zk_min_latency'] = int(m.group(1))
  173. result['zk_avg_latency'] = int(m.group(2))
  174. result['zk_max_latency'] = int(m.group(3))
  175. continue
  176. m = re.match('Received: (\d+)', line)
  177. if m is not None:
  178. result['zk_packets_received'] = int(m.group(1))
  179. continue
  180. m = re.match('Sent: (\d+)', line)
  181. if m is not None:
  182. result['zk_packets_sent'] = int(m.group(1))
  183. continue
  184. m = re.match('Alive connections: (\d+)', line)
  185. if m is not None:
  186. result['zk_num_alive_connections'] = int(m.group(1))
  187. continue
  188. m = re.match('Outstanding: (\d+)', line)
  189. if m is not None:
  190. result['zk_outstanding_requests'] = int(m.group(1))
  191. continue
  192. m = re.match('Mode: (.*)', line)
  193. if m is not None:
  194. result['zk_server_state'] = m.group(1)
  195. continue
  196. m = re.match('Node count: (\d+)', line)
  197. if m is not None:
  198. result['zk_znode_count'] = int(m.group(1))
  199. continue
  200. m = re.match('Watch count: (\d+)', line)
  201. if m is not None:
  202. result['zk_watch_count'] = int(m.group(1))
  203. continue
  204. m = re.match('Ephemerals count: (\d+)', line)
  205. if m is not None:
  206. result['zk_ephemerals_count'] = int(m.group(1))
  207. continue
  208. m = re.match('Approximate data size: (\d+)', line)
  209. if m is not None:
  210. result['zk_approximate_data_size'] = int(m.group(1))
  211. continue
  212. m = re.match('Open file descriptor count: (\d+)', line)
  213. if m is not None:
  214. result['zk_open_file_descriptor_count'] = int(m.group(1))
  215. continue
  216. m = re.match('Max file descriptor count: (\d+)', line)
  217. if m is not None:
  218. result['zk_max_file_descriptor_count'] = int(m.group(1))
  219. continue
  220. m = re.match('Zxid: (0x[0-9a-fA-F]+)', line)
  221. if m is not None:
  222. result['zk_zxid'] = m.group(1)
  223. result['zk_zxid_counter'] = int(m.group(1), 16) & int('0xffffffff', 16) # lower 32 bits
  224. result['zk_zxid_epoch'] = int(m.group(1), 16) >>32 # high 32 bits
  225. continue
  226. m = re.match('Proposal sizes last/min/max: (\d+)/(\d+)/(\d+)', line)
  227. if m is not None:
  228. result['zk_last_proposal_size'] = int(m.group(1))
  229. result['zk_min_proposal_size'] = int(m.group(2))
  230. result['zk_max_proposal_size'] = int(m.group(3))
  231. continue
  232. return result
  233. def _parse_line(self, line):
  234. try:
  235. key, value = map(str.strip, line.split('\t'))
  236. except ValueError:
  237. raise ValueError('Found invalid line: %s' % line)
  238. if not key:
  239. raise ValueError('The key is mandatory and should not be empty')
  240. for typ in [int, float]:
  241. try:
  242. value = typ(value)
  243. break
  244. except (TypeError, ValueError):
  245. pass
  246. return key, value
  247. def main():
  248. opts, args = parse_cli()
  249. cluster_stats = get_cluster_stats(opts.servers)
  250. if opts.output is None:
  251. dump_stats(cluster_stats)
  252. return 0
  253. handler = create_handler(opts.output)
  254. if handler is None:
  255. log.error('undefined handler: %s' % opts.output)
  256. sys.exit(1)
  257. return handler.analyze(opts, cluster_stats)
  258. def create_handler(name):
  259. """ Return an instance of a platform specific analyzer """
  260. try:
  261. return globals()['%sHandler' % name.capitalize()]()
  262. except KeyError:
  263. return None
  264. def get_all_handlers():
  265. """ Get a list containing all the platform specific analyzers """
  266. return [NagiosHandler, CactiHandler, GangliaHandler]
  267. def dump_stats(cluster_stats):
  268. """ Dump cluster statistics in an user friendly format """
  269. for server, stats in cluster_stats.items():
  270. print 'Server:', server
  271. for key, value in stats.items():
  272. print "%30s" % key, ' ', value
  273. print
  274. def get_cluster_stats(servers):
  275. """ Get stats for all the servers in the cluster """
  276. stats = {}
  277. for host, port in servers:
  278. try:
  279. zk = ZooKeeperServer(host, port)
  280. stats["%s:%s" % (host, port)] = zk.get_stats()
  281. except socket.error, e:
  282. # ignore because the cluster can still work even
  283. # if some servers fail completely
  284. # this error should be also visible in a variable
  285. # exposed by the server in the statistics
  286. logging.info('unable to connect to server '\
  287. '"%s" on port "%s"' % (host, port))
  288. return stats
  289. def get_version():
  290. return '.'.join(map(str, __version__))
  291. def parse_cli():
  292. parser = OptionParser(usage='./check_zookeeper.py <options>', version=get_version())
  293. parser.add_option('-s', '--servers', dest='servers',
  294. help='a list of SERVERS', metavar='SERVERS')
  295. parser.add_option('-o', '--output', dest='output',
  296. help='output HANDLER: nagios, ganglia, cacti', metavar='HANDLER')
  297. parser.add_option('-k', '--key', dest='key')
  298. for handler in get_all_handlers():
  299. handler.register_options(parser)
  300. opts, args = parser.parse_args()
  301. if opts.servers is None:
  302. parser.error('The list of servers is mandatory')
  303. opts.servers = [s.split(':') for s in opts.servers.split(',')]
  304. return (opts, args)
  305. if __name__ == '__main__':
  306. sys.exit(main())