Java Code Examples for org.apache.zookeeper.Watcher.Event.KeeperState#Expired

The following examples show how to use org.apache.zookeeper.Watcher.Event.KeeperState#Expired . 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: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void processStateChanged(WatchedEvent event) {
    LOG.info("zookeeper state changed (" + event.getState() + ")");
    setCurrentState(event.getState());
    if (getShutdownTrigger()) {
        return;
    }
    fireStateChangedEvent(event.getState());
    if (event.getState() == KeeperState.Expired) {
        try {
            reconnect();
            fireNewSessionEvents();
        } catch (final Exception e) {
            LOG.info("Unable to re-establish connection. Notifying consumer of the following exception: ", e);
            fireSessionEstablishmentError(e);
        }
    }
}
 
Example 2
Source File: ClusterManagerService.java    From blog with MIT License 6 votes vote down vote up
@Override
public void process(WatchedEvent event) {

    LOGGER.debug("Got Event from ZooKeeper: " + event + " Connection state: " + event.getState());

    if (event.getState() == KeeperState.Expired) {
        previousState = KeeperState.Disconnected;
        goToSlaveMode();
        try {
            init();
        } catch (IOException | ClusterManagerException e) {
            LOGGER.error("Failed to init after session timeout", e);
        }
        return;
    }

    if (event.getState() != KeeperState.SyncConnected) {
        previousState = event.getState();
        goToSlaveMode();
        return;
    }

    handleStateChange(event);
}
 
Example 3
Source File: ZkClient.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
private void processStateChanged(WatchedEvent event) {
    LOG.info("zookeeper state changed (" + event.getState() + ")");
    setCurrentState(event.getState());
    if (getShutdownTrigger()) {
        return;
    }
    fireStateChangedEvent(event.getState());
    if (event.getState() == KeeperState.Expired) {
        try {
            reconnect();
            fireNewSessionEvents();
        } catch (final Exception e) {
            LOG.info("Unable to re-establish connection. Notifying consumer of the following exception: ", e);
            fireSessionEstablishmentError(e);
        }
    }
}
 
Example 4
Source File: SimpleZKSecureTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
public synchronized void process(WatchedEvent event) {
    LOG.info("Watcher " + name + " got event " + event);

    state = event.getState();
    if (state == KeeperState.SyncConnected) {
        connected = true;
        clientConnected.countDown();
    } else if (state == KeeperState.SaslAuthenticated) {
    } else {
        connected = false;
    }
    if (state == KeeperState.Expired) {
        expired = true;
    } else if (state == KeeperState.SaslAuthenticated) {
    } else {
        expired = false;
    }
    notifyAll();
}
 
Example 5
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 6 votes vote down vote up
private void processStateChanged(WatchedEvent event) {
    logger.info("zookeeper state changed (" + event.getState() + ")");
    setCurrentState(event.getState());
    if (getShutdownTrigger()) {
        return;
    }
    try {
        fireStateChangedEvent(event.getState());

        if (event.getState() == KeeperState.Expired) {
            reconnect();
            fireNewSessionEvents();
        }
    } catch (final Exception e) {
        throw new RuntimeException("Exception while restarting zk client", e);
    }
}
 
Example 6
Source File: SimpleZKTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
public synchronized void process(WatchedEvent event) {
    LOG.info("Watcher " + name + " got event " + event);

    state = event.getState();
    if (state == KeeperState.SyncConnected) {
        connected = true;
        clientConnected.countDown();
    } else {
        connected = false;
    }
    if (state == KeeperState.Expired) {
        expired = true;
    } else {
        expired = false;
    }
    notifyAll();
}
 
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: 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 9
Source File: ZooKeeperSessionWatcherTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcess1() {
    WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Expired, null);
    sessionWatcher.process(event);
    assertTrue(sessionWatcher.isShutdownStarted());
    assertEquals(shutdownService.getExitCode(), -1);
}
 
