org.apache.zookeeper.Watcher.Event.EventType Java Examples

The following examples show how to use org.apache.zookeeper.Watcher.Event.EventType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Command} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *         removal.
 */
public Watcher registerExpirationHandler(final ZooKeeperSessionExpireNotifier onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                try {
                    onExpired.notifySessionExpired();
                } catch (Exception exc) {
                    // do nothing
                }
            }
        }
    };
    register(watcher);
    return watcher;
}
 
Example #2
Source File: Client.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
public void process(WatchedEvent e) { 
    System.out.println(e);
    if(e.getType() == Event.EventType.None){
        switch (e.getState()) {
        case SyncConnected:
            connected = true;
            break;
        case Disconnected:
            connected = false;
            break;
        case Expired:
            expired = true;
            connected = false;
            System.out.println("Exiting due to session expiration");
        default:
            break;
        }
    }
}
 
Example #3
Source File: ZookeeperRegistry.java    From Distributed-KV with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	// 传来NONE类型事件,一般是连接事件等
	if(event.getType() == EventType.None) {
		// 事件状态为:连接中
		if(event.getState() == KeeperState.SyncConnected) {
			// 唤醒等待连接成功的线程
			mutex.lock();
			try {
				// 唤醒等待连接成功的线程
				connCondition.signalAll();
			} finally {
				mutex.unlock();
			}
		}
	}
	
}
 
Example #4
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void processDataOrChildChange(WatchedEvent event) {
    final String path = event.getPath();

    if (event.getType() == EventType.NodeChildrenChanged || event.getType() == EventType.NodeCreated || event.getType() == EventType.NodeDeleted) {
        Set<IZkChildListener> childListeners = _childListener.get(path);
        if (childListeners != null && !childListeners.isEmpty()) {
            fireChildChangedEvents(path, childListeners);
        }
    }

    if (event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted || event.getType() == EventType.NodeCreated) {
        Set<IZkDataListener> listeners = _dataListener.get(path);
        if (listeners != null && !listeners.isEmpty()) {
            fireDataChangedEvents(event.getPath(), listeners);
        }
    }
}
 
Example #5
Source File: ZkCallbackCache.java    From helix with Apache License 2.0 6 votes vote down vote up
@Override
public void handleDataDeleted(String dataPath) throws Exception {
  // System.out.println("handleDataDeleted: " + dataPath);

  try {
    _lock.writeLock().lock();
    _accessor.unsubscribeDataChanges(dataPath, this);
    _accessor.unsubscribeChildChanges(dataPath, this);

    String parentPath = HelixUtil.getZkParentPath(dataPath);
    String name = HelixUtil.getZkName(dataPath);
    removeFromParentChildSet(parentPath, name);
    _cache.remove(dataPath);

    fireEvents(dataPath, EventType.NodeDeleted);
  } finally {
    _lock.writeLock().unlock();
  }
}
 
Example #6
Source File: TestZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }},
        zk.getSessionId(),
        zk.getSessionPasswd());

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }

    newZk.close();
}
 
Example #7
Source File: ZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
/**
 * Clients that need to re-establish state after session expiration can register an
 * {@code onExpired} command to execute.
 *
 * @param onExpired the {@code Command} to register
 * @return the new {@link Watcher} which can later be passed to {@link #unregister} for
 *         removal.
 */
public Watcher registerExpirationHandler(final ZooKeeperSessionExpireNotifier onExpired) {
    Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) {
                try {
                    onExpired.notifySessionExpired();
                } catch (Exception exc) {
                    // do nothing
                }
            }
        }
    };
    register(watcher);
    return watcher;
}
 
Example #8
Source File: ZkDistributedSemaphore.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void onEvent(WatchedEvent event) {

    if(event.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
      Collection<UpdateListener> col = new ArrayList<>(listeners.keySet());
      for(UpdateListener l : col) {
        l.updated();
      }
    } else if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected){
      // re set the watcher after a disconnect.
      try {
        setWatcher();
      } catch (Exception e) {
        logger.error("Failure while re-setting watcher after reconnect.", e);
      }
    }
  }
 
Example #9
Source File: ZKNodeListener.java    From zkclient with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String path, EventType eventType, Object data) throws Exception {
    
    if (eventType == EventType.NodeCreated) {
        handleDataCreated(path,data);
    }
    
    if (eventType == EventType.NodeDataChanged) {
        handleDataChanged(path,data);
    }
    
    if(eventType == EventType.NodeDeleted ){
        handleDataDeleted(path);
    }
    
    if(eventType == eventType.None){
        handleSessionExpired(path);
    }
}
 
