List of usage examples for org.apache.zookeeper WatchedEvent getPath
public String getPath()
From source file:com.splicemachine.ddl.ZooKeeperDDLWatchChecker.java
License:Apache License
@Override public boolean initialize(final CommunicationListener changeIdListener) throws IOException { this.id = zkClient.registerThisServer(); if (id == null) return false; //not a server, so inform the world if (id.startsWith("/")) id = id.substring(1); //strip the leading / to make sure that we register properly changeIdWatcher = new Watcher() { @Override/* w ww . j a v a 2 s. c o m*/ public void process(WatchedEvent watchedEvent) { if (watchedEvent.getType().equals(Event.EventType.NodeChildrenChanged)) { if (LOG.isTraceEnabled()) LOG.trace("Received watch event, signalling refresh"); changeIdListener.onCommunicationEvent(watchedEvent.getPath()); } } }; return true; }
From source file:com.takin.rpc.zkclient.ZkClient.java
License:Apache License
public void process(WatchedEvent event) { logger.debug("Received event: " + event); _zookeeperEventThread = Thread.currentThread(); boolean stateChanged = event.getPath() == null; boolean znodeChanged = event.getPath() != null; boolean dataChanged = event.getType() == EventType.NodeDataChanged || // event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated || // event.getType() == EventType.NodeChildrenChanged; getEventLock().lock();//from ww w .j a va2 s . c o m try { // We might have to install child change event listener if a new node was created if (getShutdownTrigger()) { logger.debug("ignoring event '{" + event.getType() + " | " + event.getPath() + "}' since shutdown triggered"); return; } if (stateChanged) { processStateChanged(event); } if (dataChanged) { processDataOrChildChange(event); } } finally { if (stateChanged) { getEventLock().getStateChangedCondition().signalAll(); // If the session expired we have to signal all conditions, because watches might have been removed and // there is no guarantee that those // conditions will be signaled at all after an Expired event if (event.getState() == KeeperState.Expired) { getEventLock().getZNodeEventCondition().signalAll(); getEventLock().getDataChangedCondition().signalAll(); // We also have to notify all listeners that something might have changed fireAllEvents(); } } if (znodeChanged) { getEventLock().getZNodeEventCondition().signalAll(); } if (dataChanged) { getEventLock().getDataChangedCondition().signalAll(); } getEventLock().unlock(); logger.debug("Leaving process event"); } }
From source file:com.taobao.common.tedis.replicator.ZKTest.java
License:Open Source License
@Test public void testConfig() throws Exception { final ZKClient client = new ZKClient("localhost:2181", 500000); client.init();//from www. j a v a 2 s . c o m String path = ZKUtil.contact("tedis", "replicator-config"); path = ZKUtil.contact(ZKUtil.MUTEXLOCK_ROOT, path); path = ZKUtil.normalize(path); if (client.useAble()) { client.delete(path); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String path = ZKUtil.contact("tedis", "replicator-config"); path = ZKUtil.contact(ZKUtil.MUTEXLOCK_ROOT, path); path = ZKUtil.normalize(path); try { client.rcreate(path, "word".getBytes()); } catch (ZKException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); if (!client.exists(path)) { client.rcreate(path, "test".getBytes()); System.out.println("create path"); } System.out.println(path); System.out.println(new String(client.getData(path, new Watcher() { @Override public void process(WatchedEvent event) { System.out.println(event.getPath()); try { System.out.println(new String(client.getData(event.getPath()))); } catch (ZKException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }))); Thread.sleep(10000); } }
From source file:com.twitter.distributedlog.impl.ZKLogSegmentMetadataStore.java
License:Apache License
/** * Process the watched events for registered listeners *//*from w w w . j ava 2 s . c o m*/ @Override public void process(WatchedEvent event) { if (Event.EventType.None == event.getType() && Event.KeeperState.Expired == event.getState()) { Set<String> keySet = new HashSet<String>(listeners.keySet()); for (String logSegmentsPath : keySet) { scheduleTask(logSegmentsPath, new ReadLogSegmentsTask(logSegmentsPath, this), 0L); } return; } String path = event.getPath(); if (null == path) { return; } switch (event.getType()) { case NodeDeleted: listeners.remove(path); break; case NodeChildrenChanged: new ReadLogSegmentsTask(path, this).run(); break; default: break; } }
From source file:com.twitter.distributedlog.lock.ZKSessionLock.java
License:Apache License
private void handleNodeDelete(int lockEpoch, final WatchedEvent event) { executeLockAction(lockEpoch, new LockAction() { @Override//from w w w . jav a 2s . c o m public void execute() { // The lock is either expired or closed if (!lockState.inState(State.WAITING)) { LOG.info("{} ignore watched node {} deleted event, since lock state has moved to {}.", new Object[] { lockId, event.getPath(), lockState.getState() }); return; } lockState.transition(State.PREPARED); // we don't need to wait and check the result, since: // 1) if it claimed the ownership, it would notify the waiters when claimed ownerships // 2) if it failed, it would also notify the waiters, the waiters would cleanup the state. checkLockOwnerAndWaitIfPossible(watcher, true); } @Override public String getActionName() { return "handleNodeDelete(path=" + event.getPath() + ")"; } }); }
From source file:com.twitter.distributedlog.zk.ZKWatcherManager.java
License:Apache License
private void handleChildWatchEvent(WatchedEvent event) { String path = event.getPath(); if (null == path) { logger.warn("Received zookeeper watch event with null path : {}", event); return;//from w w w . j av a2s .c om } Set<Watcher> watchers = childWatches.get(path); if (null == watchers) { return; } Set<Watcher> watchersToFire; synchronized (watchers) { watchersToFire = new HashSet<Watcher>(watchers.size()); watchersToFire.addAll(watchers); } for (Watcher watcher : watchersToFire) { watcher.process(event); } }
From source file:com.twitter.heron.statemgr.zookeeper.ZkWatcherCallback.java
License:Open Source License
public static Watcher makeZkWatcher(final WatchCallback watcher) { return watcher == null ? null : new Watcher() { @Override/*from w ww . j av a 2 s. c o m*/ public void process(WatchedEvent watchedEvent) { WatchCallback.WatchEventType watchEventType; switch (watchedEvent.getType()) { case None: watchEventType = WatchCallback.WatchEventType.None; break; case NodeCreated: watchEventType = WatchCallback.WatchEventType.NodeCreated; break; case NodeDeleted: watchEventType = WatchCallback.WatchEventType.NodeDeleted; break; case NodeDataChanged: watchEventType = WatchCallback.WatchEventType.NodeDataChanged; break; case NodeChildrenChanged: watchEventType = WatchCallback.WatchEventType.NodeChildrenChanged; break; default: throw new RuntimeException("Invalid integer value for conversion to EventType"); } watcher.processWatch(watchedEvent.getPath(), watchEventType); } }; }
From source file:com.yahoo.pulsar.broker.loadbalance.LeaderElectionService.java
License:Apache License
/** * We try to get the data in the ELECTION_ROOT node. If the node is present (i.e. leader is present), we store it in * the currentLeader and keep a watch on the election node. If we lose the leader, then watch gets triggered and we * do the election again. If the node does not exist while getting the data, we get NoNodeException. This means, * there is no leader and we create the node at ELECTION_ROOT and write the leader broker's service URL in the node. * Once the leader is known, we call the listener method so that leader can take further actions. *//*from w ww . j a va2s . c om*/ private void elect() { try { byte[] data = zkClient.getData(ELECTION_ROOT, new Watcher() { @Override public void process(WatchedEvent event) { log.warn("Type of the event is [{}] and path is [{}]", event.getType(), event.getPath()); switch (event.getType()) { case NodeDeleted: log.warn("Election node {} is deleted, attempting re-election...", event.getPath()); if (event.getPath().equals(ELECTION_ROOT)) { log.info("This should call elect again..."); executor.execute(new Runnable() { @Override public void run() { // If the node is deleted, attempt the re-election log.info("Broker [{}] is calling re-election from the thread", pulsar.getWebServiceAddress()); elect(); } }); } break; default: log.warn("Got something wrong on watch: {}", event); break; } } }, null); LeaderBroker leaderBroker = jsonMapper.readValue(data, LeaderBroker.class); currentLeader.set(leaderBroker); isLeader.set(false); leaderListener.brokerIsAFollowerNow(); // If broker comes here it is a follower. Do nothing, wait for the watch to trigger log.info("Broker [{}] is the follower now. Waiting for the watch to trigger...", pulsar.getWebServiceAddress()); } catch (NoNodeException nne) { // There's no leader yet... try to become the leader try { // Create the root node and add current broker's URL as its contents LeaderBroker leaderBroker = new LeaderBroker(pulsar.getWebServiceAddress()); ZkUtils.createFullPathOptimistic(pulsar.getLocalZkCache().getZooKeeper(), ELECTION_ROOT, jsonMapper.writeValueAsBytes(leaderBroker), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); // Update the current leader and set the flag to true currentLeader.set(new LeaderBroker(leaderBroker.getServiceUrl())); isLeader.set(true); // Notify the listener that this broker is now the leader so that it can collect usage and start load // manager. log.info("Broker [{}] is the leader now, notifying the listener...", pulsar.getWebServiceAddress()); leaderListener.brokerIsTheLeaderNow(); } catch (NodeExistsException nee) { // Re-elect the new leader log.warn( "Got exception [{}] while creating election node because it already exists. Attempting re-election...", nee.getMessage()); executor.execute(new Runnable() { @Override public void run() { elect(); } }); } catch (Exception e) { // Kill the broker because this broker's session with zookeeper might be stale. Killing the broker will // make sure that we get the fresh zookeeper session. log.error("Got exception [{}] while creating the election node", e.getMessage()); pulsar.getShutdownService().shutdown(-1); } } catch (Exception e) { // Kill the broker log.error("Could not get the content of [{}], got exception [{}]. Shutting down the broker...", ELECTION_ROOT, e); pulsar.getShutdownService().shutdown(-1); } }
From source file:com.yahoo.pulsar.zookeeper.GlobalZooKeeperCache.java
License:Apache License
@Override public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) { synchronized (this) { if (LOG.isDebugEnabled()) { LOG.debug("[{}] Got Global ZooKeeper WatchdEvent: EventType: {}, KeeperState: {}, path: {}", this.hashCode(), event.getType(), event.getState(), event.getPath()); }//from ww w.j a v a2 s. c om if (event.getType() == Event.EventType.None) { switch (event.getState()) { case Expired: // in case of expired, the zkSession is no longer good for sure. // We need to restart the session immediately. // cancel any timer event since it is already bad ZooKeeper oldSession = this.zkSession.getAndSet(null); LOG.warn("Global ZK session lost. Triggering reconnection {}", oldSession); safeCloseZkSession(oldSession); asyncRestartZooKeeperSession(); return; case SyncConnected: case ConnectedReadOnly: checkNotNull(zkSession.get()); LOG.info("Global ZK session {} restored connection.", zkSession.get()); // dataCache.synchronous().invalidateAll(); childrenCache.invalidateAll(); return; default: break; } } } // Other types of events super.process(event, updater); }
From source file:com.yahoo.pulsar.zookeeper.LocalZooKeeperCache.java
License:Apache License
@Override public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) { if (LOG.isDebugEnabled()) { LOG.debug("Got Local ZooKeeper WatchedEvent: EventType: {}, KeeperState: {}, Path: {}", event.getType(), event.getState(), event.getPath()); }//ww w . j av a2s .c o m if (event.getType() == Event.EventType.None) { switch (event.getState()) { case Expired: // in case of expired, the zkSession is no longer good LOG.warn("Lost connection from local ZK. Invalidating the whole cache."); dataCache.synchronous().invalidateAll(); childrenCache.invalidateAll(); return; default: break; } } super.process(event, updater); }