Search in sources :

Example 21 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project x-pipe by ctripcorp.

the class TestPathChildren method testPathChildernAlreadyExist.

@Test
public void testPathChildernAlreadyExist() throws Exception {
    createPath(client, path, 0, count);
    CountDownLatch latch = new CountDownLatch(count);
    List<String> result = new LinkedList<>();
    PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
    pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {

        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            try {
                sleep(50);
                logger.info("event");
                int realSize = pathChildrenCache.getCurrentData().size();
                if (count != realSize) {
                    String desc = String.format("expected:%d, real:%d", count, realSize);
                    result.add(desc);
                    logger.info("expected:{}, real:{}", count, realSize);
                }
            } finally {
                latch.countDown();
            }
        }
    });
    try {
        pathChildrenCache.start();
    } catch (Exception e) {
        logger.error("[start]", e);
    }
    latch.await();
    Assert.assertEquals(0, result.size());
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) Test(org.junit.Test) AbstractMetaServerTest(com.ctrip.xpipe.redis.meta.server.AbstractMetaServerTest)

Example 22 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project yuzhouwan by asdf2014.

the class CuratorChildrenCache method addChildrenListener.

public void addChildrenListener(String path) throws Exception {
    Stat existStat = curatorFramework.checkExists().forPath(path);
    if (existStat == null)
        curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path);
    final PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, path, false);
    pathChildrenCache.start(PathChildrenCache.StartMode.NORMAL);
    pathChildrenCache.getListenable().addListener((CuratorFramework client, PathChildrenCacheEvent event) -> {
        PathChildrenCacheEvent.Type type = event.getType();
        LOG.info("Event type: {}", type);
        switch(type) {
            case CONNECTION_RECONNECTED:
                LOG.info("Reconnected...");
                break;
            case CONNECTION_LOST:
                LOG.info("Connection lost...");
                pathChildrenCache.rebuild();
                LOG.info("Rebuild pathChildrenCache...");
                break;
            case CONNECTION_SUSPENDED:
                LOG.info("Connection suspended...");
                break;
            case CHILD_ADDED:
                LOG.info("Add new child: {}", event.getData().getPath());
                break;
            case CHILD_UPDATED:
                LOG.info("Updated child: {}", event.getData().getPath());
                break;
            case CHILD_REMOVED:
                LOG.info("Removed child: {}", event.getData().getPath());
                break;
            default:
                LOG.error(String.format("Something was not excepted: %s", type));
                break;
        }
    });
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Stat(org.apache.zookeeper.data.Stat) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache)

Example 23 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project java-basic by tzuyichao.

the class PathChildrenCacheTest method main.

public static void main(String[] args) {
    try (CuratorFramework client = CuratorFrameworkFactory.builder().connectString(ZK_ADDRESS).retryPolicy(new ExponentialBackoffRetry(1000, 3)).build()) {
        client.start();
        client.create().creatingParentsIfNeeded().forPath(zkPathBase, "init".getBytes(StandardCharsets.UTF_8));
        PathChildrenCache cache = new PathChildrenCache(client, zkPathBase, true);
        cache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        cache.getListenable().addListener(new PathChildrenCacheListener() {

            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                switch(event.getType()) {
                    case CHILD_ADDED:
                        log.info("Child Add: {}", event.getData().getPath());
                        break;
                    case CHILD_UPDATED:
                        log.info("Child Update: {}", event.getData().getPath());
                        break;
                    case CHILD_REMOVED:
                        log.info("Child Delete: {}", event.getData().getPath());
                        break;
                    default:
                        break;
                }
            }
        });
        String path = zkPathBase + "/c1";
        client.create().withMode(CreateMode.EPHEMERAL).forPath(path);
        TimeUnit.SECONDS.sleep(1);
        client.setData().forPath(path, "test".getBytes(StandardCharsets.UTF_8));
        TimeUnit.SECONDS.sleep(1);
        client.delete().forPath(path);
        TimeUnit.SECONDS.sleep(1);
        cache.close();
        client.delete().forPath(zkPathBase);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache)

Example 24 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project dcache by dCache.

the class EventNotifierTest method givenZooKeeperEvent.

private void givenZooKeeperEvent(PathChildrenCacheEvent.Type type, String path, PnfsId id, Collection<EventType> types) {
    byte[] data = EventNotifier.toZkData(Collections.singletonMap(id, types));
    ChildData childData = new ChildData(path, null, data);
    PathChildrenCacheEvent event = new PathChildrenCacheEvent(type, childData);
    try {
        notifier.childEvent(null, event);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("Unexpected exception: " + e, e);
    }
}
Also used : PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) ChildData(org.apache.curator.framework.recipes.cache.ChildData) CacheException(diskCacheV111.util.CacheException) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException)

