org.apache.zookeeper.Watcher.Event.KeeperState Java Examples
The following examples show how to use
org.apache.zookeeper.Watcher.Event.KeeperState.
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: ZKConnectionImpl.java From zkclient with Apache License 2.0 | 6 votes |
/** * 等待直到连接处于某个状态才停止,如果超时返回false,当正确处于某个状态返回true * 这里使用到了EventLock的 stateChangedCondition 条件, * 如果当前状态不是期待的状态,则此时线程处于等待状态。 * 1.如果事件监听器发现ZooKeeper状态改变,则会标记stateChangedCondition,当前线程被唤醒, * 当前线程继续判断是否是期待的状态,如果是则返回true,如果不是,则线程继续处于等待状态,直到下次ZooKeeper状态改变,重复上述操作。 * 2.如果等待超时则直接返回false。 * @param keeperState ZooKeeper状态 * @param timeout 超时时间 * @param timeUnit 时间单位 * @return * @throws ZKInterruptedException * @return boolean */ private boolean waitForKeeperState(KeeperState keeperState, long timeout, TimeUnit timeUnit) throws ZKInterruptedException { Date timeoutDate = new Date(System.currentTimeMillis() + timeUnit.toMillis(timeout)); LOG.info("Waiting for ZooKeeper state " + keeperState); //使用可中断锁 acquireEventLockInterruptibly(); try { boolean stillWaiting = true; while (currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeoutDate); if (currentState == KeeperState.AuthFailed && isZkSaslEnabled) { throw new ZKException("authorization failed"); } } LOG.info("ZooKeeper State is " + currentState); return true; } catch (InterruptedException e) { throw new ZKInterruptedException(e); } finally { releaseEventLock(); } }
Example #2
Source File: ZkClientZkClient.java From light-task-scheduler with Apache License 2.0 | 6 votes |
public ZkClientZkClient(Config config) { String registryAddress = NodeRegistryUtils.getRealRegistryAddress(config.getRegistryAddress()); zkClient = new ZkClient(registryAddress, connectionTimeout); zkClient.subscribeStateChanges(new IZkStateListener() { public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception { ZkClientZkClient.this.state = state; if (state == KeeperState.Disconnected) { stateChanged(StateListener.DISCONNECTED); } else if (state == KeeperState.SyncConnected) { stateChanged(StateListener.CONNECTED); } else if (state == KeeperState.Expired) { stateChanged(StateListener.DISCONNECTED); } } public void handleNewSession() throws Exception { stateChanged(StateListener.RECONNECTED); } }); }
Example #3
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 6 votes |
/** * {@link https://issues.apache.org/jira/browse/DL-34}. */ @DistributedLogAnnotations.FlakyTest @Ignore @Test(timeout = 60000) public void testAclAuthSpansExpirationNonRetryableClient() throws Exception { ZooKeeperClient zkcAuth = clientBuilder().retryPolicy(null).zkAclId("test").build(); zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth); CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth); expireZooKeeperSession(zkcAuth.get(), 2000); expired.await(2, TimeUnit.SECONDS); connected.await(2, TimeUnit.SECONDS); zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); rmAll(zkcAuth, "/test"); }
Example #4
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 6 votes |
/** * {@link https://issues.apache.org/jira/browse/DL-34}. */ @DistributedLogAnnotations.FlakyTest @Ignore @Test(timeout = 60000) public void testAclAuthSpansExpiration() throws Exception { ZooKeeperClient zkcAuth = buildAuthdClient("test"); zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth); CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth); expireZooKeeperSession(zkcAuth.get(), 2000); expired.await(2, TimeUnit.SECONDS); connected.await(2, TimeUnit.SECONDS); zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); rmAll(zkcAuth, "/test"); }
Example #5
Source File: ZkclientZookeeperClient.java From JobX with Apache License 2.0 | 6 votes |
public ZkclientZookeeperClient(URL url) { super(url); client = new ZkClient(url.getBackupAddress(), Constants.ZK_CONNECTION_TIMEOUT); client.subscribeStateChanges(new IZkStateListener() { public void handleStateChanged(KeeperState state) throws Exception { ZkclientZookeeperClient.this.state = state; if (state == KeeperState.Disconnected) { stateChanged(StateListener.DISCONNECTED); } else if (state == KeeperState.SyncConnected) { stateChanged(StateListener.CONNECTED); } } public void handleNewSession() throws Exception { stateChanged(StateListener.RECONNECTED); } @Override public void handleSessionEstablishmentError(Throwable throwable) throws Exception { } }); }
Example #6
Source File: ZkclientZookeeperClient.java From dubbox with Apache License 2.0 | 6 votes |
public ZkclientZookeeperClient(URL url) { super(url); client = new ZkClient( url.getBackupAddress(), url.getParameter(Constants.SESSION_TIMEOUT_KEY, Constants.DEFAULT_SESSION_TIMEOUT), url.getParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_REGISTRY_CONNECT_TIMEOUT)); client.subscribeStateChanges(new IZkStateListener() { public void handleStateChanged(KeeperState state) throws Exception { ZkclientZookeeperClient.this.state = state; if (state == KeeperState.Disconnected) { stateChanged(StateListener.DISCONNECTED); } else if (state == KeeperState.SyncConnected) { stateChanged(StateListener.CONNECTED); } } public void handleNewSession() throws Exception { stateChanged(StateListener.RECONNECTED); } }); }
Example #7
Source File: ZkDistributedSemaphore.java From dremio-oss with Apache License 2.0 | 6 votes |
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 #8
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 6 votes |
/** * {@link https://issues.apache.org/jira/browse/DL-34} */ @DistributedLogAnnotations.FlakyTest @Ignore @Test(timeout = 60000) public void testAclAuthSpansExpirationNonRetryableClient() throws Exception { ZooKeeperClient zkcAuth = clientBuilder().retryPolicy(null).zkAclId("test").build(); zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth); CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth); expireZooKeeperSession(zkcAuth.get(), 2000); expired.await(2, TimeUnit.SECONDS); connected.await(2, TimeUnit.SECONDS); zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); rmAll(zkcAuth, "/test"); }
Example #9
Source File: ZkClientRegisterCenter.java From elephant with Apache License 2.0 | 6 votes |
@Override public void init() { this.zkClient = new ZkClient(this.zkAddress, this.zkSessionTimeOut, this.zkConnectionTimeOut, new SerializableSerializer()); initRootPath(); this.zkClient.subscribeStateChanges(new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { if(zkReconnectionListener != null && state.name().equals(KeeperState.SyncConnected.name())){ zkReconnectionListener.handleStateForSyncConnected(); } } @Override public void handleSessionEstablishmentError(Throwable error)throws Exception { log.error("处理会话建立错误:{}",error); } @Override public void handleNewSession() throws Exception { log.info("会话建立成功!"); } }); }
Example #10
Source File: ZkClient.java From TakinRPC with Apache License 2.0 | 6 votes |
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { if (_zookeeperEventThread != null && Thread.currentThread() == _zookeeperEventThread) { throw new IllegalArgumentException("Must not be done in the zookeeper event thread."); } Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); logger.debug("Waiting for keeper state " + keeperState); acquireEventLock(); try { boolean stillWaiting = true; while (_currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); } logger.debug("State is " + _currentState); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } }
Example #11
Source File: FlinkServerRegister.java From pinpoint with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") @Override public void process(WatchedEvent event) { logger.info("Handle Zookeeper Event({}) started.", event); KeeperState state = event.getState(); EventType eventType = event.getType(); String path = event.getPath(); if (state == KeeperState.SyncConnected || state == KeeperState.NoSyncConnected) { // when this happens, ephemeral node disappears // reconnects automatically, and process gets notified for all events if (eventType == EventType.NodeChildrenChanged) { logger.info("zookeeper Event occurs : NodeChildrenChanged event"); } else if (eventType == EventType.NodeDeleted) { logger.info("zookeeper Event occurs : NodeDeleted"); } else if (eventType == EventType.NodeDataChanged) { logger.info("zookeeper Event occurs : NodeDataChanged"); } } logger.info("Handle Zookeeper Event({}) completed.", event); }
Example #12
Source File: ZkClient.java From helix with Apache License 2.0 | 6 votes |
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) throws ZkInterruptedException { validateCurrentThread(); Date timeout = new Date(System.currentTimeMillis() + timeUnit.toMillis(time)); LOG.debug("Waiting for keeper state " + keeperState); acquireEventLock(); try { boolean stillWaiting = true; while (_currentState != keeperState) { if (!stillWaiting) { return false; } stillWaiting = getEventLock().getStateChangedCondition().awaitUntil(timeout); } LOG.debug("State is " + (_currentState == null ? "CLOSED" : _currentState)); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } }
Example #13
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 6 votes |
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 #14
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 6 votes |
/** * {@link https://issues.apache.org/jira/browse/DL-34} */ @DistributedLogAnnotations.FlakyTest @Ignore @Test(timeout = 60000) public void testAclAuthSpansExpiration() throws Exception { ZooKeeperClient zkcAuth = buildAuthdClient("test"); zkcAuth.get().create("/test", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); CountDownLatch expired = awaitConnectionEvent(KeeperState.Expired, zkcAuth); CountDownLatch connected = awaitConnectionEvent(KeeperState.SyncConnected, zkcAuth); expireZooKeeperSession(zkcAuth.get(), 2000); expired.await(2, TimeUnit.SECONDS); connected.await(2, TimeUnit.SECONDS); zkcAuth.get().create("/test/key1", new byte[0], DistributedLogConstants.EVERYONE_READ_CREATOR_ALL, CreateMode.PERSISTENT); rmAll(zkcAuth, "/test"); }
Example #15
Source File: ZkclientZookeeperClient.java From dubbo-2.6.5 with Apache License 2.0 | 6 votes |
public ZkclientZookeeperClient(URL url) { super(url); client = new ZkClientWrapper(url.getBackupAddress(), 30000); client.addListener(new IZkStateListener() { @Override public void handleStateChanged(KeeperState state) throws Exception { ZkclientZookeeperClient.this.state = state; if (state == KeeperState.Disconnected) { stateChanged(StateListener.DISCONNECTED); } else if (state == KeeperState.SyncConnected) { stateChanged(StateListener.CONNECTED); } } @Override public void handleNewSession() throws Exception { stateChanged(StateListener.RECONNECTED); } }); client.start(); }
Example #16
Source File: ZkClient.java From TakinRPC with Apache License 2.0 | 5 votes |
public void setCurrentState(KeeperState currentState) { getEventLock().lock(); try { _currentState = currentState; } finally { getEventLock().unlock(); } }
Example #17
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 5 votes |
private CountDownLatch awaitConnectionEvent(final KeeperState state, final ZooKeeperClient zkc) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == EventType.None && event.getState() == state) { connected.countDown(); } } }; zkc.register(watcher); return connected; }
Example #18
Source File: ZooKeeperSessionWatcherTest.java From pulsar with Apache License 2.0 | 5 votes |
@Test public void testProcess2() { WatchedEvent event = new WatchedEvent(EventType.None, KeeperState.Disconnected, null); sessionWatcher.process(event); assertFalse(sessionWatcher.isShutdownStarted()); assertEquals(shutdownService.getExitCode(), 0); }
Example #19
Source File: TestZooKeeperClient.java From distributedlog with Apache License 2.0 | 5 votes |
private CountDownLatch awaitConnectionEvent(final KeeperState state, final ZooKeeperClient zkc) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == EventType.None && event.getState() == state) { connected.countDown(); } } }; zkc.register(watcher); return connected; }
Example #20
Source File: ConnectionWatcher.java From disconf with Apache License 2.0 | 5 votes |
/** * 当连接成功时调用的 */ @Override public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { LOGGER.info("zk SyncConnected"); connectedSignal.countDown(); } else if (event.getState().equals(KeeperState.Disconnected)) { // 这时收到断开连接的消息,这里其实无能为力,因为这时已经和ZK断开连接了,只能等ZK再次开启了 LOGGER.warn("zk Disconnected"); } else if (event.getState().equals(KeeperState.Expired)) { if (!debug) { // 这时收到这个信息,表示,ZK已经重新连接上了,但是会话丢失了,这时需要重新建立会话。 LOGGER.error("zk Expired"); // just reconnect forever reconnect(); } else { LOGGER.info("zk Expired"); } } else if (event.getState().equals(KeeperState.AuthFailed)) { LOGGER.error("zk AuthFailed"); } }
Example #21
Source File: ZkTestHelper.java From helix with Apache License 2.0 | 5 votes |
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(EventType.None, KeeperState.Expired, null); zkClient.process(event); } }); future.get(); }
Example #22
Source File: ClientBaseWithFixes.java From hadoop with Apache License 2.0 | 5 votes |
@Override synchronized public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected || event.getState() == KeeperState.ConnectedReadOnly) { connected = true; notifyAll(); clientConnected.countDown(); } else { connected = false; notifyAll(); } }
Example #23
Source File: ZooKeeperClient.java From Mario with Apache License 2.0 | 5 votes |
@Override public void process(WatchedEvent event) { logger.info("SessionWatcher: " + connectionString + "|" + event.getType() + "|" + event.getState()); if (event.getType() == EventType.None) { if (event.getState().equals(KeeperState.SyncConnected)) { isAvailable = true; countDownLatch.countDown(); } else if (event.getState().equals(KeeperState.Expired)) { createConnection(); } else if (event.getState().equals(KeeperState.Disconnected)) { isAvailable = false; } } }
Example #24
Source File: SchemaWatcherTest.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void testDiscardReaderReference() throws Exception { schemaWatcher.discardReaderReference(); schemaWatcher.process(new WatchedEvent(EventType.NodeDataChanged, KeeperState.SyncConnected, "/test")); // after discardReaderReference, SchemaWatcher should no longer hold a ref to the reader verifyZeroInteractions(mockSchemaReader); }
Example #25
Source File: CreateGroup.java From disconf with Apache License 2.0 | 5 votes |
@Override public void process(WatchedEvent event) { // Watcher interface if (event.getState() == KeeperState.SyncConnected) { connectedSignal.countDown(); } }
Example #26
Source File: ZkClient.java From zkclient with Apache License 2.0 | 5 votes |
/** * 目前只支持2种zookeeper状态 * 1. KeeperState.Expired session 超时 * 2. KeeperState.Disconnected 连接断开时 * * @param state 监听的状态 */ public void listenState(KeeperState state, StateListener listener) { if (state.getIntValue() == KeeperState.Expired.getIntValue()) { process.listenState(state, listener); } else if (state.getIntValue() == KeeperState.Disconnected.getIntValue()) { process.listenState(state, listener); } else { throw new ZkClientException("Listener state not is Expired or Disconnected."); } }
Example #27
Source File: ZkTestHelper.java From helix with Apache License 2.0 | 5 votes |
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 #28
Source File: ZKManager.java From uncode-schedule with GNU General Public License v2.0 | 5 votes |
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 #29
Source File: ZkClient.java From helix with Apache License 2.0 | 5 votes |
public long waitForEstablishedSession(long timeout, TimeUnit timeUnit) { validateCurrentThread(); acquireEventLock(); try { if (!waitForKeeperState(KeeperState.SyncConnected, timeout, timeUnit)) { throw new ZkTimeoutException("Waiting to be connected to ZK server has timed out."); } // Reading session ID before unlocking event lock is critical to guarantee the established // session's ID won't change. return getSessionId(); } finally { getEventLock().unlock(); } }
Example #30
Source File: ConnectionManagerTest.java From lucene-solr with Apache License 2.0 | 5 votes |
public void testLikelyExpired() throws Exception { // setup a SolrZkClient to do some getBaseUrlForNodeName testing Path zkDir = createTempDir("zkData"); ZkTestServer server = new ZkTestServer(zkDir); try { server.run(); SolrZkClient zkClient = new SolrZkClient(server.getZkAddress(), TIMEOUT); ConnectionManager cm = zkClient.getConnectionManager(); try { assertFalse(cm.isLikelyExpired()); assertTrue(cm.isConnectedAndNotClosed()); cm.process(new WatchedEvent(EventType.None, KeeperState.Disconnected, "")); // disconnect shouldn't immediately set likelyExpired assertFalse(cm.isConnectedAndNotClosed()); assertFalse(cm.isLikelyExpired()); // but it should after the timeout Thread.sleep((long)(zkClient.getZkClientTimeout() * 1.5)); assertFalse(cm.isConnectedAndNotClosed()); assertTrue(cm.isLikelyExpired()); // even if we disconnect immediately again cm.process(new WatchedEvent(EventType.None, KeeperState.Disconnected, "")); assertFalse(cm.isConnectedAndNotClosed()); assertTrue(cm.isLikelyExpired()); // reconnect -- should no longer be likely expired cm.process(new WatchedEvent(EventType.None, KeeperState.SyncConnected, "")); assertFalse(cm.isLikelyExpired()); assertTrue(cm.isConnectedAndNotClosed()); } finally { cm.close(); zkClient.close(); } } finally { server.shutdown(); } }