Example usage for org.apache.zookeeper ZooKeeper getChildren

List of usage examples for org.apache.zookeeper ZooKeeper getChildren

Introduction

In this page you can find the example usage for org.apache.zookeeper ZooKeeper getChildren.

Prototype

public void getChildren(String path, boolean watch, Children2Callback cb, Object ctx) 

Source Link

Document

The asynchronous version of getChildren.

Usage

From source file:com.linkedin.d2.balancer.zkfs.ZKFSDirectory.java

License:Apache License

@Override
public void getServiceNames(final Callback<List<String>> callback) {
    final ZooKeeper zk = _connection.getZooKeeper();
    final String path = ZKFSUtil.servicePath(_basePath);
    zk.getChildren(path, false, new AsyncCallback.Children2Callback() {
        @Override/*  w w w. j a  v  a2 s  . c o m*/
        public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(children);
                break;
            case NONODE:
                callback.onSuccess(Collections.<String>emptyList());
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    }, null);
}

From source file:com.linkedin.d2.balancer.zkfs.ZKFSDirectory.java

License:Apache License

@Override
public void getClusterNames(final Callback<List<String>> callback) {
    final ZooKeeper zk = _connection.getZooKeeper();
    final String path = ZKFSUtil.clusterPath(_basePath);
    zk.getChildren(path, false, new AsyncCallback.Children2Callback() {
        @Override/* ww w .j av  a 2 s .  c  o  m*/
        public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                callback.onSuccess(children);
                break;
            case NONODE:
                callback.onSuccess(Collections.<String>emptyList());
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }
        }
    }, null);

}

From source file:com.linkedin.d2.discovery.stores.zk.ZKConnection.java

License:Apache License

/**
 * see {@link #removeNodeUnsafe} but remove recursively
 *
 * @param path/*  ww w. ja v a  2s  .co m*/
 * @param callback
 */
public void removeNodeUnsafeRecursive(final String path, final Callback<None> callback) {
    final ZooKeeper zk = zk();

    final Callback<None> deleteThisNodeCallback = new Callback<None>() {
        @Override
        public void onSuccess(None none) {
            removeNodeUnsafe(path, callback);
        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    };

    // Note ChildrenCallback is compatible with a ZK 3.2 server; Children2Callback is
    // compatible only with ZK 3.3+ server.
    final AsyncCallback.ChildrenCallback childCallback = new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                Callback<None> multiCallback = Callbacks.countDown(deleteThisNodeCallback, children.size());
                for (String child : children) {
                    removeNodeUnsafeRecursive(path + "/" + child, multiCallback);
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }

        }
    };

    try {
        zk.getChildren(path, false, childCallback, null);
    } catch (Exception e) {
        callback.onError(e);
    }
}

From source file:com.proofpoint.zookeeper.ZookeeperClient.java

License:Apache License

@Override
public List<String> getChildren(final String path) throws Exception {
    if (inBackground) {
        RetryHandler.Call<Void> backgroundCall = new RetryHandler.Call<Void>() {
            @Override//from  w  w w . j  av a  2  s.  c o  m
            public Void call(ZooKeeper client, final RetryHandler<Void> retryHandler) throws Exception {
                if (overrideWatcher != null) {
                    client.getChildren(path, overrideWatcher, new RetryChildrenCallback(retryHandler), context);
                } else {
                    client.getChildren(path, watched, new RetryChildrenCallback(retryHandler), context);
                }
                return null;
            }
        };
        RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
        return null;
    }

    RetryHandler.Call<List<String>> backgroundCall = new RetryHandler.Call<List<String>>() {
        @Override
        public List<String> call(ZooKeeper client, RetryHandler<List<String>> listRetryHandler)
                throws Exception {
            return (overrideWatcher != null) ? client.getChildren(path, overrideWatcher)
                    : client.getChildren(path, watched);
        }
    };
    return RetryHandler.makeAndStart(this, retryPolicy, backgroundCall);
}

From source file:com.twitter.distributedlog.impl.ZKLogMetadataStore.java

License:Apache License

@Override
public Future<Iterator<String>> getLogs() {
    final Promise<Iterator<String>> promise = new Promise<Iterator<String>>();
    final String nsRootPath = namespace.getPath();
    try {/*w  w  w . jav  a  2  s  .  c  o m*/
        final ZooKeeper zk = zkc.get();
        zk.sync(nsRootPath, new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int syncRc, String syncPath, Object ctx) {
                if (KeeperException.Code.OK.intValue() == syncRc) {
                    zk.getChildren(nsRootPath, false, new AsyncCallback.Children2Callback() {
                        @Override
                        public void processResult(int rc, String path, Object ctx, List<String> children,
                                Stat stat) {
                            if (KeeperException.Code.OK.intValue() == rc) {
                                List<String> results = Lists.newArrayListWithExpectedSize(children.size());
                                for (String child : children) {
                                    if (!isReservedStreamName(child)) {
                                        results.add(child);
                                    }
                                }
                                promise.setValue(results.iterator());
                            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                                List<String> streams = Lists.newLinkedList();
                                promise.setValue(streams.iterator());
                            } else {
                                promise.setException(new ZKException("Error reading namespace " + nsRootPath,
                                        KeeperException.Code.get(rc)));
                            }
                        }
                    }, null);
                } else if (KeeperException.Code.NONODE.intValue() == syncRc) {
                    List<String> streams = Lists.newLinkedList();
                    promise.setValue(streams.iterator());
                } else {
                    promise.setException(new ZKException("Error reading namespace " + nsRootPath,
                            KeeperException.Code.get(syncRc)));
                }
            }
        }, null);
        zkc.get();
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }
    return promise;
}

From source file:io.confluent.admin.utils.ClusterStatus.java

