List of usage examples for org.apache.zookeeper ZooKeeper getData
public void getData(String path, boolean watch, DataCallback cb, Object ctx)
From source file:com.nesscomputing.service.discovery.client.internal.ServiceDiscoveryReader.java
License:Apache License
@Override void visit(final List<String> childNodes, final ZooKeeper zookeeper, final long tick) throws InterruptedException { final Map<String, List<ServiceInformation>> serviceMap = new HashMap<String, List<ServiceInformation>>(); if (!childNodes.isEmpty()) { final List<ServiceInformation> rawServices = new ArrayList<ServiceInformation>(childNodes.size()); final CountDownLatch latch = new CountDownLatch(childNodes.size()); final long now = System.nanoTime(); for (final String child : childNodes) { final String childPath = getNodePath(child); if (badNodes.containsKey(childPath)) { final Long penaltyEndsTime = badNodes.get(childPath); if (penaltyEndsTime != null && penaltyEndsTime > now) { // Decrement the countdown latch, because there will be no callback for this // node. latch.countDown();//from w w w . j av a 2 s . c o m // Ignore a bad node for a while. continue; } LOG.info("Unmarking %s as a bad node!", childPath); badNodes.remove(childPath); } zookeeper.getData(childPath, false, new DataCallback() { @Override public void processResult(final int rc, final String path, final Object ctx, final byte[] data, final Stat stat) { ServiceInformation si = null; try { if (data != null && data.length > 0) { si = objectMapper.readValue(data, ServiceInformation.class); LOG.trace("%s contains %s", path, si); } else { // This can sometimes happen if a node that we want to inspect // disappears between callback post and callback processing. LOG.trace("Got callback but no data!"); } } catch (IOException ioe) { LOG.debug(ioe, "While deserializing %s", new String(data, Charsets.UTF_8)); LOG.info("Marking %s as a bad node!", path); // Put a bad node into the penalty box. badNodes.put(path, now + penaltyTime); } finally { synchronized (rawServices) { if (si != null) { rawServices.add(si); } } latch.countDown(); } } }, null); } if (!latch.await(discoveryConfig.getZookeeperTimeout().getMillis(), TimeUnit.MILLISECONDS)) { LOG.warn("Timeout waiting for callbacks, some nodes were not parsed."); } // Make sure that even with late callbacks, this will not throw spurious ConcurrentModificationExceptions synchronized (rawServices) { for (final ServiceInformation si : rawServices) { List<ServiceInformation> services = serviceMap.get(si.getServiceName()); if (services == null) { services = new ArrayList<ServiceInformation>(); serviceMap.put(si.getServiceName(), services); } services.add(si); } } } Map<String, ConsistentRingGroup> serviceGroups = Maps.newHashMap(); for (Map.Entry<String, List<ServiceInformation>> entry : serviceMap.entrySet()) { ConsistentRingGroup currentGroup = stateHolder.getState().get(entry.getKey()); //Rebuilding a group is kind of expensive, so reuse the old group if it hasn't changed if (currentGroup != null && Sets.newHashSet(entry.getValue()).equals(Sets.newHashSet(currentGroup.getAll()))) { serviceGroups.put(entry.getKey(), currentGroup); } else { serviceGroups.put(entry.getKey(), new ConsistentRingGroup(entry.getValue())); } } stateHolder.setState(serviceGroups); }
From source file:com.proofpoint.zookeeper.ZookeeperClient.java
License:Apache License
@Override public DataAndStat getDataAndStat(final String path) throws Exception { if (inBackground) { RetryHandler.Call<Void> backgroundCall = new RetryHandler.Call<Void>() { @Override/* w ww. j a va2 s.c om*/ public Void call(ZooKeeper client, final RetryHandler<Void> retryHandler) throws Exception { if (overrideWatcher != null) { client.getData(path, overrideWatcher, new RetryDataCallback(retryHandler), context); } else { client.getData(path, watched, new RetryDataCallback(retryHandler), context); } return null; } }; RetryHandler.makeAndStart(this, retryPolicy, backgroundCall); return null; } RetryHandler.Call<DataAndStat> backgroundCall = new RetryHandler.Call<DataAndStat>() { @Override public DataAndStat call(ZooKeeper client, RetryHandler<DataAndStat> dataAndStatRetryHandler) throws Exception { final Stat stat = new Stat(); final byte[] data = (overrideWatcher != null) ? client.getData(path, overrideWatcher, stat) : client.getData(path, watched, stat); return new DataAndStat() { @Override public Stat getStat() { return stat; } @Override public byte[] getData() { return data; } }; } }; return RetryHandler.makeAndStart(this, retryPolicy, backgroundCall); }
From source file:com.twitter.distributedlog.lock.ZKSessionLock.java
License:Apache License
/** * Get client id and its ephemeral owner. * * @param zkClient//from w w w .ja v a 2 s . c om * zookeeper client * @param lockPath * lock path * @param nodeName * node name * @return client id and its ephemeral owner. */ static Future<Pair<String, Long>> asyncParseClientID(ZooKeeper zkClient, String lockPath, String nodeName) { String[] parts = nodeName.split("_"); // member_<clientid>_s<owner_session>_ if (4 == parts.length && parts[2].startsWith("s")) { long sessionOwner = Long.parseLong(parts[2].substring(1)); String clientId; try { clientId = URLDecoder.decode(parts[1], UTF_8.name()); return Future.value(Pair.of(clientId, sessionOwner)); } catch (UnsupportedEncodingException e) { // if failed to parse client id, we have to get client id by zookeeper#getData. } } final Promise<Pair<String, Long>> promise = new Promise<Pair<String, Long>>(); zkClient.getData(lockPath + "/" + nodeName, false, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() != rc) { promise.setException(KeeperException.create(KeeperException.Code.get(rc))); } else { promise.setValue(Pair.of(deserializeClientId(data), stat.getEphemeralOwner())); } } }, null); return promise; }
From source file:com.twitter.distributedlog.util.Utils.java
License:Apache License
/** * Retrieve data from zookeeper <code>path</code>. * * @param path/*from w w w .jav a2s . com*/ * zookeeper path to retrieve data * @param watch * whether to watch the path * @return future representing the versioned value. null version or null value means path doesn't exist. */ public static Future<Versioned<byte[]>> zkGetData(ZooKeeper zk, String path, boolean watch) { final Promise<Versioned<byte[]>> promise = new Promise<Versioned<byte[]>>(); zk.getData(path, watch, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() == rc) { if (null == stat) { promise.setValue(new Versioned<byte[]>(null, null)); } else { promise.setValue(new Versioned<byte[]>(data, new ZkVersion(stat.getVersion()))); } } else if (KeeperException.Code.NONODE.intValue() == rc) { promise.setValue(new Versioned<byte[]>(null, null)); } else { promise.setException(KeeperException.create(KeeperException.Code.get(rc))); } } }, null); return promise; }
From source file:org.apache.bookkeeper.zookeeper.BkZooKeeperClient.java
License:Apache License
@Override public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override/*from w w w . j a va 2 s . co m*/ public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { BkZooWorker worker = (BkZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { BkZooKeeperClient.super.getData(path, watcher, dataCb, worker); } else { zkHandle.getData(path, watcher, dataCb, worker); } } @Override public String toString() { return String.format("getData (%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 getData(final String path, final boolean watch, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override//from www. j a v a 2 s . co m public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { BkZooWorker worker = (BkZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { BkZooKeeperClient.super.getData(path, watch, dataCb, worker); } else { zkHandle.getData(path, watch, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); }
From source file:org.apache.bookkeeper.zookeeper.ZooKeeperClient.java
License:Apache License
@Override public void getData(final String path, final Watcher watcher, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override//from www .ja v a 2 s .c om public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getData(path, watcher, dataCb, worker); } else { zkHandle.getData(path, watcher, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watcher); } }; // execute it immediately proc.run(); }
From source file:org.apache.bookkeeper.zookeeper.ZooKeeperClient.java
License:Apache License
@Override public void getData(final String path, final boolean watch, final DataCallback cb, final Object context) { final Runnable proc = new ZkRetryRunnable(operationRetryPolicy, rateLimiter, getStats) { final DataCallback dataCb = new DataCallback() { @Override//from w w w. j a va 2s. c om public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { ZooWorker worker = (ZooWorker) ctx; if (allowRetry(worker, rc)) { backOffAndRetry(that, worker.nextRetryWaitTime()); } else { cb.processResult(rc, path, context, data, stat); } } }; @Override void zkRun() { ZooKeeper zkHandle = zk.get(); if (null == zkHandle) { ZooKeeperClient.super.getData(path, watch, dataCb, worker); } else { zkHandle.getData(path, watch, dataCb, worker); } } @Override public String toString() { return String.format("getData (%s, watcher = %s)", path, watch); } }; // execute it immediately proc.run(); }
From source file:org.apache.distributedlog.lock.ZKSessionLock.java
License:Apache License
/** * Get client id and its ephemeral owner. * * @param zkClient// w w w .jav a 2s. c o m * zookeeper client * @param lockPath * lock path * @param nodeName * node name * @return client id and its ephemeral owner. */ static CompletableFuture<Pair<String, Long>> asyncParseClientID(ZooKeeper zkClient, String lockPath, String nodeName) { String[] parts = nodeName.split("_"); // member_<clientid>_s<owner_session>_ if (4 == parts.length && parts[2].startsWith("s")) { long sessionOwner = Long.parseLong(parts[2].substring(1)); String clientId; try { clientId = URLDecoder.decode(parts[1], UTF_8.name()); return FutureUtils.value(Pair.of(clientId, sessionOwner)); } catch (UnsupportedEncodingException e) { // if failed to parse client id, we have to get client id by zookeeper#getData. } } final CompletableFuture<Pair<String, Long>> promise = new CompletableFuture<Pair<String, Long>>(); zkClient.getData(lockPath + "/" + nodeName, false, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() != rc) { promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc))); } else { promise.complete(Pair.of(deserializeClientId(data), stat.getEphemeralOwner())); } } }, null); return promise; }
From source file:org.apache.distributedlog.util.Utils.java
License:Apache License
/** * Retrieve data from zookeeper <code>path</code>. * * @param path//from w w w.j a va 2s .co m * zookeeper path to retrieve data * @param watch * whether to watch the path * @return future representing the versioned value. null version or null value means path doesn't exist. */ public static CompletableFuture<Versioned<byte[]>> zkGetData(ZooKeeper zk, String path, boolean watch) { final CompletableFuture<Versioned<byte[]>> promise = new CompletableFuture<Versioned<byte[]>>(); zk.getData(path, watch, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { if (KeeperException.Code.OK.intValue() == rc) { if (null == stat) { promise.complete(new Versioned<byte[]>(null, null)); } else { promise.complete(new Versioned<byte[]>(data, new LongVersion(stat.getVersion()))); } } else if (KeeperException.Code.NONODE.intValue() == rc) { promise.complete(new Versioned<byte[]>(null, null)); } else { promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc))); } } }, null); return promise; }