Example 10
Source File: ZKManager.java    From uncode-schedule with Apache License 2.0 5 votes vote down vote up
private void sessionEvent(CountDownLatch connectionLatch, WatchedEvent event) {
  if (event.getState() == KeeperState.SyncConnected) {
    LOG.info("收到ZK连接成功事件!");
    connectionLatch.countDown();
  } else if (event.getState() == KeeperState.Expired) {
    LOG.error("会话超时,等待重新建立ZK连接...");
    try {
      reConnection();
    } catch (Exception e) {
      LOG.error(e.getMessage(), e);
    }
  } // Disconnected:Zookeeper会自动处理Disconnected状态重连
}
 
Example 11
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 12
Source File: ZKManager.java    From uncode-schedule with GNU General Public License v2.0 5 votes vote down vote up
private void sessionEvent(CountDownLatch connectionLatch, WatchedEvent event) {
    if (event.getState() == KeeperState.SyncConnected) {
        log.info("收到ZK连接成功事件!");
        connectionLatch.countDown();
    } else if (event.getState() == KeeperState.Expired) {
        log.error("会话超时,等待重新建立ZK连接...");
        try {
            reConnection();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
    } // Disconnected:Zookeeper会自动处理Disconnected状态重连
}
 
Example 13
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    LOG.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();
    try {

        // We might have to install child change event listener if a new node was created
        if (getShutdownTrigger()) {
            LOG.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();
        LOG.debug("Leaving process event");
    }
}
 
Example 14
Source File: ZKWatcher.java    From zkclient with Apache License 2.0 4 votes vote down vote up
/**
 * 事件处理
 * @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.WatchedEvent)
 */
@Override
public void process(WatchedEvent event) {
    LOG.debug("ZooKeeper event is arrived [" + event+" ]...");
    EventType eventType = event.getType();
    //状态更新
    boolean stateChanged = event.getPath() == null;
    //节点相关的所有事件
    boolean znodeChanged = event.getPath() != null;
    
    //节点创建、删除和数据改变的事件
    boolean nodeChanged = eventType == EventType.NodeDataChanged 
            || eventType == EventType.NodeDeleted 
            || eventType == EventType.NodeCreated;
    
    //子节点数量改变相关的事件,包括节点创建和删除(都会影响子节点数量的变化),以及子节点数量的改变
    boolean childChanged = eventType == EventType.NodeDeleted 
            || eventType == EventType.NodeCreated
            || eventType == EventType.NodeChildrenChanged;
    
    client.acquireEventLock();
    try {
        if (client.getShutdownTrigger()) {
            LOG.debug("client will shutdown,ignore the event [" + eventType + " | " + event.getPath() + "]");
            return;
        }
        if (stateChanged) {//ZooKeeper状态改变的处理
            process.processStateChanged(event);
        }
        if (nodeChanged) {//节点改变事件处理,包括节点的创建、删除、数据改变
            process.processNodeChanged(event);
        }
        if (childChanged) {//造成子节点数量改变的事件的处理,包括节点的创建、删除、子节点数量改变
            process.processChildChanged(event);
        }
    } finally {
        if (stateChanged) {
            client.getEventLock().getStateChangedCondition().signalAll();
            // 在会话失效后,服务端会取消watch.
            // 如果在会话失效后与重连这段时间内有数据发生变化,监听器是无法监听到的,
            // 所以要唤醒等待的监听,并触发所有的监听事件
            if (event.getState() == KeeperState.Expired) {
                client.getEventLock().getNodeEventCondition().signalAll();
                client.getEventLock().getNodeOrChildChangedCondition().signalAll();
                
                // 通知所有的监听器,可能存在数据变化
                process.processAllNodeAndChildListeners(event);
            }
        }
        if (znodeChanged) {
            client.getEventLock().getNodeEventCondition().signalAll();
        }
        if (nodeChanged || childChanged) {
            client.getEventLock().getNodeOrChildChangedCondition().signalAll();
        }
        client.releaseEventLock();
    }
}
 
Example 15
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 4 votes vote down vote up
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();
    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");
    }
}
 
