Search in sources :

Example 31 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project druid by druid-io.

the class CuratorInventoryManagerTest method testSanity.

@Test
public void testSanity() throws Exception {
    final MapStrategy strategy = new MapStrategy();
    CuratorInventoryManager<Map<String, Integer>, Integer> manager = new CuratorInventoryManager<>(curator, new StringInventoryManagerConfig("/container", "/inventory"), exec, strategy);
    curator.start();
    curator.blockUntilConnected();
    manager.start();
    Assert.assertTrue(Iterables.isEmpty(manager.getInventory()));
    CountDownLatch containerLatch = new CountDownLatch(1);
    strategy.setNewContainerLatch(containerLatch);
    curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/container/billy", new byte[] {});
    Assert.assertTrue(timing.awaitLatch(containerLatch));
    strategy.setNewContainerLatch(null);
    final Iterable<Map<String, Integer>> inventory = manager.getInventory();
    Assert.assertTrue(Iterables.getOnlyElement(inventory).isEmpty());
    CountDownLatch inventoryLatch = new CountDownLatch(2);
    strategy.setNewInventoryLatch(inventoryLatch);
    curator.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/inventory/billy/1", Ints.toByteArray(100));
    curator.create().withMode(CreateMode.EPHEMERAL).forPath("/inventory/billy/bob", Ints.toByteArray(2287));
    Assert.assertTrue(timing.awaitLatch(inventoryLatch));
    strategy.setNewInventoryLatch(null);
    verifyInventory(manager);
    CountDownLatch deleteLatch = new CountDownLatch(1);
    strategy.setDeadInventoryLatch(deleteLatch);
    curator.delete().forPath("/inventory/billy/1");
    Assert.assertTrue(timing.awaitLatch(deleteLatch));
    strategy.setDeadInventoryLatch(null);
    Assert.assertEquals(1, manager.getInventoryValue("billy").size());
    Assert.assertEquals(2287, manager.getInventoryValue("billy").get("bob").intValue());
    inventoryLatch = new CountDownLatch(1);
    strategy.setNewInventoryLatch(inventoryLatch);
    curator.create().withMode(CreateMode.EPHEMERAL).forPath("/inventory/billy/1", Ints.toByteArray(100));
    Assert.assertTrue(timing.awaitLatch(inventoryLatch));
    strategy.setNewInventoryLatch(null);
    verifyInventory(manager);
    final CountDownLatch latch = new CountDownLatch(1);
    curator.getCuratorListenable().addListener(new CuratorListener() {

        @Override
        public void eventReceived(CuratorFramework client, CuratorEvent event) {
            if (event.getType() == CuratorEventType.WATCHED && event.getWatchedEvent().getState() == Watcher.Event.KeeperState.Disconnected) {
                latch.countDown();
            }
        }
    });
    server.stop();
    Assert.assertTrue(timing.awaitLatch(latch));
    verifyInventory(manager);
    // Wait a bit
    Thread.sleep(50);
    verifyInventory(manager);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) CuratorListener(org.apache.curator.framework.api.CuratorListener) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch) TreeMap(java.util.TreeMap) Map(java.util.Map) Test(org.junit.Test)

Example 32 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project heron by twitter.

the class CuratorStateManager method getNodeData.

@Override
protected <M extends Message> ListenableFuture<M> getNodeData(WatchCallback watcher, String path, final Message.Builder builder) {
    final SettableFuture<M> future = SettableFuture.create();
    Watcher wc = ZkWatcherCallback.makeZkWatcher(watcher);
    BackgroundCallback cb = new BackgroundCallback() {

        @Override
        // we don't know what M is until runtime
        @SuppressWarnings("unchecked")
        public void processResult(CuratorFramework aClient, CuratorEvent event) throws Exception {
            byte[] data;
            if (event != null & (data = event.getData()) != null) {
                builder.mergeFrom(data);
                safeSetFuture(future, (M) builder.build());
            } else {
                safeSetException(future, new RuntimeException("Failed to fetch data from path: " + event.getPath()));
            }
        }
    };
    try {
        client.getData().usingWatcher(wc).inBackground(cb).forPath(path);
    // Suppress it since forPath() throws Exception
    // SUPPRESS CHECKSTYLE IllegalCatch
    } catch (Exception e) {
        safeSetException(future, new RuntimeException("Could not getNodeData using watcher for path: " + path, e));
    }
    return future;
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Watcher(org.apache.zookeeper.Watcher) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) KeeperException(org.apache.zookeeper.KeeperException) ExecutionException(java.util.concurrent.ExecutionException)

