org.apache.zookeeper.ZooKeeper.States Java Examples

The following examples show how to use org.apache.zookeeper.ZooKeeper.States. 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: AdminResource.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the broker is allowed to do read-write operations based on the existence of a node in global
 * zookeeper.
 *
 * @throws WebApplicationException
 *             if broker has a read only access if broker is not connected to the global zookeeper
 */
public void validatePoliciesReadOnlyAccess() {
    boolean arePoliciesReadOnly = true;

    try {
        arePoliciesReadOnly = globalZkCache().exists(POLICIES_READONLY_FLAG_PATH);
    } catch (Exception e) {
        log.warn("Unable to fetch contents of [{}] from global zookeeper", POLICIES_READONLY_FLAG_PATH, e);
        throw new RestException(e);
    }

    if (arePoliciesReadOnly) {
        log.debug("Policies are read-only. Broker cannot do read-write operations");
        throw new RestException(Status.FORBIDDEN, "Broker is forbidden to do read-write operations");
    } else {
        // Make sure the broker is connected to the global zookeeper before writing. If not, throw an exception.
        if (globalZkCache().getZooKeeper().getState() != States.CONNECTED) {
            log.debug("Broker is not connected to the global zookeeper");
            throw new RestException(Status.PRECONDITION_FAILED,
                    "Broker needs to be connected to global zookeeper before making a read-write operation");
        } else {
            // Do nothing, just log the message.
            log.debug("Broker is allowed to make read-write operations");
        }
    }
}
 
Example #2
Source File: MessagingServiceShutdownHook.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public void shutdown(int exitCode) {
    try {
        // Try to close ZK session to ensure all ephemeral locks gets released immediately
        if (service != null) {
            if (service.getZkClient().getState() != States.CLOSED) {
                service.getZkClient().close();
            }
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }

    LOG.info("Invoking Runtime.halt({})", exitCode);
    immediateFlushBufferedLogs();
    processTerminator.accept(exitCode);
}
 
Example #3
Source File: ZooKeeperClientAspectJTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testZkConnected() throws Exception {
    OrderedScheduler executor = OrderedScheduler.newSchedulerBuilder().build();
    try {
        ZooKeeperClientFactory zkf = new ZookeeperBkClientFactoryImpl(executor);
        CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + localZkS.getZookeeperPort(),
                SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);
    }finally{
        if (localZkc != null) {
            localZkc.close();
        }

        executor.shutdown();
    }
}
 