Example 16
Source File: ZkClient.java    From DDMQ with Apache License 2.0 4 votes vote down vote up
@Override
public void process(WatchedEvent event) {
    LOG.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();
    try {

        // We might have to install child change event listener if a new node was created
        if (getShutdownTrigger()) {
            LOG.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();
        LOG.debug("Leaving process event");
    }
}
 
Example 17
Source File: ZkClient.java    From helix with Apache License 2.0 4 votes vote down vote up
@Override
public void process(WatchedEvent event) {
  long notificationTime = System.currentTimeMillis();
  if (LOG.isDebugEnabled()) {
    LOG.debug("Received event: " + event);
  }
  _zookeeperEventThread = Thread.currentThread();

  boolean stateChanged = event.getPath() == null;
  boolean sessionExpired = stateChanged && event.getState() == KeeperState.Expired;
  boolean znodeChanged = event.getPath() != null;
  boolean dataChanged =
      event.getType() == EventType.NodeDataChanged || event.getType() == EventType.NodeDeleted
          || event.getType() == EventType.NodeCreated
          || event.getType() == EventType.NodeChildrenChanged;
  if (event.getType() == EventType.NodeDeleted) {
    LOG.debug("Path {} is deleted", event.getPath());
  }

  getEventLock().lock();
  try {
    // We might have to install child change event listener if a new node was created
    if (getShutdownTrigger()) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("ignoring event '{" + event.getType() + " | " + event.getPath()
            + "}' since shutdown triggered");
      }
      return;
    }
    if (stateChanged) {
      processStateChanged(event);
    }
    if (dataChanged) {
      processDataOrChildChange(event, notificationTime);
    }
  } 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
      // TODO PVo write a test for this
      if (event.getState() == KeeperState.Expired) {
        getEventLock().getZNodeEventCondition().signalAll();
        getEventLock().getDataChangedCondition().signalAll();
      }
    }
    if (znodeChanged) {
      getEventLock().getZNodeEventCondition().signalAll();
    }
    if (dataChanged) {
      getEventLock().getDataChangedCondition().signalAll();
    }
    getEventLock().unlock();

    // update state change counter.
    recordStateChange(stateChanged, dataChanged, sessionExpired);

    if (LOG.isDebugEnabled()) {
      LOG.debug("Leaving process event");
    }
  }
}
 
Example 18
Source File: ZkClient.java    From helix with Apache License 2.0 4 votes vote down vote up
protected void processStateChanged(WatchedEvent event) {
  LOG.info("zookeeper state changed (" + event.getState() + ")");
  setCurrentState(event.getState());
  if (getShutdownTrigger()) {
    return;
  }

  fireStateChangedEvent(event.getState());

  /*
   *  Note, the intention is that only the ZkClient managing the session would do auto reconnect
   *  and fireNewSessionEvents and fireAllEvent.
   *  Other ZkClient not managing the session would only fireAllEvent upon a new session.
   */
  if (event.getState() == KeeperState.SyncConnected) {
    if (!_isNewSessionEventFired && !"0".equals(getHexSessionId())) {
      /*
       * Before the new zookeeper instance is connected to the zookeeper service and its session
       * is established, its session id is 0.
       * New session event is not fired until the new zookeeper session receives the first
       * SyncConnected state(the zookeeper session is established).
       * Now the session id is available and non-zero, and we can fire new session events.
       */
      fireNewSessionEvents();

      /*
       * Set it true to avoid firing events again for the same session next time
       * when SyncConnected events are received.
       */
      _isNewSessionEventFired = true;

      /*
       * With this first SyncConnected state, we just get connected to zookeeper service after
       * reconnecting when the session expired. Because previous session expired, we also have to
       * notify all listeners that something might have changed.
       */
      fireAllEvents();
    }
  } else if (event.getState() == KeeperState.Expired) {
    _isNewSessionEventFired = false;
    reconnectOnExpiring();
  }
}
 