Example 33 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project dubbo by alibaba.

the class ZKTools method main.

public static void main(String[] args) throws Exception {
    client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
    client.start();
    client.getCuratorListenable().addListener(new CuratorListener() {

        @Override
        public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
            System.out.println("event notification: " + event.getPath());
            System.out.println(event);
        }
    }, executor);
    testMigrationRule();
// tesConditionRule();
// testStartupConfig();
// testProviderConfig();
// testPathCache();
// testTreeCache();
// testCuratorListener();
// Thread.sleep(100000);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) CuratorListener(org.apache.curator.framework.api.CuratorListener) CuratorEvent(org.apache.curator.framework.api.CuratorEvent)

Example 34 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project jstorm by alibaba.

the class Zookeeper method mkClient.

/**
 * connect ZK, register watchers
 */
public CuratorFramework mkClient(Map conf, List<String> servers, Object port, String root, final WatcherCallBack watcher) {
    CuratorFramework fk = Utils.newCurator(conf, servers, port, root);
    fk.getCuratorListenable().addListener(new CuratorListener() {

        @Override
        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() {

        @Override
        public void unhandledError(String msg, Throwable error) {
            String errmsg = "Unrecoverable zookeeper error, halting process: " + msg;
            LOG.error(errmsg, error);
            JStormUtils.halt_process(1, "Unrecoverable zookeeper error");
        }
    });
    fk.start();
    return fk;
}
Also used : WatchedEvent(org.apache.zookeeper.WatchedEvent) CuratorFramework(org.apache.curator.framework.CuratorFramework) CuratorListener(org.apache.curator.framework.api.CuratorListener) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) UnhandledErrorListener(org.apache.curator.framework.api.UnhandledErrorListener) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 35 with CuratorEvent

use of org.apache.curator.framework.api.CuratorEvent in project Singularity by HubSpot.

the class CuratorAsyncManager method existsThrows.

private <T extends SingularityId> List<T> existsThrows(final String pathNameforLogs, final Collection<String> paths, final IdTranscoder<T> idTranscoder) throws Exception {
    if (paths.isEmpty()) {
        return Collections.emptyList();
    }
    final List<T> objects = Lists.newArrayListWithCapacity(paths.size());
    final CountDownLatch latch = new CountDownLatch(paths.size());
    final BackgroundCallback callback = new BackgroundCallback() {

        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            try {
                if (event.getStat() != null) {
                    objects.add(Transcoders.getFromStringFunction(idTranscoder).apply(ZKPaths.getNodeFromPath(event.getPath())));
                }
            } finally {
                latch.countDown();
            }
        }
    };
    return queryAndReturnResultsThrows(objects, paths, callback, latch, pathNameforLogs, new AtomicInteger(), CuratorQueryMethod.GET_DATA);
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BackgroundCallback(org.apache.curator.framework.api.BackgroundCallback) CuratorEvent(org.apache.curator.framework.api.CuratorEvent) CountDownLatch(java.util.concurrent.CountDownLatch)

Aggregations

CuratorEvent (org.apache.curator.framework.api.CuratorEvent)60 CuratorFramework (org.apache.curator.framework.CuratorFramework)57 BackgroundCallback (org.apache.curator.framework.api.BackgroundCallback)36 CountDownLatch (java.util.concurrent.CountDownLatch)34 CuratorListener (org.apache.curator.framework.api.CuratorListener)23 Test (org.testng.annotations.Test)21 RetryOneTime (org.apache.curator.retry.RetryOneTime)18 KeeperException (org.apache.zookeeper.KeeperException)14 Test (org.junit.Test)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Watcher (org.apache.zookeeper.Watcher)8 ArrayList (java.util.ArrayList)4 Timing (org.apache.curator.test.Timing)4 WatchedEvent (org.apache.zookeeper.WatchedEvent)4 InvocationOnMock (org.mockito.invocation.InvocationOnMock)4 Message (com.google.protobuf.Message)3 IOException (java.io.IOException)3 Map (java.util.Map)3 ExecutionException (java.util.concurrent.ExecutionException)3 TimeUnit (java.util.concurrent.TimeUnit)3