Example #10
Source File: ZKChildDataListener.java    From zkclient with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String path, EventType eventType, Object data) throws Exception {
    //子节点个数变化
    if (eventType == EventType.NodeChildrenChanged 
            || eventType == EventType.NodeCreated 
            || eventType == EventType.NodeDeleted) {
        handleChildCountChanged(path,(List<String>)data);
    }
    //子节点数据变化
    if(eventType == EventType.NodeDataChanged){
        handleChildDataChanged(path,data);
    }
    //Session失效
    if(eventType == eventType.None){
        handleSessionExpired(path,data);
    }
}
 
Example #11
Source File: Worker.java    From zookeeper-book-example with Apache License 2.0 6 votes vote down vote up
/**
 * Deals with session events like connecting
 * and disconnecting.
 * 
 * @param e new event generated
 */
public void process(WatchedEvent e) { 
    LOG.info(e.toString() + ", " + hostPort);
    if(e.getType() == Event.EventType.None){
        switch (e.getState()) {
        case SyncConnected:
            /*
             * Registered with ZooKeeper
             */
            connected = true;
            break;
        case Disconnected:
            connected = false;
            break;
        case Expired:
            expired = true;
            connected = false;
            LOG.error("Session expired");
        default:
            break;
        }
    }
}
 
Example #12
Source File: ZkStateReader.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  // session events are not change events, and do not remove the watcher
  if (EventType.None.equals(event.getType())) {
    return;
  }

  boolean expired = System.nanoTime() > watchUntilNs;
  if (!collectionPropsObservers.containsKey(coll) && expired) {
    // No one can be notified of the change, we can ignore it and "unset" the watch
    log.debug("Ignoring property change for collection {}", coll);
    return;
  }

  log.info("A collection property change: [{}] for collection [{}] has occurred - updating...",
      event, coll);

  refreshAndWatch(true);
}
 
Example #13
Source File: ZkStateReader.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  if (ZkStateReader.this.closed) {
    return;
  }

  // session events are not change events, and do not remove the watcher
  if (EventType.None.equals(event.getType())) {
    return;
  }
  log.debug("A collections change: [{}], has occurred - updating...", event);
  refreshAndWatch();
  synchronized (getUpdateLock()) {
    constructState(Collections.emptySet());
  }
}
 
Example #14
Source File: WatcherProcess.java    From zkclient with Apache License 2.0 6 votes vote down vote up
/**
 * 节点数据变化处理函数
 *
 * @param path 变化的节点
 */
public void dataChange(String path) throws ZkClientException {
    try {
        if (dataListenerPool.containsKey(path)) {
            byte[] data = this.zkClient.getData(path, true);
            ListenerManager manager = dataListenerPool.get(path);
            ListenerManager lm = new ListenerManager(manager.getListener());
            lm.setData(data);
            lm.setEventType(EventType.NodeDataChanged);
            listenerPool.invoker(path, lm);
            LOGGER.debug("node:{} data change.", path);
        }
    } catch (Exception e) {
        throw new ZkClientException("Listener data change error.", e);
    }
}
 
Example #15
Source File: ZKWatcherProcess.java    From zkclient with Apache License 2.0 6 votes vote down vote up
/**
 * 处理数据改变事件
 * @param event 
 * @return void
 */
public void processNodeChanged(final WatchedEvent event){
    final String path = event.getPath();
    final EventType eventType = event.getType();
    final Set<ZKListener> listeners = client.getNodeListenerMap().get(path);
    if (listeners == null || listeners.isEmpty()) {
        return;
    }
    
    //如果listeners中如果有ZKChildDataListener类型的监听器,
    //证明是此节点是某个节点的子节点,并监听此节点的数据变化
    //这里要单独拿出来,用于触发ZKChildDataListener
    final Set<ZKListener> childDataChangeListners = new CopyOnWriteArraySet<>();
    final Set<ZKListener> nodeListners = new CopyOnWriteArraySet<>();
    
    classifyListeners(listeners,nodeListners,childDataChangeListners);
    
    //提交事件监听进行处理
    submitNodeEvent(nodeListners,childDataChangeListners,path,eventType);
    
    //当前节点作为子节点数据变化
    if(eventType == EventType.NodeDataChanged){
        //提交事件监听进行处理
        submitChildDataEvent(childDataChangeListners,path,eventType);
    }
}
 