Example 25 with PathChildrenCacheEvent

use of org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent in project hadoop by apache.

the class ZKDelegationTokenSecretManager method startThreads.

@Override
public void startThreads() throws IOException {
    if (!isExternalClient) {
        try {
            zkClient.start();
        } catch (Exception e) {
            throw new IOException("Could not start Curator Framework", e);
        }
    } else {
        // If namespace parents are implicitly created, they won't have ACLs.
        // So, let's explicitly create them.
        CuratorFramework nullNsFw = zkClient.usingNamespace(null);
        EnsurePath ensureNs = nullNsFw.newNamespaceAwareEnsurePath("/" + zkClient.getNamespace());
        try {
            ensureNs.ensure(nullNsFw.getZookeeperClient());
        } catch (Exception e) {
            throw new IOException("Could not create namespace", e);
        }
    }
    listenerThreadPool = Executors.newSingleThreadExecutor();
    try {
        delTokSeqCounter = new SharedCount(zkClient, ZK_DTSM_SEQNUM_ROOT, 0);
        if (delTokSeqCounter != null) {
            delTokSeqCounter.start();
        }
    } catch (Exception e) {
        throw new IOException("Could not start Sequence Counter", e);
    }
    try {
        keyIdSeqCounter = new SharedCount(zkClient, ZK_DTSM_KEYID_ROOT, 0);
        if (keyIdSeqCounter != null) {
            keyIdSeqCounter.start();
        }
    } catch (Exception e) {
        throw new IOException("Could not start KeyId Counter", e);
    }
    try {
        createPersistentNode(ZK_DTSM_MASTER_KEY_ROOT);
        createPersistentNode(ZK_DTSM_TOKENS_ROOT);
    } catch (Exception e) {
        throw new RuntimeException("Could not create ZK paths");
    }
    try {
        keyCache = new PathChildrenCache(zkClient, ZK_DTSM_MASTER_KEY_ROOT, true);
        if (keyCache != null) {
            keyCache.start(StartMode.BUILD_INITIAL_CACHE);
            keyCache.getListenable().addListener(new PathChildrenCacheListener() {

                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    switch(event.getType()) {
                        case CHILD_ADDED:
                            processKeyAddOrUpdate(event.getData().getData());
                            break;
                        case CHILD_UPDATED:
                            processKeyAddOrUpdate(event.getData().getData());
                            break;
                        case CHILD_REMOVED:
                            processKeyRemoved(event.getData().getPath());
                            break;
                        default:
                            break;
                    }
                }
            }, listenerThreadPool);
        }
    } catch (Exception e) {
        throw new IOException("Could not start PathChildrenCache for keys", e);
    }
    try {
        tokenCache = new PathChildrenCache(zkClient, ZK_DTSM_TOKENS_ROOT, true);
        if (tokenCache != null) {
            tokenCache.start(StartMode.BUILD_INITIAL_CACHE);
            tokenCache.getListenable().addListener(new PathChildrenCacheListener() {

                @Override
                public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                    switch(event.getType()) {
                        case CHILD_ADDED:
                            processTokenAddOrUpdate(event.getData());
                            break;
                        case CHILD_UPDATED:
                            processTokenAddOrUpdate(event.getData());
                            break;
                        case CHILD_REMOVED:
                            processTokenRemoved(event.getData());
                            break;
                        default:
                            break;
                    }
                }
            }, listenerThreadPool);
        }
    } catch (Exception e) {
        throw new IOException("Could not start PathChildrenCache for tokens", e);
    }
    super.startThreads();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) EnsurePath(org.apache.curator.utils.EnsurePath) SharedCount(org.apache.curator.framework.recipes.shared.SharedCount) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) IOException(java.io.IOException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException)

Aggregations

PathChildrenCacheEvent (org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)65 CuratorFramework (org.apache.curator.framework.CuratorFramework)55 PathChildrenCacheListener (org.apache.curator.framework.recipes.cache.PathChildrenCacheListener)49 PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)34 ChildData (org.apache.curator.framework.recipes.cache.ChildData)20 IOException (java.io.IOException)15 KeeperException (org.apache.zookeeper.KeeperException)11 CountDownLatch (java.util.concurrent.CountDownLatch)10 Test (org.junit.Test)10 DataSegment (org.apache.druid.timeline.DataSegment)5 ZKPaths (org.apache.curator.utils.ZKPaths)4 RedisConfig (cn.northpark.zookeeper.RedisConfig)3 SofaRpcRuntimeException (com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException)3 ServiceInstance (com.baidu.brpc.client.channel.ServiceInstance)3 RpcException (com.baidu.brpc.exceptions.RpcException)3 DataSegment (io.druid.timeline.DataSegment)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Releasable (com.ctrip.xpipe.api.lifecycle.Releasable)2