javaExample.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta content="Apache Forrest" name="Generator">
  6. <meta name="Forrest-version" content="0.8">
  7. <meta name="Forrest-skin-name" content="pelt">
  8. <title>ZooKeeper Java Example</title>
  9. <link type="text/css" href="skin/basic.css" rel="stylesheet">
  10. <link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
  11. <link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
  12. <link type="text/css" href="skin/profile.css" rel="stylesheet">
  13. <script src="skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="skin/fontsize.js" language="javascript" type="text/javascript"></script>
  14. <link rel="shortcut icon" href="images/favicon.ico">
  15. </head>
  16. <body onload="init()">
  17. <script type="text/javascript">ndeSetTextSize();</script>
  18. <div id="top">
  19. <!--+
  20. |breadtrail
  21. +-->
  22. <div class="breadtrail">
  23. <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://hadoop.apache.org/">Hadoop</a> &gt; <a href="http://hadoop.apache.org/zookeeper/">ZooKeeper</a><script src="skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
  24. </div>
  25. <!--+
  26. |header
  27. +-->
  28. <div class="header">
  29. <!--+
  30. |start group logo
  31. +-->
  32. <div class="grouplogo">
  33. <a href="http://hadoop.apache.org/"><img class="logoImage" alt="Hadoop" src="images/hadoop-logo.jpg" title="Apache Hadoop"></a>
  34. </div>
  35. <!--+
  36. |end group logo
  37. +-->
  38. <!--+
  39. |start Project Logo
  40. +-->
  41. <div class="projectlogo">
  42. <a href="http://hadoop.apache.org/zookeeper/"><img class="logoImage" alt="ZooKeeper" src="images/zookeeper_small.gif" title="The Hadoop database"></a>
  43. </div>
  44. <!--+
  45. |end Project Logo
  46. +-->
  47. <!--+
  48. |start Search
  49. +-->
  50. <div class="searchbox">
  51. <form action="http://www.google.com/search" method="get" class="roundtopsmall">
  52. <input value="hadoop.apache.org" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">&nbsp;
  53. <input name="Search" value="Search" type="submit">
  54. </form>
  55. </div>
  56. <!--+
  57. |end search
  58. +-->
  59. <!--+
  60. |start Tabs
  61. +-->
  62. <ul id="tabs">
  63. <li>
  64. <a class="unselected" href="http://hadoop.apache.org/zookeeper/">Project</a>
  65. </li>
  66. <li>
  67. <a class="unselected" href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  68. </li>
  69. <li class="current">
  70. <a class="selected" href="index.html">ZooKeeper Documentation</a>
  71. </li>
  72. </ul>
  73. <!--+
  74. |end Tabs
  75. +-->
  76. </div>
  77. </div>
  78. <div id="main">
  79. <div id="publishedStrip">
  80. <!--+
  81. |start Subtabs
  82. +-->
  83. <div id="level2tabs"></div>
  84. <!--+
  85. |end Endtabs
  86. +-->
  87. <script type="text/javascript"><!--
  88. document.write("Last Published: " + document.lastModified);
  89. // --></script>
  90. </div>
  91. <!--+
  92. |breadtrail
  93. +-->
  94. <div class="breadtrail">
  95. &nbsp;
  96. </div>
  97. <!--+
  98. |start Menu, mainarea
  99. +-->
  100. <!--+
  101. |start Menu
  102. +-->
  103. <div id="menu">
  104. <div onclick="SwitchMenu('menu_1.1', 'skin/')" id="menu_1.1Title" class="menutitle">Overview</div>
  105. <div id="menu_1.1" class="menuitemgroup">
  106. <div class="menuitem">
  107. <a href="index.html">Welcome</a>
  108. </div>
  109. <div class="menuitem">
  110. <a href="zookeeperOver.html">Overview</a>
  111. </div>
  112. <div class="menuitem">
  113. <a href="zookeeperStarted.html">Getting Started</a>
  114. </div>
  115. </div>
  116. <div onclick="SwitchMenu('menu_selected_1.2', 'skin/')" id="menu_selected_1.2Title" class="menutitle" style="background-image: url('skin/images/chapter_open.gif');">Developer</div>
  117. <div id="menu_selected_1.2" class="selectedmenuitemgroup" style="display: block;">
  118. <div class="menuitem">
  119. <a href="api/index.html">API Docs</a>
  120. </div>
  121. <div class="menuitem">
  122. <a href="zookeeperProgrammers.html">Programmer's Guide</a>
  123. </div>
  124. <div class="menupage">
  125. <div class="menupagetitle">Java Example</div>
  126. </div>
  127. <div class="menuitem">
  128. <a href="zookeeperTutorial.html">Barrier and Queue Tutorial</a>
  129. </div>
  130. <div class="menuitem">
  131. <a href="recipes.html">Recipes</a>
  132. </div>
  133. </div>
  134. <div onclick="SwitchMenu('menu_1.3', 'skin/')" id="menu_1.3Title" class="menutitle">Admin &amp; Ops</div>
  135. <div id="menu_1.3" class="menuitemgroup">
  136. <div class="menuitem">
  137. <a href="zookeeperAdmin.html">Administrator's Guide</a>
  138. </div>
  139. </div>
  140. <div onclick="SwitchMenu('menu_1.4', 'skin/')" id="menu_1.4Title" class="menutitle">Contributor</div>
  141. <div id="menu_1.4" class="menuitemgroup">
  142. <div class="menuitem">
  143. <a href="zookeeperInternals.html">ZooKeeper Internals</a>
  144. </div>
  145. </div>
  146. <div onclick="SwitchMenu('menu_1.5', 'skin/')" id="menu_1.5Title" class="menutitle">Informal Documentation</div>
  147. <div id="menu_1.5" class="menuitemgroup">
  148. <div class="menuitem">
  149. <a href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  150. </div>
  151. <div class="menuitem">
  152. <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ">FAQ</a>
  153. </div>
  154. <div class="menuitem">
  155. <a href="http://hadoop.apache.org/zookeeper/mailing_lists.html">Mailing Lists</a>
  156. </div>
  157. <div class="menuitem">
  158. <a href="zookeeperOtherInfo.html">Other Info</a>
  159. </div>
  160. </div>
  161. <div id="credit"></div>
  162. <div id="roundbottom">
  163. <img style="display: none" class="corner" height="15" width="15" alt="" src="skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
  164. <!--+
  165. |alternative credits
  166. +-->
  167. <div id="credit2"></div>
  168. </div>
  169. <!--+
  170. |end Menu
  171. +-->
  172. <!--+
  173. |start content
  174. +-->
  175. <div id="content">
  176. <div title="Portable Document Format" class="pdflink">
  177. <a class="dida" href="javaExample.pdf"><img alt="PDF -icon" src="skin/images/pdfdoc.gif" class="skin"><br>
  178. PDF</a>
  179. </div>
  180. <h1>ZooKeeper Java Example</h1>
  181. <div id="minitoc-area">
  182. <ul class="minitoc">
  183. <li>
  184. <a href="#ch_Introduction">A Simple Watch Client</a>
  185. <ul class="minitoc">
  186. <li>
  187. <a href="#sc_requirements">Requirements</a>
  188. </li>
  189. <li>
  190. <a href="#sc_design">Program Design</a>
  191. </li>
  192. </ul>
  193. </li>
  194. <li>
  195. <a href="#sc_executor">The Executor Class</a>
  196. </li>
  197. <li>
  198. <a href="#sc_DataMonitor">The DataMonitor Class</a>
  199. </li>
  200. <li>
  201. <a href="#sc_completeSourceCode">Complete Source Listings</a>
  202. </li>
  203. </ul>
  204. </div>
  205. <a name="N10009"></a><a name="ch_Introduction"></a>
  206. <h2 class="h3">A Simple Watch Client</h2>
  207. <div class="section">
  208. <p>To introduce you to the ZooKeeper Java API, we develop here a very simple
  209. watch client. This ZooKeeper client watches a ZooKeeper node for changes
  210. and responds to by starting or stopping a program.</p>
  211. <a name="N10012"></a><a name="sc_requirements"></a>
  212. <h3 class="h4">Requirements</h3>
  213. <p>The client has four requirements:</p>
  214. <ul>
  215. <li>
  216. <p>It takes as parameters:</p>
  217. <ul>
  218. <li>
  219. <p>the address of the ZooKeeper service</p>
  220. </li>
  221. <li>
  222. <p> a znode, by name</p>
  223. </li>
  224. <li>
  225. <p> an executable with arguments.</p>
  226. </li>
  227. </ul>
  228. </li>
  229. <li>
  230. <p>It fetches the data associated with the znode and starts the executable.</p>
  231. </li>
  232. <li>
  233. <p>If the znode changes, the client refetches the contents and restarts the executable.</p>
  234. </li>
  235. <li>
  236. <p>If the znode disappears, the client kills the executable.</p>
  237. </li>
  238. </ul>
  239. <a name="N1003B"></a><a name="sc_design"></a>
  240. <h3 class="h4">Program Design</h3>
  241. <p>Conventionally, ZooKeeper applications are broken into two units, one which maintains the connection,
  242. and the other which monitors data. In this application, the class called the <strong>Executor</strong>
  243. maintains the ZooKeeper connection, and the class called the <strong>DataMonitor</strong> monitors the data
  244. in the ZooKeeper tree. Also, Executor contains the main thread and contains the execution logic.
  245. It is responsible for what little user interaction there is, as well as interaction with the exectuable program you
  246. pass in as an argument and which the sample (per the requirements) shuts down and restarts, according to the
  247. state of the znode.</p>
  248. </div>
  249. <a name="N1004C"></a><a name="sc_executor"></a>
  250. <h2 class="h3">The Executor Class</h2>
  251. <div class="section">
  252. <p>The Executor object is the primary container of the sample application. It contains
  253. both the <strong>ZooKeeper</strong> object, <strong>DataMonitor</strong>, as described above in
  254. <a href="#sc_design">Program Design</a>. </p>
  255. <pre class="code">
  256. // from the Executor class...
  257. public static void main(String[] args) {
  258. if (args.length &lt; 4) {
  259. System.err
  260. .println("USAGE: Executor hostPort znode filename program [args ...]");
  261. System.exit(2);
  262. }
  263. String hostPort = args[0];
  264. String znode = args[1];
  265. String filename = args[2];
  266. String exec[] = new String[args.length - 3];
  267. System.arraycopy(args, 3, exec, 0, exec.length);
  268. try {
  269. Executor theExectutor = new Executor(hostPort, znode, filename, exec);
  270. theExectutor.run();
  271. } catch (Exception e) {
  272. e.printStackTrace();
  273. }
  274. }
  275. public Executor(String hostPort, String znode, String filename,
  276. String exec[]) throws KeeperException, IOException {
  277. this.filename = filename;
  278. this.exec = exec;
  279. //create a new zookeeper object, passing a self-reference in a the Watcher
  280. zk = new ZooKeeper(hostPort, 3000, this);
  281. dm = new DataMonitor(zk, znode, null, this);
  282. }
  283. public void run() {
  284. try {
  285. synchronized (this) {
  286. while (!dm.dead) {
  287. wait();
  288. }
  289. }
  290. } catch (InterruptedException e) {
  291. }
  292. }
  293. </pre>
  294. <p>
  295. Recall that the Executor's job is to starts and stop the executable whose name you pass in on the command line.
  296. It does this in response to events fired by the ZooKeeper object. As you can see in the code above, the Executor passes
  297. a reference to itself as the Watcher argument in the ZooKeeper constructor. It also passes a reference to itself
  298. as DataMonitorListener argument to the DataMonitor constructor. Per the Executor's definition, it implements both these
  299. interfaces:
  300. </p>
  301. <pre class="code">
  302. public class Executor implements Watcher, Runnable, DataMonitorListener {
  303. ...
  304. </pre>
  305. <p>The <strong>Watcher</strong> interface is defined by the ZooKeeper Java API.
  306. ZooKeeper uses it to communicate back to its container. It supports only one method, <span class="codefrag command">process()</span>, and ZooKeeper uses
  307. it to communciates generic events that the main thread would be intersted in, such as the state of the ZooKeeper connection or the ZooKeeper session.The Executor
  308. in this example simply forwards those events down to the DataMonitor to decide what to do with them. It does this simply to illustrate
  309. the point that, by convention, the Executor or some Executor-like object "owns" the ZooKeeper connection, but it is free to delegate the events to other
  310. events to other objects. It also uses this as the default channel on which to fire watch events. (More on this later.)</p>
  311. <pre class="code">
  312. public void process(WatcherEvent event) {
  313. dm.process(event);
  314. }
  315. </pre>
  316. <p>The <strong>DataMonitorListener</strong>
  317. interface, on the other hand, is not part of the the ZooKeeper API. It is a completely custom interface,
  318. designed for this sample application. The DataMonitor object uses it to communicate back to its container, which
  319. is also the the Executor object.The DataMonitorListener interface looks like this:</p>
  320. <pre class="code">
  321. public interface DataMonitorListener {
  322. /**
  323. * The existence status of the node has changed.
  324. */
  325. void exists(byte data[]);
  326. /**
  327. * The ZooKeeper session is no longer valid.
  328. *
  329. * @param rc
  330. * the ZooKeeper reason code
  331. */
  332. void closing(int rc);
  333. }
  334. </pre>
  335. <p>This interface is defined in the DataMonitor class and implemented in the Executor class.
  336. When <span class="codefrag command">Executor.exists()</span> is invoked,
  337. the Executor decides whether to start up or shut down per the requirements. Recall that the requires say to kill the executable when the
  338. znode ceases to <em>exist</em>. </p>
  339. <p>When <span class="codefrag command">Executor.closing()</span>
  340. is invoked, the Executor decides whether or not to shut itself down in response to the ZooKeeper connection permanently disappearing.</p>
  341. <p>As you might have guessed, DataMonitor is the object that invokes
  342. these methods, in response to changes in ZooKeeper's state.</p>
  343. <p>Here are Executor's implementation of
  344. <span class="codefrag command">DataMonitorListener.exists()</span> and <span class="codefrag command">DataMonitorListener.closing</span>:
  345. </p>
  346. <pre class="code">
  347. public void exists( byte[] data ) {
  348. if (data == null) {
  349. if (child != null) {
  350. System.out.println("Killing process");
  351. child.destroy();
  352. try {
  353. child.waitFor();
  354. } catch (InterruptedException e) {
  355. }
  356. }
  357. child = null;
  358. } else {
  359. if (child != null) {
  360. System.out.println("Stopping child");
  361. child.destroy();
  362. try {
  363. child.waitFor();
  364. } catch (InterruptedException e) {
  365. e.printStackTrace();
  366. }
  367. }
  368. try {
  369. FileOutputStream fos = new FileOutputStream(filename);
  370. fos.write(data);
  371. fos.close();
  372. } catch (IOException e) {
  373. e.printStackTrace();
  374. }
  375. try {
  376. System.out.println("Starting child");
  377. child = Runtime.getRuntime().exec(exec);
  378. new StreamWriter(child.getInputStream(), System.out);
  379. new StreamWriter(child.getErrorStream(), System.err);
  380. } catch (IOException e) {
  381. e.printStackTrace();
  382. }
  383. }
  384. }
  385. public void closing(int rc) {
  386. synchronized (this) {
  387. notifyAll();
  388. }
  389. }
  390. </pre>
  391. </div>
  392. <a name="N100A0"></a><a name="sc_DataMonitor"></a>
  393. <h2 class="h3">The DataMonitor Class</h2>
  394. <div class="section">
  395. <p>
  396. The DataMonitor class has the meat of the ZooKeeper logic. It is mostly
  397. asynchronous and event driven. DataMonitor kicks things off in the constructor with:</p>
  398. <pre class="code">
  399. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  400. DataMonitorListener listener) {
  401. this.zk = zk;
  402. this.znode = znode;
  403. this.chainedWatcher = chainedWatcher;
  404. this.listener = listener;
  405. // Get things started by checking if the node exists. We are going
  406. // to be completely event driven
  407. <strong>zk.exists(znode, true, this, null);</strong>
  408. }
  409. </pre>
  410. <p>The call to <span class="codefrag command">ZooKeeper.exists()</span> checks for the existence of the znode,
  411. sets a watch, and passes a reference to itself (<span class="codefrag command">this</span>)
  412. as the completion callback object. In this sense, it kicks things off, since the
  413. real processing happens when the watch is triggered.</p>
  414. <div class="note">
  415. <div class="label">Note</div>
  416. <div class="content">
  417. <p>Don't confuse the completion callback with the watch callback. The <span class="codefrag command">ZooKeeper.exists()</span>
  418. completion callback, which happens to be the method <span class="codefrag command">StatCallback.processResult()</span> implemented
  419. in the DataMonitor object, is invoked when the asynchronous <em>setting of the watch</em> operation
  420. (by <span class="codefrag command">ZooKeeper.exists()</span>) completes on the server. </p>
  421. <p>
  422. The triggering of the watch, on the other hand, sends an event to the <em>Executor</em> object, since
  423. the Executor registered as the Watcher of the ZooKeeper object.</p>
  424. <p>As an aside, you might note that the DataMonitor could also register itself as the Watcher
  425. for this particular watch event. This is new to ZooKeeper 3.0.0 (the support of multiple Watchers). In this
  426. example, however, DataMonitor does not register as the Watcher.</p>
  427. </div>
  428. </div>
  429. <p>When the <span class="codefrag command">ZooKeeper.exists()</span> operation completes on the server, the ZooKeeper API invokes this completion callback on
  430. the client:</p>
  431. <pre class="code">
  432. public void processResult(int rc, String path, Object ctx, Stat stat) {
  433. boolean exists;
  434. switch (rc) {
  435. case Code.Ok:
  436. exists = true;
  437. break;
  438. case Code.NoNode:
  439. exists = false;
  440. break;
  441. case Code.SessionExpired:
  442. case Code.NoAuth:
  443. dead = true;
  444. listener.closing(rc);
  445. return;
  446. default:
  447. // Retry errors
  448. zk.exists(znode, true, this, null);
  449. return;
  450. }
  451. byte b[] = null;
  452. if (exists) {
  453. try {
  454. <strong>b = zk.getData(znode, false, null);</strong>
  455. } catch (KeeperException e) {
  456. // We don't need to worry about recovering now. The watch
  457. // callbacks will kick off any exception handling
  458. e.printStackTrace();
  459. } catch (InterruptedException e) {
  460. return;
  461. }
  462. }
  463. if ((b == null &amp;&amp; b != prevData)
  464. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  465. <strong>listener.exists(b);</strong>
  466. prevData = b;
  467. }
  468. }
  469. </pre>
  470. <p>
  471. The code first checks the error codes for znode existence, fatal errors, and
  472. recoverable errors. If the file (or znode) exists, it gets the data from the znode, and
  473. then invoke the exists() callback of Executor if the state has changed. Note,
  474. it doesn't have to do any Exception processing for the getData call because it
  475. has watches pending for anything that could cause an error: if the node is deleted
  476. before it calls <span class="codefrag command">ZooKeeper.getData()</span>, the watch event set by
  477. the <span class="codefrag command">ZooKeeper.exists()</span> triggers a callback;
  478. if there is a communication error, a connection watch event fires when
  479. the connection comes back up.
  480. </p>
  481. <p>Finally, notice how DataMonitor processes watch events: </p>
  482. <pre class="code">
  483. public void process(WatcherEvent event) {
  484. String path = event.getPath();
  485. if (event.getType() == Watcher.Event.EventNone) {
  486. // We are are being told that the state of the
  487. // connection has changed
  488. switch (event.getState()) {
  489. case Event.KeeperStateSyncConnected:
  490. // Everything is happy. Lets kick things off
  491. // again by checking the existence of the znode
  492. zk.exists(znode, true, this, null);
  493. break;
  494. case Event.KeeperStateExpired:
  495. // It's all over
  496. dead = true;
  497. listener.closing(KeeperException.Code.SessionExpired);
  498. break;
  499. }
  500. } else {
  501. if (path != null &amp;&amp; path.equals(znode)) {
  502. // Something has changed on the node, let's find out
  503. zk.exists(znode, true, this, null);
  504. }
  505. }
  506. if (chainedWatcher != null) {
  507. chainedWatcher.process(event);
  508. }
  509. }
  510. </pre>
  511. <p>
  512. If the client-side ZooKeeper libraries can reestablish the communication channel to ZooKeeper, DataMonitor simply kicks
  513. everything off again with the call to <span class="codefrag command">ZooKeeper.exists()</span>.
  514. If it gets an event for a znode, it calls <span class="codefrag command">ZooKeeper.exists()</span> to find out what has changed.
  515. </p>
  516. </div>
  517. <a name="N10104"></a><a name="sc_completeSourceCode"></a>
  518. <h2 class="h3">Complete Source Listings</h2>
  519. <div class="section">
  520. <div class="note example">
  521. <div class="label">Executor.java</div>
  522. <div class="content">
  523. <title>Executor.java</title>
  524. <pre class="code">
  525. /**
  526. * A simple example program to use DataMonitor to start and
  527. * stop executables based on a znode. The program watches the
  528. * specified znode and saves the data that corresponds to the
  529. * znode in the filesystem. It also starts the specified program
  530. * with the specified arguments when the znode exists and kills
  531. * the program if the znode goes away.
  532. */
  533. package com.yahoo.zk.executor;
  534. import java.io.FileOutputStream;
  535. import java.io.IOException;
  536. import java.io.InputStream;
  537. import java.io.OutputStream;
  538. import com.yahoo.zk.executor.DataMonitor.DataMonitorListener;
  539. import com.yahoo.zookeeper.KeeperException;
  540. import com.yahoo.zookeeper.Watcher;
  541. import com.yahoo.zookeeper.ZooKeeper;
  542. import com.yahoo.zookeeper.proto.WatcherEvent;
  543. public class Executor implements Watcher, Runnable, DataMonitorListener {
  544. String znode;
  545. DataMonitor dm;
  546. ZooKeeper zk;
  547. String filename;
  548. String exec[];
  549. Process child;
  550. public Executor(String hostPort, String znode, String filename,
  551. String exec[]) throws KeeperException, IOException {
  552. this.filename = filename;
  553. this.exec = exec;
  554. zk = new ZooKeeper(hostPort, 3000, this);
  555. dm = new DataMonitor(zk, znode, null, this);
  556. }
  557. /**
  558. * @param args
  559. */
  560. public static void main(String[] args) {
  561. if (args.length &lt; 4) {
  562. System.err
  563. .println("USAGE: Executor hostPort znode filename program [args ...]");
  564. System.exit(2);
  565. }
  566. String hostPort = args[0];
  567. String znode = args[1];
  568. String filename = args[2];
  569. String exec[] = new String[args.length - 3];
  570. System.arraycopy(args, 3, exec, 0, exec.length);
  571. try {
  572. new Executor(hostPort, znode, filename, exec).run();
  573. } catch (Exception e) {
  574. e.printStackTrace();
  575. }
  576. }
  577. /***************************************************************************
  578. * We do process any events ourselves, we just need to forward them on.
  579. *
  580. * @see com.yahoo.zookeeper.Watcher#process(com.yahoo.zookeeper.proto.WatcherEvent)
  581. */
  582. @Override
  583. public void process(WatcherEvent event) {
  584. dm.process(event);
  585. }
  586. @Override
  587. public void run() {
  588. try {
  589. synchronized (this) {
  590. while (!dm.dead) {
  591. wait();
  592. }
  593. }
  594. } catch (InterruptedException e) {
  595. }
  596. }
  597. @Override
  598. public void closing(int rc) {
  599. synchronized (this) {
  600. notifyAll();
  601. }
  602. }
  603. static class StreamWriter extends Thread {
  604. OutputStream os;
  605. InputStream is;
  606. StreamWriter(InputStream is, OutputStream os) {
  607. this.is = is;
  608. this.os = os;
  609. start();
  610. }
  611. public void run() {
  612. byte b[] = new byte[80];
  613. int rc;
  614. try {
  615. while ((rc = is.read(b)) &gt; 0) {
  616. os.write(b, 0, rc);
  617. }
  618. } catch (IOException e) {
  619. }
  620. }
  621. }
  622. @Override
  623. public void exists(byte[] data) {
  624. if (data == null) {
  625. if (child != null) {
  626. System.out.println("Killing process");
  627. child.destroy();
  628. try {
  629. child.waitFor();
  630. } catch (InterruptedException e) {
  631. }
  632. }
  633. child = null;
  634. } else {
  635. if (child != null) {
  636. System.out.println("Stopping child");
  637. child.destroy();
  638. try {
  639. child.waitFor();
  640. } catch (InterruptedException e) {
  641. e.printStackTrace();
  642. }
  643. }
  644. try {
  645. FileOutputStream fos = new FileOutputStream(filename);
  646. fos.write(data);
  647. fos.close();
  648. } catch (IOException e) {
  649. e.printStackTrace();
  650. }
  651. try {
  652. System.out.println("Starting child");
  653. child = Runtime.getRuntime().exec(exec);
  654. new StreamWriter(child.getInputStream(), System.out);
  655. new StreamWriter(child.getErrorStream(), System.err);
  656. } catch (IOException e) {
  657. e.printStackTrace();
  658. }
  659. }
  660. }
  661. }
  662. </pre>
  663. </div>
  664. </div>
  665. <div class="note example">
  666. <div class="label">DataMonitor.java</div>
  667. <div class="content">
  668. <title>DataMonitor.java</title>
  669. <pre class="code">
  670. /**
  671. * A simple class that monitors the data and existence of a ZooKeeper
  672. * node. It uses asynchronous ZooKeeper APIs.
  673. */
  674. package com.yahoo.zk.executor;
  675. import java.util.Arrays;
  676. import com.yahoo.zookeeper.KeeperException;
  677. import com.yahoo.zookeeper.Watcher;
  678. import com.yahoo.zookeeper.ZooKeeper;
  679. import com.yahoo.zookeeper.AsyncCallback.StatCallback;
  680. import com.yahoo.zookeeper.KeeperException.Code;
  681. import com.yahoo.zookeeper.data.Stat;
  682. import com.yahoo.zookeeper.proto.WatcherEvent;
  683. public class DataMonitor implements Watcher, StatCallback {
  684. ZooKeeper zk;
  685. String znode;
  686. Watcher chainedWatcher;
  687. boolean dead;
  688. DataMonitorListener listener;
  689. byte prevData[];
  690. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  691. DataMonitorListener listener) {
  692. this.zk = zk;
  693. this.znode = znode;
  694. this.chainedWatcher = chainedWatcher;
  695. this.listener = listener;
  696. // Get things started by checking if the node exists. We are going
  697. // to be completely event driven
  698. zk.exists(znode, true, this, null);
  699. }
  700. /**
  701. * Other classes use the DataMonitor by implementing this method
  702. */
  703. public interface DataMonitorListener {
  704. /**
  705. * The existence status of the node has changed.
  706. */
  707. void exists(byte data[]);
  708. /**
  709. * The ZooKeeper session is no longer valid.
  710. *
  711. * @param rc
  712. * the ZooKeeper reason code
  713. */
  714. void closing(int rc);
  715. }
  716. @Override
  717. /**
  718. * This is a watch event callback. The node we were watching has changed or
  719. * something happened to our connection to ZooKeeper.
  720. */
  721. public void process(WatcherEvent event) {
  722. String path = event.getPath();
  723. if (event.getType() == Watcher.Event.EventNone) {
  724. // We are are being told that the state of the
  725. // connection has changed
  726. switch (event.getState()) {
  727. case Event.KeeperStateSyncConnected:
  728. // Everything is happy. Lets kick things off
  729. // again by checking the existence of the znode
  730. zk.exists(znode, true, this, null);
  731. break;
  732. case Event.KeeperStateExpired:
  733. // It's all over
  734. dead = true;
  735. listener.closing(KeeperException.Code.SessionExpired);
  736. break;
  737. }
  738. } else {
  739. if (path != null &amp;&amp; path.equals(znode)) {
  740. // Something has changed on the node, let's find out
  741. zk.exists(znode, true, this, null);
  742. }
  743. }
  744. if (chainedWatcher != null) {
  745. chainedWatcher.process(event);
  746. }
  747. }
  748. @Override
  749. public void processResult(int rc, String path, Object ctx, Stat stat) {
  750. boolean exists;
  751. switch (rc) {
  752. case Code.Ok:
  753. exists = true;
  754. break;
  755. case Code.NoNode:
  756. exists = false;
  757. break;
  758. case Code.SessionExpired:
  759. case Code.NoAuth:
  760. dead = true;
  761. listener.closing(rc);
  762. return;
  763. default:
  764. // Retry errors
  765. zk.exists(znode, true, this, null);
  766. return;
  767. }
  768. byte b[] = null;
  769. if (exists) {
  770. try {
  771. b = zk.getData(znode, false, null);
  772. } catch (KeeperException e) {
  773. // We don't need to worry about recovering now. The watch
  774. // callbacks will kick off any exception handling
  775. e.printStackTrace();
  776. } catch (InterruptedException e) {
  777. return;
  778. }
  779. }
  780. if ((b == null &amp;&amp; b != prevData)
  781. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  782. listener.exists(b);
  783. prevData = b;
  784. }
  785. }
  786. }
  787. </pre>
  788. </div>
  789. </div>
  790. </div>
  791. <p align="right">
  792. <font size="-2"></font>
  793. </p>
  794. </div>
  795. <!--+
  796. |end content
  797. +-->
  798. <div class="clearboth">&nbsp;</div>
  799. </div>
  800. <div id="footer">
  801. <!--+
  802. |start bottomstrip
  803. +-->
  804. <div class="lastmodified">
  805. <script type="text/javascript"><!--
  806. document.write("Last Published: " + document.lastModified);
  807. // --></script>
  808. </div>
  809. <div class="copyright">
  810. Copyright &copy;
  811. 2008 <a href="http://www.apache.org/licenses/">The Apache Software Foundation.</a>
  812. </div>
  813. <!--+
  814. |end bottomstrip
  815. +-->
  816. </div>
  817. </body>
  818. </html>