List of usage examples for org.apache.zookeeper WatchedEvent getPath
public String getPath()
From source file:com.bigdata.zookeeper.HierarchicalZNodeWatcher.java
License:Open Source License
/** * Note: Synchronized for mutex with {@link #cancel()}. *//* w w w. j a v a2 s .c o m*/ synchronized public void process(final WatchedEvent event) { if (cancelled) { // ignore events once cancelled. return; } if (log.isInfoEnabled()) log.info(event.toString()); /* * Put ALL events in the queue. * * Note: This does NOT mean that the application will see all state * changes for watched znodes. Zookeeper DOES NOT provide that * guarantee. The application CAN miss events between the time that a * state change triggers a WatchedEvent and the time that the * application handles the event and resets the watch. */ queue.add(event); switch (event.getState()) { case Disconnected: return; default: break; } final String path = event.getPath(); switch (event.getType()) { case NodeCreated: /* * We always reset the watch when we see a NodeCreated event for a * znode that we are already watching. * * This event type can occur for the root of the watched hierarchy * since we set the watch regardless of the existence of the zroot. * * If the event occurs for a different znode then it may have been * deleted and re-created and we may have missed the delete event. */ try { zookeeper.exists(path, this); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; case NodeDeleted: /* * A watched znode was deleted. Unless this is the zroot, we will * remove our watch on the znode (the expectation is that the watch * will be re-established if the child is re-created since we will * notice the NodeChildrenChanged event). */ if (zroot.equals(path)) { try { zookeeper.exists(path, this); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } } else { watched.remove(path); removedWatch(path); } return; case NodeDataChanged: try { zookeeper.getData(path, this, new Stat()); } catch (KeeperException e1) { log.error("path=" + path, e1); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; case NodeChildrenChanged: /* * Get the children (and reset our watch on the path). */ try { acceptChildren(path, zookeeper.getChildren(event.getPath(), this)); } catch (KeeperException e) { log.error(this, e); } catch (InterruptedException e1) { if (log.isInfoEnabled()) log.info("path=" + path); } return; default: return; } }
From source file:com.bigdata.zookeeper.TestHierarchicalZNodeWatcher.java
License:Open Source License
/** * Test when the node at the root of the hierarchy does not exist when we * setup the watcher, then create the znode and verify that we see the event * in the queue./* ww w .j a va 2 s .co m*/ * * @throws KeeperException * @throws InterruptedException */ public void test_noticeCreate() throws KeeperException, InterruptedException { WatchedEvent e; final String zroot = this.zroot + "/" + "a"; final HierarchicalZNodeWatcher watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, EXISTS) { @Override protected int watch(String path, String child) { return NONE; } }; assertTrue(watcher.queue.isEmpty()); assertTrue(watcher.isWatched(zroot)); /* * Create the zroot and verify the event is placed into the queue. */ zookeeper.create(zroot, new byte[0], acl, CreateMode.PERSISTENT); // look for the create event. e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); assertNotNull(e); assertEquals(zroot, e.getPath()); assertEquals(Event.EventType.NodeCreated, e.getType()); assertTrue(watcher.queue.isEmpty()); /* * Delete the znode and verify the event is placed into the queue. */ zookeeper.delete(zroot, -1/*version*/); // look for the delete event. e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); /* FIXME There is a stochastic CI failure at the following assertion. * I have increased the poll timeout to the sessionTimeout to see if * that makes the problem go away. BT 6/22/2011. */ assertNotNull(e); assertEquals(zroot, e.getPath()); assertEquals(Event.EventType.NodeDeleted, e.getType()); assertTrue(watcher.queue.isEmpty()); /* * Re-create the zroot and verify the event is placed into the queue * (this makes sure that we are keeping the watch in place). */ zookeeper.create(zroot, new byte[0], acl, CreateMode.PERSISTENT); // look for the create event. e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); assertNotNull(e); assertEquals(zroot, e.getPath()); assertEquals(Event.EventType.NodeCreated, e.getType()); assertTrue(watcher.queue.isEmpty()); /* * cancel the watcher and verify that it does not notice a delete of the * zroot after it was cancelled. */ watcher.cancel(); /* * Delete the znode - no event should appear. */ zookeeper.delete(zroot, -1/*version*/); // look for the delete event. e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); assertNull(e); }
From source file:com.bigdata.zookeeper.TestHierarchicalZNodeWatcher.java
License:Open Source License
/** * Unit test verifies that we notice specific children as they are created * and destroyed. "red" znodes are ignored. if the znode is "blue" then we * extend the watch over its children as well. * //from ww w.j a v a2 s . co m * @throws KeeperException * @throws InterruptedException * * @todo test queue when data is changed. */ public void test_noticeChildren() throws InterruptedException, KeeperException { WatchedEvent e; HierarchicalZNodeWatcher watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, EXISTS | CHILDREN) { @Override protected int watch(String path, String child) { if (child.equals("red")) return NONE; if (child.equals("blue")) return EXISTS | CHILDREN; if (child.equals("green")) return DATA; throw new AssertionFailedError("Not expecting: path=" + path + ", child=" + child); } }; zookeeper.create(zroot + "/" + "red", new byte[0], acl, CreateMode.PERSISTENT); e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); assertNotNull(e); assertEquals(zroot, e.getPath()); assertEquals(Event.EventType.NodeChildrenChanged, e.getType()); zookeeper.create(zroot + "/" + "blue", new byte[0], acl, CreateMode.PERSISTENT); // e = watcher.queue.poll(super.sessionTimeout,TimeUnit.MILLISECONDS); // assertNotNull(e); // assertEquals(zroot+"/"+"red",e.getPath()); // assertEquals(Event.EventType.NodeCreated,e.getType()); zookeeper.create(zroot + "/" + "blue" + "/" + "green", new byte[0], acl, CreateMode.PERSISTENT); assertEquals(NONE, watcher.getFlags(zroot + "/" + "red")); assertEquals(EXISTS | CHILDREN, watcher.getFlags(zroot + "/" + "blue")); assertEquals(DATA, watcher.getFlags(zroot + "/" + "blue" + "/" + "green")); // clear any events in the queue. watcher.queue.clear(); // update the data. zookeeper.setData(zroot + "/" + "blue" + "/" + "green", new byte[] { 1 }, -1/* version */); // verify event. e = watcher.queue.poll(super.sessionTimeout, TimeUnit.MILLISECONDS); assertNotNull(e); assertEquals(zroot + "/" + "blue" + "/" + "green", e.getPath()); assertEquals(Event.EventType.NodeDataChanged, e.getType()); // won't been seen since a "red" path. zookeeper.create(zroot + "/" + "red" + "/" + "blue", new byte[0], acl, CreateMode.PERSISTENT); assertEquals(NONE, watcher.getFlags(zroot + "/" + "red" + "/" + "blue")); /* * There should be three watched znodes: zroot; zroot/blue; and * zroot/blue/green */ assertEquals(3, watcher.getWatchedSize()); watcher.cancel(); assertEquals(0, watcher.getWatchedSize()); assertFalse(watcher.isWatched(zroot)); assertFalse(watcher.isWatched(zroot + "/" + "blue")); assertFalse(watcher.isWatched(zroot + "/" + "blue" + "/" + "green")); assertTrue(watcher.queue.isEmpty()); /* * Setup a new watcher that wathes all paths but the red ones. The * znodes already exist. Now verify that we receive various notices when * the watcher is created. */ watcher = new HierarchicalZNodeWatcher(zookeeper, zroot, ALL, true/* pumpMockEventsDuringStartup */) { @Override protected int watch(String path, String child) { return ALL; } // @Override // protected void addedWatch(String path, int flags) { // // placeMockEventInQueue(path, flags); // // } }; /* * We created 4 znodes plus the pre-existing zroot, so there should be * five nodes picked up by the new watcher. */ final String[] nodes = new String[] { zroot, zroot + "/" + "red", zroot + "/" + "red" + "/" + "blue", zroot + "/" + "blue", zroot + "/" + "green" + "/" + "green", }; // verify new watched size. assertEquals(nodes.length, watcher.getWatchedSize()); /* * Verify mock events were pumped into the queue. Since we specified * ALL, there should be three events for each znode. */ assertEquals(3 * 5, watcher.queue.size()); while ((e = watcher.queue.poll()) != null) { if (log.isInfoEnabled()) log.info("mockEvent: " + e); } // // put into a set. // final HashSet<String> set = new HashSet<String>(Arrays.asList(nodes)); // // for (int i = 0; i < nodes.length; i++) { // // log.info("mockEvent: "+e); // // e = watcher.queue.take(); // // final String path = e.getPath(); // // assertTrue(set.contains(path)); // // e = watcher.queue.take(); // // assertEquals(path, e.getPath()); // // e = watcher.queue.take(); // // assertEquals(path, e.getPath()); // // set.remove(path); // // } watcher.cancel(); }
From source file:com.bigdatafly.flume.zookeeper.Zookeeper.java
License:Apache License
/** * connect ZK, register Watch/unhandle Watch * /*from w w w . j av a 2 s. c o m*/ * @return */ public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root, final WatcherCallBack watcher) { CuratorFramework fk = newCurator(conf, servers, port, root); fk.getCuratorListenable().addListener(new CuratorListener() { public void eventReceived(CuratorFramework _fk, CuratorEvent e) throws Exception { if (e.getType().equals(CuratorEventType.WATCHED)) { WatchedEvent event = e.getWatchedEvent(); watcher.execute(event.getState(), event.getType(), event.getPath()); } } }); fk.getUnhandledErrorListenable().addListener(new UnhandledErrorListener() { public void unhandledError(String msg, Throwable error) { String errmsg = "Unrecoverable Zookeeper error, halting process: " + msg; LOG.error(errmsg, error); } }); fk.start(); return fk; }
From source file:com.brainlounge.zooterrain.zkclient.ZkStateObserver.java
License:Apache License
@Override public void process(WatchedEvent event) { try {/*from w w w . j av a 2 s . c o m*/ final String eventPath = event.getPath(); switch (event.getType()) { case None: break; case NodeCreated: //propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.C)); break; case NodeDeleted: //propagateToListeners(new ZNodeMessage(eventPath, ZNodeMessage.Type.D)); break; case NodeDataChanged: handleDataChanged(eventPath); case NodeChildrenChanged: handleChildrenChanged(eventPath); break; } } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } }
From source file:com.cc.zk.common.ConnectionManager.java
License:Apache License
@Override public synchronized void process(WatchedEvent event) { if (log.isInfoEnabled()) { log.info("Watcher " + this + " name:" + name + " got event " + event + " path:" + event.getPath() + " type:" + event.getType()); }/* w ww. j a v a2 s .c o m*/ if (isClosed) { log.info("Client->ZooKeeper status change trigger but we are already closed"); return; } state = event.getState(); if (state == KeeperState.SyncConnected) { connected = true; clientConnected.countDown(); connectionStrategy.connected(); } else if (state == KeeperState.Expired) { connected = false; log.info( "Our previous ZooKeeper session was expired. Attempting to reconnect to recover relationship with ZooKeeper..."); try { connectionStrategy.reconnect(zkServerAddress, zkClientTimeout, this, new ZkClientConnectionStrategy.ZkUpdate() { @Override public void update(CeZooKeeper keeper) { // if keeper does not replace oldKeeper we must // be sure to close it synchronized (connectionUpdateLock) { try { waitForConnected(Long.MAX_VALUE); } catch (Exception e1) { closeKeeper(keeper); throw new RuntimeException(e1); } log.info("Connection with ZooKeeper reestablished."); try { client.updateKeeper(keeper); } catch (InterruptedException e) { closeKeeper(keeper); Thread.currentThread().interrupt(); // we must have been asked to stop throw new RuntimeException(e); } catch (Throwable t) { closeKeeper(keeper); throw new RuntimeException(t); } if (onReconnect != null) { onReconnect.command(); } synchronized (ConnectionManager.this) { ConnectionManager.this.connected = true; } } } }); } catch (Exception e) { CeException.log(log, "", e); } log.info("Connected:" + connected); } else if (state == KeeperState.Disconnected) { log.info("zkClient has disconnected"); connected = false; connectionStrategy.disconnected(); } else { connected = false; } notifyAll(); }
From source file:com.cloudera.flume.master.ZooKeeperConfigStore.java
License:Apache License
@Override /**/*w w w . j a v a 2 s. co m*/ * This is called whenever an event is seen on the ZK ensemble that we * have registered for. We care particularly about changes to the list of * configurations, made by some other peer. * * TODO This is broken because the translation mechanism "buries" these configs. */ public synchronized void process(WatchedEvent event) { if (client == null) { // This is the 'death-rattle' callback, made when we close the client. return; } LOG.debug("Saw ZooKeeper watch event " + event); if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { if (event.getPath().equals(CFGS_PATH)) { try { LOG.info("Config was updated - reloading"); loadConfigs(CFGS_PATH); } catch (IOException e) { LOG.error("IOException when reloading configs", e); } } if (event.getPath().equals(NODEMAPS_PATH)) { try { LOG.info("Nodemaps were updated - reloading"); loadNodeMaps(NODEMAPS_PATH); } catch (IOException e) { LOG.error("IOException when reloading nodemaps", e); } } if (event.getPath().equals(CHOKEMAP_PATH)) { try { LOG.info("chokemaps were updated - reloading"); loadChokeMap(CHOKEMAP_PATH); } catch (IOException e) { LOG.error("IOException when reloading ChokeMap", e); } } } }
From source file:com.codefollower.lealone.zookeeper.ZooKeeperWatcher.java
License:Apache License
@Override public void process(WatchedEvent event) { switch (event.getType()) { case None: {//from w w w .j a v a 2 s . c o m connectionEvent(event); break; } case NodeCreated: { for (ZooKeeperListener listener : listeners) { listener.nodeCreated(event.getPath()); } break; } case NodeDeleted: { for (ZooKeeperListener listener : listeners) { listener.nodeDeleted(event.getPath()); } break; } case NodeDataChanged: { for (ZooKeeperListener listener : listeners) { listener.nodeDataChanged(event.getPath()); } break; } case NodeChildrenChanged: { for (ZooKeeperListener listener : listeners) { listener.nodeChildrenChanged(event.getPath()); } break; } } }
From source file:com.codemacro.jcm.storage.ZookeeperStorageEngine.java
License:Apache License
public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case SyncConnected: // no matter session expired or not, we simply reload all for (ZookeeperPathWatcher w : watchers.values()) { w.onConnected();/*w w w.j a va 2 s. c om*/ } countDownLatch.countDown(); break; case Disconnected: // zookeeper client will reconnect logger.warn("disconnected from zookeeper"); break; // to test session expired, just close the laptop cover, making OS sleeping case Expired: // session expired by zookeeper server (after reconnected) logger.warn("session expired from zookeeper"); for (ZookeeperPathWatcher w : watchers.values()) { w.onSessionExpired(); } reconnect(); break; default: break; } } String path = event.getPath(); ZookeeperPathWatcher watcher = findWatcher(path); if (watcher == null) { return; } switch (event.getType()) { case NodeChildrenChanged: watcher.onListChanged(); break; case NodeDataChanged: watcher.onChildData(path.substring(1 + path.lastIndexOf('/'))); default: break; } }
From source file:com.dang.crawler.conlony.zookeeper.election.LeaderElectionSupport.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType().equals(Event.EventType.NodeDeleted)) { if (!event.getPath().equals(leaderOffer.getNodePath()) && state != State.STOP) { logger.debug("Node {} deleted. Need to run through the election process.", event.getPath()); try { determineElectionStatus(); } catch (KeeperException e) { becomeFailed(e);/*from w w w . j a v a2 s .c om*/ } catch (InterruptedException e) { becomeFailed(e); } } } }