private void checkClusterIdExists(final String id, final String checker) { try { final Stat stat = client.checkExists().usingWatcher(watcher).forPath(Paths.configId(id)); final boolean exists = stat != null; clusterIdExists.set(exists); log.info("Cluster ID {} {} when checked by {}", id, exists ? "exists" : "does not exist", checker); } catch (Exception e) { clusterIdExists.set(false); log.error("Exception while checking ZooKeeper cluster ID {}", clusterId, e); } } }
private void watchNode() throws Exception { if (!isActive()) return; String localNodePath = nodePath.get(); if (localNodePath == null) return; try { client.checkExists().usingWatcher(watcher).inBackground( checkExistsCallback).forPath(localNodePath); } catch (Exception e) { LOG.error("Watching node: " + localNodePath, e); throw e; } }
private void createInstanceNodeForInitialization() throws Exception { String parent = String.format("%s/%s/instances", CONSTANTS_ROOT_PATH, CommonUtils.getApplication(this.endpoint)); String path = String.format("%s/%s", parent, this.endpoint); byte[] versionByteArray = ByteUtils.longToByteArray(this.instanceVersion); try { this.curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(path, versionByteArray); } catch (NodeExistsException error) { try { this.instanceLock.lock(); this.instanceInited = false; this.curatorFramework.checkExists().usingWatcher(this).inBackground(this).forPath(path); this.instanceCond.await(this.initializeWaitingSeconds, TimeUnit.SECONDS); if (this.instanceInited == false) { throw error; } } catch (InterruptedException ignore) { // ignore } finally { this.instanceLock.unlock(); } } }
private void determineLeadership() { ReentrantReadWriteLock.WriteLock lock = this.readWriteLock.writeLock(); lock.lock(); try { List<String> children = this.zooKeeper.getChildren().forPath(this.leaderElectionNode); Collections.sort(children); int idx = children.indexOf(this.nodeId); if (idx == 0) { Stat stat = this.zooKeeper.checkExists().forPath(this.leaderNode); if (stat == null) { this.zooKeeper.create().forPath(this.leaderNode, serializeMetadata(this.localMetadata)); } else { this.zooKeeper.setData().forPath(this.leaderNode, serializeMetadata(this.localMetadata)); } this.isLeader = true; } else { this.isLeader = false; String watchedNode = this.leaderElectionNode + "/" + children.get(idx - 1); this.zooKeeper.checkExists().usingWatcher(new DetermineLeadershipWatcher()).forPath(watchedNode); } findLeader(); } catch (KeeperException exc) { reset(); } catch (Throwable exc) { log.error("Fatal failure.", exc); this.fatalFailure = true; } finally { lock.unlock(); } }
private void findLeader() { ReentrantReadWriteLock.WriteLock lock = this.readWriteLock.writeLock(); lock.lock(); try { if (this.zooKeeper.checkExists().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode) == null) { determineLeadership(); } byte[] leaderData = this.zooKeeper.getData().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode); this.leaderMetadata = deserializeMetadata(leaderData); } catch (KeeperException exc) { reset(); } catch (Throwable exc) { log.error("Fatal failure.", exc); this.fatalFailure = true; } finally { lock.unlock(); } }
if (zooKeeperClient.checkExists().usingWatcher(watcher).forPath(znodePath) == null) {
); final Stat stat = curator.checkExists().usingWatcher( (CuratorWatcher) watchedEvent -> { switch (watchedEvent.getType()) {
private void checkClusterIdExists(final String id, final String checker) { try { final Stat stat = client.checkExists().usingWatcher(watcher).forPath(Paths.configId(id)); final boolean exists = stat != null; clusterIdExists.set(exists); log.info("Cluster ID {} {} when checked by {}", id, exists ? "exists" : "does not exist", checker); } catch (Exception e) { clusterIdExists.set(false); log.error("Exception while checking ZooKeeper cluster ID {}", clusterId, e); } } }
private void reset() throws Exception { if ( (state.get() == State.STARTED) && isConnected.get() ) { client.checkExists().usingWatcher(watcher).inBackground(backgroundCallback).forPath(path); } }
/** * Register existing {@link CuratorWatcher} for a state path. */ protected void registerWatcherForStatePath() { try { if (curatorClient.getState() != CuratorFrameworkState.STOPPED) { curatorClient.checkExists().usingWatcher(watcher).forPath(statePath); } } catch (Exception e) { log.warn("Registering watcher for path " + statePath + " threw error", e); } }
public void checkEphemeral() { try { if (!created) { final Stat stat = client.checkExists().usingWatcher(this).forPath(path); if (stat != null) { ephemeral = stat.getEphemeralOwner() != 0; created = true; } } } catch (Exception ex) { LOG.error("Exception:", ex); throw Throwables.propagate(ex); } } private final Watcher childrenWatcher = new Watcher() {
private void watchNode() throws Exception { if (!isActive()) return; String localNodePath = nodePath.get(); if (localNodePath == null) return; try { client.checkExists().usingWatcher(watcher).inBackground( checkExistsCallback).forPath(localNodePath); } catch (Exception e) { LOG.error("Watching node: " + localNodePath, e); throw e; } }
private void watchNode() throws Exception { if ( !isActive() ) { return; } String localNodePath = nodePath.get(); if ( localNodePath != null ) { client.checkExists().usingWatcher(watcher).inBackground(checkExistsCallback).forPath(localNodePath); } }
/** * Enter the barrier and block until all members have entered or the timeout has * elapsed * * @param maxWait max time to block * @param unit time unit * @return true if the entry was successful, false if the timeout elapsed first * @throws Exception interruptions, errors, etc. */ public boolean enter(long maxWait, TimeUnit unit) throws Exception { long startMs = System.currentTimeMillis(); boolean hasMaxWait = (unit != null); long maxWaitMs = hasMaxWait ? TimeUnit.MILLISECONDS.convert(maxWait, unit) : Long.MAX_VALUE; boolean readyPathExists = (client.checkExists().usingWatcher(watcher).forPath(readyPath) != null); client.create().creatingParentContainersIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(ourPath); boolean result = (readyPathExists || internalEnter(startMs, hasMaxWait, maxWaitMs)); if ( connectionLost.get() ) { throw new KeeperException.ConnectionLossException(); } return result; }
private void findLeader() { ReentrantReadWriteLock.WriteLock lock = this.readWriteLock.writeLock(); lock.lock(); try { if (this.zooKeeper.checkExists().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode) == null) { determineLeadership(); } byte[] leaderData = this.zooKeeper.getData().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode); this.leaderMetadata = deserializeMetadata(leaderData); } catch (KeeperException exc) { reset(); } catch (Throwable exc) { log.error("Fatal failure.", exc); this.fatalFailure = true; } finally { lock.unlock(); } }
private void findLeader() { ReentrantReadWriteLock.WriteLock lock = this.readWriteLock.writeLock(); lock.lock(); try { if (this.zooKeeper.checkExists().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode) == null) { determineLeadership(); } byte[] leaderData = this.zooKeeper.getData().usingWatcher(new FindLeaderWatcher()).forPath(this.leaderNode); this.leaderMetadata = deserializeMetadata(leaderData); } catch (KeeperException exc) { reset(); } catch (Throwable exc) { log.error("Fatal failure.", exc); this.fatalFailure = true; } finally { lock.unlock(); } }
@Override public void addListener(final String node, final Listener listener) { try { LOG.info("Adding listener {} on {}", listener, possiblyWithSequence(node)); final MyWatcher watcher = new MyWatcher(listener, possiblyWithSequence(node)); watcher.checkEphemeral(); watcher.setChildren(); client.checkExists().usingWatcher(watcher).forPath(watcher.path); client.getChildren().inBackground(new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { final List<String> children = event.getChildren(); if (children != null) { for (String child : children) listener.nodeChildAdded(nodeName(node), nodeName(child)); } } }).forPath(node); } catch (Exception ex) { LOG.error("Adding listener on node " + node + " has failed!", ex); throw Throwables.propagate(ex); } }
@Override public void process(WatchedEvent event) { try { if (event.getPath() != null) { if (!removedListeners.remove(listener)) { if (event.getType() == Watcher.Event.EventType.NodeDataChanged) { assert path.equals(parent(event.getPath())); LOG.info("Node child data changed: {} ({})", nodeName(event.getPath()), event.getPath()); listener.nodeChildUpdated(path, child(nodeName(event.getPath()))); } client.checkExists().usingWatcher(this).forPath(event.getPath()); } } } catch (Exception ex) { LOG.error("Exception:", ex); throw Throwables.propagate(ex); } } };
public void usingWatcher(ZookeeperWatcherType watcherType, String path) throws Exception { if (watcherType == null) { throw new ZookeeperException("Watcher type is null"); } PathUtils.validatePath(path); this.watcherType = watcherType; this.path = path; switch (watcherType) { case EXISTS: usingWatcher(client.checkExists().usingWatcher(this), path); break; case GET_CHILDREN: usingWatcher(client.getChildren().usingWatcher(this), path); break; case GET_DATA: usingWatcher(client.getData().usingWatcher(this), path); break; } }
void getDataAndStat(final String fullPath) throws Exception { if (client.checkExists().forPath(fullPath) == null) { return; } final List<String> children = client.getChildren().usingWatcher(watcher).forPath(fullPath); if ( cacheData ) { Stat stat = new Stat(); byte[] data = null; if ( dataIsCompressed ) { data = client.getData().decompressed().storingStatIn(stat).usingWatcher(watcher).forPath(fullPath); } else { data = client.getData().storingStatIn(stat).usingWatcher(watcher).forPath(fullPath); } applyNewData(fullPath, KeeperException.Code.OK.intValue(), stat, data, children); } else { Stat stat = client.checkExists().usingWatcher(watcher).forPath(fullPath); applyNewData(fullPath, KeeperException.Code.OK.intValue(), stat, null, children); } }