#include <string.h>#include <errno.h>#include "zookeeper.h"staticzhandle_t*zh;/** * In this example this method gets the cert for your * environment -- you must provide */char*foo_get_cert_once(char*id){return0;}/** Watcher function -- empty for this example, not something you should * do in real code */voidwatcher(zhandle_t*zzh,inttype,intstate,constchar*path,void*watcherCtx){}intmain(intargc,charargv){charbuffer[512];charp[2048];char*cert=0;charappId[64];strcpy(appId,"example.foo_test");cert=foo_get_cert_once(appId);if(cert!=0){fprintf(stderr,"Certificate for appid [%s] is [%s]\n",appId,cert);strncpy(p,cert,sizeof(p)-1);free(cert);}else{fprintf(stderr,"Certificate for appid [%s] not found\n",appId);strcpy(p,"dummy");}zoo_set_debug_level(ZOO_LOG_LEVEL_DEBUG);zh=zookeeper_init("localhost:3181",watcher,10000,0,0,0);if(!zh){returnerrno;}if(zoo_add_auth(zh,"foo",p,strlen(p),0,0)!=ZOK)return2;structACLCREATE_ONLY_ACL[]=;structACL_vectorCREATE_ONLY={1,CREATE_ONLY_ACL};intrc=zoo_create(zh,"/xyz","value",5,&CREATE_ONLY,ZOO_EPHEMERAL,buffer,sizeof(buffer)-1);/** this operation will fail with a ZNOAUTH error */intbuflen=sizeof(buffer);structStatstat;rc=zoo_get(zh,"/xyz",0,buffer,&buflen,&stat);if(rc){fprintf(stderr,"Error %d for %s\n",rc,__LINE__);}zookeeper_close(zh);return0;}
/** * A simple example program to use DataMonitor to start and * stop executables based on a znode. The program watches the * specified znode and saves the data that corresponds to the * znode in the filesystem. It also starts the specified program * with the specified arguments when the znode exists and kills * the program if the znode goes away. */importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importorg.apache.zookeeper.KeeperException;importorg.apache.zookeeper.WatchedEvent;importorg.apache.zookeeper.Watcher;importorg.apache.zookeeper.ZooKeeper;publicclassExecutorimplementsWatcher,Runnable,DataMonitor.DataMonitorListener{Stringznode;DataMonitordm;ZooKeeperzk;Stringfilename;Stringexec[];Processchild;publicExecutor(StringhostPort,Stringznode,Stringfilename,Stringexec[])throwsKeeperException,IOException{this.filename=filename;this.exec=exec;zk=newZooKeeper(hostPort,3000,this);dm=newDataMonitor(zk,znode,null,this);}/** * @param args */publicstaticvoidmain(String[]args){if(args.length<4){System.err.println("USAGE: Executor hostPort znode filename program [args ...]");System.exit(2);}StringhostPort=args[0];Stringznode=args[1];Stringfilename=args[2];Stringexec[]=newString[args.length-3];System.arraycopy(args,3,exec,0,exec.length);try{newExecutor(hostPort,znode,filename,exec).run();}catch(Exceptione){e.printStackTrace();}}/*************************************************************************** * We do process any events ourselves, we just need to forward them on. * * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent) */publicvoidprocess(WatchedEventevent){dm.process(event);}publicvoidrun(){try{synchronized(this){while(!dm.dead){wait();}}}catch(InterruptedExceptione){}}publicvoidclosing(intrc){synchronized(this){notifyAll();}}staticclassStreamWriterextendsThread{OutputStreamos;InputStreamis;StreamWriter(InputStreamis,OutputStreamos){this.is=is;this.os=os;start();}publicvoidrun(){byteb[]=newbyte[80];intrc;try{while((rc=is.read(b))>0){os.write(b,0,rc);}}catch(IOExceptione){}}}publicvoidexists(byte[]data){if(data==null){if(child!=null){System.out.println("Killing process");child.destroy();try{child.waitFor();}catch(InterruptedExceptione){}}child=null;}else{if(child!=null){System.out.println("Stopping child");child.destroy();try{child.waitFor();}catch(InterruptedExceptione){e.printStackTrace();}}try{FileOutputStreamfos=newFileOutputStream(filename);fos.write(data);fos.close();}catch(IOExceptione){e.printStackTrace();}try{System.out.println("Starting child");child=Runtime.getRuntime().exec(exec);newStreamWriter(child.getInputStream(),System.out);newStreamWriter(child.getErrorStream(),System.err);}catch(IOExceptione){e.printStackTrace();}}}}
/** * A simple class that monitors the data and existence of a ZooKeeper * node. It uses asynchronous ZooKeeper APIs. */importjava.util.Arrays;importorg.apache.zookeeper.KeeperException;importorg.apache.zookeeper.WatchedEvent;importorg.apache.zookeeper.Watcher;importorg.apache.zookeeper.ZooKeeper;importorg.apache.zookeeper.AsyncCallback.StatCallback;importorg.apache.zookeeper.KeeperException.Code;importorg.apache.zookeeper.data.Stat;publicclassDataMonitorimplementsWatcher,StatCallback{ZooKeeperzk;Stringznode;WatcherchainedWatcher;booleandead;DataMonitorListenerlistener;byteprevData[];publicDataMonitor(ZooKeeperzk,Stringznode,WatcherchainedWatcher,DataMonitorListenerlistener){this.zk=zk;this.znode=znode;this.chainedWatcher=chainedWatcher;this.listener=listener;// Get things started by checking if the node exists. We are going// to be completely event drivenzk.exists(znode,true,this,null);}/** * Other classes use the DataMonitor by implementing this method */publicinterfaceDataMonitorListener{/** * The existence status of the node has changed. */voidexists(bytedata[]);/** * The ZooKeeper session is no longer valid. * * @param rc * the ZooKeeper reason code */voidclosing(intrc);}publicvoidprocess(WatchedEventevent){Stringpath=event.getPath();if(event.getType()==Event.EventType.None){// We are are being told that the state of the// connection has changedswitch(event.getState()){caseSyncConnected:// In this particular example we don't need to do anything// here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course)break;caseExpired:// It's all overdead=true;listener.closing(KeeperException.Code.SessionExpired);break;}}else{if(path!=null&&path.equals(znode)){// Something has changed on the node, let's find outzk.exists(znode,true,this,null);}}if(chainedWatcher!=null){chainedWatcher.process(event);}}publicvoidprocessResult(intrc,Stringpath,Objectctx,Statstat){booleanexists;switch(rc){caseCode.Ok:exists=true;break;caseCode.NoNode:exists=false;break;caseCode.SessionExpired:caseCode.NoAuth:dead=true;listener.closing(rc);return;default:// Retry errorszk.exists(znode,true,this,null);return;}byteb[]=null;if(exists){try{b=zk.getData(znode,false,null);}catch(KeeperExceptione){// We don't need to worry about recovering now. The watch// callbacks will kick off any exception handlinge.printStackTrace();}catch(InterruptedExceptione){return;}}if((b==null&&b!=prevData)||(b!=null&&!Arrays.equals(prevData,b))){listener.exists(b);prevData=b;}}}