List of usage examples for org.apache.zookeeper WatchedEvent getType
public EventType getType()
From source file:org.prot.controller.zookeeper.jobs.RegisterController.java
License:Open Source License
@Override public void process(WatchedEvent event) { switch (event.getType()) { case NodeDeleted: case NodeDataChanged: zooHelper.getQueue().insert(this); }//from w w w . java2s .co m }
From source file:org.prot.controller.zookeeper.jobs.WatchApp.java
License:Open Source License
@Override public void process(WatchedEvent event) { try {//w ww . j a va 2s .c om // Check the event type if (event.getType() == EventType.None) return; // Check the path final String path = event.getPath(); if (path == null) return; // Connection to zookeeper ZooKeeper zk = zooHelper.getZooKeeper(); // Extract the AppEntry object Stat stat = new Stat(); byte[] data = zk.getData(path, false, stat); ObjectSerializer serializer = new ObjectSerializer(); AppEntry entry = (AppEntry) serializer.deserialize(data); // The ZooKeeper API cannot remove watches. We have to check here if // the appId is still in the watchlist if (watching.containsKey(entry.appId)) appDeployed(entry.appId); } catch (InterruptedException e) { logger.error("InterruptedException", e); } catch (KeeperException e) { logger.error("KeeperException", e); } finally { // Reschedule this task (install watchers) zooHelper.getQueue().insert(this); } }
From source file:org.prot.manager.zookeeper.jobs.RegisterMaster.java
License:Open Source License
@Override public void process(WatchedEvent event) { switch (event.getType()) { case NodeDeleted: case None://from w ww .jav a2 s . com logger.debug("ZooKeeper master node has changed"); zooHelper.getQueue().insert(this); } }
From source file:org.rioproject.zookeeper.watcher.ZooKeeperServiceWatcher.java
License:Apache License
public void process(WatchedEvent event) { String path = event.getPath(); if (logger.isDebugEnabled()) logger.debug("{}", event); if (path == null) return;//from w w w.j a v a 2s. co m if (event.getType() == Event.EventType.None && event.getState().equals(Event.KeeperState.Expired)) { services.remove(path).serviceFailure(null, path); } else { if (logger.isDebugEnabled()) logger.debug("Path: {}", path); if (services.get(path) != null) { /* Something has changed on the node, let's find out if it still exists */ zooKeeper.exists(path, false, new AsyncCallback.StatCallback() { public void processResult(int rc, String path, Object ctx, Stat stat) { if (KeeperException.Code.NONODE.equals(KeeperException.Code.get(rc))) { services.remove(path).serviceFailure(null, path); } } }, null); } } }
From source file:org.wltea.analyzer.dic.Dictionary.java
License:Apache License
public void process(WatchedEvent event) { // TODO Auto-generated method stub logger.debug("path: " + event.getPath() + " EventType: " + event.getType()); if (event.getType() == Watcher.Event.EventType.NodeDataChanged && event.getPath() != null) { String path = event.getPath(); logger.debug("path: " + path); if (path.equals(ZK_DIC_EXT + ".add")) { Collection<String> words = this.getDataFromZkFile(path); this.updateWordsToDict(words, true, singleton._MainDict); } else if (path.equals(ZK_DIC_EXT + ".del")) { Collection<String> words = this.getDataFromZkFile(path); this.updateWordsToDict(words, false, singleton._MainDict); } else if (path.equals(ZK_DIC_STOP + ".add")) { Collection<String> words = this.getDataFromZkFile(path); this.updateWordsToDict(words, true, singleton._StopWordDict); } else if (path.equals(ZK_DIC_STOP + ".del")) { Collection<String> words = this.getDataFromZkFile(path); this.updateWordsToDict(words, true, singleton._StopWordDict); }/*from w w w .j av a2 s. c o m*/ } }
From source file:org.wso2.andes.server.cluster.ClusterManager.java
License:Open Source License
/** * Initialize the Cluster manager. This will create ZNodes related to nodes and assign node ids * * @throws CoordinationException in a Error when communicating with Zookeeper *//*from w ww . ja v a2 s . c o m*/ public void init() throws CoordinationException { final ClusterConfiguration config = ClusterResourceHolder.getInstance().getClusterConfiguration(); /** * do following if clustering is disabled. Here no Zookeeper is involved * so nodeID will be always 0 */ if (!config.isClusteringEnabled()) { //update node information in durable store List<String> nodeList = subscriptionStore.getStoredNodeIDList(); for (String node : nodeList) { subscriptionStore.deleteNodeData(node); } clearAllPersistedStatesOfDissapearedNode(nodeId); subscriptionStore.addNodeDetails("" + nodeId, config.getBindIpAddress()); //start all global queue workers on the node startAllGlobalQueueWorkers(); return; } /** * do following if cluster is enabled */ try { // create a new node with a generated randomId // get the node name and id zkAgent = new ZooKeeperAgent(connectionString); zkAgent.initQueueWorkerCoordination(); final String nodeName = CoordinationConstants.QUEUE_WORKER_NODE + (UUID.randomUUID()).toString().replace("-", "_"); String path = CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT + nodeName; //Register the watcher for zoo keeper parent to be fired when children changed zkAgent.getZooKeeper().getChildren(CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if (Event.EventType.NodeChildrenChanged == watchedEvent.getType()) { try { List<String> nodeListFromZK = zkAgent.getZooKeeper().getChildren( CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT, false); //identify and register this node for (String node : nodeListFromZK) { if ((CoordinationConstants.NODE_SEPARATOR + node).contains(nodeName)) { zkNode = node; nodeId = getNodeIdFromZkNode(node); log.info("Initializing Cluster Manager , " + "Selected Node id : " + nodeId); //add node information to durable store subscriptionStore.addNodeDetails("" + nodeId, config.getBindIpAddress()); //register a listener for changes on my node data only zkAgent.getZooKeeper().getData( CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT + CoordinationConstants.NODE_SEPARATOR + node, new NodeDataChangeListener(), null); break; } } for (String node : nodeListFromZK) { //update in-memory node list int id = getNodeIdFromZkNode(node); clusterNodeIDList.add(id); } List<String> storedNodes = subscriptionStore.getStoredNodeIDList(); /** * If nodeList size is one, this is the first node joining to cluster. Here we check if there has been * any nodes that lived before and somehow suddenly got killed. If there are such nodes clear the state of them and * copy back node queue messages of them back to global queue. * If node was the same machine:ip and zookeeper assigned a different id this logic will handle the confusion * We need to clear up current node's state as well as there might have been a node with same id and it was killed */ clearAllPersistedStatesOfDissapearedNode(nodeId); for (String storedNode : storedNodes) { int storedNodeId = Integer.parseInt(storedNode); if (!clusterNodeIDList.contains(storedNodeId)) { clearAllPersistedStatesOfDissapearedNode(storedNodeId); checkAndCopyMessagesOfNodeQueueBackToGlobalQueue(nodeId, AndesUtils.getNodeQueueNameForNodeId(storedNodeId)); } } } catch (Exception e) { log.error( "Error while coordinating cluster information while joining to cluster", e); throw new RuntimeException(e); } } } }); // Once this method called above defined watcher will be fired zkAgent.getZooKeeper().create(path, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); //wait until above task is completed Thread.sleep(4000); //update global queue synchronizing ID reAssignGlobalQueueSyncId(); //handle global queue addition for this node handleGlobalQueueAddition(); //notify node addition to all nodes and register node existence listeners for all nodes on this node List<String> nodeList = zkAgent.getZooKeeper() .getChildren(CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT, false); for (String node : nodeList) { String currentNodePath = CoordinationConstants.QUEUE_WORKER_COORDINATION_PARENT + CoordinationConstants.NODE_SEPARATOR + node; String data = CoordinationConstants.NODE_CHANGED_PREFIX + zkNode; //notify all other nodes that a new node joined with node ID zkAgent.getZooKeeper().setData(currentNodePath, data.getBytes(), -1); //Add Listener for node existence of any node in the cluster zkAgent.getZooKeeper().exists(currentNodePath, new NodeExistenceListener(node)); } } catch (Exception e) { e.printStackTrace(); String msg = "Error while initializing the zookeeper coordination "; log.error("Error while initializing the zookeeper coordination ", e); throw new CoordinationException(msg, e); } }
From source file:org.zookeeper.app.ConfigWatcher.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.NodeDataChanged) try {//from w w w.j a v a2 s.com displayConfig(); } catch (InterruptedException e) { System.err.println("Interrupted. Exiting."); Thread.currentThread().interrupt(); } catch (KeeperException e) { System.err.printf("KeeperException: %s. Exiting.\n", e); } catch (Exception e) { System.err.println("Unsupported. Exiting."); Thread.currentThread().interrupt(); } }
From source file:yangqi.code.DataMonitor.java
License:Open Source License
public void process(WatchedEvent event) { String path = event.getPath(); System.out.println("GOT EVENT " + event + " @" + new Date() + ",type is " + event.getType()); if (event.getType() == Event.EventType.None) { // We are are being told that the state of the // connection has changed switch (event.getState()) { case SyncConnected: // In this particular example we don't need to do anything // here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course) break; case Expired: // It's all over dead = true;/*www .ja v a2 s .c om*/ listener.closing(KeeperException.Code.SessionExpired); break; case AuthFailed: break; case ConnectedReadOnly: break; case Disconnected: break; case NoSyncConnected: break; case SaslAuthenticated: break; case Unknown: break; default: break; } } else { if (path != null && path.equals(znode)) { // Something has changed on the node, let's find out zk.exists(znode, true, this, null); } } if (chainedWatcher != null) { chainedWatcher.process(event); } }
From source file:yangqi.zookeeper.example.masterworker.ChildrenCallbackMonitor.java
License:Open Source License
/** * @param args/*from w w w . j a va 2 s. co m*/ * @throws IOException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { final ZooKeeper zookeeper = new ZooKeeper("localhost:2181", 2000, null); final ChildrenCallback callback = new ChildrenCallback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children) { System.out.println(children); } }; Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { System.out.println("Event is " + event); if (event.getType() == EventType.NodeChildrenChanged) { System.out.println("Changed " + event); zookeeper.getChildren("/workers", this, callback, null); } } }; zookeeper.getChildren("/workers", watcher, callback, null); System.out.println("begin finish"); Thread.sleep(200000); System.out.println("finish"); }
From source file:zk.ha.ActiveStandbyElector.java
License:Apache License
synchronized void processWatchEvent(ZooKeeper zk, WatchedEvent event) { Event.EventType eventType = event.getType(); if (eventType == Event.EventType.None) { // the connection state has changed switch (event.getState()) { case SyncConnected: LOG.info("Session connected."); // if the listener was asked to move to safe state then it needs to // be undone ConnectionState prevConnectionState = zkConnectionState; zkConnectionState = ConnectionState.CONNECTED; if (prevConnectionState == ConnectionState.DISCONNECTED && wantToBeInElection) { monitorActiveStatus();/* ww w . j a v a 2s .c om*/ } break; case Disconnected: LOG.info("Session disconnected. Entering neutral mode..."); // ask the app to move to safe state because zookeeper connection // is not active and we dont know our state zkConnectionState = ConnectionState.DISCONNECTED; // enterNeutralMode(); break; case Expired: // the connection got terminated because of session timeout // call listener to reconnect // LOG.info("Session expired. Entering neutral mode and rejoining..."); // enterNeutralMode(); // reJoinElection(0); break; case SaslAuthenticated: LOG.info("Successfully authenticated to ZooKeeper using SASL."); break; default: fatalError("Unexpected Zookeeper watch event state: " + event.getState()); break; } return; } // a watch on lock path in zookeeper has fired. so something has changed on // the lock. ideally we should check that the path is the same as the lock // path but trusting zookeeper for now String path = event.getPath(); if (path != null) { switch (eventType) { case NodeDeleted: if (state == State.ACTIVE) { enterNeutralMode(); } joinElectionInternal(); break; case NodeDataChanged: // monitorActiveStatus(); break; default: if (LOG.isDebugEnabled()) { LOG.debug("Unexpected node event: " + eventType + " for path: " + path); } // monitorActiveStatus(); } return; } // some unexpected error has occurred fatalError("Unexpected watch error from Zookeeper"); }