Example #16
Source File: ZookeeperClusterService.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    logger.debug("Process Zookeeper Event({})", event);

    EventType eventType = event.getType();

    if (serviceState.isStarted() && client.isConnected()) {
        // duplicate event possible - but the logic does not change
        if (eventType == EventType.NodeChildrenChanged) {
            String path = event.getPath();

            if (ZookeeperConstants.PINPOINT_WEB_CLUSTER_PATH.equals(path)) {
                webClusterManager.handleAndRegisterWatcher(path);
            } else {
                logger.warn("Unknown Path ChildrenChanged {}.", path);
            }
        }
    }
}
 
Example #17
Source File: FlinkClusterService.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    logger.debug("Process Zookeeper Event({})", event);

    EventType eventType = event.getType();

    if (serviceState.isStarted() && client.isConnected()) {
        // duplicate event possible - but the logic does not change
        if (eventType == EventType.NodeChildrenChanged) {
            String eventPath = event.getPath();

            if (pinpointFlinkClusterPath.equals(eventPath)) {
                zookeeperClusterManager.handleAndRegisterWatcher(eventPath);
            } else {
                logger.warn("Unknown Path ChildrenChanged {}.", eventPath);
            }
        }
    }
}
 
Example #18
Source File: ClusterManagerService.java    From blog with MIT License 5 votes vote down vote up
private void handleStateChange(WatchedEvent event) {
    if (finishedInitialization.get()) {

        if (previousState != KeeperState.SyncConnected && event.getState() == KeeperState.SyncConnected) {
            previousState = event.getState();
            checkMasterIsAvailable();
        }

        EventType eventType = event.getType();
        if (EventType.NodeDeleted == eventType && event.getPath().equalsIgnoreCase(watchedNodePath)) {
            checkMasterIsAvailable();
        }
    }
}
 
Example #19
Source File: ZooKeeperAnnotationBeanPostProcessor.java    From zookeeper-spring with Apache License 2.0 5 votes vote down vote up
protected void lookup(final String path, final Setter setter) {
  lookup(path, setter, new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      // check that path and event.getPath match?
      LOG.info("Watcher for '{}' received watched event: {}", path, event);
      if (event.getType() == EventType.NodeDataChanged) {
        lookup(path, setter, this);
      }
    }
  });
}
 
Example #20
Source File: ZookeeperWatcher.java    From shark with Apache License 2.0 5 votes vote down vote up
@Override
public void process(WatchedEvent event) {
	if (null == zk_client)
		return;
	try {
		Thread.sleep(100);
		/* 重新注册节点 */
		zk_client.exists(nodePath, this);
		EventType eventType = event.getType();
		switch (eventType) {
		case NodeCreated:
			logger.info("create node-->" + event.getPath());
			break;
		case NodeDataChanged:
			final String nodePathValue = new String(zk_client.getData(nodePath, false, null));
			RegisterDataSource.register(nodePathValue, "zookeeper");
			logger.info("change node data-->" + event.getPath());
			break;
		case NodeChildrenChanged:
			break;
		case NodeDeleted:
		default:
			break;
		}
	} catch (Exception e) {
		throw new ConnectionException(e.toString());
	}
}
 
Example #21
Source File: ZooKeeperSessionWatcherTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcess3() {
    WatchedEvent event = new WatchedEvent(EventType.NodeCreated, KeeperState.Expired, null);
    sessionWatcher.process(event);
    assertFalse(sessionWatcher.isShutdownStarted());
    assertEquals(shutdownService.getExitCode(), 0);
}
 
Example #22
Source File: ZKWatcherProcess.java    From zkclient with Apache License 2.0 5 votes vote down vote up
/**
 * 提交子节点数据改变的事件进行处理
 * @param listeners
 * @param path
 * @param eventType 
 * @return void
 */
private void submitChildDataEvent(final Set<ZKListener> listeners,final String path,final EventType eventType){
    if (listeners != null && !listeners.isEmpty()) {
        for (final ZKListener listener : listeners) {
            ZKEvent zkEvent = new ZKEvent("Children of " + path + " changed sent to "+ listener) {
                @Override
                public void run() throws Exception {
                    //原生的zookeeper 的监听只生效一次,重新注册监听
                    LOG.debug("rewatch the path ["+path+"]");
                    client.exists(path, true);
                    LOG.debug("rewatched the path ["+path+"]");
                    try {
                        LOG.debug("Try to get child changed data  [path:"+path+" | EventType:"+eventType+"]");
                        //在事件触发后到获取数据之间的时间,节点的值是可能改变的,
                        //所以此处的获取也只是,获取到最新的值,而不一定是事件触发时的值
                        //重新监听节点变化
                        Object data = client.getData(path, null);
                        LOG.debug("Child changed data is  [path:"+path+" | data:"+data+" | EventType:"+eventType+"]");
                        listener.handle(path, eventType, data);
                    } catch (ZKNoNodeException e) {
                        //ignore
                    }
                }
            };
            eventThreadPool.submit(zkEvent);
        }
    }
}
 
