From commits-return-6789-archive-asf-public=cust-asf.ponee.io@zookeeper.apache.org Mon Aug 6 14:14:16 2018 Return-Path: X-Original-To: archive-asf-public@cust-asf.ponee.io Delivered-To: archive-asf-public@cust-asf.ponee.io Received: from mail.apache.org (hermes.apache.org [140.211.11.3]) by mx-eu-01.ponee.io (Postfix) with SMTP id A0BB81807BD for ; Mon, 6 Aug 2018 14:14:13 +0200 (CEST) Received: (qmail 54831 invoked by uid 500); 6 Aug 2018 12:14:12 -0000 Mailing-List: contact commits-help@zookeeper.apache.org; run by ezmlm Precedence: bulk List-Help: List-Unsubscribe: List-Post: List-Id: Reply-To: dev@zookeeper.apache.org Delivered-To: mailing list commits@zookeeper.apache.org Received: (qmail 52781 invoked by uid 99); 6 Aug 2018 12:14:10 -0000 Received: from git1-us-west.apache.org (HELO git1-us-west.apache.org) (140.211.11.23) by apache.org (qpsmtpd/0.29) with ESMTP; Mon, 06 Aug 2018 12:14:10 +0000 Received: by git1-us-west.apache.org (ASF Mail Server at git1-us-west.apache.org, from userid 33) id B8E28DFF92; Mon, 6 Aug 2018 12:14:10 +0000 (UTC) Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit From: andor@apache.org To: commits@zookeeper.apache.org Date: Mon, 06 Aug 2018 12:14:27 -0000 Message-Id: In-Reply-To: <23d59816fc864cdcaa333309761a6f23@git.apache.org> References: <23d59816fc864cdcaa333309761a6f23@git.apache.org> X-Mailer: ASF-Git Admin Mailer Subject: [18/45] zookeeper git commit: ZOOKEEPER-3030: MAVEN MIGRATION - Step 1.3 - move contrib directories http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/webapp/org/apache/zookeeper/graph/resources/yui-min.js ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/webapp/org/apache/zookeeper/graph/resources/yui-min.js b/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/webapp/org/apache/zookeeper/graph/resources/yui-min.js new file mode 100644 index 0000000..55f017d --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-loggraph/src/main/webapp/org/apache/zookeeper/graph/resources/yui-min.js @@ -0,0 +1,12 @@ +/* +Copyright (c) 2010, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.html +version: 3.1.0 +build: 2026 +*/ +if(typeof YUI==="undefined"){var YUI=function(F,E,D,C,A){var B=this,J=arguments,I,G=J.length,H=(typeof YUI_config!=="undefined")&&YUI_config;if(!(B instanceof YUI)){return new YUI(F,E,D,C,A);}else{B._init();if(H){B._config(H);}for(I=0;I-1){M="3.0.0";}YUI.prototype={_config:function(Y){Y=Y||{};var T,V,W,U=this.config,X=U.modules,S=U.groups;for(V in Y){T=Y[V];if(X&&V=="modules"){for(W in T){X[W]=T[W];}}else{if(S&&V=="groups"){for(W in T){S[W]=T[W];}}else{if(V=="win"){U[V]=T.contentWindow||T;U.doc=U[V].document;}else{U[V]=T;}}}}},_init:function(){var U,V=this,S=YUI.Env,T=V.Env;V.version=M;if(!T){V.Env={mods:{},base:K,cdn:K+M+"/build/",bootstrapped:false,_idx:0,_used:{},_attached:{},_yidx:0,_uidx:0,_guidp:"y",_loaded:{},getBase:function(c,a){var W,X,Z,d,Y;X=(R&&R.getElementsByTagName("script"))||[];for(Z=0;ZJ)?H[J]:true;}}return L;};F.indexOf=(D.indexOf)?function(G,H){return D.indexOf.call(G,H);}:function(G,I){for(var H=0;H-1);};E.owns=F;E.each=function(K,J,L,I){var H=L||B,G;for(G in K){if(I||F(K,G)){J.call(H,K[G],G,K);}}return B;};E.some=function(K,J,L,I){var H=L||B,G;for(G in K){if(I||F(K,G)){if(J.call(H,K[G],G,K)){return true;}}}return false;};E.getValue=function(K,J){if(!B.Lang.isObject(K)){return D;}var H,I=B.Array(J),G=I. length;for(H=0;K!==D&&H=0){for(G=0;H!==D&&G0){C=D(I);if(C){return C;}else{E=I.lastIndexOf("-");if(E>=0){I=I.substring(0,E);if(E>=2&&I.charAt(E-2)==="-"){I=I.substring(0,E-2);}}else{break;}}}}return"";}});},"3.1.0",{requires:["yui-base"]});YUI.add("yui-log",function(A){(function(){var E,D=A,F="yui:log",B="undefined",C={debug:1,info:1,warn:1,error:1};D.log=function(I,Q,G,O){var K,N,L,J,M,H=D,P=H.config;if(P.debug){if(G){N=P.logExclude;L=P.logInclude;if(L&&!(G in L)){K=1;}else{if(N&&(G in N)){K=1;}}}if(!K){if(P.useBrowserConsole){J=(G)?G+": "+I:I;if(H.Lang.isFunction(P.logFn)){P.logFn(I,Q,G);}else{if(typeof console!=B&&console.log){M=(Q&&console[Q]&&(Q in C))?Q:"log";console[M](J);}else{if(typeof opera!=B){opera.postError(J);}}}}if(H.fire&&!O){i f(!E){H.publish(F,{broadcast:2});E=1;}H.fire(F,{msg:I,cat:Q,src:G});}}}return H;};D.message=function(){return D.log.apply(D,arguments);};})();},"3.1.0",{requires:["yui-base"]});YUI.add("yui-later",function(A){(function(){var B=A.Lang,C=function(K,E,L,G,H){K=K||0;E=E||{};var F=L,J=A.Array(G),I,D;if(B.isString(L)){F=E[L];}if(!F){}I=function(){F.apply(E,J);};D=(H)?setInterval(I,K):setTimeout(I,K);return{id:D,interval:H,cancel:function(){if(this.interval){clearInterval(D);}else{clearTimeout(D);}}};};A.later=C;B.later=C;})();},"3.1.0",{requires:["yui-base"]});YUI.add("yui-throttle",function(Y){ +/* Based on work by Simon Willison: http://gist.github.com/292562 */ +var throttle=function(fn,ms){ms=(ms)?ms:(Y.config.throttleTime||150);if(ms===-1){return(function(){fn.apply(null,arguments);});}var last=(new Date()).getTime();return(function(){var now=(new Date()).getTime();if(now-last>ms){last=now;fn.apply(null,arguments);}});};Y.throttle=throttle;},"3.1.0",{requires:["yui-base"]});YUI.add("yui",function(A){},"3.1.0",{use:["yui-base","get","intl-base","yui-log","yui-later","yui-throttle"]}); \ No newline at end of file http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/JMX-RESOURCES ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/JMX-RESOURCES b/zookeeper-contrib/zookeeper-contrib-monitoring/JMX-RESOURCES new file mode 100644 index 0000000..1d1aa98 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/JMX-RESOURCES @@ -0,0 +1,38 @@ + +Resources for monitoring ZooKeeper using JMX +-------------------------------------------- + +JMX/REST Bridge +--------------- + +http://code.google.com/p/polarrose-jmx-rest-bridge/ + +"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." + +JMXetric +-------- + +http://code.google.com/p/jmxetric/ + +"JMXetric is a 100% java, configurable JVM agent that periodically polls MBean attributes and reports their values to Ganglia." + +jmxquery +-------- + +http://code.google.com/p/jmxquery/ + +"a plugin for nagios to check jmx" + +check_jmx +--------- + +http://exchange.nagios.org/directory/Plugins/Java-Applications-and-Servers/check_jmx/details + + +jmx2snmp +-------- + +http://github.com/tcurdt/jmx2snmp + +Expose application JMX properties via SNMP + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/README ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/README b/zookeeper-contrib/zookeeper-contrib-monitoring/README new file mode 100644 index 0000000..81521fc --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/README @@ -0,0 +1,85 @@ + +Tools and Recipes for ZooKeeper Monitoring +------------------------------------------ + +How To Monitor +-------------- + +A ZooKeeper cluster can be monitored in two ways: + 1. by using the 'mntr' 4letterword command + 2. by using JMX to query the MBeans + +This repo contains tools and recipes for monitoring ZooKeeper using the first method. + +Check the file JMX-RESOURCE for some links to resources that could help you monitor a ZooKeeper cluster using the JMX interface. + +Requirements +------------ + +ZooKeeper 3.4.0 or later or you can apply ZOOKEEPER-744 patch over the latest 3.3.x release. +The server should understand the 'mntr' 4letterword command. + +$ echo 'mntr' | nc localhost 2181 +zk_version 3.4.0--1, built on 06/19/2010 15:07 GMT +zk_avg_latency 141 +zk_max_latency 1788 +zk_min_latency 0 +zk_packets_received 385466 +zk_packets_sent 435364 +zk_num_alive_connections 1 +zk_outstanding_requests 0 +zk_server_state follower +zk_znode_count 5 +zk_watch_count 0 +zk_ephemerals_count 0 +zk_approximate_data_size 41 +zk_open_file_descriptor_count 20 +zk_max_file_descriptor_count 1024 + +Python 2.6 (maybe it works on previous version but it's not tested yet). + +In a nutshell +------------- + +All you need is check_zookeeper.py It has no external dependencies. + + +*** On Nagios call the script like this: + +./check_zookeeper.py -o nagios -s "" -k -w -c + + +*** On Cacti define a custom data input method using the script like this: + +./check_zookeeper.py -o cacti -s "" -k --leader + +-- outputs a single value for the given key fetched from the cluster leader + +OR + +./check_zookeeper.py -o cacti -s "" -k + +-- outputs multiple values on for each cluster node +ex: localhost_2182:0 localhost_2183:0 localhost_2181:0 localhost_2184:0 localhost_2185:0 + +*** On Ganglia: + +install the plugin found in the ganglia/ subfolder OR + +./check_zookeeper.py -o ganglia -s "" + +it will use gmetric to send zookeeper node status data. + + +Check the subfolders for configuration details and samples for each platform. + +License +------- + +Apache License 2.0 or later. + +ZooKeeper 4letterwords Commands +------------------------------- + +http://zookeeper.apache.org/docs/current/zookeeperAdmin.html#sc_zkCommands + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/cacti/README ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/cacti/README b/zookeeper-contrib/zookeeper-contrib-monitoring/cacti/README new file mode 100644 index 0000000..8188723 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/cacti/README @@ -0,0 +1,56 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Recipes for ZooKeeper monitoring using Cacti +-------------------------------------------- + +Cacti install guide: https://help.ubuntu.com/community/Cacti + +Cacti Manual: http://www.cacti.net/downloads/docs/html/ +PDF version: http://www.cacti.net/downloads/docs/pdf/manual.pdf + +Check Chapter 16: Simplest Method of Going from Script to Graph + http://www.cacti.net/downloads/docs/html/how_to.html#SCRIPT_TO_GRAPH + +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. + +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. + +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. + + +The check_zookeeper.py script can be used a custom data input method for Cacti. + +Single value (check cluster status by sending queries to the leader): +--------------------------------------------------------------------- + +python scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k -o cacti --leader + +When you will call the script this way it will about a single value representing the value attached to this . + + +Multiple values (one for each cluster node): +-------------------------------------------- + +python scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k -o cacti + +Output: +localhost_2182:0 localhost_2183:0 localhost_2181:0 localhost_2184:0 localhost_2185:0 + + +TBD: Step by step guide + + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/check_zookeeper.py ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/check_zookeeper.py b/zookeeper-contrib/zookeeper-contrib-monitoring/check_zookeeper.py new file mode 100755 index 0000000..cff6a1f --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/check_zookeeper.py @@ -0,0 +1,407 @@ +#! /usr/bin/env python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Check Zookeeper Cluster + +Generic monitoring script that could be used with multiple platforms (Ganglia, Nagios, Cacti). + +It requires ZooKeeper 3.4.0 or greater. The script needs the 'mntr' 4letter word +command (patch ZOOKEEPER-744) that was now commited to the trunk. +The script also works with ZooKeeper 3.3.x but in a limited way. +""" + +import sys +import socket +import logging +import re +import subprocess + +from StringIO import StringIO +from optparse import OptionParser, OptionGroup + +__version__ = (0, 1, 0) + +log = logging.getLogger() +logging.basicConfig(level=logging.ERROR) + +class NagiosHandler(object): + + @classmethod + def register_options(cls, parser): + group = OptionGroup(parser, 'Nagios specific options') + + group.add_option('-w', '--warning', dest='warning') + group.add_option('-c', '--critical', dest='critical') + + parser.add_option_group(group) + + def analyze(self, opts, cluster_stats): + try: + warning = int(opts.warning) + critical = int(opts.critical) + + except (TypeError, ValueError): + print >>sys.stderr, 'Invalid values for "warning" and "critical".' + return 2 + + if opts.key is None: + print >>sys.stderr, 'You should specify a key name.' + return 2 + + warning_state, critical_state, values = [], [], [] + for host, stats in cluster_stats.items(): + if opts.key in stats: + + value = stats[opts.key] + values.append('%s=%s;%s;%s' % (host, value, warning, critical)) + + if warning >= value > critical or warning <= value < critical: + warning_state.append(host) + + elif (warning < critical and critical <= value) or (warning > critical and critical >= value): + critical_state.append(host) + + if not values: + # Zookeeper may be down, not serving requests or we may have a bad configuration + print 'Critical, %s not found' % opts.key + return 2 + + values = ' '.join(values) + if critical_state: + print 'Critical "%s" %s!|%s' % (opts.key, ', '.join(critical_state), values) + return 2 + + elif warning_state: + print 'Warning "%s" %s!|%s' % (opts.key, ', '.join(warning_state), values) + return 1 + + else: + print 'Ok "%s"!|%s' % (opts.key, values) + return 0 + +class CactiHandler(object): + + @classmethod + def register_options(cls, parser): + group = OptionGroup(parser, 'Cacti specific options') + + group.add_option('-l', '--leader', dest='leader', + action="store_true", help="only query the cluster leader") + + parser.add_option_group(group) + + def analyze(self, opts, cluster_stats): + if opts.key is None: + print >>sys.stderr, 'The key name is mandatory.' + return 1 + + if opts.leader is True: + try: + leader = [x for x in cluster_stats.values() \ + if x.get('zk_server_state', '') == 'leader'][0] + + except IndexError: + print >>sys.stderr, 'No leader found.' + return 3 + + if opts.key in leader: + print leader[opts.key] + return 0 + + else: + print >>sys.stderr, 'Unknown key: "%s"' % opts.key + return 2 + else: + for host, stats in cluster_stats.items(): + if opts.key not in stats: + continue + + host = host.replace(':', '_') + print '%s:%s' % (host, stats[opts.key]), + + +class GangliaHandler(object): + + @classmethod + def register_options(cls, parser): + group = OptionGroup(parser, 'Ganglia specific options') + + group.add_option('-g', '--gmetric', dest='gmetric', + default='/usr/bin/gmetric', help='ganglia gmetric binary '\ + 'location: /usr/bin/gmetric') + + parser.add_option_group(group) + + def call(self, *args, **kwargs): + subprocess.call(*args, **kwargs) + + def analyze(self, opts, cluster_stats): + if len(cluster_stats) != 1: + print >>sys.stderr, 'Only allowed to monitor a single node.' + return 1 + + for host, stats in cluster_stats.items(): + for k, v in stats.items(): + try: + self.call([opts.gmetric, '-n', k, '-v', str(int(v)), '-t', 'uint32']) + except (TypeError, ValueError): + pass + +class ZooKeeperServer(object): + + def __init__(self, host='localhost', port='2181', timeout=1): + self._address = (host, int(port)) + self._timeout = timeout + + def get_stats(self): + """ Get ZooKeeper server stats as a map """ + data = self._send_cmd('mntr') + stat = self._parse_stat(self._send_cmd('stat')) + if data: + mntr = self._parse(data) + missing = ['zk_zxid', 'zk_zxid_counter', 'zk_zxid_epoch'] + for m in missing: + if m in stat: + mntr[m] = stat[m] + return mntr + else: + return stat + + 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 _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_stat(self, data): + """ Parse the output from the 'stat' 4letter word command """ + h = StringIO(data) + + result = {} + + version = h.readline() + if version: + result['zk_version'] = version[version.index(':')+1:].strip() + + # skip all lines until we find the empty one + while h.readline().strip(): pass + + for line in h.readlines(): + m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line) + if m is not None: + result['zk_min_latency'] = int(m.group(1)) + result['zk_avg_latency'] = int(m.group(2)) + result['zk_max_latency'] = int(m.group(3)) + continue + + m = re.match('Received: (\d+)', line) + if m is not None: + result['zk_packets_received'] = int(m.group(1)) + continue + + m = re.match('Sent: (\d+)', line) + if m is not None: + result['zk_packets_sent'] = int(m.group(1)) + continue + + m = re.match('Alive connections: (\d+)', line) + if m is not None: + result['zk_num_alive_connections'] = int(m.group(1)) + continue + + m = re.match('Outstanding: (\d+)', line) + if m is not None: + result['zk_outstanding_requests'] = int(m.group(1)) + continue + + m = re.match('Mode: (.*)', line) + if m is not None: + result['zk_server_state'] = m.group(1) + continue + + m = re.match('Node count: (\d+)', line) + if m is not None: + result['zk_znode_count'] = int(m.group(1)) + continue + + m = re.match('Watch count: (\d+)', line) + if m is not None: + result['zk_watch_count'] = int(m.group(1)) + continue + + m = re.match('Ephemerals count: (\d+)', line) + if m is not None: + result['zk_ephemerals_count'] = int(m.group(1)) + continue + + m = re.match('Approximate data size: (\d+)', line) + if m is not None: + result['zk_approximate_data_size'] = int(m.group(1)) + continue + + m = re.match('Open file descriptor count: (\d+)', line) + if m is not None: + result['zk_open_file_descriptor_count'] = int(m.group(1)) + continue + + m = re.match('Max file descriptor count: (\d+)', line) + if m is not None: + result['zk_max_file_descriptor_count'] = int(m.group(1)) + continue + + m = re.match('Zxid: (0x[0-9a-fA-F]+)', line) + if m is not None: + result['zk_zxid'] = m.group(1) + result['zk_zxid_counter'] = int(m.group(1), 16) & int('0xffffffff', 16) # lower 32 bits + result['zk_zxid_epoch'] = int(m.group(1), 16) >>32 # high 32 bits + continue + + m = re.match('Proposal sizes last/min/max: (\d+)/(\d+)/(\d+)', line) + if m is not None: + result['zk_last_proposal_size'] = int(m.group(1)) + result['zk_min_proposal_size'] = int(m.group(2)) + result['zk_max_proposal_size'] = int(m.group(3)) + continue + + 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 main(): + opts, args = parse_cli() + + cluster_stats = get_cluster_stats(opts.servers) + if opts.output is None: + dump_stats(cluster_stats) + return 0 + + handler = create_handler(opts.output) + if handler is None: + log.error('undefined handler: %s' % opts.output) + sys.exit(1) + + return handler.analyze(opts, cluster_stats) + +def create_handler(name): + """ Return an instance of a platform specific analyzer """ + try: + return globals()['%sHandler' % name.capitalize()]() + except KeyError: + return None + +def get_all_handlers(): + """ Get a list containing all the platform specific analyzers """ + return [NagiosHandler, CactiHandler, GangliaHandler] + +def dump_stats(cluster_stats): + """ Dump cluster statistics in an user friendly format """ + for server, stats in cluster_stats.items(): + print 'Server:', server + + for key, value in stats.items(): + print "%30s" % key, ' ', value + print + +def get_cluster_stats(servers): + """ Get stats for all the servers in the cluster """ + stats = {} + for host, port in servers: + try: + zk = ZooKeeperServer(host, port) + stats["%s:%s" % (host, port)] = zk.get_stats() + + except socket.error, e: + # ignore because the cluster can still work even + # if some servers fail completely + + # this error should be also visible in a variable + # exposed by the server in the statistics + + logging.info('unable to connect to server '\ + '"%s" on port "%s"' % (host, port)) + + return stats + + +def get_version(): + return '.'.join(map(str, __version__)) + + +def parse_cli(): + parser = OptionParser(usage='./check_zookeeper.py ', version=get_version()) + + parser.add_option('-s', '--servers', dest='servers', + help='a list of SERVERS', metavar='SERVERS') + + parser.add_option('-o', '--output', dest='output', + help='output HANDLER: nagios, ganglia, cacti', metavar='HANDLER') + + parser.add_option('-k', '--key', dest='key') + + for handler in get_all_handlers(): + handler.register_options(parser) + + opts, args = parser.parse_args() + + if opts.servers is None: + parser.error('The list of servers is mandatory') + + opts.servers = [s.split(':') for s in opts.servers.split(',')] + + return (opts, args) + + +if __name__ == '__main__': + sys.exit(main()) + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/README ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/README b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/README new file mode 100644 index 0000000..578adfe --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/README @@ -0,0 +1,48 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Recipes for ZooKeeper monitoring using Ganglia +---------------------------------------------- + +Ganglia Install guide: http://sourceforge.net/apps/trac/ganglia/wiki/Ganglia%203.1.x%20Installation%20and%20Configuration + +Gmond configuration: http://sourceforge.net/apps/trac/ganglia/wiki/Gmond%203.1.x%20General%20Configuration + +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. + +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. + +You can monitoring ZooKeeper using Ganglia in two ways: + +1. Using a python module: + + WARNING! The python module only works with Ganglia 3.1.x + + a. enable python modules: you can find instructions in modpython.confg + b. copy zookeeper.pyconf in /etc/ganglia/conf.d/ + c. copy zookeeper_ganglia.py in /usr/lib/ganglia/python_plugins + d. restart the ganglia-monitor + + This is the recommended way! + +2. OR Using check_zookeeper.py and gmetric: + + Monitoring ZooKeeper using Ganglia is a simple as calling: + + ./check_zookeeper.py -o ganglia -s localhost:2181 + + on each of the ZooKeeper cluster nodes. I'm making the assumption that you have already configured gmond and installed gmetric on each node. + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/Screenshot.png ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/Screenshot.png b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/Screenshot.png new file mode 100644 index 0000000..bc0e41d Binary files /dev/null and b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/Screenshot.png differ http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/modpython.conf ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/modpython.conf b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/modpython.conf new file mode 100644 index 0000000..5cd051a --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/modpython.conf @@ -0,0 +1,28 @@ +/* Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ + +/* Update gmond.conf */ + +modules { + module { + name = "python_module" + path = "/usr/lib/ganglia/modpython.so" + params = "/usr/lib/ganglia/python_modules" + } +} + +include ('/etc/ganglia/conf.d/*.pyconf') + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper.pyconf ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper.pyconf b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper.pyconf new file mode 100644 index 0000000..44acd93 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper.pyconf @@ -0,0 +1,53 @@ +/* Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ + +/* Update /etc/ganglia/gmond.conf with the content of this file. */ + +/* ATTENTION: Change the host and the port to meet your setup. */ + +modules { + module { + name = "zookeeper_ganglia" + language = "python" + param host { value = "127.0.0.1" } + param port { value = 2181 } + } +} + +collection_group { + collect_every = 20 + time_threshold = 60 + metric { name = "zk_avg_latency" } + metric { name = "zk_max_latency" } + metric { name = "zk_min_latency" } + metric { name = "zk_packets_received" } + metric { name = "zk_packets_sent" } + metric { name = "zk_num_alive_connections" } + metric { name = "zk_outstanding_requests" } + metric { name = "zk_znode_count" } + metric { name = "zk_watch_count" } + metric { name = "zk_ephemerals_count" } + metric { name = "zk_approximate_data_size" } + metric { name = "zk_open_file_descriptor_count" } + metric { name = "zk_max_file_descriptor_count" } + metric { name = "zk_followers" } + metric { name = "zk_synced_followers" } + metric { name = "zk_pending_syncs" } + metric { name = "zk_last_proposal_size" } + metric { name = "zk_min_proposal_size" } + metric { name = "zk_max_proposal_size" } +} + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper_ganglia.py ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper_ganglia.py b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper_ganglia.py new file mode 100644 index 0000000..bbb7a8e --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/ganglia/zookeeper_ganglia.py @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Python Ganglia Module for ZooKeeper monitoring + +Inspired by: http://gist.github.com/448007 + +Copy this file to /usr/lib/ganglia/python_plugins + +""" + +import sys +import socket +import time +import re +import copy + +from StringIO import StringIO + +TIME_BETWEEN_QUERIES = 20 +ZK_METRICS = { + 'time' : 0, + 'data' : {} +} +ZK_LAST_METRICS = copy.deepcopy(ZK_METRICS) + + +class ZooKeeperServer(object): + + def __init__(self, host='localhost', port='2181', timeout=1): + self._address = (host, int(port)) + self._timeout = timeout + + def get_stats(self): + """ Get ZooKeeper server stats as a map """ + global ZK_METRICS, ZK_LAST_METRICS + # update cache + ZK_METRICS = { + 'time' : time.time(), + 'data' : {} + } + data = self._send_cmd('mntr') + if data: + parsed_data = self._parse(data) + else: + data = self._send_cmd('stat') + parsed_data = self._parse_stat(data) + ZK_METRICS['data'] = parsed_data + ZK_LAST_METRICS = copy.deepcopy(ZK_METRICS) + return parsed_data + + 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 _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_stat(self, data): + """ Parse the output from the 'stat' 4letter word command """ + global ZK_METRICS, ZK_LAST_METRICS + + h = StringIO(data) + + result = {} + + version = h.readline() + if version: + result['zk_version'] = version[version.index(':')+1:].strip() + + # skip all lines until we find the empty one + while h.readline().strip(): pass + + for line in h.readlines(): + m = re.match('Latency min/avg/max: (\d+)/(\d+)/(\d+)', line) + if m is not None: + result['zk_min_latency'] = int(m.group(1)) + result['zk_avg_latency'] = int(m.group(2)) + result['zk_max_latency'] = int(m.group(3)) + continue + + m = re.match('Received: (\d+)', line) + if m is not None: + cur_packets = int(m.group(1)) + packet_delta = cur_packets - ZK_LAST_METRICS['data'].get('zk_packets_received_total', cur_packets) + time_delta = ZK_METRICS['time'] - ZK_LAST_METRICS['time'] + time_delta = 10.0 + try: + result['zk_packets_received_total'] = cur_packets + result['zk_packets_received'] = packet_delta / float(time_delta) + except ZeroDivisionError: + result['zk_packets_received'] = 0 + continue + + m = re.match('Sent: (\d+)', line) + if m is not None: + cur_packets = int(m.group(1)) + packet_delta = cur_packets - ZK_LAST_METRICS['data'].get('zk_packets_sent_total', cur_packets) + time_delta = ZK_METRICS['time'] - ZK_LAST_METRICS['time'] + try: + result['zk_packets_sent_total'] = cur_packets + result['zk_packets_sent'] = packet_delta / float(time_delta) + except ZeroDivisionError: + result['zk_packets_sent'] = 0 + continue + + m = re.match('Outstanding: (\d+)', line) + if m is not None: + result['zk_outstanding_requests'] = int(m.group(1)) + continue + + m = re.match('Mode: (.*)', line) + if m is not None: + result['zk_server_state'] = m.group(1) + continue + + m = re.match('Node count: (\d+)', line) + if m is not None: + result['zk_znode_count'] = int(m.group(1)) + continue + + 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 metric_handler(name): + if time.time() - ZK_LAST_METRICS['time'] > TIME_BETWEEN_QUERIES: + zk = ZooKeeperServer(metric_handler.host, metric_handler.port, 5) + try: + metric_handler.info = zk.get_stats() + except Exception, e: + print >>sys.stderr, e + metric_handler.info = {} + + return metric_handler.info.get(name, 0) + +def metric_init(params=None): + params = params or {} + + metric_handler.host = params.get('host', 'localhost') + metric_handler.port = int(params.get('port', 2181)) + metric_handler.timestamp = 0 + + metrics = { + 'zk_avg_latency': {'units': 'ms'}, + 'zk_max_latency': {'units': 'ms'}, + 'zk_min_latency': {'units': 'ms'}, + 'zk_packets_received': { + 'units': 'pps', + 'value_type': 'float', + 'format': '%f' + }, + 'zk_packets_sent': { + 'units': 'pps', + 'value_type': 'double', + 'format': '%f' + }, + 'zk_num_alive_connections': {'units': 'connections'}, + 'zk_outstanding_requests': {'units': 'connections'}, + 'zk_znode_count': {'units': 'znodes'}, + 'zk_watch_count': {'units': 'watches'}, + 'zk_ephemerals_count': {'units': 'znodes'}, + 'zk_approximate_data_size': {'units': 'bytes'}, + 'zk_open_file_descriptor_count': {'units': 'descriptors'}, + 'zk_max_file_descriptor_count': {'units': 'descriptors'}, + 'zk_followers': {'units': 'nodes'}, + 'zk_synced_followers': {'units': 'nodes'}, + 'zk_pending_syncs': {'units': 'syncs'}, + 'zk_last_proposal_size': {'units': 'bytes'}, + 'zk_min_proposal_size': {'units': 'bytes'}, + 'zk_max_proposal_size': {'units': 'bytes'} + } + metric_handler.descriptors = {} + for name, updates in metrics.iteritems(): + descriptor = { + 'name': name, + 'call_back': metric_handler, + 'time_max': 90, + 'value_type': 'int', + 'units': '', + 'slope': 'both', + 'format': '%d', + 'groups': 'zookeeper', + } + descriptor.update(updates) + metric_handler.descriptors[name] = descriptor + + return metric_handler.descriptors.values() + +def metric_cleanup(): + pass + + +if __name__ == '__main__': + ds = metric_init({'host':'localhost', 'port': '2181'}) + while True: + for d in ds: + print "%s=%s" % (d['name'], metric_handler(d['name'])) + time.sleep(10) + + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/README.txt ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/README.txt b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/README.txt new file mode 100644 index 0000000..317ae14 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/README.txt @@ -0,0 +1,86 @@ +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +Configuration Recipe for monitoring ZooKeeper using Nagios +---------------------------------------------------------- + +I will start by making the assumption that you already have an working Nagios install. + +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. + +WARNING: You should customize the config files as suggested in order to match your Nagios and Zookeeper install. + +WARNING: This README assumes you know how to configure Nagios and how it works. + +WARNING: You should customize the warning and critical levels on service checks to meet your own needs. + +1. Install the plugin + +$ cp check_zookeeper.py /usr/lib/nagios/plugins/ + +2. Install the new commands + +$ cp zookeeper.cfg /etc/nagios-plugins/config + +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) + +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. + +5. Define service checks like I have ilustrated bellow or just use the provided definitions. + +define service { + use generic-service + host_name zookeeper-cluster + service_description ... + check_command check_zookeeper!!! +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Open_File_Descriptors_Count + check_command check_zk_node!!! +} + +Ex: + +a. check the number of open file descriptors + +define service{ + use generic-service + host_name zookeeper-cluster + service_description ZK_Open_File_Descriptor_Count + check_command check_zookeeper!zk_open_file_descriptor_count!500!800 +} + +b. check the number of ephemerals nodes + +define service { + use generic-service + host_name localhost + service_description ZK_Ephemerals_Count + check_command check_zookeeper!zk_ephemerals_count!10000!100000 +} + +c. check the number of open file descriptors for each host in the group + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Open_File_Descriptors_Count + check_command check_zk_node!zk_open_file_descriptor_count!500!800 +} + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot-1.png ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot-1.png b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot-1.png new file mode 100644 index 0000000..2dc55c5 Binary files /dev/null and b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot-1.png differ http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot.png ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot.png b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot.png new file mode 100644 index 0000000..3219fea Binary files /dev/null and b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/Screenshot.png differ http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/hostgroups.cfg ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/hostgroups.cfg b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/hostgroups.cfg new file mode 100644 index 0000000..ea59a66 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/hostgroups.cfg @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# A group containing all the ZooKeeper nodes + +define hostgroup { + hostgroup_name zookeeper-servers + alias ZooKeeper Servers + members localhost +} + + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/services.cfg ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/services.cfg b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/services.cfg new file mode 100644 index 0000000..dde6ab7 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/services.cfg @@ -0,0 +1,67 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# ZooKeeper Node specific services + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Open_File_Descriptors_Count + check_command check_zk_node!zk_open_file_descriptor_count!500!800 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Ephemerals_Count + check_command check_zk_node!zk_ephemerals_count!10000!100000 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Avg_Latency + check_command check_zk_node!zk_avg_latency!500!1000 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Max_Latency + check_command check_zk_node!zk_max_latency!1000!2000 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Min_Latency + check_command check_zk_node!zk_min_latency!500!1000 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Outstanding_Requests + check_command check_zk_node!zk_outstanding_requests!20!50 +} + +define service { + hostgroup_name zookeeper-servers + use generic-service + service_description ZK_Watch_Count + check_command check_zk_node!zk_watch_count!100!500 +} + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/zookeeper.cfg ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/zookeeper.cfg b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/zookeeper.cfg new file mode 100644 index 0000000..ed4cfab --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/nagios/zookeeper.cfg @@ -0,0 +1,30 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# 'check_zookeeper' command definition +define command { + command_name check_zookeeper + command_line /usr/lib/nagios/plugins/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183" -o nagios -k '$ARG1$' -w '$ARG2$' -c '$ARG3$' + # ATTENTION: you should update the list of servers defined above +} + +# 'check_zk_node' command definition +define command { + command_name check_zk_node + command_line /usr/lib/nagios/plugins/check_zookeeper.py -s $HOSTADDRESS$:2181 -o nagios -k '$ARG1$' -w '$ARG2$' -c '$ARG3$' + # ATTENTION: you should update the port. default: 2181 +} + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-monitoring/test.py ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-monitoring/test.py b/zookeeper-contrib/zookeeper-contrib-monitoring/test.py new file mode 100755 index 0000000..3941291 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-monitoring/test.py @@ -0,0 +1,282 @@ +#! /usr/bin/env python +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest +import socket +import sys + +from StringIO import StringIO + +from check_zookeeper import ZooKeeperServer, NagiosHandler, CactiHandler, GangliaHandler + +ZK_MNTR_OUTPUT = """zk_version\t3.4.0--1, built on 06/19/2010 15:07 GMT +zk_avg_latency\t1 +zk_max_latency\t132 +zk_min_latency\t0 +zk_packets_received\t640 +zk_packets_sent\t639 +zk_outstanding_requests\t0 +zk_server_state\tfollower +zk_znode_count\t4 +zk_watch_count\t0 +zk_ephemerals_count\t0 +zk_approximate_data_size\t27 +zk_open_file_descriptor_count\t22 +zk_max_file_descriptor_count\t1024 +""" + +ZK_MNTR_OUTPUT_WITH_BROKEN_LINES = """zk_version\t3.4.0 +zk_avg_latency\t23 +broken-line + +""" + +ZK_STAT_OUTPUT = """Zookeeper version: 3.3.0-943314, built on 05/11/2010 22:20 GMT +Clients: + /0:0:0:0:0:0:0:1:34564[0](queued=0,recved=1,sent=0) + +Latency min/avg/max: 0/40/121 +Received: 11 +Sent: 10 +Outstanding: 0 +Zxid: 0x700000003 +Mode: follower +Node count: 4 +""" + +class SocketMock(object): + def __init__(self): + self.sent = [] + + def settimeout(self, timeout): + self.timeout = timeout + + def connect(self, address): + self.address = address + + def send(self, data): + self.sent.append(data) + return len(data) + + def recv(self, size): + return ZK_MNTR_OUTPUT[:size] + + def close(self): pass + +class ZK33xSocketMock(SocketMock): + def __init__(self): + SocketMock.__init__(self) + self.got_stat_cmd = False + + def recv(self, size): + if 'stat' in self.sent: + return ZK_STAT_OUTPUT[:size] + else: + return '' + +class UnableToConnectSocketMock(SocketMock): + def connect(self, _): + raise socket.error('[Errno 111] Connection refused') + +def create_server_mock(socket_class): + class ZooKeeperServerMock(ZooKeeperServer): + def _create_socket(self): + return socket_class() + return ZooKeeperServerMock() + +class TestCheckZookeeper(unittest.TestCase): + + def setUp(self): + self.zk = ZooKeeperServer() + + def test_parse_valid_line(self): + key, value = self.zk._parse_line('something\t5') + + self.assertEqual(key, 'something') + self.assertEqual(value, 5) + + def test_parse_line_raises_exception_on_invalid_output(self): + invalid_lines = ['something', '', 'a\tb\tc', '\t1'] + for line in invalid_lines: + self.assertRaises(ValueError, self.zk._parse_line, line) + + def test_parser_on_valid_output(self): + data = self.zk._parse(ZK_MNTR_OUTPUT) + + self.assertEqual(len(data), 14) + self.assertEqual(data['zk_znode_count'], 4) + + def test_parse_should_ignore_invalid_lines(self): + data = self.zk._parse(ZK_MNTR_OUTPUT_WITH_BROKEN_LINES) + + self.assertEqual(len(data), 2) + + def test_parse_stat_valid_output(self): + data = self.zk._parse_stat(ZK_STAT_OUTPUT) + + result = { + 'zk_version' : '3.3.0-943314, built on 05/11/2010 22:20 GMT', + 'zk_min_latency' : 0, + 'zk_avg_latency' : 40, + 'zk_max_latency' : 121, + 'zk_packets_received': 11, + 'zk_packets_sent': 10, + 'zk_server_state': 'follower', + 'zk_znode_count': 4 + } + for k, v in result.iteritems(): + self.assertEqual(v, data[k]) + + def test_recv_valid_output(self): + zk = create_server_mock(SocketMock) + + data = zk.get_stats() + self.assertEqual(len(data), 14) + self.assertEqual(data['zk_znode_count'], 4) + + def test_socket_unable_to_connect(self): + zk = create_server_mock(UnableToConnectSocketMock) + + self.assertRaises(socket.error, zk.get_stats) + + def test_use_stat_cmd_if_mntr_is_not_available(self): + zk = create_server_mock(ZK33xSocketMock) + + data = zk.get_stats() + self.assertEqual(data['zk_version'], '3.3.0-943314, built on 05/11/2010 22:20 GMT') + +class HandlerTestCase(unittest.TestCase): + + def setUp(self): + try: + sys._stdout + except: + sys._stdout = sys.stdout + + sys.stdout = StringIO() + + def tearDown(self): + sys.stdout = sys._stdout + + def output(self): + sys.stdout.seek(0) + return sys.stdout.read() + + +class TestNagiosHandler(HandlerTestCase): + + def _analyze(self, w, c, k, stats): + class Opts(object): + warning = w + critical = c + key = k + + return NagiosHandler().analyze(Opts(), {'localhost:2181':stats}) + + def test_ok_status(self): + r = self._analyze(10, 20, 'a', {'a': 5}) + + self.assertEqual(r, 0) + self.assertEqual(self.output(), 'Ok "a"!|localhost:2181=5;10;20\n') + + r = self._analyze(20, 10, 'a', {'a': 30}) + self.assertEqual(r, 0) + + def test_warning_status(self): + r = self._analyze(10, 20, 'a', {'a': 15}) + self.assertEqual(r, 1) + self.assertEqual(self.output(), + 'Warning "a" localhost:2181!|localhost:2181=15;10;20\n') + + r = self._analyze(20, 10, 'a', {'a': 15}) + self.assertEqual(r, 1) + + def test_critical_status(self): + r = self._analyze(10, 20, 'a', {'a': 30}) + self.assertEqual(r, 2) + self.assertEqual(self.output(), + 'Critical "a" localhost:2181!|localhost:2181=30;10;20\n') + + r = self._analyze(20, 10, 'a', {'a': 5}) + self.assertEqual(r, 2) + + def test_check_a_specific_key_on_all_hosts(self): + class Opts(object): + warning = 10 + critical = 20 + key = 'latency' + + r = NagiosHandler().analyze(Opts(), { + 's1:2181': {'latency': 5}, + 's2:2181': {'latency': 15}, + 's3:2181': {'latency': 35}, + }) + self.assertEqual(r, 2) + self.assertEqual(self.output(), + 'Critical "latency" s3:2181!|s1:2181=5;10;20 '\ + 's3:2181=35;10;20 s2:2181=15;10;20\n') + +class TestCactiHandler(HandlerTestCase): + class Opts(object): + key = 'a' + leader = False + + def __init__(self, leader=False): + self.leader = leader + + def test_output_values_for_all_hosts(self): + r = CactiHandler().analyze(TestCactiHandler.Opts(), { + 's1:2181':{'a':1}, + 's2:2181':{'a':2, 'b':3} + }) + self.assertEqual(r, None) + self.assertEqual(self.output(), 's1_2181:1 s2_2181:2') + + def test_output_single_value_for_leader(self): + r = CactiHandler().analyze(TestCactiHandler.Opts(leader=True), { + 's1:2181': {'a':1, 'zk_server_state': 'leader'}, + 's2:2181': {'a':2} + }) + self.assertEqual(r, 0) + self.assertEqual(self.output(), '1\n') + + +class TestGangliaHandler(unittest.TestCase): + + class TestableGangliaHandler(GangliaHandler): + def __init__(self): + GangliaHandler.__init__(self) + self.cli_calls = [] + + def call(self, cli): + self.cli_calls.append(' '.join(cli)) + + def test_send_single_metric(self): + class Opts(object): + @property + def gmetric(self): return '/usr/bin/gmetric' + opts = Opts() + + h = TestGangliaHandler.TestableGangliaHandler() + h.analyze(opts, {'localhost:2181':{'latency':10}}) + + cmd = "%s -n latency -v 10 -t uint32" % opts.gmetric + assert cmd in h.cli_calls + +if __name__ == '__main__': + unittest.main() + http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-rest/NOTICE.txt ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-rest/NOTICE.txt b/zookeeper-contrib/zookeeper-contrib-rest/NOTICE.txt new file mode 100644 index 0000000..2a92254 --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-rest/NOTICE.txt @@ -0,0 +1,7 @@ +This contrib module includes software developed under the +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 + +This contrib depends on binary only jar libraries developed at: + +https://jersey.dev.java.net/ +https://grizzly.dev.java.net/ http://git-wip-us.apache.org/repos/asf/zookeeper/blob/eab8c1eb/zookeeper-contrib/zookeeper-contrib-rest/README.txt ---------------------------------------------------------------------- diff --git a/zookeeper-contrib/zookeeper-contrib-rest/README.txt b/zookeeper-contrib/zookeeper-contrib-rest/README.txt new file mode 100644 index 0000000..30f2e5d --- /dev/null +++ b/zookeeper-contrib/zookeeper-contrib-rest/README.txt @@ -0,0 +1,72 @@ + +ZooKeeper REST implementation using Jersey JAX-RS. +-------------------------------------------------- + +This is an implementation of version 2 of the ZooKeeper REST spec. + +Note: This interface is currently experimental, may change at any time, +etc... In general you should be using the Java/C client bindings to access +the ZooKeeper server. + +This REST ZooKeeper gateway is useful because most of the languages +have built-in support for working with HTTP based protocols. + +See SPEC.txt for details on the REST binding. + +Quickstart: +----------- + +1) start a zookeeper server on localhost port 2181 + +2) run "ant run" + +3) use a REST client to access the data (see below for more details) + + curl http://localhost:9998/znodes/v1/ + +or use the provided src/python scripts + + zk_dump_tree.py + + +Tests: +---------- + +1) the full testsuite can be run via "ant test" target +2) the python client library also contains a test suite + +Examples Using CURL +------------------- + +First review the spec SPEC.txt in this directory. + +#get the root node data +curl http://localhost:9998/znodes/v1/ + +#get children of the root node +curl http://localhost:9998/znodes/v1/?view=children + +#get "/cluster1/leader" as xml (default is json) +curl -H'Accept: application/xml' http://localhost:9998/znodes/v1/cluster1/leader + +#get the data as text +curl -w "\n%{http_code}\n" "http://localhost:9998/znodes/v1/cluster1/leader?dataformat=utf8" + +#set a node (data.txt contains the ascii text you want to set on the node) +curl -T data.txt -w "\n%{http_code}\n" "http://localhost:9998/znodes/v1/cluster1/leader?dataformat=utf8" + +#create a node +curl -d "data1" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" "http://localhost:9998/znodes/v1/?op=create&name=cluster2&dataformat=utf8" + +curl -d "data2" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" "http://localhost:9998/znodes/v1/cluster2?op=create&name=leader&dataformat=utf8" + +#create a new session +curl -d "" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" "http://localhost:9998/sessions/v1/?op=create&expire=10" + +#session heartbeat +curl -X "PUT" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" "http://localhost:9998/sessions/v1/02dfdcc8-8667-4e53-a6f8-ca5c2b495a72" + +#delete a session +curl -X "DELETE" -H'Content-Type: application/octet-stream' -w "\n%{http_code}\n" "http://localhost:9998/sessions/v1/02dfdcc8-8667-4e53-a6f8-ca5c2b495a72" + +