Search in sources :

Example 1 with PathChildrenCache

use of org.apache.curator.framework.recipes.cache.PathChildrenCache 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);
            loadFromZKCache(false);
        }
    } 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);
            loadFromZKCache(true);
        }
    } 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)

Example 2 with PathChildrenCache

use of org.apache.curator.framework.recipes.cache.PathChildrenCache in project druid by druid-io.

the class Announcer method stop.

@LifecycleStop
public void stop() {
    synchronized (toAnnounce) {
        if (!started) {
            return;
        }
        started = false;
        Closer closer = Closer.create();
        for (PathChildrenCache cache : listeners.values()) {
            closer.register(cache);
        }
        try {
            CloseQuietly.close(closer);
        } finally {
            pathChildrenCacheExecutor.shutdown();
        }
        for (Map.Entry<String, ConcurrentMap<String, byte[]>> entry : announcements.entrySet()) {
            String basePath = entry.getKey();
            for (String announcementPath : entry.getValue().keySet()) {
                unannounce(ZKPaths.makePath(basePath, announcementPath));
            }
        }
        if (!parentsIBuilt.isEmpty()) {
            CuratorTransaction transaction = curator.inTransaction();
            for (String parent : parentsIBuilt) {
                try {
                    transaction = transaction.delete().forPath(parent).and();
                } catch (Exception e) {
                    log.info(e, "Unable to delete parent[%s], boooo.", parent);
                }
            }
            try {
                ((CuratorTransactionFinal) transaction).commit();
            } catch (Exception e) {
                log.info(e, "Unable to commit transaction. Please feed the hamsters");
            }
        }
    }
}
Also used : Closer(com.google.common.io.Closer) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) CuratorTransaction(org.apache.curator.framework.api.transaction.CuratorTransaction) CuratorTransactionFinal(org.apache.curator.framework.api.transaction.CuratorTransactionFinal) ConcurrentMap(java.util.concurrent.ConcurrentMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) Map(java.util.Map) KeeperException(org.apache.zookeeper.KeeperException) LifecycleStop(io.druid.java.util.common.lifecycle.LifecycleStop)

Example 3 with PathChildrenCache

use of org.apache.curator.framework.recipes.cache.PathChildrenCache in project BRFS by zhangnianli.

the class FileCenter method main.

