├── .gitignore ├── JMX-RESOURCES ├── LICENSE.txt ├── NOTICE.txt ├── README ├── cacti ├── .gitignore └── README ├── check_zookeeper.py ├── ganglia ├── .gitignore ├── README ├── Screenshot.png ├── modpython.conf ├── zookeeper.pyconf └── zookeeper_ganglia.py ├── nagios ├── .gitignore ├── README.txt ├── Screenshot-1.png ├── Screenshot.png ├── hostgroups.cfg ├── services.cfg └── zookeeper.cfg └── test.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | -------------------------------------------------------------------------------- /JMX-RESOURCES: -------------------------------------------------------------------------------- 1 | 2 | Resources for monitoring ZooKeeper using JMX 3 | -------------------------------------------- 4 | 5 | JMX/REST Bridge 6 | --------------- 7 | 8 | http://code.google.com/p/polarrose-jmx-rest-bridge/ 9 | 10 | "Simple Java Web Application that exposes JMX servers through HTTP. This was written so that external tools can easily query JMX attributes of Java applications. More specifically, this was written to allow Cacti to generate fancy graphs of ActiveMQ instances." 11 | 12 | JMXetric 13 | -------- 14 | 15 | http://code.google.com/p/jmxetric/ 16 | 17 | "JMXetric is a 100% java, configurable JVM agent that periodically polls MBean attributes and reports their values to Ganglia." 18 | 19 | jmxquery 20 | -------- 21 | 22 | http://code.google.com/p/jmxquery/ 23 | 24 | "a plugin for nagios to check jmx" 25 | 26 | check_jmx 27 | --------- 28 | 29 | http://exchange.nagios.org/directory/Plugins/Java-Applications-and-Servers/check_jmx/details 30 | 31 | 32 | jmx2snmp 33 | -------- 34 | 35 | http://github.com/tcurdt/jmx2snmp 36 | 37 | Expose application JMX properties via SNMP 38 | 39 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Apache ZooKeeper 2 | Copyright 2009 The Apache Software Foundation 3 | 4 | This product includes software developed at 5 | The Apache Software Foundation (http://www.apache.org/). 6 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Tools and Recipes for ZooKeeper Monitoring 2 | ------------------------------------------ 3 | 4 | UPDATE: This repository have been committed [1] to the ZooKeeper trunk as a contrib. You can find it under src/contrib/monitoring. Please use the ZooKeeper JIRA [2] to submit issues and feature requests. It's going to be a part of the upcoming 3.4.0 release. Thanks. 5 | 6 | [1] https://issues.apache.org/jira/browse/ZOOKEEPER-799 7 | [2] https://issues.apache.org/jira/browse/ZOOKEEPER 8 | 9 | How To Monitor 10 | -------------- 11 | 12 | A ZooKeeper cluster can be monitored in two ways: 13 | 1. by using the 'mntr' 4letterword command 14 | 2. by using JMX to query the MBeans 15 | 16 | This repo contains tools and recipes for monitoring ZooKeeper using the first method. 17 | 18 | Check the file JMX-RESOURCE for some links to resources that could help you monitor a ZooKeeper cluster using the JMX interface. 19 | 20 | Requirements 21 | ------------ 22 | 23 | ZooKeeper 3.4.0 or later or you can apply ZOOKEEPER-744 patch over the latest 3.3.x release. 24 | The server should understand the 'mntr' 4letterword command. 25 | 26 | $ echo 'mntr' | nc localhost 2181 27 | zk_version 3.4.0--1, built on 06/19/2010 15:07 GMT 28 | zk_avg_latency 141 29 | zk_max_latency 1788 30 | zk_min_latency 0 31 | zk_packets_received 385466 32 | zk_packets_sent 435364 33 | zk_outstanding_requests 0 34 | zk_server_state follower 35 | zk_znode_count 5 36 | zk_watch_count 0 37 | zk_ephemerals_count 0 38 | zk_approximate_data_size 41 39 | zk_open_file_descriptor_count 20 40 | zk_max_file_descriptor_count 1024 41 | 42 | Python 2.6 (maybe it works on previous version but it's not tested yet). 43 | 44 | In a nutshell 45 | ------------- 46 | 47 | All you need is check_zookeeper.py It has no external dependencies. 48 | 49 | 50 | *** On Nagios call the script like this: 51 | 52 | ./check_zookeeper.py -o nagios -s "" -k -w -c 53 | 54 | 55 | *** On Cacti define a custom data input method using the script like this: 56 | 57 | ./check_zookeeper.py -o cacti -s "" -k --leader 58 | 59 | -- outputs a single value for the given key fetched from the cluster leader 60 | 61 | OR 62 | 63 | ./check_zookeeper.py -o cacti -s "" -k 64 | 65 | -- outputs multiple values on for each cluster node 66 | ex: localhost_2182:0 localhost_2183:0 localhost_2181:0 localhost_2184:0 localhost_2185:0 67 | 68 | *** On Ganglia: 69 | 70 | install the plugin found in the ganglia/ subfolder OR 71 | 72 | ./check_zookeeper.py -o ganglia -s "" 73 | 74 | it will use gmetric to send zookeeper node status data. 75 | 76 | 77 | Check the subfolders for configuration details and samples for each platform. 78 | 79 | ZooKeeper 4letterwords Commands 80 | ------------------------------- 81 | 82 | http://hadoop.apache.org/zookeeper/docs/current/zookeeperAdmin.html#sc_zkCommands 83 | 84 | -------------------------------------------------------------------------------- /cacti/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/cacti/.gitignore -------------------------------------------------------------------------------- /cacti/README: -------------------------------------------------------------------------------- 1 | 2 | Recipes for ZooKeeper monitoring using Cacti 3 | -------------------------------------------- 4 | 5 | Cacti install guide: https://help.ubuntu.com/community/Cacti 6 | 7 | Cacti Manual: http://www.cacti.net/downloads/docs/html/ 8 | PDF version: http://www.cacti.net/downloads/docs/pdf/manual.pdf 9 | 10 | Check Chapter 16: Simplest Method of Going from Script to Graph 11 | http://www.cacti.net/downloads/docs/html/how_to.html#SCRIPT_TO_GRAPH 12 | 13 | WARNING: I have wrote these instructions while installing and configuring the plugin on my desktop computer running Ubuntu 9.10. I've installed Cacti using apt-get. 14 | 15 | WARNING: I'm going to make the assumption that you know how to work with Cacti and how to setup Data Input Methods for custom scripts. I'm also going to assume that you have already installed Cacti and everything works as expected. 16 | 17 | You can extend the Cacti's data gathering functionality through external scripts. Cacti comes with a number of scripts out of the box wich are localted in the scripts/ directory. 18 | 19 | 20 | The check_zookeeper.py script can be used a custom data input method for Cacti. 21 | 22 | Single value (check cluster status by sending queries to the leader): 23 | --------------------------------------------------------------------- 24 | 25 | python scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k -o cacti --leader 26 | 27 | When you will call the script this way it will about a single value representing the value attached to this . 28 | 29 | 30 | Multiple values (one for each cluster node): 31 | -------------------------------------------- 32 | 33 | python scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k -o cacti 34 | 35 | Output: 36 | localhost_2182:0 localhost_2183:0 localhost_2181:0 localhost_2184:0 localhost_2185:0 37 | 38 | 39 | TBD: Step by step guide 40 | 41 | 42 | -------------------------------------------------------------------------------- /check_zookeeper.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ Check Zookeeper Cluster 3 | 4 | Generic monitoring script that could be used with multiple platforms (Ganglia, Nagios, Cacti). 5 | 6 | It requires ZooKeeper 3.4.0 or greater. The script needs the 'mntr' 4letter word 7 | command (patch ZOOKEEPER-744) that was now commited to the trunk. 8 | The script also works with ZooKeeper 3.3.x but in a limited way. 9 | """ 10 | 11 | import sys 12 | import socket 13 | import logging 14 | import re 15 | import subprocess 16 | 17 | from StringIO import StringIO 18 | from optparse import OptionParser, OptionGroup 19 | 20 | __version__ = (0, 1, 0) 21 | 22 | log = logging.getLogger() 23 | logging.basicConfig(level=logging.ERROR) 24 | 25 | class NagiosHandler(object): 26 | 27 | @classmethod 28 | def register_options(cls, parser): 29 | group = OptionGroup(parser, 'Nagios specific options') 30 | 31 | group.add_option('-w', '--warning', dest='warning') 32 | group.add_option('-c', '--critical', dest='critical') 33 | 34 | parser.add_option_group(group) 35 | 36 | def analyze(self, opts, cluster_stats): 37 | try: 38 | warning = int(opts.warning) 39 | critical = int(opts.critical) 40 | 41 | except (TypeError, ValueError): 42 | print >>sys.stderr, 'Invalid values for "warning" and "critical".' 43 | return 2 44 | 45 | if opts.key is None: 46 | print >>sys.stderr, 'You should specify a key name.' 47 | return 2 48 | 49 | warning_state, critical_state, values = [], [], [] 50 | for host, stats in cluster_stats.items(): 51 | if opts.key in stats: 52 | 53 | value = stats[opts.key] 54 | values.append('%s=%s;%s;%s' % (host, value, warning, critical)) 55 | 56 | if warning >= value > critical or warning <= value < critical: 57 | warning_state.append(host) 58 | 59 | elif (warning < critical and critical <= value) or (warning > critical and critical >= value): 60 | critical_state.append(host) 61 | 62 | values = ' '.join(values) 63 | if critical_state: 64 | print 'Critical "%s" %s!|%s' % (opts.key, ', '.join(critical_state), values) 65 | return 2 66 | 67 | elif warning_state: 68 | print 'Warning "%s" %s!|%s' % (opts.key, ', '.join(warning_state), values) 69 | return 1 70 | 71 | else: 72 | print 'Ok "%s"!|%s' % (opts.key, values) 73 | return 0 74 | 75 | class CactiHandler(object): 76 | 77 | @classmethod 78 | def register_options(cls, parser): 79 | group = OptionGroup(parser, 'Cacti specific options') 80 | 81 | group.add_option('-l', '--leader', dest='leader', 82 | action="store_true", help="only query the cluster leader") 83 | 84 | parser.add_option_group(group) 85 | 86 | def analyze(self, opts, cluster_stats): 87 | if opts.key is None: 88 | print >>sys.stderr, 'The key name is mandatory.' 89 | return 1 90 | 91 | if opts.leader is True: 92 | try: 93 | leader = [x for x in cluster_stats.values() \ 94 | if x.get('zk_server_state', '') == 'leader'][0] 95 | 96 | except IndexError: 97 | print >>sys.stderr, 'No leader found.' 98 | return 3 99 | 100 | if opts.key in leader: 101 | print leader[opts.key] 102 | return 0 103 | 104 | else: 105 | print >>sys.stderr, 'Unknown key: "%s"' % opts.key 106 | return 2 107 | else: 108 | for host, stats in cluster_stats.items(): 109 | if opts.key not in stats: 110 | continue 111 | 112 | host = host.replace(':', '_') 113 | print '%s:%s' % (host, stats[opts.key]), 114 | 115 | 116 | class GangliaHandler(object): 117 | 118 | @classmethod 119 | def register_options(cls, parser): 120 | group = OptionGroup(parser, 'Ganglia specific options') 121 | 122 | group.add_option('-g', '--gmetric', dest='gmetric', 123 | default='/usr/bin/gmetric', help='ganglia gmetric binary '\ 124 | 'location: /usr/bin/gmetric') 125 | 126 | parser.add_option_group(group) 127 | 128 | def call(self, *args, **kwargs): 129 | subprocess.call(*args, **kwargs) 130 | 131 | def analyze(self, opts, cluster_stats): 132 | if len(cluster_stats) != 1: 133 | print >>sys.stderr, 'Only allowed to monitor a single node.' 134 | return 1 135 | 136 | for host, stats in cluster_stats.items(): 137 | for k, v in stats.items(): 138 | try: 139 | self.call([opts.gmetric, '-n', k, '-v', str(int(v)), '-t', 'uint32']) 140 | except (TypeError, ValueError): 141 | pass 142 | 143 | class ZooKeeperServer(object): 144 | 145 | def __init__(self, host='localhost', port='2181', timeout=1): 146 | self._address = (host, int(port)) 147 | self._timeout = timeout 148 | 149 | def get_stats(self): 150 | """ Get ZooKeeper server stats as a map """ 151 | data = self._send_cmd('mntr') 152 | if data: 153 | return self._parse(data) 154 | else: 155 | data = self._send_cmd('stat') 156 | return self._parse_stat(data) 157 | 158 | def _create_socket(self): 159 | return socket.socket() 160 | 161 | def _send_cmd(self, cmd): 162 | """ Send a 4letter word command to the server """ 163 | s = self._create_socket() 164 | s.settimeout(self._timeout) 165 | 166 | s.connect(self._address) 167 | s.send(cmd) 168 | 169 | data = s.recv(2048) 170 | s.close() 171 | 172 | return data 173 | 174 | def _parse(self, data): 175 | """ Parse the output from the 'mntr' 4letter word command """ 176 | h = StringIO(data) 177 | 178 | result = {} 179 | for line in h.readlines(): 180 | try: 181 | key, value = self._parse_line(line) 182 | result[key] = value 183 | except ValueError: 184 | pass # ignore broken lines 185 | 186 | return result 187 | 188 | def _parse_stat(self, data): 189 | """ Parse the output from the 'stat' 4letter word command """ 190 | h = StringIO(data) 191 | 192 | result = {} 193 | 194 | version = h.readline() 195 | if version: 196 | result['zk_version'] = version[version.index(':')+1:].strip() 197 | 198 | # skip all lines until we find the empty one 199 | while h.readline().strip(): pass 200 | 201 | for line in h.readlines(): 202 | m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line) 203 | if m is not None: 204 | result['zk_min_latency'] = int(m.group(1)) 205 | result['zk_avg_latency'] = int(m.group(2)) 206 | result['zk_max_latency'] = int(m.group(3)) 207 | continue 208 | 209 | m = re.match('Received: (\d+)', line) 210 | if m is not None: 211 | result['zk_packets_received'] = int(m.group(1)) 212 | continue 213 | 214 | m = re.match('Sent: (\d+)', line) 215 | if m is not None: 216 | result['zk_packets_sent'] = int(m.group(1)) 217 | continue 218 | 219 | m = re.match('Outstanding: (\d+)', line) 220 | if m is not None: 221 | result['zk_outstanding_requests'] = int(m.group(1)) 222 | continue 223 | 224 | m = re.match('Mode: (.*)', line) 225 | if m is not None: 226 | result['zk_server_state'] = m.group(1) 227 | continue 228 | 229 | m = re.match('Node count: (\d+)', line) 230 | if m is not None: 231 | result['zk_znode_count'] = int(m.group(1)) 232 | continue 233 | 234 | return result 235 | 236 | def _parse_line(self, line): 237 | try: 238 | key, value = map(str.strip, line.split('\t')) 239 | except ValueError: 240 | raise ValueError('Found invalid line: %s' % line) 241 | 242 | if not key: 243 | raise ValueError('The key is mandatory and should not be empty') 244 | 245 | try: 246 | value = int(value) 247 | except (TypeError, ValueError): 248 | pass 249 | 250 | return key, value 251 | 252 | def main(): 253 | opts, args = parse_cli() 254 | 255 | cluster_stats = get_cluster_stats(opts.servers) 256 | if opts.output is None: 257 | dump_stats(cluster_stats) 258 | return 0 259 | 260 | handler = create_handler(opts.output) 261 | if handler is None: 262 | log.error('undefined handler: %s' % opts.output) 263 | sys.exit(1) 264 | 265 | return handler.analyze(opts, cluster_stats) 266 | 267 | def create_handler(name): 268 | """ Return an instance of a platform specific analyzer """ 269 | try: 270 | return globals()['%sHandler' % name.capitalize()]() 271 | except KeyError: 272 | return None 273 | 274 | def get_all_handlers(): 275 | """ Get a list containing all the platform specific analyzers """ 276 | return [NagiosHandler, CactiHandler, GangliaHandler] 277 | 278 | def dump_stats(cluster_stats): 279 | """ Dump cluster statistics in an user friendly format """ 280 | for server, stats in cluster_stats.items(): 281 | print 'Server:', server 282 | 283 | for key, value in stats.items(): 284 | print "%30s" % key, ' ', value 285 | print 286 | 287 | def get_cluster_stats(servers): 288 | """ Get stats for all the servers in the cluster """ 289 | stats = {} 290 | for host, port in servers: 291 | try: 292 | zk = ZooKeeperServer(host, port) 293 | stats["%s:%s" % (host, port)] = zk.get_stats() 294 | 295 | except socket.error, e: 296 | # ignore because the cluster can still work even 297 | # if some servers fail completely 298 | 299 | # this error should be also visible in a variable 300 | # exposed by the server in the statistics 301 | 302 | logging.info('unable to connect to server '\ 303 | '"%s" on port "%s"' % (host, port)) 304 | 305 | return stats 306 | 307 | 308 | def get_version(): 309 | return '.'.join(map(str, __version__)) 310 | 311 | 312 | def parse_cli(): 313 | parser = OptionParser(usage='./check_zookeeper.py ', version=get_version()) 314 | 315 | parser.add_option('-s', '--servers', dest='servers', 316 | help='a list of SERVERS', metavar='SERVERS') 317 | 318 | parser.add_option('-o', '--output', dest='output', 319 | help='output HANDLER: nagios, ganglia, cacti', metavar='HANDLER') 320 | 321 | parser.add_option('-k', '--key', dest='key') 322 | 323 | for handler in get_all_handlers(): 324 | handler.register_options(parser) 325 | 326 | opts, args = parser.parse_args() 327 | 328 | if opts.servers is None: 329 | parser.error('The list of servers is mandatory') 330 | 331 | opts.servers = [s.split(':') for s in opts.servers.split(',')] 332 | 333 | return (opts, args) 334 | 335 | 336 | if __name__ == '__main__': 337 | sys.exit(main()) 338 | 339 | -------------------------------------------------------------------------------- /ganglia/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/ganglia/.gitignore -------------------------------------------------------------------------------- /ganglia/README: -------------------------------------------------------------------------------- 1 | 2 | Recipes for ZooKeeper monitoring using Ganglia 3 | ---------------------------------------------- 4 | 5 | Ganglia Install guide: http://sourceforge.net/apps/trac/ganglia/wiki/Ganglia%203.1.x%20Installation%20and%20Configuration 6 | 7 | Gmond configuration: http://sourceforge.net/apps/trac/ganglia/wiki/Gmond%203.1.x%20General%20Configuration 8 | 9 | WARNING: I have wrote these instructions while installing and configuring the plugin on my desktop computer running Ubuntu 9.10. I've installed Ganglia using apt-get. 10 | 11 | WARNING: I'm going to make the assumption that you know how to work with Ganglia. I'm also going to assume that you have already installed Gangli and everything works as expected. 12 | 13 | You can monitoring ZooKeeper using Ganglia in two ways: 14 | 15 | 1. Using a python module: 16 | 17 | WARNING! The python module only works with Ganglia 3.1.x 18 | 19 | a. enable python modules: you can find instructions in modpython.confg 20 | b. copy zookeeper.pyconf in /etc/ganglia/conf.d/ 21 | c. copy zookeeper_ganglia.py in /usr/lib/ganglia/python_plugins 22 | d. restart the ganglia-monitor 23 | 24 | This is the recommended way! 25 | 26 | 2. OR Using check_zookeeper.py and gmetric: 27 | 28 | Monitoring ZooKeeper using Ganglia is a simple as calling: 29 | 30 | ./check_zookeeper.py -o ganglia -s localhost:2181 31 | 32 | on each of the ZooKeeper cluster nodes. I'm making the assumption that you have already configured gmond and installed gmetric on each node. 33 | 34 | -------------------------------------------------------------------------------- /ganglia/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/ganglia/Screenshot.png -------------------------------------------------------------------------------- /ganglia/modpython.conf: -------------------------------------------------------------------------------- 1 | 2 | /* Update gmond.conf */ 3 | 4 | modules { 5 | module { 6 | name = "python_module" 7 | path = "/usr/lib/ganglia/modpython.so" 8 | params = "/usr/lib/ganglia/python_modules" 9 | } 10 | } 11 | 12 | include ('/etc/ganglia/conf.d/*.pyconf') 13 | 14 | -------------------------------------------------------------------------------- /ganglia/zookeeper.pyconf: -------------------------------------------------------------------------------- 1 | 2 | /* Update /etc/ganglia/gmond.conf with the content of this file. */ 3 | 4 | /* ATTENTION: Change the host and the port to meet your setup. */ 5 | 6 | modules { 7 | module { 8 | name = "zookeeper_ganglia" 9 | language = "python" 10 | param host { value = "127.0.0.1" } 11 | param port { value = 2181 } 12 | } 13 | } 14 | 15 | collection_group { 16 | collect_every = 20 17 | time_threshold = 60 18 | metric { name = "zk_avg_latency" } 19 | metric { name = "zk_max_latency" } 20 | metric { name = "zk_min_latency" } 21 | metric { name = "zk_packets_received" } 22 | metric { name = "zk_packets_sent" } 23 | metric { name = "zk_outstanding_requests" } 24 | metric { name = "zk_znode_count" } 25 | metric { name = "zk_watch_count" } 26 | metric { name = "zk_ephemerals_count" } 27 | metric { name = "zk_approximate_data_size" } 28 | metric { name = "zk_open_file_descriptor_count" } 29 | metric { name = "zk_max_file_descriptor_count" } 30 | metric { name = "zk_followers" } 31 | metric { name = "zk_synced_followers" } 32 | metric { name = "zk_pending_syncs" } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /ganglia/zookeeper_ganglia.py: -------------------------------------------------------------------------------- 1 | """ Python Ganglia Module for ZooKeeper monitoring 2 | 3 | Inspired by: http://gist.github.com/448007 4 | 5 | Copy this file to /usr/lib/ganglia/python_plugins 6 | 7 | """ 8 | 9 | import sys 10 | import socket 11 | import time 12 | import re 13 | import copy 14 | 15 | from StringIO import StringIO 16 | 17 | TIME_BETWEEN_QUERIES = 20 18 | ZK_METRICS = { 19 | 'time' : 0, 20 | 'data' : {} 21 | } 22 | ZK_LAST_METRICS = copy.deepcopy(ZK_METRICS) 23 | 24 | 25 | class ZooKeeperServer(object): 26 | 27 | def __init__(self, host='localhost', port='2181', timeout=1): 28 | self._address = (host, int(port)) 29 | self._timeout = timeout 30 | 31 | def get_stats(self): 32 | """ Get ZooKeeper server stats as a map """ 33 | global ZK_METRICS, ZK_LAST_METRICS 34 | # update cache 35 | ZK_METRICS = { 36 | 'time' : time.time(), 37 | 'data' : {} 38 | } 39 | data = self._send_cmd('mntr') 40 | if data: 41 | parsed_data = self._parse(data) 42 | else: 43 | data = self._send_cmd('stat') 44 | parsed_data = self._parse_stat(data) 45 | ZK_METRICS['data'] = parsed_data 46 | ZK_LAST_METRICS = copy.deepcopy(ZK_METRICS) 47 | return parsed_data 48 | 49 | def _create_socket(self): 50 | return socket.socket() 51 | 52 | def _send_cmd(self, cmd): 53 | """ Send a 4letter word command to the server """ 54 | s = self._create_socket() 55 | s.settimeout(self._timeout) 56 | 57 | s.connect(self._address) 58 | s.send(cmd) 59 | 60 | # read all the data until the socket closes 61 | data = "" 62 | newdata = s.recv(2048) 63 | while newdata: 64 | data += newdata 65 | newdata = s.recv(2048) 66 | 67 | s.close() 68 | 69 | return data 70 | 71 | def _parse(self, data): 72 | """ Parse the output from the 'mntr' 4letter word command """ 73 | h = StringIO(data) 74 | 75 | result = {} 76 | for line in h.readlines(): 77 | try: 78 | key, value = self._parse_line(line) 79 | result[key] = value 80 | except ValueError: 81 | pass # ignore broken lines 82 | 83 | return result 84 | 85 | def _parse_stat(self, data): 86 | """ Parse the output from the 'stat' 4letter word command """ 87 | global ZK_METRICS, ZK_LAST_METRICS 88 | 89 | h = StringIO(data) 90 | 91 | result = {} 92 | 93 | version = h.readline() 94 | if version: 95 | result['zk_version'] = version[version.index(':')+1:].strip() 96 | 97 | # skip all lines until we find the empty one 98 | while h.readline().strip(): pass 99 | 100 | for line in h.readlines(): 101 | m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line) 102 | if m is not None: 103 | result['zk_min_latency'] = int(m.group(1)) 104 | result['zk_avg_latency'] = int(m.group(2)) 105 | result['zk_max_latency'] = int(m.group(3)) 106 | continue 107 | 108 | m = re.match('Received: (\d+)', line) 109 | if m is not None: 110 | cur_packets = int(m.group(1)) 111 | packet_delta = cur_packets - ZK_LAST_METRICS['data'].get('zk_packets_received_total', cur_packets) 112 | time_delta = ZK_METRICS['time'] - ZK_LAST_METRICS['time'] 113 | time_delta = 10.0 114 | try: 115 | result['zk_packets_received_total'] = cur_packets 116 | result['zk_packets_received'] = packet_delta / float(time_delta) 117 | except ZeroDivisionError: 118 | result['zk_packets_received'] = 0 119 | continue 120 | 121 | m = re.match('Sent: (\d+)', line) 122 | if m is not None: 123 | cur_packets = int(m.group(1)) 124 | packet_delta = cur_packets - ZK_LAST_METRICS['data'].get('zk_packets_sent_total', cur_packets) 125 | time_delta = ZK_METRICS['time'] - ZK_LAST_METRICS['time'] 126 | try: 127 | result['zk_packets_sent_total'] = cur_packets 128 | result['zk_packets_sent'] = packet_delta / float(time_delta) 129 | except ZeroDivisionError: 130 | result['zk_packets_sent'] = 0 131 | continue 132 | 133 | m = re.match('Outstanding: (\d+)', line) 134 | if m is not None: 135 | result['zk_outstanding_requests'] = int(m.group(1)) 136 | continue 137 | 138 | m = re.match('Mode: (.*)', line) 139 | if m is not None: 140 | result['zk_server_state'] = m.group(1) 141 | continue 142 | 143 | m = re.match('Node count: (\d+)', line) 144 | if m is not None: 145 | result['zk_znode_count'] = int(m.group(1)) 146 | continue 147 | 148 | return result 149 | 150 | def _parse_line(self, line): 151 | try: 152 | key, value = map(str.strip, line.split('\t')) 153 | except ValueError: 154 | raise ValueError('Found invalid line: %s' % line) 155 | 156 | if not key: 157 | raise ValueError('The key is mandatory and should not be empty') 158 | 159 | try: 160 | value = int(value) 161 | except (TypeError, ValueError): 162 | pass 163 | 164 | return key, value 165 | 166 | def metric_handler(name): 167 | if time.time() - ZK_LAST_METRICS['time'] > TIME_BETWEEN_QUERIES: 168 | zk = ZooKeeperServer(metric_handler.host, metric_handler.port, 5) 169 | try: 170 | metric_handler.info = zk.get_stats() 171 | except Exception, e: 172 | print >>sys.stderr, e 173 | metric_handler.info = {} 174 | 175 | return metric_handler.info.get(name, 0) 176 | 177 | def metric_init(params=None): 178 | params = params or {} 179 | 180 | metric_handler.host = params.get('host', 'localhost') 181 | metric_handler.port = int(params.get('port', 2181)) 182 | metric_handler.timestamp = 0 183 | 184 | metrics = { 185 | 'zk_avg_latency': {'units': 'ms'}, 186 | 'zk_max_latency': {'units': 'ms'}, 187 | 'zk_min_latency': {'units': 'ms'}, 188 | 'zk_packets_received': { 189 | 'units': 'pps', 190 | 'value_type': 'float', 191 | 'format': '%f' 192 | }, 193 | 'zk_packets_sent': { 194 | 'units': 'pps', 195 | 'value_type': 'double', 196 | 'format': '%f' 197 | }, 198 | 'zk_outstanding_requests': {'units': 'connections'}, 199 | 'zk_znode_count': {'units': 'znodes'}, 200 | 'zk_watch_count': {'units': 'watches'}, 201 | 'zk_ephemerals_count': {'units': 'znodes'}, 202 | 'zk_approximate_data_size': {'units': 'bytes'}, 203 | 'zk_open_file_descriptor_count': {'units': 'descriptors'}, 204 | 'zk_max_file_descriptor_count': {'units': 'descriptors'}, 205 | 'zk_followers': {'units': 'nodes'}, 206 | 'zk_synced_followers': {'units': 'nodes'}, 207 | 'zk_pending_syncs': {'units': 'syncs'} 208 | } 209 | metric_handler.descriptors = {} 210 | for name, updates in metrics.iteritems(): 211 | descriptor = { 212 | 'name': name, 213 | 'call_back': metric_handler, 214 | 'time_max': 90, 215 | 'value_type': 'int', 216 | 'units': '', 217 | 'slope': 'both', 218 | 'format': '%d', 219 | 'groups': 'zookeeper', 220 | } 221 | descriptor.update(updates) 222 | metric_handler.descriptors[name] = descriptor 223 | 224 | return metric_handler.descriptors.values() 225 | 226 | def metric_cleanup(): 227 | pass 228 | 229 | 230 | if __name__ == '__main__': 231 | ds = metric_init({'host':'localhost', 'port': '2181'}) 232 | while True: 233 | for d in ds: 234 | print "%s=%s" % (d['name'], metric_handler(d['name'])) 235 | time.sleep(10) 236 | 237 | 238 | -------------------------------------------------------------------------------- /nagios/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/nagios/.gitignore -------------------------------------------------------------------------------- /nagios/README.txt: -------------------------------------------------------------------------------- 1 | 2 | Configuration Recipe for monitoring ZooKeeper using Nagios 3 | ---------------------------------------------------------- 4 | 5 | I will start by making the assumption that you already have an working Nagios install. 6 | 7 | WARNING: I have wrote these instructions while installing and configuring the plugin on my desktop computer running Ubuntu 9.10. I've installed Nagios using apt-get. 8 | 9 | WARNING: You should customize the config files as suggested in order to match your Nagios and Zookeeper install. 10 | 11 | WARNING: This README assumes you know how to configure Nagios and how it works. 12 | 13 | WARNING: You should customize the warning and critical levels on service checks to meet your own needs. 14 | 15 | 1. Install the plugin 16 | 17 | $ cp check_zookeeper.py /usr/lib/nagios/plugins/ 18 | 19 | 2. Install the new commands 20 | 21 | $ cp zookeeper.cfg /etc/nagios-plugins/config 22 | 23 | 3. Update the list of servers in zookeeper.cfg for the command 'check_zookeeper' and update the port for the command 'check_zk_node' (default: 2181) 24 | 25 | 4. Create a virtual host in Nagios used for monitoring the cluster as a whole -OR- Create a hostgroup named 'zookeeper-servers' and add all the zookeeper cluster nodes. 26 | 27 | 5. Define service checks like I have ilustrated bellow or just use the provided definitions. 28 | 29 | define service { 30 | use generic-service 31 | host_name zookeeper-cluster 32 | service_description ... 33 | check_command check_zookeeper!!! 34 | } 35 | 36 | define service { 37 | hostgroup_name zookeeper-servers 38 | use generic-service 39 | service_description ZK_Open_File_Descriptors_Count 40 | check_command check_zk_node!!! 41 | } 42 | 43 | Ex: 44 | 45 | a. check the number of open file descriptors 46 | 47 | define service{ 48 | use generic-service 49 | host_name zookeeper-cluster 50 | service_description ZK_Open_File_Descriptor_Count 51 | check_command check_zookeeper!zk_open_file_descriptor_count!500!800 52 | } 53 | 54 | b. check the number of ephemerals nodes 55 | 56 | define service { 57 | use generic-service 58 | host_name localhost 59 | service_description ZK_Ephemerals_Count 60 | check_command check_zookeeper!zk_ephemerals_count!10000!100000 61 | } 62 | 63 | c. check the number of open file descriptors for each host in the group 64 | 65 | define service { 66 | hostgroup_name zookeeper-servers 67 | use generic-service 68 | service_description ZK_Open_File_Descriptors_Count 69 | check_command check_zk_node!zk_open_file_descriptor_count!500!800 70 | } 71 | 72 | -------------------------------------------------------------------------------- /nagios/Screenshot-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/nagios/Screenshot-1.png -------------------------------------------------------------------------------- /nagios/Screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andreisavu/zookeeper-monitoring/f0aaddd640e3aa1cd0f2984b754b74938e383681/nagios/Screenshot.png -------------------------------------------------------------------------------- /nagios/hostgroups.cfg: -------------------------------------------------------------------------------- 1 | 2 | # A group containing all the ZooKeeper nodes 3 | 4 | define hostgroup { 5 | hostgroup_name zookeeper-servers 6 | alias ZooKeeper Servers 7 | members localhost 8 | } 9 | 10 | 11 | -------------------------------------------------------------------------------- /nagios/services.cfg: -------------------------------------------------------------------------------- 1 | # ZooKeeper Node specific services 2 | 3 | define service { 4 | hostgroup_name zookeeper-servers 5 | use generic-service 6 | service_description ZK_Open_File_Descriptors_Count 7 | check_command check_zk_node!zk_open_file_descriptor_count!500!800 8 | } 9 | 10 | define service { 11 | hostgroup_name zookeeper-servers 12 | use generic-service 13 | service_description ZK_Ephemerals_Count 14 | check_command check_zk_node!zk_ephemerals_count!10000!100000 15 | } 16 | 17 | define service { 18 | hostgroup_name zookeeper-servers 19 | use generic-service 20 | service_description ZK_Avg_Latency 21 | check_command check_zk_node!zk_avg_latency!500!1000 22 | } 23 | 24 | define service { 25 | hostgroup_name zookeeper-servers 26 | use generic-service 27 | service_description ZK_Max_Latency 28 | check_command check_zk_node!zk_max_latency!1000!2000 29 | } 30 | 31 | define service { 32 | hostgroup_name zookeeper-servers 33 | use generic-service 34 | service_description ZK_Min_Latency 35 | check_command check_zk_node!zk_min_latency!500!1000 36 | } 37 | 38 | define service { 39 | hostgroup_name zookeeper-servers 40 | use generic-service 41 | service_description ZK_Outstanding_Requests 42 | check_command check_zk_node!zk_outstanding_requests!20!50 43 | } 44 | 45 | define service { 46 | hostgroup_name zookeeper-servers 47 | use generic-service 48 | service_description ZK_Watch_Count 49 | check_command check_zk_node!zk_watch_count!100!500 50 | } 51 | 52 | -------------------------------------------------------------------------------- /nagios/zookeeper.cfg: -------------------------------------------------------------------------------- 1 | 2 | # 'check_zookeeper' command definition 3 | define command { 4 | command_name check_zookeeper 5 | command_line /usr/lib/nagios/plugins/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183" -o nagios -k '$ARG1$' -w '$ARG2$' -c '$ARG3$' 6 | # ATTENTION: you should update the list of servers defined above 7 | } 8 | 9 | # 'check_zk_node' command definition 10 | define command { 11 | command_name check_zk_node 12 | command_line /usr/lib/nagios/plugins/check_zookeeper.py -s $HOSTADDRESS$:2181 -o nagios -k '$ARG1$' -w '$ARG2$' -c '$ARG3$' 13 | # ATTENTION: you should update the port. default: 2181 14 | } 15 | 16 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | 3 | import unittest 4 | import socket 5 | import sys 6 | 7 | from StringIO import StringIO 8 | 9 | from check_zookeeper import ZooKeeperServer, NagiosHandler, CactiHandler, GangliaHandler 10 | 11 | ZK_MNTR_OUTPUT = """zk_version\t3.4.0--1, built on 06/19/2010 15:07 GMT 12 | zk_avg_latency\t1 13 | zk_max_latency\t132 14 | zk_min_latency\t0 15 | zk_packets_received\t640 16 | zk_packets_sent\t639 17 | zk_outstanding_requests\t0 18 | zk_server_state\tfollower 19 | zk_znode_count\t4 20 | zk_watch_count\t0 21 | zk_ephemerals_count\t0 22 | zk_approximate_data_size\t27 23 | zk_open_file_descriptor_count\t22 24 | zk_max_file_descriptor_count\t1024 25 | """ 26 | 27 | ZK_MNTR_OUTPUT_WITH_BROKEN_LINES = """zk_version\t3.4.0 28 | zk_avg_latency\t23 29 | broken-line 30 | 31 | """ 32 | 33 | ZK_STAT_OUTPUT = """Zookeeper version: 3.3.0-943314, built on 05/11/2010 22:20 GMT 34 | Clients: 35 | /0:0:0:0:0:0:0:1:34564[0](queued=0,recved=1,sent=0) 36 | 37 | Latency min/avg/max: 0/40/121 38 | Received: 11 39 | Sent: 10 40 | Outstanding: 0 41 | Zxid: 0x700000003 42 | Mode: follower 43 | Node count: 4 44 | """ 45 | 46 | class SocketMock(object): 47 | def __init__(self): 48 | self.sent = [] 49 | 50 | def settimeout(self, timeout): 51 | self.timeout = timeout 52 | 53 | def connect(self, address): 54 | self.address = address 55 | 56 | def send(self, data): 57 | self.sent.append(data) 58 | return len(data) 59 | 60 | def recv(self, size): 61 | return ZK_MNTR_OUTPUT[:size] 62 | 63 | def close(self): pass 64 | 65 | class ZK33xSocketMock(SocketMock): 66 | def __init__(self): 67 | SocketMock.__init__(self) 68 | self.got_stat_cmd = False 69 | 70 | def recv(self, size): 71 | if 'stat' in self.sent: 72 | return ZK_STAT_OUTPUT[:size] 73 | else: 74 | return '' 75 | 76 | class UnableToConnectSocketMock(SocketMock): 77 | def connect(self, _): 78 | raise socket.error('[Errno 111] Connection refused') 79 | 80 | def create_server_mock(socket_class): 81 | class ZooKeeperServerMock(ZooKeeperServer): 82 | def _create_socket(self): 83 | return socket_class() 84 | return ZooKeeperServerMock() 85 | 86 | class TestCheckZookeeper(unittest.TestCase): 87 | 88 | def setUp(self): 89 | self.zk = ZooKeeperServer() 90 | 91 | def test_parse_valid_line(self): 92 | key, value = self.zk._parse_line('something\t5') 93 | 94 | self.assertEqual(key, 'something') 95 | self.assertEqual(value, 5) 96 | 97 | def test_parse_line_raises_exception_on_invalid_output(self): 98 | invalid_lines = ['something', '', 'a\tb\tc', '\t1'] 99 | for line in invalid_lines: 100 | self.assertRaises(ValueError, self.zk._parse_line, line) 101 | 102 | def test_parser_on_valid_output(self): 103 | data = self.zk._parse(ZK_MNTR_OUTPUT) 104 | 105 | self.assertEqual(len(data), 14) 106 | self.assertEqual(data['zk_znode_count'], 4) 107 | 108 | def test_parse_should_ignore_invalid_lines(self): 109 | data = self.zk._parse(ZK_MNTR_OUTPUT_WITH_BROKEN_LINES) 110 | 111 | self.assertEqual(len(data), 2) 112 | 113 | def test_parse_stat_valid_output(self): 114 | data = self.zk._parse_stat(ZK_STAT_OUTPUT) 115 | 116 | result = { 117 | 'zk_version' : '3.3.0-943314, built on 05/11/2010 22:20 GMT', 118 | 'zk_min_latency' : 0, 119 | 'zk_avg_latency' : 40, 120 | 'zk_max_latency' : 121, 121 | 'zk_packets_received': 11, 122 | 'zk_packets_sent': 10, 123 | 'zk_server_state': 'follower', 124 | 'zk_znode_count': 4 125 | } 126 | for k, v in result.iteritems(): 127 | self.assertEqual(v, data[k]) 128 | 129 | def test_recv_valid_output(self): 130 | zk = create_server_mock(SocketMock) 131 | 132 | data = zk.get_stats() 133 | self.assertEqual(len(data), 14) 134 | self.assertEqual(data['zk_znode_count'], 4) 135 | 136 | def test_socket_unable_to_connect(self): 137 | zk = create_server_mock(UnableToConnectSocketMock) 138 | 139 | self.assertRaises(socket.error, zk.get_stats) 140 | 141 | def test_use_stat_cmd_if_mntr_is_not_available(self): 142 | zk = create_server_mock(ZK33xSocketMock) 143 | 144 | data = zk.get_stats() 145 | self.assertEqual(data['zk_version'], '3.3.0-943314, built on 05/11/2010 22:20 GMT') 146 | 147 | class HandlerTestCase(unittest.TestCase): 148 | 149 | def setUp(self): 150 | try: 151 | sys._stdout 152 | except: 153 | sys._stdout = sys.stdout 154 | 155 | sys.stdout = StringIO() 156 | 157 | def tearDown(self): 158 | sys.stdout = sys._stdout 159 | 160 | def output(self): 161 | sys.stdout.seek(0) 162 | return sys.stdout.read() 163 | 164 | 165 | class TestNagiosHandler(HandlerTestCase): 166 | 167 | def _analyze(self, w, c, k, stats): 168 | class Opts(object): 169 | warning = w 170 | critical = c 171 | key = k 172 | 173 | return NagiosHandler().analyze(Opts(), {'localhost:2181':stats}) 174 | 175 | def test_ok_status(self): 176 | r = self._analyze(10, 20, 'a', {'a': 5}) 177 | 178 | self.assertEqual(r, 0) 179 | self.assertEqual(self.output(), 'Ok "a"!|localhost:2181=5;10;20\n') 180 | 181 | r = self._analyze(20, 10, 'a', {'a': 30}) 182 | self.assertEqual(r, 0) 183 | 184 | def test_warning_status(self): 185 | r = self._analyze(10, 20, 'a', {'a': 15}) 186 | self.assertEqual(r, 1) 187 | self.assertEqual(self.output(), 188 | 'Warning "a" localhost:2181!|localhost:2181=15;10;20\n') 189 | 190 | r = self._analyze(20, 10, 'a', {'a': 15}) 191 | self.assertEqual(r, 1) 192 | 193 | def test_critical_status(self): 194 | r = self._analyze(10, 20, 'a', {'a': 30}) 195 | self.assertEqual(r, 2) 196 | self.assertEqual(self.output(), 197 | 'Critical "a" localhost:2181!|localhost:2181=30;10;20\n') 198 | 199 | r = self._analyze(20, 10, 'a', {'a': 5}) 200 | self.assertEqual(r, 2) 201 | 202 | def test_check_a_specific_key_on_all_hosts(self): 203 | class Opts(object): 204 | warning = 10 205 | critical = 20 206 | key = 'latency' 207 | 208 | r = NagiosHandler().analyze(Opts(), { 209 | 's1:2181': {'latency': 5}, 210 | 's2:2181': {'latency': 15}, 211 | 's3:2181': {'latency': 35}, 212 | }) 213 | self.assertEqual(r, 2) 214 | self.assertEqual(self.output(), 215 | 'Critical "latency" s3:2181!|s1:2181=5;10;20 '\ 216 | 's3:2181=35;10;20 s2:2181=15;10;20\n') 217 | 218 | class TestCactiHandler(HandlerTestCase): 219 | class Opts(object): 220 | key = 'a' 221 | leader = False 222 | 223 | def __init__(self, leader=False): 224 | self.leader = leader 225 | 226 | def test_output_values_for_all_hosts(self): 227 | r = CactiHandler().analyze(TestCactiHandler.Opts(), { 228 | 's1:2181':{'a':1}, 229 | 's2:2181':{'a':2, 'b':3} 230 | }) 231 | self.assertEqual(r, None) 232 | self.assertEqual(self.output(), 's1_2181:1 s2_2181:2') 233 | 234 | def test_output_single_value_for_leader(self): 235 | r = CactiHandler().analyze(TestCactiHandler.Opts(leader=True), { 236 | 's1:2181': {'a':1, 'zk_server_state': 'leader'}, 237 | 's2:2181': {'a':2} 238 | }) 239 | self.assertEqual(r, 0) 240 | self.assertEqual(self.output(), '1\n') 241 | 242 | 243 | class TestGangliaHandler(unittest.TestCase): 244 | 245 | class TestableGangliaHandler(GangliaHandler): 246 | def __init__(self): 247 | GangliaHandler.__init__(self) 248 | self.cli_calls = [] 249 | 250 | def call(self, cli): 251 | self.cli_calls.append(' '.join(cli)) 252 | 253 | def test_send_single_metric(self): 254 | class Opts(object): 255 | @property 256 | def gmetric(self): return '/usr/bin/gmetric' 257 | opts = Opts() 258 | 259 | h = TestGangliaHandler.TestableGangliaHandler() 260 | h.analyze(opts, {'localhost:2181':{'latency':10}}) 261 | 262 | cmd = "%s -n latency -v 10 -t uint32" % opts.gmetric 263 | assert cmd in h.cli_calls 264 | 265 | if __name__ == '__main__': 266 | unittest.main() 267 | 268 | --------------------------------------------------------------------------------