Example 19
Source File: NodeWatcher.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 回调函数
 */
@Override
public void process(WatchedEvent event) {

    //
    // 结点更新时
    //
    if (event.getType() == EventType.NodeDataChanged) {

        try {

            LOGGER.info("============GOT UPDATE EVENT " + event.toString() + ": (" + monitorPath + "," + keyName
                    + "," + disConfigTypeEnum.getModelName() + ")======================");

            // 调用回调函数, 回调函数里会重新进行监控
            callback();

        } catch (Exception e) {

            LOGGER.error("monitor node exception. " + monitorPath, e);
        }
    }

    //
    // 结点断开连接,这时不要进行处理
    //
    if (event.getState() == KeeperState.Disconnected) {

        if (!debug) {
            LOGGER.warn("============GOT Disconnected EVENT " + event.toString() + ": (" + monitorPath + ","
                    + keyName + "," + disConfigTypeEnum.getModelName() + ")======================");
        } else {
            LOGGER.debug("============DEBUG MODE: GOT Disconnected EVENT " + event.toString() + ": (" +
                    monitorPath +
                    "," +
                    keyName +
                    "," + disConfigTypeEnum.getModelName() + ")======================");
        }
    }

    //
    // session expired,需要重新关注哦
    //
    if (event.getState() == KeeperState.Expired) {

        if (!debug) {

            LOGGER.error("============GOT Expired  " + event.toString() + ": (" + monitorPath + "," + keyName
                    + "," + disConfigTypeEnum.getModelName() + ")======================");

            // 重新连接
            ZookeeperMgr.getInstance().reconnect();

            callback();
        } else {
            LOGGER.debug("============DEBUG MODE: GOT Expired  " + event.toString() + ": (" + monitorPath + ","
                    + "" + keyName + "," + disConfigTypeEnum.getModelName() + ")======================");
        }
    }
}
 
Example 20
Source File: NodeWatcher.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 回调函数
 */
@Override
public void process(WatchedEvent event) {

    //
    // 结点更新时
    //
    if (event.getType() == EventType.NodeDataChanged) {

        try {

            LOGGER.info("============GOT UPDATE EVENT " + event.toString() + ": (" + monitorPath + "," + keyName
                    + "," + disConfigTypeEnum.getModelName() + ")======================");

            // 调用回调函数, 回调函数里会重新进行监控
            callback();

        } catch (Exception e) {

            LOGGER.error("monitor node exception. " + monitorPath, e);
        }
    }

    //
    // 结点断开连接,这时不要进行处理
    //
    if (event.getState() == KeeperState.Disconnected) {

        if (!debug) {
            LOGGER.warn("============GOT Disconnected EVENT " + event.toString() + ": (" + monitorPath + ","
                    + keyName + "," + disConfigTypeEnum.getModelName() + ")======================");
        } else {
            LOGGER.debug("============DEBUG MODE: GOT Disconnected EVENT " + event.toString() + ": (" +
                    monitorPath +
                    "," +
                    keyName +
                    "," + disConfigTypeEnum.getModelName() + ")======================");
        }
    }

    //
    // session expired,需要重新关注哦
    //
    if (event.getState() == KeeperState.Expired) {

        if (!debug) {

            LOGGER.error("============GOT Expired  " + event.toString() + ": (" + monitorPath + "," + keyName
                    + "," + disConfigTypeEnum.getModelName() + ")======================");

            // 重新连接
            ZookeeperMgr.getInstance().reconnect();

            callback();
        } else {
            LOGGER.debug("============DEBUG MODE: GOT Expired  " + event.toString() + ": (" + monitorPath + ","
                    + "" + keyName + "," + disConfigTypeEnum.getModelName() + ")======================");
        }
    }
}