public static void main(String[] args) {
    id = new Random().nextInt(10);
    System.out.println("id = " + id);
    System.out.println("hahahahha");
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.builder().namespace(ROOT).connectString(zk_address).retryPolicy(retryPolicy).build();
    client.start();
    try {
        Stat stat = client.checkExists().forPath(DUPS);
        System.out.println("stat =" + stat);
        if (stat == null) {
            System.out.println("create--" + client.create().forPath(DUPS));
        }
        ExecutorService pool = Executors.newFixedThreadPool(5);
        PathChildrenCache pathCache = new PathChildrenCache(client, DUPS, true, false, pool);
        pathCache.getListenable().addListener(new PathNodeListener());
        pathCache.start();
    // TreeCache cache = new TreeCache(client, DUPS);
    // cache.getListenable().addListener(new TreeNodeListener(), pool);
    // cache.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
    synchronized (client) {
        try {
            client.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    client.close();
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Stat(org.apache.zookeeper.data.Stat) Random(java.util.Random) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ExecutorService(java.util.concurrent.ExecutorService) RetryPolicy(org.apache.curator.RetryPolicy)

Example 4 with PathChildrenCache

use of org.apache.curator.framework.recipes.cache.PathChildrenCache in project BRFS by zhangnianli.

the class TestZKNode method main.

public static void main(String[] args) throws Exception {
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient(zk_address, 5 * 1000, 30 * 1000, retryPolicy);
    client.start();
    client.blockUntilConnected();
    PathChildrenCache cache = new PathChildrenCache(client.usingNamespace("test"), "/fileCoordinator/big", true);
    cache.getListenable().addListener(new PathChildrenCacheListener() {

        @Override
        public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
            System.out.println("---" + event);
            ChildData data = event.getData();
            if (data != null) {
                switch(event.getType()) {
                    case CHILD_ADDED:
                        System.out.println("###PATH-" + data.getPath());
                        break;
                    default:
                        break;
                }
            }
        }
    });
    cache.start();
    PersistentNode node = new PersistentNode(client.usingNamespace("test"), CreateMode.EPHEMERAL, false, "/fileCoordinator/temp-1", "node1".getBytes());
    node.getListenable().addListener(new PersistentNodeListener() {

        @Override
        public void nodeCreated(String path) throws Exception {
            System.out.println("node1--created:" + path);
        }
    });
    node.start();
    PersistentNode node2 = new PersistentNode(client.usingNamespace("test"), CreateMode.EPHEMERAL, false, "/fileCoordinator/temp-1", "node2".getBytes());
    node2.getListenable().addListener(new PersistentNodeListener() {

        @Override
        public void nodeCreated(String path) throws Exception {
            System.out.println("node2--created:" + path);
        }
    });
    node2.start();
    Thread.sleep(2000);
    node2.close();
    synchronized (node) {
        node.wait();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCacheEvent(org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent) PersistentNodeListener(org.apache.curator.framework.recipes.nodes.PersistentNodeListener) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) ChildData(org.apache.curator.framework.recipes.cache.ChildData) PersistentNode(org.apache.curator.framework.recipes.nodes.PersistentNode) RetryPolicy(org.apache.curator.RetryPolicy)

Example 5 with PathChildrenCache

use of org.apache.curator.framework.recipes.cache.PathChildrenCache in project pravega by pravega.

the class ZKStreamMetadataStore method registerBucketOwnershipListener.

@Override
@SneakyThrows
public void registerBucketOwnershipListener(BucketOwnershipListener listener) {
    Preconditions.checkNotNull(listener);
    PathChildrenCacheListener bucketListener = (client, event) -> {
        switch(event.getType()) {
            case CHILD_ADDED:
                // no action required
                break;
            case CHILD_REMOVED:
                int bucketId = Integer.parseInt(ZKPaths.getNodeFromPath(event.getData().getPath()));
                listener.notify(new BucketNotification(bucketId, BucketNotification.NotificationType.BucketAvailable));
                break;
            case CONNECTION_LOST:
                listener.notify(new BucketNotification(Integer.MIN_VALUE, BucketNotification.NotificationType.ConnectivityError));
                break;
            default:
                log.warn("Received unknown event {}", event.getType());
        }
    };
    bucketOwnershipCacheRef.compareAndSet(null, new PathChildrenCache(storeHelper.getClient(), ZKStoreHelper.BUCKET_OWNERSHIP_PATH, true));
    bucketOwnershipCacheRef.get().getListenable().addListener(bucketListener);
    bucketOwnershipCacheRef.get().start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
    log.info("bucket ownership listener registered");
}
Also used : SneakyThrows(lombok.SneakyThrows) StreamImpl(io.pravega.client.stream.impl.StreamImpl) RetentionPolicy(io.pravega.client.stream.RetentionPolicy) SerializationUtils(org.apache.commons.lang3.SerializationUtils) CompletableFuture(java.util.concurrent.CompletableFuture) StreamNotification(io.pravega.controller.server.retention.BucketChangeListener.StreamNotification) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentMap(java.util.concurrent.ConcurrentMap) BucketOwnershipListener(io.pravega.controller.server.retention.BucketOwnershipListener) ZKPaths(org.apache.curator.utils.ZKPaths) BucketNotification(io.pravega.controller.server.retention.BucketOwnershipListener.BucketNotification) Data(io.pravega.controller.store.stream.tables.Data) NotificationType(io.pravega.controller.server.retention.BucketChangeListener.StreamNotification.NotificationType) BucketChangeListener(io.pravega.controller.server.retention.BucketChangeListener) Executor(java.util.concurrent.Executor) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) Slf4j(lombok.extern.slf4j.Slf4j) Base64(java.util.Base64) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Config(io.pravega.controller.util.Config) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) Preconditions(com.google.common.base.Preconditions) ZKHostIndex(io.pravega.controller.store.index.ZKHostIndex) PathChildrenCacheListener(org.apache.curator.framework.recipes.cache.PathChildrenCacheListener) PathChildrenCache(org.apache.curator.framework.recipes.cache.PathChildrenCache) BucketNotification(io.pravega.controller.server.retention.BucketOwnershipListener.BucketNotification) SneakyThrows(lombok.SneakyThrows)

Aggregations

PathChildrenCache (org.apache.curator.framework.recipes.cache.PathChildrenCache)68 IOException (java.io.IOException)25 CuratorFramework (org.apache.curator.framework.CuratorFramework)21 PathChildrenCacheListener (org.apache.curator.framework.recipes.cache.PathChildrenCacheListener)20 PathChildrenCacheEvent (org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent)14 KeeperException (org.apache.zookeeper.KeeperException)10 AtomicReference (java.util.concurrent.atomic.AtomicReference)8 ChildData (org.apache.curator.framework.recipes.cache.ChildData)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 ExponentialBackoffRetry (org.apache.curator.retry.ExponentialBackoffRetry)6 Before (org.junit.Before)5 Test (org.junit.Test)5 ConcurrentMap (java.util.concurrent.ConcurrentMap)4 ExecutorService (java.util.concurrent.ExecutorService)4 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)4 Slf4j (lombok.extern.slf4j.Slf4j)4 ZKPaths (org.apache.curator.utils.ZKPaths)4 Preconditions (com.google.common.base.Preconditions)3 StreamImpl (io.pravega.client.stream.impl.StreamImpl)3 CompletableFuture (java.util.concurrent.CompletableFuture)3