javaExample.html 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <META http-equiv="Content-Type" content="text/html; charset=UTF-8">
  5. <meta content="Apache Forrest" name="Generator">
  6. <meta name="Forrest-version" content="0.8">
  7. <meta name="Forrest-skin-name" content="pelt">
  8. <title>ZooKeeper Java Example</title>
  9. <link type="text/css" href="skin/basic.css" rel="stylesheet">
  10. <link media="screen" type="text/css" href="skin/screen.css" rel="stylesheet">
  11. <link media="print" type="text/css" href="skin/print.css" rel="stylesheet">
  12. <link type="text/css" href="skin/profile.css" rel="stylesheet">
  13. <script src="skin/getBlank.js" language="javascript" type="text/javascript"></script><script src="skin/getMenu.js" language="javascript" type="text/javascript"></script><script src="skin/fontsize.js" language="javascript" type="text/javascript"></script>
  14. <link rel="shortcut icon" href="images/favicon.ico">
  15. </head>
  16. <body onload="init()">
  17. <script type="text/javascript">ndeSetTextSize();</script>
  18. <div id="top">
  19. <!--+
  20. |breadtrail
  21. +-->
  22. <div class="breadtrail">
  23. <a href="http://www.apache.org/">Apache</a> &gt; <a href="http://hadoop.apache.org/">Hadoop</a> &gt; <a href="http://hadoop.apache.org/zookeeper/">ZooKeeper</a><script src="skin/breadcrumbs.js" language="JavaScript" type="text/javascript"></script>
  24. </div>
  25. <!--+
  26. |header
  27. +-->
  28. <div class="header">
  29. <!--+
  30. |start group logo
  31. +-->
  32. <div class="grouplogo">
  33. <a href="http://hadoop.apache.org/"><img class="logoImage" alt="Hadoop" src="images/hadoop-logo.jpg" title="Apache Hadoop"></a>
  34. </div>
  35. <!--+
  36. |end group logo
  37. +-->
  38. <!--+
  39. |start Project Logo
  40. +-->
  41. <div class="projectlogo">
  42. <a href="http://hadoop.apache.org/zookeeper/"><img class="logoImage" alt="ZooKeeper" src="images/zookeeper_small.gif" title="The Hadoop database"></a>
  43. </div>
  44. <!--+
  45. |end Project Logo
  46. +-->
  47. <!--+
  48. |start Search
  49. +-->
  50. <div class="searchbox">
  51. <form action="http://www.google.com/search" method="get" class="roundtopsmall">
  52. <input value="hadoop.apache.org" name="sitesearch" type="hidden"><input onFocus="getBlank (this, 'Search the site with google');" size="25" name="q" id="query" type="text" value="Search the site with google">&nbsp;
  53. <input name="Search" value="Search" type="submit">
  54. </form>
  55. </div>
  56. <!--+
  57. |end search
  58. +-->
  59. <!--+
  60. |start Tabs
  61. +-->
  62. <ul id="tabs">
  63. <li>
  64. <a class="unselected" href="http://hadoop.apache.org/zookeeper/">Project</a>
  65. </li>
  66. <li>
  67. <a class="unselected" href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  68. </li>
  69. <li class="current">
  70. <a class="selected" href="index.html">ZooKeeper Documentation</a>
  71. </li>
  72. </ul>
  73. <!--+
  74. |end Tabs
  75. +-->
  76. </div>
  77. </div>
  78. <div id="main">
  79. <div id="publishedStrip">
  80. <!--+
  81. |start Subtabs
  82. +-->
  83. <div id="level2tabs"></div>
  84. <!--+
  85. |end Endtabs
  86. +-->
  87. <script type="text/javascript"><!--
  88. document.write("Last Published: " + document.lastModified);
  89. // --></script>
  90. </div>
  91. <!--+
  92. |breadtrail
  93. +-->
  94. <div class="breadtrail">
  95. &nbsp;
  96. </div>
  97. <!--+
  98. |start Menu, mainarea
  99. +-->
  100. <!--+
  101. |start Menu
  102. +-->
  103. <div id="menu">
  104. <div onclick="SwitchMenu('menu_1.1', 'skin/')" id="menu_1.1Title" class="menutitle">Overview</div>
  105. <div id="menu_1.1" class="menuitemgroup">
  106. <div class="menuitem">
  107. <a href="index.html">Welcome</a>
  108. </div>
  109. <div class="menuitem">
  110. <a href="zookeeperOver.html">Overview</a>
  111. </div>
  112. <div class="menuitem">
  113. <a href="zookeeperStarted.html">Getting Started</a>
  114. </div>
  115. <div 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>
  143. <div onclick="SwitchMenu('menu_1.4', 'skin/')" id="menu_1.4Title" class="menutitle">Contributor</div>
  144. <div id="menu_1.4" class="menuitemgroup">
  145. <div class="menuitem">
  146. <a href="zookeeperInternals.html">ZooKeeper Internals</a>
  147. </div>
  148. </div>
  149. <div onclick="SwitchMenu('menu_1.5', 'skin/')" id="menu_1.5Title" class="menutitle">Informal Documentation</div>
  150. <div id="menu_1.5" class="menuitemgroup">
  151. <div class="menuitem">
  152. <a href="http://wiki.apache.org/hadoop/ZooKeeper">Wiki</a>
  153. </div>
  154. <div class="menuitem">
  155. <a href="http://wiki.apache.org/hadoop/ZooKeeper/FAQ">FAQ</a>
  156. </div>
  157. <div class="menuitem">
  158. <a href="http://hadoop.apache.org/zookeeper/mailing_lists.html">Mailing Lists</a>
  159. </div>
  160. <div class="menuitem">
  161. <a href="zookeeperOtherInfo.html">Other Info</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> a znode, by name</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. Executor theExectutor = new Executor(hostPort, znode, filename, exec);
  273. theExectutor.run();
  274. } catch (Exception e) {
  275. e.printStackTrace();
  276. }
  277. }
  278. public Executor(String hostPort, String znode, String filename,
  279. String exec[]) throws KeeperException, IOException {
  280. this.filename = filename;
  281. this.exec = exec;
  282. //create a new zookeeper object, passing a self-reference in a the Watcher
  283. zk = new ZooKeeper(hostPort, 3000, this);
  284. dm = new DataMonitor(zk, znode, null, this);
  285. }
  286. public void run() {
  287. try {
  288. synchronized (this) {
  289. while (!dm.dead) {
  290. wait();
  291. }
  292. }
  293. } catch (InterruptedException e) {
  294. }
  295. }
  296. </pre>
  297. <p>
  298. Recall that the Executor's job is to starts and stop the executable whose name you pass in on the command line.
  299. It does this in response to events fired by the ZooKeeper object. As you can see in the code above, the Executor passes
  300. a reference to itself as the Watcher argument in the ZooKeeper constructor. It also passes a reference to itself
  301. as DataMonitorListener argument to the DataMonitor constructor. Per the Executor's definition, it implements both these
  302. interfaces:
  303. </p>
  304. <pre class="code">
  305. public class Executor implements Watcher, Runnable, DataMonitorListener {
  306. ...
  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(WatcherEvent 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(WatcherEvent event) {
  487. String path = event.getPath();
  488. if (event.getType() == Watcher.Event.EventNone) {
  489. // We are are being told that the state of the
  490. // connection has changed
  491. switch (event.getState()) {
  492. case Event.KeeperStateSyncConnected:
  493. // Everything is happy. Lets kick things off
  494. // again by checking the existence of the znode
  495. zk.exists(znode, true, this, null);
  496. break;
  497. case Event.KeeperStateExpired:
  498. // It's all over
  499. dead = true;
  500. listener.closing(KeeperException.Code.SessionExpired);
  501. break;
  502. }
  503. } else {
  504. if (path != null &amp;&amp; path.equals(znode)) {
  505. // Something has changed on the node, let's find out
  506. zk.exists(znode, true, this, null);
  507. }
  508. }
  509. if (chainedWatcher != null) {
  510. chainedWatcher.process(event);
  511. }
  512. }
  513. </pre>
  514. <p>
  515. If the client-side ZooKeeper libraries can reestablish the communication channel to ZooKeeper, DataMonitor simply kicks
  516. everything off again with the call to <span class="codefrag command">ZooKeeper.exists()</span>.
  517. If it gets an event for a znode, it calls <span class="codefrag command">ZooKeeper.exists()</span> to find out what has changed.
  518. </p>
  519. </div>
  520. <a name="N10104"></a><a name="sc_completeSourceCode"></a>
  521. <h2 class="h3">Complete Source Listings</h2>
  522. <div class="section">
  523. <div class="note example">
  524. <div class="label">Executor.java</div>
  525. <div class="content">
  526. <title>Executor.java</title>
  527. <pre class="code">
  528. /**
  529. * A simple example program to use DataMonitor to start and
  530. * stop executables based on a znode. The program watches the
  531. * specified znode and saves the data that corresponds to the
  532. * znode in the filesystem. It also starts the specified program
  533. * with the specified arguments when the znode exists and kills
  534. * the program if the znode goes away.
  535. */
  536. package com.yahoo.zk.executor;
  537. import java.io.FileOutputStream;
  538. import java.io.IOException;
  539. import java.io.InputStream;
  540. import java.io.OutputStream;
  541. import com.yahoo.zk.executor.DataMonitor.DataMonitorListener;
  542. import com.yahoo.zookeeper.KeeperException;
  543. import com.yahoo.zookeeper.Watcher;
  544. import com.yahoo.zookeeper.ZooKeeper;
  545. import com.yahoo.zookeeper.proto.WatcherEvent;
  546. public class Executor implements Watcher, Runnable, DataMonitorListener {
  547. String znode;
  548. DataMonitor dm;
  549. ZooKeeper zk;
  550. String filename;
  551. String exec[];
  552. Process child;
  553. public Executor(String hostPort, String znode, String filename,
  554. String exec[]) throws KeeperException, IOException {
  555. this.filename = filename;
  556. this.exec = exec;
  557. zk = new ZooKeeper(hostPort, 3000, this);
  558. dm = new DataMonitor(zk, znode, null, this);
  559. }
  560. /**
  561. * @param args
  562. */
  563. public static void main(String[] args) {
  564. if (args.length &lt; 4) {
  565. System.err
  566. .println("USAGE: Executor hostPort znode filename program [args ...]");
  567. System.exit(2);
  568. }
  569. String hostPort = args[0];
  570. String znode = args[1];
  571. String filename = args[2];
  572. String exec[] = new String[args.length - 3];
  573. System.arraycopy(args, 3, exec, 0, exec.length);
  574. try {
  575. new Executor(hostPort, znode, filename, exec).run();
  576. } catch (Exception e) {
  577. e.printStackTrace();
  578. }
  579. }
  580. /***************************************************************************
  581. * We do process any events ourselves, we just need to forward them on.
  582. *
  583. * @see com.yahoo.zookeeper.Watcher#process(com.yahoo.zookeeper.proto.WatcherEvent)
  584. */
  585. @Override
  586. public void process(WatcherEvent event) {
  587. dm.process(event);
  588. }
  589. @Override
  590. public void run() {
  591. try {
  592. synchronized (this) {
  593. while (!dm.dead) {
  594. wait();
  595. }
  596. }
  597. } catch (InterruptedException e) {
  598. }
  599. }
  600. @Override
  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. @Override
  626. public void exists(byte[] data) {
  627. if (data == null) {
  628. if (child != null) {
  629. System.out.println("Killing process");
  630. child.destroy();
  631. try {
  632. child.waitFor();
  633. } catch (InterruptedException e) {
  634. }
  635. }
  636. child = null;
  637. } else {
  638. if (child != null) {
  639. System.out.println("Stopping child");
  640. child.destroy();
  641. try {
  642. child.waitFor();
  643. } catch (InterruptedException e) {
  644. e.printStackTrace();
  645. }
  646. }
  647. try {
  648. FileOutputStream fos = new FileOutputStream(filename);
  649. fos.write(data);
  650. fos.close();
  651. } catch (IOException e) {
  652. e.printStackTrace();
  653. }
  654. try {
  655. System.out.println("Starting child");
  656. child = Runtime.getRuntime().exec(exec);
  657. new StreamWriter(child.getInputStream(), System.out);
  658. new StreamWriter(child.getErrorStream(), System.err);
  659. } catch (IOException e) {
  660. e.printStackTrace();
  661. }
  662. }
  663. }
  664. }
  665. </pre>
  666. </div>
  667. </div>
  668. <div class="note example">
  669. <div class="label">DataMonitor.java</div>
  670. <div class="content">
  671. <title>DataMonitor.java</title>
  672. <pre class="code">
  673. /**
  674. * A simple class that monitors the data and existence of a ZooKeeper
  675. * node. It uses asynchronous ZooKeeper APIs.
  676. */
  677. package com.yahoo.zk.executor;
  678. import java.util.Arrays;
  679. import com.yahoo.zookeeper.KeeperException;
  680. import com.yahoo.zookeeper.Watcher;
  681. import com.yahoo.zookeeper.ZooKeeper;
  682. import com.yahoo.zookeeper.AsyncCallback.StatCallback;
  683. import com.yahoo.zookeeper.KeeperException.Code;
  684. import com.yahoo.zookeeper.data.Stat;
  685. import com.yahoo.zookeeper.proto.WatcherEvent;
  686. public class DataMonitor implements Watcher, StatCallback {
  687. ZooKeeper zk;
  688. String znode;
  689. Watcher chainedWatcher;
  690. boolean dead;
  691. DataMonitorListener listener;
  692. byte prevData[];
  693. public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,
  694. DataMonitorListener listener) {
  695. this.zk = zk;
  696. this.znode = znode;
  697. this.chainedWatcher = chainedWatcher;
  698. this.listener = listener;
  699. // Get things started by checking if the node exists. We are going
  700. // to be completely event driven
  701. zk.exists(znode, true, this, null);
  702. }
  703. /**
  704. * Other classes use the DataMonitor by implementing this method
  705. */
  706. public interface DataMonitorListener {
  707. /**
  708. * The existence status of the node has changed.
  709. */
  710. void exists(byte data[]);
  711. /**
  712. * The ZooKeeper session is no longer valid.
  713. *
  714. * @param rc
  715. * the ZooKeeper reason code
  716. */
  717. void closing(int rc);
  718. }
  719. @Override
  720. /**
  721. * This is a watch event callback. The node we were watching has changed or
  722. * something happened to our connection to ZooKeeper.
  723. */
  724. public void process(WatcherEvent event) {
  725. String path = event.getPath();
  726. if (event.getType() == Watcher.Event.EventNone) {
  727. // We are are being told that the state of the
  728. // connection has changed
  729. switch (event.getState()) {
  730. case Event.KeeperStateSyncConnected:
  731. // Everything is happy. Lets kick things off
  732. // again by checking the existence of the znode
  733. zk.exists(znode, true, this, null);
  734. break;
  735. case Event.KeeperStateExpired:
  736. // It's all over
  737. dead = true;
  738. listener.closing(KeeperException.Code.SessionExpired);
  739. break;
  740. }
  741. } else {
  742. if (path != null &amp;&amp; path.equals(znode)) {
  743. // Something has changed on the node, let's find out
  744. zk.exists(znode, true, this, null);
  745. }
  746. }
  747. if (chainedWatcher != null) {
  748. chainedWatcher.process(event);
  749. }
  750. }
  751. @Override
  752. public void processResult(int rc, String path, Object ctx, Stat stat) {
  753. boolean exists;
  754. switch (rc) {
  755. case Code.Ok:
  756. exists = true;
  757. break;
  758. case Code.NoNode:
  759. exists = false;
  760. break;
  761. case Code.SessionExpired:
  762. case Code.NoAuth:
  763. dead = true;
  764. listener.closing(rc);
  765. return;
  766. default:
  767. // Retry errors
  768. zk.exists(znode, true, this, null);
  769. return;
  770. }
  771. byte b[] = null;
  772. if (exists) {
  773. try {
  774. b = zk.getData(znode, false, null);
  775. } catch (KeeperException e) {
  776. // We don't need to worry about recovering now. The watch
  777. // callbacks will kick off any exception handling
  778. e.printStackTrace();
  779. } catch (InterruptedException e) {
  780. return;
  781. }
  782. }
  783. if ((b == null &amp;&amp; b != prevData)
  784. || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
  785. listener.exists(b);
  786. prevData = b;
  787. }
  788. }
  789. }
  790. </pre>
  791. </div>
  792. </div>
  793. </div>
  794. <p align="right">
  795. <font size="-2"></font>
  796. </p>
  797. </div>
  798. <!--+
  799. |end content
  800. +-->
  801. <div class="clearboth">&nbsp;</div>
  802. </div>
  803. <div id="footer">
  804. <!--+
  805. |start bottomstrip
  806. +-->
  807. <div class="lastmodified">
  808. <script type="text/javascript"><!--
  809. document.write("Last Published: " + document.lastModified);
  810. // --></script>
  811. </div>
  812. <div class="copyright">
  813. Copyright &copy;
  814. 2008 <a href="http://www.apache.org/licenses/">The Apache Software Foundation.</a>
  815. </div>
  816. <!--+
  817. |end bottomstrip
  818. +-->
  819. </div>
  820. </body>
  821. </html>