Example #23
Source File: TestWatchesBuilder.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveAllWatches() throws Exception
{       
    Timing timing = new Timing();
    CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder().
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
    try
    {
        client.start();
        
        final String path = "/";
        final CountDownLatch removedLatch = new CountDownLatch(2);
        
        Watcher watcher1 = new CountDownWatcher(path, removedLatch, EventType.ChildWatchRemoved);            
        Watcher watcher2 = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved);                        
        
        client.getChildren().usingWatcher(watcher1).forPath(path);
        client.checkExists().usingWatcher(watcher2).forPath(path);

        client.watches().removeAll().forPath(path);

        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #24
Source File: ZKHelixManager.java    From helix with Apache License 2.0 5 votes vote down vote up
@Override
public void addCustomizedStateChangeListener(CustomizedStateChangeListener listener,
    String instanceName, String customizedStateType) throws Exception {
  addListener(listener,
      new Builder(_clusterName).customizedStates(instanceName, customizedStateType),
      ChangeType.CUSTOMIZED_STATE, new EventType[]{EventType.NodeChildrenChanged});
}
 
Example #25
Source File: ZKHelixManager.java    From helix with Apache License 2.0 5 votes vote down vote up
@Deprecated
@Override
public void addCurrentStateChangeListener(org.apache.helix.CurrentStateChangeListener listener,
    String instanceName, String sessionId) throws Exception {
  addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId),
      ChangeType.CURRENT_STATE, new EventType[] { EventType.NodeChildrenChanged
      });
}
 
Example #26
Source File: ZkTestHelper.java    From helix with Apache License 2.0 5 votes vote down vote up
public static void injectExpire(RealmAwareZkClient client)
    throws ExecutionException, InterruptedException {
  final ZkClient zkClient = (ZkClient) client;
  Future future = _executor.submit(new Runnable() {
    @Override
    public void run() {
      WatchedEvent event =
          new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null);
      zkClient.process(event);
    }
  });
  future.get();
}
 
Example #27
Source File: TestWatchesBuilder.java    From curator with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoveWatchInBackgroundWithNoCallback() throws Exception
{       
    Timing timing = new Timing();
    CuratorFrameworkImpl client = (CuratorFrameworkImpl)CuratorFrameworkFactory.builder().
            connectString(server.getConnectString()).
            retryPolicy(new RetryOneTime(1)).
            build();
    try
    {
        client.start();
        
        final String path = "/";
        final CountDownLatch removedLatch = new CountDownLatch(1);
        Watcher watcher = new CountDownWatcher(path, removedLatch, EventType.DataWatchRemoved);
        
        client.checkExists().usingWatcher(watcher).forPath(path);

        client.watches().remove(watcher).inBackground().forPath(path);

        Assert.assertTrue(timing.awaitLatch(removedLatch), "Timed out waiting for watch removal");
        
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}
 
Example #28
Source File: ZkTestHelper.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * Simulate a zk state change by calling {@link ZkClient#process(WatchedEvent)} directly
 */
public static void simulateZkStateReconnected(RealmAwareZkClient client) {
  ZkClient zkClient = (ZkClient) client;
  WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Disconnected, null);
  zkClient.process(event);
  event = new WatchedEvent(EventType.None, KeeperState.SyncConnected, null);
  zkClient.process(event);
}
 
Example #29
Source File: TestPersistentEphemeralNode.java    From curator with Apache License 2.0 5 votes vote down vote up
public Trigger(Event.EventType... types)
{
    assertNotNull(types);

    this.types = ImmutableSet.copyOf(types);
    this.latch = new CountDownLatch(1);
}
 
Example #30
Source File: ZKChildCountListener.java    From zkclient with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(String path, EventType eventType, Object data) throws Exception {
    List<String> children = null;
    if(data!=null){
        children = (List<String>)data;
    }
    if(eventType == eventType.None){
        handleSessionExpired(path,children);
    }else{
        
        handleChildCountChanged(path,children);
    }
    
}