List of usage examples for org.apache.zookeeper WatchedEvent getType
public EventType getType()
From source file:com.linkedin.d2.discovery.stores.zk.SymlinkAwareZooKeeperTest.java
License:Apache License
@Test public void testSymlinkWithExistWatch3() throws InterruptedException, ExecutionException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.StatCallback existCallback = new AsyncCallback.StatCallback() { @Override/*from ww w . j av a 2 s. c o m*/ public void processResult(int rc, String path, Object ctx, Stat stat) { KeeperException.Code result = KeeperException.Code.get(rc); Assert.assertEquals(result, KeeperException.Code.OK); latch.countDown(); } }; Watcher existWatch = new Watcher() { @Override public void process(WatchedEvent event) { Assert.assertEquals(event.getType(), Event.EventType.NodeCreated); _zkClient.getZooKeeper().exists(event.getPath(), null, existCallback, null); } }; AsyncCallback.StatCallback existCallback2 = new AsyncCallback.StatCallback() { @Override public void processResult(int rc, String path, Object ctx, Stat stat) { KeeperException.Code result = KeeperException.Code.get(rc); Assert.assertEquals(result, KeeperException.Code.NONODE); latch2.countDown(); } }; // symlink /$link doesn't exist. _zkClient.getZooKeeper().exists("/$link", existWatch, existCallback2, null); latch2.await(30, TimeUnit.SECONDS); // create symlink /$link -> /foo/bar. existWatch should be notified. _zkClient.createSymlink("/$link", "/foo/bar", new FutureCallback<None>()); latch.await(30, TimeUnit.SECONDS); // delete symlink /$link _zkClient.removeNodeUnsafe("/$link", new FutureCallback<None>()); }
From source file:com.linkedin.d2.discovery.stores.zk.SymlinkAwareZooKeeperTest.java
License:Apache License
@Test public void testSymlinkWithChildrenWatch() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.ChildrenCallback childrenCallback = new AsyncCallback.ChildrenCallback() { @Override/*from www.j a v a 2s . c o m*/ public void processResult(int rc, String path, Object ctx, List<String> children) { KeeperException.Code result = KeeperException.Code.get(rc); Assert.assertEquals(result, KeeperException.Code.OK); Assert.assertEquals(children.size(), 11); latch.countDown(); } }; Watcher childrenWatch = new Watcher() { @Override public void process(WatchedEvent event) { Assert.assertEquals(event.getType(), Event.EventType.NodeChildrenChanged); _zkClient.getZooKeeper().getChildren(event.getPath(), null, childrenCallback, null); } }; AsyncCallback.ChildrenCallback childrenCallback2 = new AsyncCallback.ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { KeeperException.Code result = KeeperException.Code.get(rc); Assert.assertEquals(result, KeeperException.Code.OK); latch2.countDown(); } }; // symlink: /foo/$link -> /foo/bar _zkClient.getZooKeeper().getChildren("/foo/$link", childrenWatch, childrenCallback2, null); latch2.await(30, TimeUnit.SECONDS); _zkClient.ensurePersistentNodeExists("/foo/bar/newNode", new FutureCallback<None>()); latch.await(30, TimeUnit.SECONDS); _zkClient.removeNodeUnsafe("/foo/bar/newNode", new FutureCallback<None>()); }
From source file:com.linkedin.d2.discovery.stores.zk.SymlinkAwareZooKeeperTest.java
License:Apache License
@Test public void testSymlinkWithChildrenWatcher2() throws ExecutionException, InterruptedException { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.ChildrenCallback callback2 = new AsyncCallback.ChildrenCallback() { @Override/*from w ww.ja v a 2 s . c o m*/ public void processResult(int rc, String path, Object ctx, List<String> children) { Assert.assertEquals(path, "/foo/$link"); Assert.assertEquals(children.size(), 5); latch2.countDown(); } }; Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { Assert.assertEquals(event.getType(), Event.EventType.NodeChildrenChanged); _zkClient.getZooKeeper().getChildren(event.getPath(), null, callback2, null); } }; AsyncCallback.ChildrenCallback callback = new AsyncCallback.ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { latch1.countDown(); } }; // set watcher to /foo/$link _zkClient.getZooKeeper().getChildren("/foo/$link", watcher, callback, null); latch1.await(30, TimeUnit.SECONDS); // update symlink _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback<None>()); latch2.await(30, TimeUnit.SECONDS); FutureCallback<None> fcb = new FutureCallback<None>(); // restore symlink _zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb); fcb.get(); }
From source file:com.linkedin.d2.discovery.stores.zk.SymlinkAwareZooKeeperTest.java
License:Apache License
@Test public void testSymlinkWithChildrenWatcher3() throws ExecutionException, InterruptedException, KeeperException { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Stat expectedStat1 = _zkClient.getZooKeeper().exists("/foo/bar", false); Stat expectedStat2 = _zkClient.getZooKeeper().exists("/bar/foo", false); final AsyncCallback.Children2Callback callback2 = new AsyncCallback.Children2Callback() { @Override// ww w .ja v a2s .c o m public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { Assert.assertEquals(path, "/foo/$link"); Assert.assertEquals(children.size(), 5); Assert.assertEquals(stat, expectedStat2); latch2.countDown(); } }; Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { Assert.assertEquals(event.getType(), Event.EventType.NodeChildrenChanged); _zkClient.getZooKeeper().getChildren(event.getPath(), null, callback2, null); } }; AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { Assert.assertEquals(stat, expectedStat1); latch1.countDown(); } }; // set watcher to /foo/$link _zkClient.getZooKeeper().getChildren("/foo/$link", watcher, callback, null); latch1.await(30, TimeUnit.SECONDS); // update symlink _zkClient.setSymlinkData("/foo/$link", "/bar/foo", new FutureCallback<None>()); latch2.await(30, TimeUnit.SECONDS); FutureCallback<None> fcb = new FutureCallback<None>(); // restore symlink _zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb); fcb.get(); }
From source file:com.linkedin.d2.discovery.stores.zk.SymlinkAwareZooKeeperTest.java
License:Apache License
@Test public void testInvalidSymlinkWithExists() throws ExecutionException, InterruptedException { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); final AsyncCallback.StatCallback callback = new AsyncCallback.StatCallback() { @Override// ww w . j a v a 2s. co m public void processResult(int rc, String path, Object ctx, Stat stat) { Assert.assertEquals(path, "/foo/$link"); KeeperException.Code result = KeeperException.Code.get(rc); Assert.assertEquals(result, KeeperException.Code.NONODE); latch1.countDown(); } }; final Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { Assert.assertEquals(event.getType(), Event.EventType.NodeDataChanged); latch2.countDown(); } }; FutureCallback<None> fcb = new FutureCallback<None>(); _zkClient.setSymlinkData("/foo/$link", "INVALID", fcb); fcb.get(); _zkClient.getZooKeeper().exists("/foo/$link", watcher, callback, null); latch1.await(30, TimeUnit.SECONDS); _zkClient.setSymlinkData("/foo/$link", "/foo/bar", fcb); if (!latch2.await(30, TimeUnit.SECONDS)) { Assert.fail("Exists Watch is not triggered"); } }
From source file:com.liveramp.hank.test.ZkTestCase.java
License:Apache License
@Before public final void setUpZk() throws Exception { setupZkServer();//w w w . j a v a2 s . c om final Object lock = new Object(); final AtomicBoolean connected = new AtomicBoolean(false); zk = new ZooKeeperPlus("127.0.0.1:" + zkClientPort, 1000000, new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { case None: if (event.getState() == KeeperState.SyncConnected) { connected.set(true); synchronized (lock) { lock.notifyAll(); } } } LOG.debug(event.toString()); } }); synchronized (lock) { lock.wait(2000); } if (!connected.get()) { fail("timed out waiting for the zk client connection to come online!"); } LOG.debug("session timeout: " + zk.getSessionTimeout()); zk.deleteNodeRecursively(zkRoot); WaitUntil.orDie(() -> { try { return zk.exists(zkRoot, false) == null; } catch (KeeperException | InterruptedException e) { throw new RuntimeException(e); } }); createNodeRecursively(zkRoot); }
From source file:com.liveramp.hank.zookeeper.ZooKeeperConnection.java
License:Apache License
/** * Listens for notifications from the ZooKeeper service telling that we have * been connected, disconnected, or our session has expired. * <p/>/* w ww . j ava 2 s. c om*/ * Upon connection, we first make a call to {@link #onConnect()}, and then we * release all threads that are blocking on {@link #waitForConnection()}. * <p/> * Upon disconnection, we call {@link #onDisconnect()}, and then we reset the * latch to block any threads that call {@link #waitForConnection()}. * <p/> * On session expiry, we call {@link #onSessionExpire()}, reset the latch, and * then manually try to reconnect to the ZooKeeper service. * * @param event */ @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { KeeperState state = event.getState(); LOG.info("Getting event: " + state); for (Coordinator.StateChangeListener listener : listeners) { listener.process(state.name()); } switch (state) { case SyncConnected: onConnect(); connectedSignal.countDown(); break; case Disconnected: onDisconnect(); connectedSignal = new CountDownLatch(1); break; case Expired: onSessionExpire(); connectedSignal = new CountDownLatch(1); try { LOG.info("Attempting ZooKeeper reconnect"); connect(maxConnectAttempts); } catch (IOException e) { LOG.error("Failed to connect to the ZooKeeper service", e); throw new RuntimeException("Couldn't connect to the ZooKeeper service", e); } break; } // Return because we are done processing this event; do not let subclasses // process. return; } }
From source file:com.metamx.druid.master.LoadQueuePeon.java
License:Open Source License
private void doNext() { synchronized (lock) { if (currentlyLoading == null) { if (!segmentsToDrop.isEmpty()) { currentlyLoading = segmentsToDrop.first(); log.info("Server[%s] dropping [%s]", basePath, currentlyLoading); } else if (!segmentsToLoad.isEmpty()) { currentlyLoading = segmentsToLoad.first(); log.info("Server[%s] loading [%s]", basePath, currentlyLoading); } else { return; }//from ww w . j a v a2 s. c o m zkWritingExecutor.execute(new Runnable() { @Override public void run() { synchronized (lock) { try { if (currentlyLoading == null) { log.makeAlert("Crazy race condition! server[%s]", basePath).emit(); actionCompleted(); doNext(); return; } log.info("Server[%s] adding segment[%s]", basePath, currentlyLoading.getSegmentIdentifier()); final String path = ZKPaths.makePath(basePath, currentlyLoading.getSegmentIdentifier()); final byte[] payload = jsonMapper .writeValueAsBytes(currentlyLoading.getChangeRequest()); curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload); zkWritingExecutor.schedule(new Runnable() { @Override public void run() { try { if (curator.checkExists().forPath(path) != null) { failAssign(new ISE("%s was never removed! Failing this assign!", path)); } } catch (Exception e) { failAssign(e); } } }, config.getLoadTimeoutDelay().getMillis(), TimeUnit.MILLISECONDS); final Stat stat = curator.checkExists().usingWatcher(new CuratorWatcher() { @Override public void process(WatchedEvent watchedEvent) throws Exception { switch (watchedEvent.getType()) { case NodeDeleted: entryRemoved(watchedEvent.getPath()); } } }).forPath(path); if (stat == null) { final byte[] noopPayload = jsonMapper .writeValueAsBytes(new SegmentChangeRequestNoop()); // Create a node and then delete it to remove the registered watcher. This is a work-around for // a zookeeper race condition. Specifically, when you set a watcher, it fires on the next event // that happens for that node. If no events happen, the watcher stays registered foreverz. // Couple that with the fact that you cannot set a watcher when you create a node, but what we // want is to create a node and then watch for it to get deleted. The solution is that you *can* // set a watcher when you check to see if it exists so, we first create the node and then set a // watcher on its existence. However, if already does not exist by the time the existence check // returns, then the watcher that was set will never fire (nobody will ever create the node // again) and thus lead to a slow, but real, memory leak. So, we create another node to cause // that watcher to fire and delete it right away. // // We do not create the existence watcher first, because then it will fire when we create the // node and we'll have the same race when trying to refresh that watcher. curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, noopPayload); entryRemoved(path); } } catch (Exception e) { failAssign(e); } } } }); } else { log.info("Server[%s] skipping doNext() because something is currently loading[%s].", basePath, currentlyLoading); } } }
From source file:com.navercorp.client.Client.java
License:Apache License
public Client(String connectionString, int timeoutms) throws IOException, InterruptedException { final CountDownLatch sync = new CountDownLatch(1); zk = new ZooKeeper(connectionString, timeoutms, new Watcher() { public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None && event.getState() == Event.KeeperState.SyncConnected) { sync.countDown();/* w ww . j ava 2 s . c om*/ } } }); if (sync.await(timeoutms, TimeUnit.MILLISECONDS) == false) { zk.close(); throw new IOException("Connection to zookeeper timed out. connectionString: " + connectionString); } }
From source file:com.navercorp.nbasearc.confmaster.server.leaderelection.LeaderElectionSupport.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType().equals(Watcher.Event.EventType.NodeDeleted) && !event.getPath().equals(leaderOffer.getNodePath()) && state != State.STOP) { logger.debug("Node {} deleted. Need to run through the election process.", event.getPath()); try {/*www . j a va 2 s .c o m*/ determineElectionStatus(); } catch (KeeperException e) { becomeFailed(e); } catch (InterruptedException e) { becomeFailed(e); } } }