javaExample.html 28 KB

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