List of usage examples for org.apache.zookeeper Watcher Watcher
Watcher
From source file:com.greplin.zookeeper.RobustZooKeeperTest.java
License:Apache License
private void checkNoRemainingLocks(String lockName) throws IOException, InterruptedException, KeeperException { ZooKeeper verifier = new ZooKeeper("localhost:" + ZK_PORT, Integer.MAX_VALUE, new Watcher() { @Override//from w w w. j a v a 2s . c om public void process(WatchedEvent event) { // no-op watcher } }); List<String> children = verifier.getChildren(RobustZooKeeper.LOCK_NODE_PREFIX + lockName, false); Assert.assertEquals(0, children.size()); }
From source file:com.griddynamics.jagger.coordinator.zookeeper.DefaultZNodeLock.java
License:Open Source License
@Override public void lock() { while (true) { ZNode node = lockDir().createChild(znode().ephemeralSequential()); final String currentNodeName = node.getShortPath(); int currentFlag = Integer.valueOf(currentNodeName); final List<ZNode> children = lockDir().children(); int lowestNodeVal = Integer.MAX_VALUE; int nextNodeFlag = -1; String nextNodePath = null; for (ZNode child : children) { String childPath = child.getShortPath(); int childFlag = Integer.valueOf(childPath); if (childFlag < lowestNodeVal) { lowestNodeVal = childFlag; }/*from w w w . j ava 2 s. co m*/ if (childFlag < currentFlag && childFlag > nextNodeFlag) { nextNodeFlag = childFlag; nextNodePath = childPath; } } if (currentFlag == lowestNodeVal) { lockNode = node; break; } final CountDownLatch signal = new CountDownLatch(1); boolean hasChild = lockDir().hasChild(nextNodePath, new Watcher() { @Override public void process(WatchedEvent event) { signal.countDown(); } }); if (hasChild) { lockNode = node; try { signal.await(); break; } catch (InterruptedException e) { throw new RuntimeException(e); } } node.remove(); } }
From source file:com.griddynamics.jagger.coordinator.zookeeper.ZookeeperCoordinator.java
License:Open Source License
@Override public void registerNode(NodeContext nodeContext, Set<Worker> workers, final StatusChangeListener listener) throws CoordinatorException { log.info("Going to register node {} with {} workers", nodeContext.getId(), workers.size()); ZNode typeNode = rootNode.child(CoordinationUtil.nodeNameOf(nodeContext.getId().getType())); ZNode node = typeNode.createChild(znode().withPath(nodeContext.getId().getIdentifier())); Set<CommandExecutor<?, ?>> executors = Sets.newHashSet(); Set<Qualifier<?>> qualifiers = Sets.newHashSet(); for (Worker worker : workers) { for (CommandExecutor<?, ?> executor : worker.getExecutors()) { Qualifier<?> qualifier = executor.getQualifier(); if (qualifiers.contains(qualifier)) { throw new CoordinatorException( "Executor for qualifier " + qualifier + " is already registered"); }//from w ww . j a v a 2 s.c o m executors.add(executor); } } for (CommandExecutor<?, ?> executor : executors) { registerExecutor(nodeContext, executor, node); } rootNode.addNodeWatcher(new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.Disconnected) { listener.onCoordinatorDisconnected(); } if (event.getState() == Event.KeeperState.SyncConnected) { listener.onCoordinatorConnected(); } } }); ZNode statuses = rootNode.child(CoordinationUtil.STATUSES_NODE_NAME); statuses.createChild(znode().ephemeralSequential().withDataObject(nodeContext.getId())); Lock lock = new ReentrantLock(); lock.lock(); try { Collection<NodeId> nodeIds = Sets.newHashSet(); StatusWatcher statusWatcher = new StatusWatcher(statuses, lock, nodeIds, listener); List<ZNode> nodes = statuses.children(statusWatcher); for (ZNode zNode : nodes) { nodeIds.add(zNode.getObject(NodeId.class)); } } finally { lock.unlock(); } node.createChild(znode().withPath(CoordinationUtil.AVAILABLE_NODE_NAME)); }
From source file:com.griddynamics.jagger.coordinator.zookeeper.ZookeeperCoordinator.java
License:Open Source License
private <C extends Command<R>, R extends Serializable> void registerExecutor(final NodeContext nodeContext, final CommandExecutor<C, R> executor, ZNode node) { final ZNode executorNode = node.createChild(znode().withPath(nodeNameOf(executor.getQualifier()))); final ZNode queueNode = executorNode.createChild(znode().withPath("queue")); executorNode.createChild(znode().withPath("result")); log.debug("Created znodes for executor {}", executorNode.getPath()); queueNode.addChildrenWatcher(new Watcher() { @Override// w w w .j a v a 2 s .c o m public void process(WatchedEvent event) { if (event.getType() != Event.EventType.NodeChildrenChanged) { return; } synchronized (lock) { if (log.isDebugEnabled()) { log.debug("Children changed {} event type {}", queueNode.getPath(), event.getType()); } List<QueueEntry<C, R>> entries = getEntries(queueNode, this); for (final QueueEntry<C, R> entry : entries) { Runnable run = new Runnable() { @Override public void run() { executeCommand(executor, executorNode, entry, nodeContext); } }; ZookeeperCoordinator.this.executor.execute(run); } } } }); }
From source file:com.griddynamics.jagger.coordinator.zookeeper.ZooKeeperFactory.java
License:Open Source License
public IZookeeper create() { final CountDownLatch connectedSignal = new CountDownLatch(1); IZookeeper zooKeeper = null;//from www . ja v a 2 s .c om try { zooKeeper = new DefaultZookeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { connectedSignal.countDown(); } } }, reconnectPeriod); connectedSignal.await(); } catch (Exception e) { throw new ZooException(e); } return zooKeeper; }
From source file:com.griddynamics.jagger.coordinator.zookeeper.ZooKeeperRemoteExecutor.java
License:Open Source License
@Override public <C extends Command<R>, R extends Serializable> void run(final C command, final NodeCommandExecutionListener<C> listener, final AsyncCallback<R> callback) { ZNode commandNode = rootNode.child(nodeId.getType().name().toLowerCase()).child(nodeId.getIdentifier()) .child(command.getClass().getName()); ZNode queueNode = commandNode.child("queue"); ZNode resultNode = commandNode.child("result"); final ZNode outputNode = resultNode.createChild(znode().persistentSequential()); outputNode.addNodeWatcher(new Watcher() { @Override/*from w w w .j ava 2s. c om*/ public void process(WatchedEvent event) { log.debug("command {} execution done", command); CommandExecutionResult result = outputNode.getObject(CommandExecutionResult.class); switch (result.getStatus()) { case SUCCEEDED: log.debug("success"); callback.onSuccess((R) result.getResult()); break; case FAILED: Throwable e = result.getException(); log.error("fail", e); callback.onFailure(e); break; default: throw new IllegalStateException("Unknown status"); } outputNode.removeWithChildren(); } }); queueNode.createChild(znode().persistentSequential() .withDataObject(new QueueEntry<C, R>(command, listener, outputNode.getPath()))); log.debug("command {} is ready to be executed", command); }
From source file:com.gxl.shark.resources.conn.ZookeeperConnectionManager.java
License:Apache License
/** * zookeeper//from ww w . ja v a 2 s . c om * * @author JohnGao */ private void connection() { try { zk_client = new ZooKeeper(zk_address, zk_session_timeout, new Watcher() { @Override public void process(WatchedEvent event) { final KeeperState STATE = event.getState(); final String VALUE = "zookeeper?[" + zk_address + "]"; switch (STATE) { case SyncConnected: countDownLatch.countDown(); logger.info(VALUE + "?"); break; case Disconnected: logger.warn(VALUE + "?"); break; case Expired: logger.error(VALUE + "??"); break; case AuthFailed: logger.error(VALUE + "?ACL?"); default: break; } } }); countDownLatch.await(); /* ?? */ registerNode.register(zk_client, nodePath); } catch (IOException e) { throw new ResourceException("zookeeper?[" + e.toString() + "]"); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:com.gxl.test.shark.resource.zkSetData.java
License:Apache License
public @Test void testSetData() { try (BufferedReader reader = new BufferedReader(new FileReader("c:/shark-datasource.xml"))) { StringBuffer str = new StringBuffer(); String value = ""; while (null != (value = reader.readLine())) str.append(value);/*from w w w . ja va 2 s . c om*/ final CountDownLatch countDownLatch = new CountDownLatch(1); ZooKeeper zk_client = new ZooKeeper( "120.25.58.116:2181,120.25.58.116:2182,120.25.58.116:2183,120.25.58.116:2184", 30000, new Watcher() { @Override public void process(WatchedEvent event) { final KeeperState STATE = event.getState(); switch (STATE) { case SyncConnected: countDownLatch.countDown(); logger.info("?zookeeper?"); break; case Disconnected: logger.warn("zookeeper?"); break; case Expired: logger.error("session?..."); break; case AuthFailed: logger.error("ACL?..."); default: break; } } }); countDownLatch.await(); zk_client.setData("/info/datasource", str.toString().getBytes(), -1); logger.info("insert success"); } catch (Exception e) { logger.error("insert fail", e); } }
From source file:com.gxl.zk.ZKConnectionManager.java
License:Apache License
/** * zookeeper/* www . j a v a2 s.c o m*/ * * @author gaoxianglong * * @throws ConnectionException * * @return void */ private void connection() { countDownLatch = new CountDownLatch(1); try { zk_client = new ZooKeeper(address, zk_session_timeout, new Watcher() { @Override public void process(WatchedEvent event) { final KeeperState STATE = event.getState(); switch (STATE) { case SyncConnected: countDownLatch.countDown(); logger.info("connection zookeeper success"); break; case Disconnected: logger.warn("zookeeper connection is disconnected"); break; case Expired: logger.error("zookeeper session expired"); break; case AuthFailed: logger.error("authentication failure"); default: break; } } }); countDownLatch.await(); String samplingRate = null; /* ?? */ if (null == zk_client.exists("/tracing", false)) { zk_client.create("/tracing", new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } /* ?znode? */ if (null != zk_client.exists(samplingRate_path, false)) { samplingRate = new String(zk_client.getData(samplingRate_path, new SamplingRateWatcher(zk_client, samplingRate_path), null)); } else { logger.warn("-->" + samplingRate_path + "?,"); /* ?1/1024 */ zk_client.create(samplingRate_path, "1024".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); samplingRate = new String(zk_client.getData(samplingRate_path, new SamplingRateWatcher(zk_client, samplingRate_path), null)); } /* */ TraceFilter.samplingNum = Integer.parseInt(samplingRate); } catch (Exception e) { logger.error("error", e); } }
From source file:com.iquanwai.confucius.biz.util.zk.RobustZooKeeper.java
License:Apache License
private void lockRecipeStepTwo(final String fullPath, final String relativePath, final String lockName, final Runnable action) throws IOException, InterruptedException, KeeperException { log.info("Client " + this.clientNumber + " at start of lockRecipeStepTwo with relativePath = " + relativePath);/* ww w . j a v a2 s .co m*/ if (this.shutdown.get()) { log.warn("Client " + this.clientNumber + " is shutdown - so I'm going to give up my attempt to lock"); return; } // step 2 final List<String> children = getClient().getChildren(getLockParent(lockName), false); assert children.size() > 0; // at the ver least, my node should be there. Collections.sort(children); // step 3 if (relativePath.equals(children.get(0))) { log.info("Client " + this.clientNumber + " has the lowest number lock attempt (" + relativePath + "), so it holds the lock"); try { action.run(); } finally { log.info("Client " + this.clientNumber + " finished doing my work with " + relativePath + ", so I'm giving up the lock."); try { getClient().delete(fullPath, -1); } catch (KeeperException.NoNodeException e) { log.warn("After I finished running an action with lock " + lockName + " the actions lock node (" + fullPath + ") no longer exists. This should only happen if you manually deleted " + fullPath + " or there was an underlying network failure, and we had to reconnect"); } } return; } // step 4 final int indexOfNodeBefore = children.indexOf(relativePath) - 1; if (indexOfNodeBefore < 0) { throw new IllegalStateException( "indexOfNodeBefore is " + indexOfNodeBefore + ", and children are: " + children); } final String nodeBeforeMine = children.get(indexOfNodeBefore); log.info("Client " + this.clientNumber + " (at " + relativePath + ") is setting a watch on the node before me (" + nodeBeforeMine + ")"); final Stat exists = getClient().exists(getLockParent(lockName) + "/" + nodeBeforeMine, new Watcher() { @Override public void process(WatchedEvent event) { try { log.info("Client " + RobustZooKeeper.this.clientNumber + ", when watching " + nodeBeforeMine + ", got notified: " + event); lockRecipeStepTwo(fullPath, relativePath, lockName, action); } catch (Exception e) { log.warn("Unable to execute action with lock " + lockName, e); } } }); // step 5 if (exists == null) { log.info("Client " + this.clientNumber + " expected " + nodeBeforeMine + " to exist - but it doesn't so re-running step 2"); lockRecipeStepTwo(fullPath, relativePath, lockName, action); } }