Example #4
Source File: ZooKeeperClientAspectJTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitZk() throws Exception {
    try {
        ZooKeeperClientFactory zkfactory = new ZookeeperClientFactoryImpl();
        CompletableFuture<ZooKeeper> zkFuture = zkfactory.create("127.0.0.1:" + localZkS.getZookeeperPort(),
                SessionType.ReadWrite,
                (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
        assertTrue(localZkc.getState().isConnected());
        assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);

        String connection = "127.0.0.1:" + localZkS.getZookeeperPort() + "/prefix";
        ZooKeeper chrootZkc = PulsarClusterMetadataSetup.initZk(connection, (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
        assertTrue(chrootZkc.getState().isConnected());
        assertNotEquals(chrootZkc.getState(), States.CONNECTEDREADONLY);
        chrootZkc.close();

        assertNotNull(localZkc.exists("/prefix", false));
    } finally {
        if (localZkc != null) {
            localZkc.close();
        }
    }
}
 
Example #5
Source File: ZookeeperClient.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
/**
 * Is the zookeeper client connected?
 *
 * @return
 */
public boolean isConnected() {
	if (zookeeper == null) {
		return false;
	}

	return zookeeper.getState() == States.CONNECTED;
}
 
Example #6
Source File: ConnectionWatcher.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 含有重试机制的retry,加锁, 一直尝试连接,直至成功
 */
public synchronized void reconnect() {

    LOGGER.info("start to reconnect....");

    int retries = 0;
    while (true) {

        try {

            if (!zk.getState().equals(States.CLOSED)) {
                break;
            }

            LOGGER.warn("zookeeper lost connection, reconnect");

            close();

            connect(internalHost);

        } catch (Exception e) {

            LOGGER.error(retries + "\t" + e.toString());

            // sleep then retry
            try {
                int sec = ResilientActiveKeyValueStore.RETRY_PERIOD_SECONDS;
                LOGGER.warn("sleep " + sec);
                TimeUnit.SECONDS.sleep(sec);
            } catch (InterruptedException e1) {
            }
        }
    }
}
 
Example #7
Source File: ConnectionWatcher.java    From disconf with Apache License 2.0 5 votes vote down vote up
/**
 * 含有重试机制的retry,加锁, 一直尝试连接,直至成功
 */
public synchronized void reconnect() {

    LOGGER.info("start to reconnect....");

    int retries = 0;
    while (true) {

        try {

            if (!zk.getState().equals(States.CLOSED)) {
                break;
            }

            LOGGER.warn("zookeeper lost connection, reconnect");

            close();

            connect(internalHost);

        } catch (Exception e) {

            LOGGER.error(retries + "\t" + e.toString());

            // sleep then retry
            try {
                int sec = ResilientActiveKeyValueStore.RETRY_PERIOD_SECONDS;
                LOGGER.warn("sleep " + sec);
                TimeUnit.SECONDS.sleep(sec);
            } catch (InterruptedException e1) {
            }
        }
    }
}
 
Example #8
Source File: ZkTestHelper.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * expire zk session asynchronously
 * @param client
 * @throws Exception
 */
public static void asyncExpireSession(RealmAwareZkClient client)
    throws Exception {
  final ZkClient zkClient = (ZkClient) client;
  ZkConnection connection = ((ZkConnection) zkClient.getConnection());
  ZooKeeper curZookeeper = connection.getZookeeper();
  LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Process watchEvent: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  dupZookeeper.close();

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();

  // System.err.println("zk: " + oldZookeeper);
  LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
 
Example #9
Source File: ZkTestHelper.java    From helix with Apache License 2.0 5 votes vote down vote up
/**
 * expire zk session asynchronously
 * @param client
 * @throws Exception
 */
public static void asyncExpireSession(RealmAwareZkClient client) throws Exception {
  final ZkClient zkClient = (ZkClient) client;
  ZkConnection connection = ((ZkConnection) zkClient.getConnection());
  ZooKeeper curZookeeper = connection.getZookeeper();
  LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Process watchEvent: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  dupZookeeper.close();

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();

  // System.err.println("zk: " + oldZookeeper);
  LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
 
Example #10
Source File: ZookeeperClientFactoryImplTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testZKCreationRW() throws Exception {
    ZooKeeperClientFactory zkf = new ZookeeperClientFactoryImpl();
    CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + localZkS.getZookeeperPort(), SessionType.ReadWrite,
            (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
    localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    assertTrue(localZkc.getState().isConnected());
    assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);
    localZkc.close();
}
 
Example #11
Source File: ZookeeperBkClientFactoryImplTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Test
public void testZKCreationRW() throws Exception {
    ZooKeeperClientFactory zkf = new ZookeeperBkClientFactoryImpl(executor);
    CompletableFuture<ZooKeeper> zkFuture = zkf.create("127.0.0.1:" + localZkS.getZookeeperPort(), SessionType.ReadWrite,
            (int) ZOOKEEPER_SESSION_TIMEOUT_MILLIS);
    localZkc = zkFuture.get(ZOOKEEPER_SESSION_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
    assertTrue(localZkc.getState().isConnected());
    assertNotEquals(localZkc.getState(), States.CONNECTEDREADONLY);
    localZkc.close();
}
 
Example #12
Source File: PulsarAuthorizationProvider.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private void validatePoliciesReadOnlyAccess() {
    boolean arePoliciesReadOnly = true;
    ZooKeeperCache globalZkCache = configCache.cache();

    try {
        arePoliciesReadOnly = globalZkCache.exists(POLICIES_READONLY_FLAG_PATH);
    } catch (Exception e) {
        log.warn("Unable to fetch contents of [{}] from global zookeeper", POLICIES_READONLY_FLAG_PATH, e);
        throw new IllegalStateException("Unable to fetch content from global zk");
    }

    if (arePoliciesReadOnly) {
        if (log.isDebugEnabled()) {
            log.debug("Policies are read-only. Broker cannot do read-write operations");
        }
        throw new IllegalStateException("policies are in readonly mode");
    } else {
        // Make sure the broker is connected to the global zookeeper before writing. If not, throw an exception.
        if (globalZkCache.getZooKeeper().getState() != States.CONNECTED) {
            if (log.isDebugEnabled()) {
                log.debug("Broker is not connected to the global zookeeper");
            }
            throw new IllegalStateException("not connected woith global zookeeper");
        } else {
            // Do nothing, just log the message.
            log.debug("Broker is allowed to make read-write operations");
        }
    }
}
 
Example #13
Source File: ZooKeeperConnection.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
    ZooKeeperConnection zooKeeperConnection = new ZooKeeperConnection();
    ZooKeeper zk = zooKeeperConnection.connect(HOST);
    States state = zk.getState();
    System.out.println("ZooKeeper isAlive:" + state.isAlive());
    zk.close();
}
 
Example #14
Source File: ZkClient.java    From TakinRPC with Apache License 2.0 5 votes vote down vote up
public synchronized void connect(final long maxMsToWaitUntilConnected, Watcher watcher) {
    if (_eventThread != null) {
        return;
    }
    boolean started = false;
    try {
        getEventLock().lockInterruptibly();
        setShutdownTrigger(false);
        _eventThread = new ZkEventThread(_connection.getServers());
        _eventThread.start();//这样的 线程很可能会直接退回
        _connection.connect(watcher);

        logger.debug("Awaiting connection to Zookeeper server: " + maxMsToWaitUntilConnected);
        if (!waitUntilConnected(maxMsToWaitUntilConnected, TimeUnit.MILLISECONDS)) {
            throw new ZkTimeoutException(String.format("Unable to connect to zookeeper server[%s] within timeout %dms", _connection.getServers(), maxMsToWaitUntilConnected));
        }
        started = true;
    } catch (InterruptedException e) {
        States state = _connection.getZookeeperState();
        throw new IllegalStateException("Not connected with zookeeper server yet. Current state is " + state);
    } finally {
        getEventLock().unlock();

        // we should close the zookeeper instance, otherwise it would keep
        // on trying to connect
        if (!started) {
            close();
        }
    }
}
 
Example #15
Source File: ZookeeperBkClientFactoryImpl.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<ZooKeeper> create(String serverList, SessionType sessionType, int zkSessionTimeoutMillis) {
    CompletableFuture<ZooKeeper> future = new CompletableFuture<>();

    executor.execute(safeRun(() -> {
        try {
            ZooKeeper zk = ZooKeeperClient.newBuilder().connectString(serverList)
                    .sessionTimeoutMs(zkSessionTimeoutMillis)
                    .connectRetryPolicy(new BoundExponentialBackoffRetryPolicy(zkSessionTimeoutMillis,
                            zkSessionTimeoutMillis, 0))
                    .build();

            if (zk.getState() == States.CONNECTEDREADONLY && sessionType != SessionType.AllowReadOnly) {
                zk.close();
                future.completeExceptionally(new IllegalStateException("Cannot use a read-only session"));
            }

            log.info("ZooKeeper session established: {}", zk);
            future.complete(zk);
        } catch (IOException | KeeperException | InterruptedException exception) {
            log.error("Failed to establish ZooKeeper session: {}", exception.getMessage());
            future.completeExceptionally(exception);
        }
    }, throwable -> {
        future.completeExceptionally(throwable);
    }));

    return future;
}
 
Example #16
Source File: ZKManager.java    From stategen with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean checkZookeeperState() throws Exception{
	return zk != null && zk.getState() == States.CONNECTED;
}
 
Example #17
Source File: ZKManager.java    From uncode-schedule with Apache License 2.0 4 votes vote down vote up
public boolean isZookeeperConnected() throws Exception {
  return zk != null && zk.getState() == States.CONNECTED;
}
 
Example #18
Source File: HBaseTestingUtility.java    From hbase with Apache License 2.0 4 votes vote down vote up
/**
 * Expire a ZooKeeper session as recommended in ZooKeeper documentation
 * http://hbase.apache.org/book.html#trouble.zookeeper
 * There are issues when doing this:
 * [1] http://www.mail-archive.com/[email protected]/msg01942.html
 * [2] https://issues.apache.org/jira/browse/ZOOKEEPER-1105
 *
 * @param nodeZK - the ZK watcher to expire
 * @param checkStatus - true to check if we can create a Table with the
 *                    current configuration.
 */
public void expireSession(ZKWatcher nodeZK, boolean checkStatus)
  throws Exception {
  Configuration c = new Configuration(this.conf);
  String quorumServers = ZKConfig.getZKQuorumServersString(c);
  ZooKeeper zk = nodeZK.getRecoverableZooKeeper().getZooKeeper();
  byte[] password = zk.getSessionPasswd();
  long sessionID = zk.getSessionId();

  // Expiry seems to be asynchronous (see comment from P. Hunt in [1]),
  //  so we create a first watcher to be sure that the
  //  event was sent. We expect that if our watcher receives the event
  //  other watchers on the same machine will get is as well.
  // When we ask to close the connection, ZK does not close it before
  //  we receive all the events, so don't have to capture the event, just
  //  closing the connection should be enough.
  ZooKeeper monitor = new ZooKeeper(quorumServers,
    1000, new org.apache.zookeeper.Watcher(){
    @Override
    public void process(WatchedEvent watchedEvent) {
      LOG.info("Monitor ZKW received event="+watchedEvent);
    }
  } , sessionID, password);

  // Making it expire
  ZooKeeper newZK = new ZooKeeper(quorumServers,
      1000, EmptyWatcher.instance, sessionID, password);

  //ensure that we have connection to the server before closing down, otherwise
  //the close session event will be eaten out before we start CONNECTING state
  long start = System.currentTimeMillis();
  while (newZK.getState() != States.CONNECTED
       && System.currentTimeMillis() - start < 1000) {
     Thread.sleep(1);
  }
  newZK.close();
  LOG.info("ZK Closed Session 0x" + Long.toHexString(sessionID));

  // Now closing & waiting to be sure that the clients get it.
  monitor.close();

  if (checkStatus) {
    getConnection().getTable(TableName.META_TABLE_NAME).close();
  }
}
 
Example #19
Source File: RecoverableZooKeeper.java    From hbase with Apache License 2.0 4 votes vote down vote up
public synchronized States getState() {
  return zk == null ? null : zk.getState();
}
 
Example #20
Source File: ZkTestHelper.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * Expire current zk session and wait for {@link IZkStateListener#handleNewSession(String)} invoked
 * @param client
 * @throws Exception
 */

public static void disconnectSession(HelixZkClient client) throws Exception {
  final ZkClient zkClient = (ZkClient) client;
  IZkStateListener listener = new IZkStateListener() {
    @Override
    public void handleStateChanged(KeeperState state) throws Exception {
      // System.err.println("disconnectSession handleStateChanged. state: " + state);
    }

    @Override
    public void handleNewSession(final String sessionId) throws Exception {
      // make sure zkclient is connected again
      zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);

      LOG.info("handleNewSession. sessionId: {}.", sessionId);
    }

    @Override
    public void handleSessionEstablishmentError(Throwable var1) throws Exception {
    }
  };

  zkClient.subscribeStateChanges(listener);
  ZkConnection connection = (ZkConnection) zkClient.getConnection();
  ZooKeeper curZookeeper = connection.getZookeeper();
  LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Process watchEvent: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  dupZookeeper.close();

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();
  zkClient.unsubscribeStateChanges(listener);

  // System.err.println("zk: " + oldZookeeper);
  LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
 
Example #21
Source File: ZkTestHelper.java    From helix with Apache License 2.0 4 votes vote down vote up
public static void expireSession(RealmAwareZkClient client) throws Exception {
  final CountDownLatch waitNewSession = new CountDownLatch(1);
  final ZkClient zkClient = (ZkClient) client;

  IZkStateListener listener = new IZkStateListener() {
    @Override
    public void handleStateChanged(KeeperState state) throws Exception {
      LOG.info("IZkStateListener#handleStateChanged, state: " + state);
    }

    @Override
    public void handleNewSession(final String sessionId) throws Exception {
      // make sure zkclient is connected again
      zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);

      LOG.info("handleNewSession. sessionId: {}.", sessionId);
      waitNewSession.countDown();
    }

    @Override
    public void handleSessionEstablishmentError(Throwable var1) throws Exception {
    }
  };

  zkClient.subscribeStateChanges(listener);

  ZkConnection connection = ((ZkConnection) zkClient.getConnection());
  ZooKeeper curZookeeper = connection.getZookeeper();
  String oldSessionId = Long.toHexString(curZookeeper.getSessionId());
  LOG.info("Before session expiry. sessionId: " + oldSessionId + ", zk: " + curZookeeper);

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Watcher#process, event: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  Assert.assertEquals(dupZookeeper.getState(), States.CONNECTED,
      "Fail to connect to zk using current session info");
  dupZookeeper.close();

  // make sure session expiry really happens
  waitNewSession.await();
  zkClient.unsubscribeStateChanges(listener);

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();

  String newSessionId = Long.toHexString(curZookeeper.getSessionId());
  LOG.info("After session expiry. sessionId: " + newSessionId + ", zk: " + curZookeeper);
  Assert.assertFalse(newSessionId.equals(oldSessionId),
      "Fail to expire current session, zk: " + curZookeeper);
}
 
Example #22
Source File: ZKManager.java    From uncode-schedule with GNU General Public License v2.0 4 votes vote down vote up
public boolean checkZookeeperState() throws Exception{
    return zk != null && zk.getState() == States.CONNECTED;
}
 
Example #23
Source File: ZkConnection.java    From helix with Apache License 2.0 4 votes vote down vote up
@Override
public States getZookeeperState() {
  return _zk != null ? _zk.getState() : null;
}
 
Example #24
Source File: ZkTestHelper.java    From helix with Apache License 2.0 4 votes vote down vote up
/**
 * Expire current zk session and wait for {@link IZkStateListener#handleNewSession(String)} invoked
 * @param client
 * @throws Exception
 */
public static void disconnectSession(HelixZkClient client)
    throws Exception {
  final ZkClient zkClient = (ZkClient) client;
  IZkStateListener listener = new IZkStateListener() {
    @Override
    public void handleStateChanged(KeeperState state)
        throws Exception {
      // System.err.println("disconnectSession handleStateChanged. state: " + state);
    }

    @Override
    public void handleNewSession(final String sessionId)
        throws Exception {
      // make sure zkclient is connected again
      zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);

      LOG.info("handleNewSession. sessionId: {}.", sessionId);
    }

    @Override
    public void handleSessionEstablishmentError(Throwable var1)
        throws Exception {
    }
  };

  zkClient.subscribeStateChanges(listener);
  ZkConnection connection = (ZkConnection) zkClient.getConnection();
  ZooKeeper curZookeeper = connection.getZookeeper();
  LOG.info("Before expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Process watchEvent: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  dupZookeeper.close();

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();
  zkClient.unsubscribeStateChanges(listener);

  // System.err.println("zk: " + oldZookeeper);
  LOG.info("After expiry. sessionId: " + Long.toHexString(curZookeeper.getSessionId()));
}
 
Example #25
Source File: ZkTestHelper.java    From helix with Apache License 2.0 4 votes vote down vote up
public static void expireSession(RealmAwareZkClient client)
    throws Exception {
  final CountDownLatch waitNewSession = new CountDownLatch(1);
  final ZkClient zkClient = (ZkClient) client;

  IZkStateListener listener = new IZkStateListener() {
    @Override
    public void handleStateChanged(KeeperState state)
        throws Exception {
      LOG.info("IZkStateListener#handleStateChanged, state: " + state);
    }

    @Override
    public void handleNewSession(final String sessionId)
        throws Exception {
      // make sure zkclient is connected again
      zkClient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.SECONDS);

      LOG.info("handleNewSession. sessionId: {}.", sessionId);
      waitNewSession.countDown();
    }

    @Override
    public void handleSessionEstablishmentError(Throwable var1)
        throws Exception {
    }
  };

  zkClient.subscribeStateChanges(listener);

  ZkConnection connection = ((ZkConnection) zkClient.getConnection());
  ZooKeeper curZookeeper = connection.getZookeeper();
  String oldSessionId = Long.toHexString(curZookeeper.getSessionId());
  LOG.info("Before session expiry. sessionId: " + oldSessionId + ", zk: " + curZookeeper);

  Watcher watcher = new Watcher() {
    @Override
    public void process(WatchedEvent event) {
      LOG.info("Watcher#process, event: " + event);
    }
  };

  final ZooKeeper dupZookeeper =
      new ZooKeeper(connection.getServers(), curZookeeper.getSessionTimeout(), watcher,
          curZookeeper.getSessionId(), curZookeeper.getSessionPasswd());
  // wait until connected, then close
  while (dupZookeeper.getState() != States.CONNECTED) {
    Thread.sleep(10);
  }
  Assert.assertEquals(dupZookeeper.getState(), States.CONNECTED,
      "Fail to connect to zk using current session info");
  dupZookeeper.close();

  // make sure session expiry really happens
  waitNewSession.await();
  zkClient.unsubscribeStateChanges(listener);

  connection = (ZkConnection) zkClient.getConnection();
  curZookeeper = connection.getZookeeper();

  String newSessionId = Long.toHexString(curZookeeper.getSessionId());
  LOG.info("After session expiry. sessionId: " + newSessionId + ", zk: " + curZookeeper);
  Assert.assertFalse(newSessionId.equals(oldSessionId),
      "Fail to expire current session, zk: " + curZookeeper);
}
 
Example #26
Source File: ZkConnection.java    From TakinRPC with Apache License 2.0 4 votes vote down vote up
public States getZookeeperState() {
    return _zk != null ? _zk.getState() : null;
}
 
Example #27
Source File: ZKManager.java    From tbschedule with Apache License 2.0 4 votes vote down vote up
public boolean checkZookeeperState() {
    return zk != null && zk.getState() == States.CONNECTED;
}
 
Example #28
Source File: IZkConnection.java    From helix with Apache License 2.0 votes vote down vote up
public States getZookeeperState();