javaExample.html 28 KB

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