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); } }
public ZkclientZookeeperClient(URL url) { super(url); client = new ZkClient(url.getBackupAddress()); 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); } }); }
public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { if (latch != null) { latch.countDown(); } } if (event.getType() == EventType.None) { return; } try { events.put(event); } catch (InterruptedException e) { Assert.assertTrue("interruption unexpected", false); } }
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); } }); }
private static void subscribeStateChanges() { getZkClient().subscribeStateChanges(new IZkStateListener() { public void handleStateChanged(KeeperState state) throws Exception { if(state == null) { ZkClientFactory.LOGGER.info("ZOOKEEPER连接状态改变"); } else { ZkClientFactory.LOGGER.info("ZOOKEEPER连接状态改变为" + state.name()); } } public void handleNewSession() throws Exception { ZkClientFactory.LOGGER.info("SESSIONTIMEOUT,ZOOKEEPER重连,产生新SESSION"); } }); }
@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("会话建立成功!"); } }); }
private void processStateChanged(WatchedEvent event) { LOG.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); } }
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)); 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); return true; } catch (InterruptedException e) { throw new ZkInterruptedException(e); } finally { getEventLock().unlock(); } }
public boolean waitForKeeperState(KeeperState keeperState, long time, TimeUnit timeUnit) { 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 RuntimeException("error when conn"); } finally { getEventLock().unlock(); } }
synchronized public void process(WatchedEvent event) { KeeperState state = event.getState(); if (state == KeeperState.SyncConnected) { connected = true; syncConnected = true; readOnlyConnected = false; } else if (state == KeeperState.ConnectedReadOnly) { connected = true; syncConnected = false; readOnlyConnected = true; } else { connected = false; syncConnected = false; readOnlyConnected = false; } notifyAll(); if (connected) { clientConnected.countDown(); } }
@Override public synchronized void process(WatchedEvent event) { if (event.getState() == KeeperState.AuthFailed) { authFailed.countDown(); } else { super.process(event); } }
private void fireStateChangedEvent(final KeeperState state) { for (final IZkStateListener stateListener : _stateListener) { _eventThread.send(new ZkEvent("State changed to " + state + " sent to " + stateListener) { @Override public void run() throws Exception { stateListener.handleStateChanged(state); } }); } }
/** * zookeeper 链接事件监听 * * @param connectionLatch 同步锁 * @param event 事件 */ 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状态重连 }
public void setCurrentState(KeeperState currentState) { getEventLock().lock(); try { _currentState = currentState; } finally { getEventLock().unlock(); } }
/** * Test method for {@link com.takin.rpc.zkclient.ZkClient#waitUntilConnected()} * . */ @Test public void testWaitUntilConnected() { ZkClient client2 = new ZkClient("localhost:4711", 15000); assertTrue(client2.waitUntilConnected()); server.shutdown(); // assertTrue(client2.waitForKeeperState(KeeperState.Disconnected, 1, TimeUnit.SECONDS)); // assertFalse(client2.waitUntilConnected(1, TimeUnit.SECONDS)); client2.close(); }
@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(); } }
/** * 连接zookeeper * * @author gaoxianglong */ public void init() { try { zkClient = new ZooKeeper(zkAddress, zkSessionTimeout, new Watcher() { @Override public void process(WatchedEvent event) { KeeperState state = event.getState(); switch (state) { case SyncConnected: countDownLatch.countDown(); logger.info("connection zookeeper success"); break; case Disconnected: logger.warn("zookeeper connection is disconnected"); break; case Expired: logger.error("zookeeper session expired"); break; case AuthFailed: logger.error("authentication failure"); break; default: break; } } }); countDownLatch.await(); } catch (Exception e) { logger.error("error", e); } }
@Override public void process(WatchedEvent event) { KeeperState state = event.getState(); if (state == KeeperState.SyncConnected) { ZooKeeperConnectionDescriptor zooKeeperConnectionDescriptor = getDescriptor(); List<AuthInfo> authInfos = zooKeeperConnectionDescriptor.getAuthInfos(); if (authInfos != null && !authInfos.isEmpty()) { for (AuthInfo authInfo : authInfos) { String scheme = authInfo.getScheme(); byte[] auth; try { auth = authInfo.getAuth(); } catch (IOException e) { e.printStackTrace(); continue; } // TODO: Is the lack of thread saftey of this method a concern here? addAuthInfo(scheme, auth); } } } fireConnectionStateChanged(); }
public void process(WatchedEvent event) { if (event.getState() == KeeperState.SyncConnected) { synchronized(this) { connected = true; notifyAll(); } } else if (event.getState() == KeeperState.Disconnected) { synchronized(this) { connected = false; notifyAll(); } } }
public KeeperState getKeeperState() { if (saslClient != null) { if (saslState == SaslState.FAILED) { return KeeperState.AuthFailed; } if (saslClient.isComplete()) { if (saslState == SaslState.INTERMEDIATE) { saslState = SaslState.COMPLETE; return KeeperState.SaslAuthenticated; } } } // No event ready to emit yet. return null; }
public void process(WatchedEvent event) { if (KeeperState.Expired == event.getState()) { // It's all over LOG.error("Lost session"); System.exit(4); } if (event.getPath() != null && event.getPath().equals(assignmentsNode)) { // children have changed, so read in the new list zk.getChildren(assignmentsNode, true, this, null); } }
/** * Callback invoked by the ClientCnxnSocket once a connection has been * established. * * @param _negotiatedSessionTimeout * @param _sessionId * @param _sessionPasswd * @param isRO * @throws IOException */ void onConnected(int _negotiatedSessionTimeout, long _sessionId, byte[] _sessionPasswd, boolean isRO) throws IOException { negotiatedSessionTimeout = _negotiatedSessionTimeout; if (negotiatedSessionTimeout <= 0) { state = States.CLOSED; eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null)); eventThread.queueEventOfDeath(); String warnInfo; warnInfo = "Unable to reconnect to ZooKeeper service, session 0x" + Long.toHexString(sessionId) + " has expired"; LOG.warn(warnInfo); throw new SessionExpiredException(warnInfo); } if (!readOnly && isRO) { LOG.error("Read/write client got connected to read-only server"); } readTimeout = negotiatedSessionTimeout * 2 / 3; connectTimeout = negotiatedSessionTimeout / hostProvider.size(); hostProvider.onConnected(); sessionId = _sessionId; sessionPasswd = _sessionPasswd; state = (isRO) ? States.CONNECTEDREADONLY : States.CONNECTED; seenRwServerBefore |= !isRO; LOG.info("Session establishment complete on server " + clientCnxnSocket.getRemoteSocketAddress() + ", sessionid = 0x" + Long.toHexString(sessionId) + ", negotiated timeout = " + negotiatedSessionTimeout + (isRO ? " (READ-ONLY mode)" : "")); KeeperState eventState = (isRO) ? KeeperState.ConnectedReadOnly : KeeperState.SyncConnected; eventThread.queueEvent(new WatchedEvent( Watcher.Event.EventType.None, eventState, null)); }
public void process(WatchedEvent event) { System.err.println(event); synchronized (this) { if (event.getType() == EventType.None) { connected = (event.getState() == KeeperState.SyncConnected); notifyAll(); } } }
public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.None) { synchronized (this) { connected = event.getState() == Watcher.Event.KeeperState.SyncConnected; notifyAll(); } } }
@Override public synchronized void process(WatchedEvent event) { if (event.getState() == KeeperState.AuthFailed) { authFailed.incrementAndGet(); } else { super.process(event); } }
public void process(WatchedEvent event) { LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath()); if (event.getState() == KeeperState.SyncConnected) { if (startSignal != null && startSignal.getCount() > 0) { LOG.info("startsignal.countDown()"); startSignal.countDown(); } else { LOG.warn("startsignal " + startSignal); } } }
@Override public synchronized void process(WatchedEvent event) { if (event.getState() == KeeperState.AuthFailed) { authFailed.incrementAndGet(); authCompleted.countDown(); } else if (event.getState() == KeeperState.SaslAuthenticated) { authCompleted.countDown(); } else { super.process(event); } }
public void process(WatchedEvent event) { LOG.info(name + " event:" + event.getState() + " " + event.getType() + " " + event.getPath()); if (event.getState() == KeeperState.SyncConnected && startSignal != null && startSignal.getCount() > 0) { startSignal.countDown(); } }
public void process(WatchedEvent event) { LOG.info("Event:" + event.getState() + " " + event.getType() + " " + event.getPath()); if (event.getState() == KeeperState.SyncConnected && startSignal != null && startSignal.getCount() > 0) { startSignal.countDown(); } }
@Test public void testIntConversion() { // Ensure that we can convert all valid integers to KeeperStates EnumSet<KeeperState> allStates = EnumSet.allOf(KeeperState.class); for(KeeperState as : allStates) { Assert.assertEquals(as, KeeperState.fromInt( as.getIntValue() ) ); } }
@Test public void testInvalidIntConversion() { try { KeeperState ks = KeeperState.fromInt(324142); Assert.fail("Was able to create an invalid KeeperState via an integer"); } catch(RuntimeException re) { // we're good. } }