javaExample.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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 3.1 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="zookeeperJMX.html">JMX</a>
  144. </div>
  145. </div>
  146. <div onclick="SwitchMenu('menu_1.4', 'skin/')" id="menu_1.4Title" class="menutitle">Contributor</div>
  147. <div id="menu_1.4" class="menuitemgroup">
  148. <div class="menuitem">
  149. <a href="zookeeperInternals.html">ZooKeeper Internals</a>
  150. </div>
  151. </div>
  152. <div onclick="SwitchMenu('menu_1.5', 'skin/')" id="menu_1.5Title" class="menutitle">Miscellaneous</div>
  153. <div id="menu_1.5" class="menuitemgroup">
  154. <div class="menuitem">
  155. <a href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  156. </div>
  157. <div class="menuitem">
  158. <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ">FAQ</a>
  159. </div>
  160. <div class="menuitem">
  161. <a href="http://hadoop.apache.org/zookeeper/mailing_lists.html">Mailing Lists</a>
  162. </div>
  163. </div>
  164. <div id="credit"></div>
  165. <div id="roundbottom">
  166. <img style="display: none" class="corner" height="15" width="15" alt="" src="skin/images/rc-b-l-15-1body-2menu-3menu.png"></div>
  167. <!--+
  168. |alternative credits
  169. +-->
  170. <div id="credit2"></div>
  171. </div>
  172. <!--+
  173. |end Menu
  174. +-->
  175. <!--+
  176. |start content
  177. +-->
  178. <div id="content">
  179. <div title="Portable Document Format" class="pdflink">
  180. <a class="dida" href="javaExample.pdf"><img alt="PDF -icon" src="skin/images/pdfdoc.gif" class="skin"><br>
  181. PDF</a>
  182. </div>
  183. <h1>ZooKeeper Java Example</h1>
  184. <div id="minitoc-area">
  185. <ul class="minitoc">
  186. <li>
  187. <a href="#ch_Introduction">A Simple Watch Client</a>
  188. <ul class="minitoc">
  189. <li>
  190. <a href="#sc_requirements">Requirements</a>
  191. </li>
  192. <li>
  193. <a href="#sc_design">Program Design</a>
  194. </li>
  195. </ul>
  196. </li>
  197. <li>
  198. <a href="#sc_executor">The Executor Class</a>
  199. </li>
  200. <li>
  201. <a href="#sc_DataMonitor">The DataMonitor Class</a>
  202. </li>
  203. <li>
  204. <a href="#sc_completeSourceCode">Complete Source Listings</a>
  205. </li>
  206. </ul>
  207. </div>
  208. <a name="N10009"></a><a name="ch_Introduction"></a>
  209. <h2 class="h3">A Simple Watch Client</h2>
  210. <div class="section">
  211. <p>To introduce you to the ZooKeeper Java API, we develop here a very simple
  212. watch client. This ZooKeeper client watches a ZooKeeper node for changes
  213. and responds to by starting or stopping a program.</p>
  214. <a name="N10012"></a><a name="sc_requirements"></a>
  215. <h3 class="h4">Requirements</h3>
  216. <p>The client has four requirements:</p>
  217. <ul>
  218. <li>
  219. <p>It takes as parameters:</p>
  220. <ul>
  221. <li>
  222. <p>the address of the ZooKeeper service</p>
  223. </li>
  224. <li>
  225. <p>then name of a znode - the one to be watched</p>
  226. </li>
  227. <li>
  228. <p>an executable with arguments.</p>
  229. </li>
  230. </ul>
  231. </li>
  232. <li>
  233. <p>It fetches the data associated with the znode and starts the executable.</p>
  234. </li>
  235. <li>
  236. <p>If the znode changes, the client refetches the contents and restarts the executable.</p>
  237. </li>
  238. <li>
  239. <p>If the znode disappears, the client kills the executable.</p>
  240. </li>
  241. </ul>
  242. <a name="N1003B"></a><a name="sc_design"></a>
  243. <h3 class="h4">Program Design</h3>
  244. <p>Conventionally, ZooKeeper applications are broken into two units, one which maintains the connection,
  245. and the other which monitors data. In this application, the class called the <strong>Executor</strong>
  246. maintains the ZooKeeper connection, and the class called the <strong>DataMonitor</strong> monitors the data
  247. in the ZooKeeper tree. Also, Executor contains the main thread and contains the execution logic.
  248. It is responsible for what little user interaction there is, as well as interaction with the exectuable program you
  249. pass in as an argument and which the sample (per the requirements) shuts down and restarts, according to the
  250. state of the znode.</p>
  251. </div>
  252. <a name="N1004C"></a><a name="sc_executor"></a>
  253. <h2 class="h3">The Executor Class</h2>
  254. <div class="section">
  255. <p>The Executor object is the primary container of the sample application. It contains
  256. both the <strong>ZooKeeper</strong> object, <strong>DataMonitor</strong>, as described above in
  257. <a href="#sc_design">Program Design</a>. </p>
  258. <pre class="code">
  259. // from the Executor class...
  260. public static void main(String[] args) {
  261. if (args.length &lt; 4) {
  262. System.err
  263. .println("USAGE: Executor hostPort znode filename program [args ...]");
  264. System.exit(2);
  265. }
  266. String hostPort = args[0];
  267. String znode = args[1];
  268. String filename = args[2];
  269. String exec[] = new String[args.length - 3];
  270. System.arraycopy(args, 3, exec, 0, exec.length);
  271. try {
  272. new Executor(hostPort, znode, filename, exec).run();
  273. } catch (Exception e) {
  274. e.printStackTrace();
  275. }
  276. }
  277. public Executor(String hostPort, String znode, String filename,
  278. String exec[]) throws KeeperException, IOException {
  279. this.filename = filename;
  280. this.exec = exec;
  281. zk = new ZooKeeper(hostPort, 3000, this);
  282. dm = new DataMonitor(zk, znode, null, this);
  283. }
  284. public void run() {
  285. try {
  286. synchronized (this) {
  287. while (!dm.dead) {
  288. wait();
  289. }
  290. }
  291. } catch (InterruptedException e) {
  292. }
  293. }
  294. </pre>
  295. <p>
  296. Recall that the Executor's job is to starts and stop the executable whose name you pass in on the command line.
  297. It does this in response to events fired by the ZooKeeper object. As you can see in the code above, the Executor passes
  298. a reference to itself as the Watcher argument in the ZooKeeper constructor. It also passes a reference to itself
  299. as DataMonitorListener argument to the DataMonitor constructor. Per the Executor's definition, it implements both these
  300. interfaces:
  301. </p>
  302. <pre class="code">
  303. public class Executor implements Watcher, Runnable, DataMonitor.DataMonitorListener {
  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(WatchedEvent 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(WatchedEvent event) {
  484. String path = event.getPath();
  485. if (event.getType() == Event.EventType.None) {
  486. // We are are being told that the state of the
  487. // connection has changed
  488. switch (event.getState()) {
  489. case SyncConnected:
  490. // In this particular example we don't need to do anything
  491. // here - watches are automatically re-registered with
  492. // server and any watches triggered while the client was
  493. // disconnected will be delivered (in order of course)
  494. break;
  495. case Expired:
  496. // It's all over
  497. dead = true;
  498. listener.closing(KeeperException.Code.SessionExpired);
  499. break;
  500. }
  501. } else {
  502. if (path != null &amp;&amp; path.equals(znode)) {
  503. // Something has changed on the node, let's find out
  504. zk.exists(znode, true, this, null);
  505. }
  506. }
  507. if (chainedWatcher != null) {
  508. chainedWatcher.process(event);
  509. }
  510. }
  511. </pre>
  512. <p>
  513. If the client-side ZooKeeper libraries can re-establish the
  514. communication channel (SyncConnected event) to ZooKeeper before
  515. session expiration (Expired event) all of the session's watches will
  516. automatically be re-established with the server (auto-reset of watches
  517. is new in ZooKeeper 3.0.0). See <a href="zookeeperProgrammers.html#ch_zkWatches">ZooKeeper Watches</a>
  518. in the programmer guide for more on this. A bit lower down in this
  519. function, when DataMonitor gets an event for a znode, it calls
  520. <span class="codefrag command">ZooKeeper.exists()</span> to find out what has changed.
  521. </p>
  522. </div>
  523. <a name="N10104"></a><a name="sc_completeSourceCode"></a>
  524. <h2 class="h3">Complete Source Listings</h2>
  525. <div class="section">
  526. <div class="note example">
  527. <div class="label">Executor.java</div>
  528. <div class="content">
  529. <title>Executor.java</title>
  530. <pre class="code">
  531. /**
  532. * A simple example program to use DataMonitor to start and
  533. * stop executables based on a znode. The program watches the
  534. * specified znode and saves the data that corresponds to the
  535. * znode in the filesystem. It also starts the specified program
  536. * with the specified arguments when the znode exists and kills
  537. * the program if the znode goes away.
  538. */
  539. import java.io.FileOutputStream;
  540. import java.io.IOException;
  541. import java.io.InputStream;
  542. import java.io.OutputStream;
  543. import org.apache.zookeeper.KeeperException;
  544. import org.apache.zookeeper.WatchedEvent;
  545. import org.apache.zookeeper.Watcher;
  546. import org.apache.zookeeper.ZooKeeper;
  547. public class Executor
  548. implements Watcher, Runnable, DataMonitor.DataMonitorListener
  549. {
  550. String znode;
  551. DataMonitor dm;
  552. ZooKeeper zk;
  553. String filename;
  554. String exec[];
  555. Process child;
  556. public Executor(String hostPort, String znode, String filename,
  557. String exec[]) throws KeeperException, IOException {
  558. this.filename = filename;
  559. this.exec = exec;
  560. zk = new ZooKeeper(hostPort, 3000, this);
  561. dm = new DataMonitor(zk, znode, null, this);
  562. }
  563. /**
  564. * @param args
  565. */
  566. public static void main(String[] args) {
  567. if (args.length &lt; 4) {
  568. System.err
  569. .println("USAGE: Executor hostPort znode filename program [args ...]");
  570. System.exit(2);
  571. }
  572. String hostPort = args[0];
  573. String znode = args[1];
  574. String filename = args[2];
  575. String exec[] = new String[args.length - 3];
  576. System.arraycopy(args, 3, exec, 0, exec.length);
  577. try {
  578. new Executor(hostPort, znode, filename, exec).run();
  579. } catch (Exception e) {
  580. e.printStackTrace();
  581. }
  582. }
  583. /***************************************************************************
  584. * We do process any events ourselves, we just need to forward them on.
  585. *
  586. * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)
  587. */
  588. public void process(WatchedEvent event) {
  589. dm.process(event);
  590. }
  591. public void run() {
  592. try {
  593. synchronized (this) {
  594. while (!dm.dead) {
  595. wait();
  596. }
  597. }
  598. } catch (InterruptedException e) {
  599. }
  600. }
  601. public void closing(int rc) {
  602. synchronized (this) {
  603. notifyAll();
  604. }
  605. }
  606. static class StreamWriter extends Thread {
  607. OutputStream os;
  608. InputStream is;
  609. StreamWriter(InputStream is, OutputStream os) {
  610. this.is = is;
  611. this.os = os;
  612. start();
  613. }
  614. public void run() {
  615. byte b[] = new byte[80];
  616. int rc;
  617. try {
  618. while ((rc = is.read(b)) &gt; 0) {
  619. os.write(b, 0, rc);
  620. }
  621. } catch (IOException e) {
  622. }
  623. }
  624. }
  625. public void exists(byte[] data) {
  626. if (data == null) {
  627. if (child != null) {
  628. System.out.println("Killing process");
  629. child.destroy();
  630. try {
  631. child.waitFor();
  632. } catch (InterruptedException e) {
  633. }
  634. }
  635. child = null;
  636. } else {
  637. if (child != null) {
  638. System.out.println("Stopping child");
  639. child.destroy();
  640. try {
  641. child.waitFor();
  642. } catch (InterruptedException e) {
  643. e.printStackTrace();
  644. }
  645. }
  646. try {
  647. FileOutputStream fos = new FileOutputStream(filename);
  648. fos.write(data);
  649. fos.close();
  650. } catch (IOException e) {
  651. e.printStackTrace();
  652. }
  653. try {
  654. System.out.println("Starting child");
  655. child = Runtime.getRuntime().exec(exec);
  656. new StreamWriter(child.getInputStream(), System.out);
  657. new StreamWriter(child.getErrorStream(), System.err);
  658. } catch (IOException e) {
  659. e.printStackTrace();
  660. }
  661. }
  662. }
  663. }
  664. </pre>
  665. </div>
  666. </div>
  667. <div class="note example">
  668. <div class="label">DataMonitor.java</div>
  669. <div class="content">
  670. <title>DataMonitor.java</title>
  671. <pre class="code">
  672. /**
  673. * A simple class that monitors the data and existence of a ZooKeeper
  674. * node. It uses asynchronous ZooKeeper APIs.
  675. */
  676. import java.util.Arrays;
  677. import org.apache.zookeeper.KeeperException;
  678. import org.apache.zookeeper.WatchedEvent;
  679. import org.apache.zookeeper.Watcher;
  680. import org.apache.zookeeper.ZooKeeper;
  681. import org.apache.zookeeper.AsyncCallback.StatCallback;
  682. import org.apache.zookeeper.KeeperException.Code;
  683. import org.apache.zookeeper.data.Stat;
  684. public class DataMonitor implements Watcher, StatCallback {
  685. ZooKeeper zk;
  686. String znode;
  687. Watcher chainedWatcher;
  688. boolean dead;
  689. DataMonitorListener listener;
  690. byte prevData[];
  691. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  692. DataMonitorListener listener) {
  693. this.zk = zk;
  694. this.znode = znode;
  695. this.chainedWatcher = chainedWatcher;
  696. this.listener = listener;
  697. // Get things started by checking if the node exists. We are going
  698. // to be completely event driven
  699. zk.exists(znode, true, this, null);
  700. }
  701. /**
  702. * Other classes use the DataMonitor by implementing this method
  703. */
  704. public interface DataMonitorListener {
  705. /**
  706. * The existence status of the node has changed.
  707. */
  708. void exists(byte data[]);
  709. /**
  710. * The ZooKeeper session is no longer valid.
  711. *
  712. * @param rc
  713. * the ZooKeeper reason code
  714. */
  715. void closing(int rc);
  716. }
  717. public void process(WatchedEvent event) {
  718. String path = event.getPath();
  719. if (event.getType() == Event.EventType.None) {
  720. // We are are being told that the state of the
  721. // connection has changed
  722. switch (event.getState()) {
  723. case SyncConnected:
  724. // In this particular example we don't need to do anything
  725. // here - watches are automatically re-registered with
  726. // server and any watches triggered while the client was
  727. // disconnected will be delivered (in order of course)
  728. break;
  729. case Expired:
  730. // It's all over
  731. dead = true;
  732. listener.closing(KeeperException.Code.SessionExpired);
  733. break;
  734. }
  735. } else {
  736. if (path != null &amp;&amp; path.equals(znode)) {
  737. // Something has changed on the node, let's find out
  738. zk.exists(znode, true, this, null);
  739. }
  740. }
  741. if (chainedWatcher != null) {
  742. chainedWatcher.process(event);
  743. }
  744. }
  745. public void processResult(int rc, String path, Object ctx, Stat stat) {
  746. boolean exists;
  747. switch (rc) {
  748. case Code.Ok:
  749. exists = true;
  750. break;
  751. case Code.NoNode:
  752. exists = false;
  753. break;
  754. case Code.SessionExpired:
  755. case Code.NoAuth:
  756. dead = true;
  757. listener.closing(rc);
  758. return;
  759. default:
  760. // Retry errors
  761. zk.exists(znode, true, this, null);
  762. return;
  763. }
  764. byte b[] = null;
  765. if (exists) {
  766. try {
  767. b = zk.getData(znode, false, null);
  768. } catch (KeeperException e) {
  769. // We don't need to worry about recovering now. The watch
  770. // callbacks will kick off any exception handling
  771. e.printStackTrace();
  772. } catch (InterruptedException e) {
  773. return;
  774. }
  775. }
  776. if ((b == null &amp;&amp; b != prevData)
  777. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  778. listener.exists(b);
  779. prevData = b;
  780. }
  781. }
  782. }
  783. </pre>
  784. </div>
  785. </div>
  786. </div>
  787. <p align="right">
  788. <font size="-2"></font>
  789. </p>
  790. </div>
  791. <!--+
  792. |end content
  793. +-->
  794. <div class="clearboth">&nbsp;</div>
  795. </div>
  796. <div id="footer">
  797. <!--+
  798. |start bottomstrip
  799. +-->
  800. <div class="lastmodified">
  801. <script type="text/javascript"><!--
  802. document.write("Last Published: " + document.lastModified);
  803. // --></script>
  804. </div>
  805. <div class="copyright">
  806. Copyright &copy;
  807. 2008 <a href="http://www.apache.org/licenses/">The Apache Software Foundation.</a>
  808. </div>
  809. <!--+
  810. |end bottomstrip
  811. +-->
  812. </div>
  813. </body>
  814. </html>