zookeeper-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From an...@apache.org
Subject [18/45] zookeeper git commit: ZOOKEEPER-3030: MAVEN MIGRATION - Step 1.3 - move contrib directories
Date Mon, 06 Aug 2018 12:13:43 GMT
http://git-wip-us.apache.org/repos/asf/zookeeper/blob/b0df8fe1/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<G;I++){B._config(J[I]);}B._setup();return B;}};}(function(){var L,B,M="3.1.0",K="http://yui.yahooapis.com/",P="yui3-js-enabled",I=function(){},G=Array.prototype.slice,N={"io.xdrReady":1,"io.xdrResponse":1,"SWF.eventHandler":1},F=(typeof window!="undefined"),E=(F)?window:null,R=(F)?E.document:null,D=R&&R.documentElement,A=D&&D.className,C={},H=new Date().getTime(),J=function(V,U,T,S){if(V&&V.addEventListener){V.addEventListener(U,T,S);}else{if(V&&V.attachEvent){V.attachEvent("on"+U,T);}}},Q=function(V,U,T,S){if(V&&V.removeEventListener){V.removeEventListener(U,T,S);}else{if(V&&V.detachEvent){V.detachEvent("on"+U,T);}}},O=function(){YUI.Env.windowLoaded=true;YUI.Env.DOMReady=true;if(F){Q(window,"load",O);}};if(D&&A.indexOf(P)==-1){if(A){A+=" ";}A+=P;D.
 className=A;}if(M.indexOf("@")>-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;Z<X.length;Z=Z+1){d=X[Z].src;if(d){Y=d.match(c);W=Y&&Y[1];if(W){U=Y[2];Y=d.match(a);if(Y&&Y[3]){W=Y[1]+Y[3];}break;}}}return W||T.cdn;}};T=V.Env;T._loaded[M]={};if(S&&V!==YUI){T._yidx=++S._yidx;T._guidp=("yui_"+M+"_"+T._yidx+"_"+H).replace(/\./g,"_");}V.id=V.stamp(V);C[V.id]=V;}V.constructor=YUI;V.config=V.config||{win:E,doc:R,debug:true,useBrowserConsole:true,throwFail:true,bootstrap:
 true,fetchCSS:true};V.config.base=YUI.config.base||V.Env.getBase(/^(.*)yui\/yui([\.\-].*)js(\?.*)?$/,/^(.*\?)(.*\&)(.*)yui\/yui[\.\-].*js(\?.*)?$/);V.config.loaderPath=YUI.config.loaderPath||"loader/loader"+(U||"-min.")+"js";},_setup:function(X){var T,W=this,S=[],V=YUI.Env.mods,U=W.config.core||["get","intl-base","loader","yui-log","yui-later","yui-throttle"];for(T=0;T<U.length;T++){if(V[U[T]]){S.push(U[T]);}}W.use("yui-base");W.use.apply(W,S);},applyTo:function(Y,X,U){if(!(X in N)){this.log(X+": applyTo not allowed","warn","yui");return null;}var T=C[Y],W,S,V;if(T){W=X.split(".");S=T;for(V=0;V<W.length;V=V+1){S=S[W[V]];if(!S){this.log("applyTo not found: "+X,"warn","yui");}}return S.apply(T,U);}return null;},add:function(T,V,S,U){U=U||{};YUI.Env.mods[T]={name:T,fn:V,version:S,details:U};return this;},_attach:function(S,W){var Y,V,b,T,a,U,c=YUI.Env.mods,X=this.Env._attached,Z=S.length;for(Y=0;Y<Z;Y++){V=S[Y];b=c[V];if(!X[V]&&b){X[V]=true;T=b.details;a=T.requires;U=T.use;if(a){this._
 attach(this.Array(a));}if(b.fn){b.fn(this,V);}if(U){this._attach(this.Array(U));}}}},use:function(){if(!this.Array){this._attach(["yui-base"]);}var i,c,j,T=this,k=YUI.Env,U=G.call(arguments,0),V=k.mods,S=T.Env,Z=S._used,g=k._loaderQueue,m=U[0],W=U[U.length-1],b=T.Array,l=T.config,a=l.bootstrap,h=[],e=[],X=l.fetchCSS,f=function(o){e.push(o);if(Z[o]){return;}var Y=V[o],p,n;if(Y){Z[o]=true;p=Y.details.requires;n=Y.details.use;}else{if(!k._loaded[M][o]){h.push(o);}else{Z[o]=true;}}if(p){b.each(b(p),f);}if(n){b.each(b(n),f);}},d=function(q){var o=q||{success:true,msg:"not dynamic"},p,n,Y,r=o.data;T._loading=false;if(r){Y=h.concat();h=[];T.Array.each(r,f);n=h.length;if(n){if(h.sort().join()==Y.sort().join()){n=false;}}}if(n&&r){p=r.concat();p.push(function(){T._attach(r);if(W){W(T,o);}});T._loading=false;T.use.apply(T,p);}else{if(r){T._attach(r);}if(W){W(T,o);}}if(T._useQueue&&T._useQueue.size()&&!T._loading){T.use.apply(T,T._useQueue.next());}};if(T._loading){T._useQueue=T._useQueue||new
  T.Queue();T._useQueue.add(U);return T;}if(typeof W==="function"){U.pop();}else{W=null;}if(m==="*"){U=T.Object.keys(V);}if(T.Loader){c=new T.Loader(l);c.require(U);c.ignoreRegistered=true;c.calculate(null,(X)?null:"js");U=c.sorted;}b.each(U,f);i=h.length;if(i){h=T.Object.keys(b.hash(h));i=h.length;}if(a&&i&&T.Loader){T._loading=true;c=new T.Loader(l);c.onEnd=d;c.context=T;c.attaching=U;c.data=U;c.require((X)?h:U);c.insert(null,(X)?null:"js");}else{if(a&&i&&T.Get&&!S.bootstrapped){T._loading=true;U=b(arguments,0,true);j=function(){T._loading=false;g.running=false;S.bootstrapped=true;T._attach(["loader"]);T.use.apply(T,U);};if(k._bootstrapping){g.add(j);}else{k._bootstrapping=true;T.Get.script(l.base+l.loaderPath,{onEnd:j});}}else{if(i){T.message("Requirement NOT loaded: "+h,"warn","yui");}T._attach(e);d();}}return T;},namespace:function(){var S=arguments,W=null,U,T,V;for(U=0;U<S.length;U=U+1){V=(""+S[U]).split(".");W=this;for(T=(V[0]=="YAHOO")?1:0;T<V.length;T=T+1){W[V[T]]=W[V[T]]||{
 };W=W[V[T]];}}return W;},log:I,message:I,error:function(T,S){if(this.config.throwFail){throw (S||new Error(T));}else{this.message(T,"error");}return this;},guid:function(S){var T=this.Env._guidp+(++this.Env._uidx);return(S)?(S+T):T;},stamp:function(U,V){if(!U){return U;}var S=(typeof U==="string")?U:U._yuid;if(!S){S=this.guid();if(!V){try{U._yuid=S;}catch(T){S=null;}}}return S;}};L=YUI.prototype;for(B in L){YUI[B]=L[B];}YUI._init();if(F){J(window,"load",O);}else{O();}YUI.Env.add=J;YUI.Env.remove=Q;if(typeof exports=="object"){exports.YUI=YUI;}})();YUI.add("yui-base",function(B){(function(){B.Lang=B.Lang||{};var R=B.Lang,G="array",I="boolean",D="date",M="error",S="function",H="number",K="null",F="object",O="regexp",N="string",C=Object.prototype.toString,P="undefined",E={"undefined":P,"number":H,"boolean":I,"string":N,"[object Function]":S,"[object RegExp]":O,"[object Array]":G,"[object Date]":D,"[object Error]":M},J=/^\s+|\s+$/g,Q="";R.isArray=function(L){return R.type(L)===G;};R.isB
 oolean=function(L){return typeof L===I;
+};R.isFunction=function(L){return R.type(L)===S;};R.isDate=function(L){return R.type(L)===D&&L.toString()!=="Invalid Date"&&!isNaN(L);};R.isNull=function(L){return L===null;};R.isNumber=function(L){return typeof L===H&&isFinite(L);};R.isObject=function(U,T){var L=typeof U;return(U&&(L===F||(!T&&(L===S||R.isFunction(U)))))||false;};R.isString=function(L){return typeof L===N;};R.isUndefined=function(L){return typeof L===P;};R.trim=function(L){try{return L.replace(J,Q);}catch(T){return L;}};R.isValue=function(T){var L=R.type(T);switch(L){case H:return isFinite(T);case K:case P:return false;default:return !!(L);}};R.type=function(L){return E[typeof L]||E[C.call(L)]||(L?F:K);};})();(function(){var C=B.Lang,D=Array.prototype,E="length",F=function(M,K,I){var J=(I)?2:F.test(M),H,G,N=K||0;if(J){try{return D.slice.call(M,N);}catch(L){G=[];H=M.length;for(;N<H;N++){G.push(M[N]);}return G;}}else{return[M];}};B.Array=F;F.test=function(I){var G=0;if(C.isObject(I)){if(C.isArray(I)){G=1;}else{try{if
 ((E in I)&&!I.tagName&&!I.alert&&!I.apply){G=2;}}catch(H){}}}return G;};F.each=(D.forEach)?function(G,H,I){D.forEach.call(G||[],H,I||B);return B;}:function(H,J,K){var G=(H&&H.length)||0,I;for(I=0;I<G;I=I+1){J.call(K||B,H[I],I,H);}return B;};F.hash=function(I,H){var L={},G=I.length,K=H&&H.length,J;for(J=0;J<G;J=J+1){if(I[J]){L[I[J]]=(K&&K>J)?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<G.length;H=H+1){if(G[H]===I){return H;}}return -1;};F.numericSort=function(H,G){return(H-G);};F.some=(D.some)?function(G,H,I){return D.some.call(G,H,I);}:function(H,J,K){var G=H.length,I;for(I=0;I<G;I=I+1){if(J.call(K,H[I],I,H)){return true;}}return false;};})();function A(){this._init();this.add.apply(this,arguments);}A.prototype={_init:function(){this._q=[];},next:function(){return this._q.shift();},last:function(){return this._q.pop();},add:function(){B.Array.each(B.Array(arguments,0,true),function(C){this._q.push(C);},this);retu
 rn this;},size:function(){return this._q.length;}};B.Queue=A;YUI.Env._loaderQueue=YUI.Env._loaderQueue||new A();(function(){var D=B.Lang,C="__",E=function(H,G){var F=G.toString;if(D.isFunction(F)&&F!=Object.prototype.toString){H.toString=F;}};B.merge=function(){var G=arguments,I={},H,F=G.length;for(H=0;H<F;H=H+1){B.mix(I,G[H],true);}return I;};B.mix=function(F,O,H,N,L,M){if(!O||!F){return F||B;}if(L){switch(L){case 1:return B.mix(F.prototype,O.prototype,H,N,0,M);case 2:B.mix(F.prototype,O.prototype,H,N,0,M);break;case 3:return B.mix(F,O.prototype,H,N,0,M);case 4:return B.mix(F.prototype,O,H,N,0,M);default:}}var K=M&&D.isArray(F),J,I,G;if(N&&N.length){for(J=0,I=N.length;J<I;++J){G=N[J];if(O.hasOwnProperty(G)){if(M&&D.isObject(F[G],true)){B.mix(F[G],O[G]);}else{if(!K&&(H||!(G in F))){F[G]=O[G];}else{if(K){F.push(O[G]);}}}}}}else{for(J in O){if(O.hasOwnProperty(J)){if(M&&D.isObject(F[J],true)){B.mix(F[J],O[J],H,N,0,true);}else{if(!K&&(H||!(J in F))){F[J]=O[J];}else{if(K){F.push(O[J]);}
 }}}}if(B.UA.ie){E(F,O);}}return F;};B.cached=function(H,F,G){F=F||{};return function(K,J){var I=(J)?Array.prototype.join.call(arguments,C):K;if(!(I in F)||(G&&F[I]==G)){F[I]=H.apply(H,arguments);}return F[I];};};})();(function(){B.Object=function(H){var G=function(){};G.prototype=H;return new G();};var E=B.Object,F=function(H,G){return H&&H.hasOwnProperty&&H.hasOwnProperty(G);},D=undefined,C=function(K,J){var I=(J===2),G=(I)?0:[],H;for(H in K){if(F(K,H)){if(I){G++;}else{G.push((J)?K[H]:H);}}}return G;};E.keys=function(G){return C(G);};E.values=function(G){return C(G,1);};E.size=function(G){return C(G,2);};E.hasKey=F;E.hasValue=function(H,G){return(B.Array.indexOf(E.values(H),G)>-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<G;H++){K=K[I[H]];}return K;};E.setValue=function(M,K,L){var G,J=B.Array(K),I=J.length-1,H=M;if(I>=0){for(G=0;H!==D&&G<I;G++){H=H[J[G]];}if(H!==D){H[J[G]]=L;}else{return D;}}return M;};})();B.UA=function(){var F=function(K){var L=0;return parseFloat(K.replace(/\./g,function(){return(L++==1)?"":".";}));},G=B.config.win,J=G&&G.navigator,I={ie:0,opera:0,gecko:0,webkit:0,chrome:0,mobile:null,air:0,caja:J&&J.cajaVersion,secure:false,os:null},E=J&&J.userAgent,H=G&&G.location,D=H&&H.href,C;I.secure=D&&(D.toLowerCase().indexOf("https")===0);if(E){if((/windows|win32/i).test(E)){I.os="windows";}else{if((/macintosh/i).test(E)){I.os="macintosh";}else{if((/rhino/i).test(E)){I.os="rhino";}}}if((/KHTML/).test(E)){I.webkit=1;}C=E.match(/AppleWebKit\/([^\s]*)/);if(C&&C[1]){I.webkit=F(C[1]);if(/ Mobile\//.test(E)){I.mobile="Apple";}else{C=E.match(/NokiaN[^\/]*|Android \d\.\d|webOS\/\d\.\d/);if(C){I.mobile=C[0];}}C=E.match(/Chrome\/([^\s]*)/);if(C&&C[1]){I.chrome=F(C[1]);}else{C
 =E.match(/AdobeAIR\/([^\s]*)/);if(C){I.air=C[0];}}}if(!I.webkit){C=E.match(/Opera[\s\/]([^\s]*)/);if(C&&C[1]){I.opera=F(C[1]);C=E.match(/Opera Mini[^;]*/);if(C){I.mobile=C[0];}}else{C=E.match(/MSIE\s([^;]*)/);if(C&&C[1]){I.ie=F(C[1]);}else{C=E.match(/Gecko\/([^\s]*)/);if(C){I.gecko=1;C=E.match(/rv:([^\s\)]*)/);if(C&&C[1]){I.gecko=F(C[1]);}}}}}}return I;}();},"3.1.0");YUI.add("get",function(A){(function(){var C=A.UA,B=A.Lang,E="text/javascript",F="text/css",D="stylesheet";A.Get=function(){var M,N,J,L={},K=0,U,W=function(a,X,b){var Y=b||A.config.win,c=Y.document,e=c.createElement(a),Z;for(Z in X){if(X[Z]&&X.hasOwnProperty(Z)){e.setAttribute(Z,X[Z]);}}return e;},T=function(Y,Z,X){var a={id:A.guid(),type:F,rel:D,href:Y};if(X){A.mix(a,X);}return W("link",a,Z);},S=function(Y,Z,X){var a={id:A.guid(),type:E};if(X){A.mix(a,X);}a.src=Y;return W("script",a,Z);},P=function(Y,Z,X){return{tId:Y.tId,win:Y.win,data:Y.data,nodes:Y.nodes,msg:Z,statusText:X,purge:function(){N(this.tId);}};},O=function
 (b,a,X){var Y=L[b],Z;
+if(Y&&Y.onEnd){Z=Y.context||Y;Y.onEnd.call(Z,P(Y,a,X));}},V=function(a,Z){var X=L[a],Y;if(X.timer){clearTimeout(X.timer);}if(X.onFailure){Y=X.context||X;X.onFailure.call(Y,P(X,Z));}O(a,Z,"failure");},I=function(a){var X=L[a],Z,Y;if(X.timer){clearTimeout(X.timer);}X.finished=true;if(X.aborted){Z="transaction "+a+" was aborted";V(a,Z);return;}if(X.onSuccess){Y=X.context||X;X.onSuccess.call(Y,P(X));}O(a,Z,"OK");},Q=function(Z){var X=L[Z],Y;if(X.onTimeout){Y=X.context||X;X.onTimeout.call(Y,P(X));}O(Z,"timeout","timeout");},H=function(Z,c){var Y=L[Z],b,g,f,e,a,X,i;if(Y.timer){clearTimeout(Y.timer);}if(Y.aborted){b="transaction "+Z+" was aborted";V(Z,b);return;}if(c){Y.url.shift();if(Y.varName){Y.varName.shift();}}else{Y.url=(B.isString(Y.url))?[Y.url]:Y.url;if(Y.varName){Y.varName=(B.isString(Y.varName))?[Y.varName]:Y.varName;}}g=Y.win;f=g.document;e=f.getElementsByTagName("head")[0];if(Y.url.length===0){I(Z);return;}X=Y.url[0];if(!X){Y.url.shift();return H(Z);}if(Y.timeout){Y.timer=setT
 imeout(function(){Q(Z);},Y.timeout);}if(Y.type==="script"){a=S(X,g,Y.attributes);}else{a=T(X,g,Y.attributes);}J(Y.type,a,Z,X,g,Y.url.length);Y.nodes.push(a);if(Y.insertBefore){i=M(Y.insertBefore,Z);if(i){i.parentNode.insertBefore(a,i);}}else{e.appendChild(a);}if((C.webkit||C.gecko)&&Y.type==="css"){H(Z,X);}},G=function(){if(U){return;}U=true;var X,Y;for(X in L){if(L.hasOwnProperty(X)){Y=L[X];if(Y.autopurge&&Y.finished){N(Y.tId);delete L[X];}}}U=false;},R=function(Y,X,Z){Z=Z||{};var d="q"+(K++),a,c=Z.purgethreshold||A.Get.PURGE_THRESH;if(K%c===0){G();}L[d]=A.merge(Z,{tId:d,type:Y,url:X,finished:false,nodes:[]});a=L[d];a.win=a.win||A.config.win;a.context=a.context||a;a.autopurge=("autopurge" in a)?a.autopurge:(Y==="script")?true:false;a.attributes=a.attributes||{};var b=Z.charset||a.attributes.charset;if(b){a.attributes.charset=b;}setTimeout(function(){H(d);},0);return{tId:d};};J=function(Z,e,d,Y,c,b,X){var a=X||H;if(C.ie){e.onreadystatechange=function(){var f=this.readyState;if("load
 ed"===f||"complete"===f){e.onreadystatechange=null;a(d,Y);}};}else{if(C.webkit){if(Z==="script"){e.addEventListener("load",function(){a(d,Y);});}}else{e.onload=function(){a(d,Y);};e.onerror=function(f){V(d,f+": "+Y);};}}};M=function(X,a){var Y=L[a],Z=(B.isString(X))?Y.win.document.getElementById(X):X;if(!Z){V(a,"target node not found: "+X);}return Z;};N=function(c){var Y,a,g,e,j,b,Z,f,X=L[c];if(X){Y=X.nodes;a=Y.length;g=X.win.document;e=g.getElementsByTagName("head")[0];if(X.insertBefore){j=M(X.insertBefore,c);if(j){e=j.parentNode;}}for(b=0;b<a;b=b+1){Z=Y[b];if(Z.clearAttributes){Z.clearAttributes();}else{for(f in Z){if(Z.hasOwnProperty(f)){delete Z[f];}}}e.removeChild(Z);}}X.nodes=[];};return{PURGE_THRESH:20,_finalize:function(X){setTimeout(function(){I(X);},0);},abort:function(Y){var Z=(B.isString(Y))?Y:Y.tId,X=L[Z];if(X){X.aborted=true;}},script:function(X,Y){return R("script",X,Y);},css:function(X,Y){return R("css",X,Y);}};}();})();},"3.1.0");YUI.add("intl-base",function(B){var 
 A=/[, ]/;B.mix(B.namespace("Intl"),{lookupBestLang:function(G,H){var F,I,C,E;function D(K){var J;for(J=0;J<H.length;J+=1){if(K.toLowerCase()===H[J].toLowerCase()){return H[J];}}}if(B.Lang.isString(G)){G=G.split(A);}for(F=0;F<G.length;F+=1){I=G[F];if(!I||I==="*"){continue;}while(I.length>0){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/b0df8fe1/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/b0df8fe1/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 "<server-or-list-of-servers>" -k <key> -w <warning> -c <critical>
+
+
+*** On Cacti define a custom data input method using the script like this:
+
+./check_zookeeper.py -o cacti -s "<list-of-servers>" -k <key> --leader
+
+-- outputs a single value for the given key fetched from the cluster leader
+
+OR 
+
+./check_zookeeper.py -o cacti -s "<list-of-servers>" -k <key> 
+
+-- 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 "<current-zookeeper-node>"
+
+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/b0df8fe1/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 <path_cacti>scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k <key> -o cacti --leader
+
+When you will call the script this way it will about a single value representing the value attached to this <key>.
+
+
+Multiple values (one for each cluster node):
+--------------------------------------------
+
+python <path_cacti>scripts/check_zookeeper.py -s "localhost:2181,localhost:2182,localhost:2183,localhost:2184,localhost:2185" -k <key> -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/b0df8fe1/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 <options>', 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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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!<exported-var>!<warning-level>!<critical-level>
+}
+
+define service {
+    hostgroup_name  zookeeper-servers                    
+    use generic-service                                  
+    service_description ZK_Open_File_Descriptors_Count   
+    check_command check_zk_node!<exported-var>!<warning-level>!<critical-level>
+}
+
+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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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/b0df8fe1/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"
+
+


Mime
View raw message