License:Apache License

/**
 * Gets raw Kafka metadata from Zookeeper.
 * @param timeoutMs timeout in ms.//  w ww  . ja v  a2  s .c o  m
 * @param zookeeper Zookeeper client.
 * @return List of Kafka metadata strings.
 * @throws InterruptedException
 * @throws KeeperException
 */
private static List<String> getRawKafkaMetadataFromZK(ZooKeeper zookeeper, int timeoutMs)
        throws InterruptedException, KeeperException {
    // Get the data.
    CountDownLatch waitForBroker = new CountDownLatch(1);

    // Get children async. Countdown when one of the following happen:
    // 1. NodeChildrenChanged is triggered (this happens when children are created after the call is made).
    // 2. ChildrenCallback gets a callback with children present (this happens when node has
    //    children when the call is made) .
    final List<String> brokers = new CopyOnWriteArrayList<>();
    zookeeper.getChildren(BROKERS_IDS_PATH, (event) -> {
        log.debug("Got event when checking for children of /brokers/ids. type={} path={}", event.getType(),
                event.getPath());
        if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
            waitForBroker.countDown();
        }
    }, (rc, path, ctx, children) -> {
        log.debug("ChildrenCallback got data for path={} children={}", path, children);
        if (children != null && children.size() > 0) {
            children.addAll(brokers);
            waitForBroker.countDown();
        }
    }, null);

    boolean waitForBrokerTimedOut = !waitForBroker.await(timeoutMs, TimeUnit.MILLISECONDS);
    if (waitForBrokerTimedOut) {
        String message = String.format(
                "Timed out waiting for Kafka to register brokers in Zookeeper. " + "timeout (ms) = %s",
                timeoutMs);
        throw new TimeoutException(message);
    }

    if (brokers.isEmpty()) {
        // Get children. Broker list will be empty if the getChildren call above is made before the children are
        // present. In that case, the ChildrenCallback will be called with an empty children list and we will wait
        // for the NodeChildren event to be fired. At this point, this has happened and we can the children
        // safely using a sync call.
        zookeeper.getChildren(BROKERS_IDS_PATH, false, null).forEach((child) -> brokers.add(child));
    }
    return brokers;
}

From source file:org.apache.bookkeeper.util.ZkUtils.java

License:Apache License

/**
 * Async get direct children under single node
 *
 * @param zk// w ww . j av a 2  s. com
 *          zookeeper client
 * @param node
 *          node path
 * @param cb
 *          callback function
 */
public static void getChildrenInSingleNode(final ZooKeeper zk, final String node,
        final GenericCallback<List<String>> cb) {
    zk.sync(node, new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (rc != Code.OK.intValue()) {
                LOG.error("ZK error syncing nodes when getting children: ",
                        KeeperException.create(KeeperException.Code.get(rc), path));
                cb.operationComplete(rc, null);
                return;
            }
            zk.getChildren(node, false, new AsyncCallback.ChildrenCallback() {
                @Override
                public void processResult(int rc, String path, Object ctx, List<String> nodes) {
                    if (rc != Code.OK.intValue()) {
                        LOG.error("Error polling ZK for the available nodes: ",
                                KeeperException.create(KeeperException.Code.get(rc), path));
                        cb.operationComplete(rc, null);
                        return;
                    }

                    cb.operationComplete(rc, nodes);

                }
            }, null);
        }
    }, null);
}

From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java

License:Apache License

@Override
public void getChildren(final String path, final Watcher watcher, final Children2Callback cb,
        final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

        final Children2Callback childCb = new Children2Callback() {

            @Override//  w w  w.j av  a2  s  . c  o  m
            public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
                BkZooWorker worker = (BkZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context, children, stat);
                }
            }

        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                BkZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
            } else {
                zkHandle.getChildren(path, watcher, childCb, worker);
            }
        }

        @Override
        public String toString() {
            return String.format("getChildren (%s, watcher = %s)", path, watcher);
        }
    };
    // execute it immediately
    proc.run();
}

From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java

License:Apache License

@Override
public void getChildren(final String path, final boolean watch, final Children2Callback cb,
        final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

        final Children2Callback childCb = new Children2Callback() {

            @Override/*  ww w  . j  a va  2s .  com*/
            public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
                BkZooWorker worker = (BkZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context, children, stat);
                }
            }

        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                BkZooKeeperClient.super.getChildren(path, watch, childCb, worker);
            } else {
                zkHandle.getChildren(path, watch, childCb, worker);
            }
        }

        @Override
        public String toString() {
            return String.format("getChildren (%s, watcher = %s)", path, watch);
        }
    };
    // execute it immediately
    proc.run();
}

From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java

License:Apache License

@Override
public void getChildren(final String path, final Watcher watcher, final ChildrenCallback cb,
        final Object context) {
    final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getChildrenStats) {

        final ChildrenCallback childCb = new ChildrenCallback() {

            @Override//from www.  j a va2 s .  com
            public void processResult(int rc, String path, Object ctx, List<String> children) {
                BkZooWorker worker = (BkZooWorker) ctx;
                if (allowRetry(worker, rc)) {
                    backOffAndRetry(that, worker.nextRetryWaitTime());
                } else {
                    cb.processResult(rc, path, context, children);
                }
            }

        };

        @Override
        void zkRun() {
            ZooKeeper zkHandle = zk.get();
            if (null == zkHandle) {
                BkZooKeeperClient.super.getChildren(path, watcher, childCb, worker);
            } else {
                zkHandle.getChildren(path, watcher, childCb, worker);
            }
        }

        @Override
        public String toString() {
            return String.format("getChildren (%s, watcher = %s)", path, watcher);
        }
    };
    // execute it immediately
    proc.run();
}