Java Code Examples for org.apache.zookeeper.WatchedEvent#getState()
The following examples show how to use
org.apache.zookeeper.WatchedEvent#getState() .
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: BKLogHandler.java From distributedlog with Apache License 2.0 | 6 votes |
@Override public void process(WatchedEvent event) { if (Watcher.Event.EventType.None.equals(event.getType())) { if (event.getState() == Watcher.Event.KeeperState.Expired) { // if the watcher is expired scheduler.schedule(new WatcherGetLedgersCallback(getFullyQualifiedName()), conf.getZKRetryBackoffStartMillis(), TimeUnit.MILLISECONDS); } } else if (Watcher.Event.EventType.NodeChildrenChanged.equals(event.getType())) { if (LOG.isTraceEnabled()) { LOG.trace("LogSegments Changed under {}.", getFullyQualifiedName()); } asyncGetLedgerListWithRetries(LogSegmentMetadata.COMPARATOR, filter, getChildrenWatcher, new WatcherGetLedgersCallback(getFullyQualifiedName())); } }
Example 2
Source File: ZkUtil.java From java-study with Apache License 2.0 | 6 votes |
public void process(WatchedEvent watchedEvent) { if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { //与zk服务器处于连接状态 //如果没有就创建 if(watchedEvent.getType() == Event.EventType.None && null == watchedEvent.getPath()) { }else if(watchedEvent.getType() == Event.EventType.NodeCreated) { System.out.println("监控到了该节点被创建"); } else if(watchedEvent.getType() == Event.EventType.NodeDataChanged) { // 节点的子节点列表发生变化 System.out.println("监控到了该节点更新"); } else if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged) { // 节点的数据内容发生变化 System.out.println("监控到了该节点的子节点更新"); }else if(watchedEvent.getType() == Event.EventType.NodeDeleted) { System.out.println("监控到了该节点删除"); } } }
Example 3
Source File: RewatchOnExpireWatcher.java From twill with Apache License 2.0 | 6 votes |
@Override public void process(WatchedEvent event) { if (delegate != null && event.getType() != Event.EventType.None) { try { delegate.process(event); } catch (Throwable t) { LOG.error("Watcher throws exception.", t); } } if (event.getState() != Event.KeeperState.Expired) { return; } switch (actionType) { case EXISTS: exists(); break; case CHILDREN: children(); break; case DATA: data(); break; } }
Example 4
Source File: TestBookKeeperConfiguration.java From big-c with Apache License 2.0 | 6 votes |
private static ZooKeeper connectZooKeeper(String ensemble) throws IOException, KeeperException, InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper zkc = new ZooKeeper(HOSTPORT, ZK_SESSION_TIMEOUT, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { latch.countDown(); } } }); if (!latch.await(ZK_SESSION_TIMEOUT, TimeUnit.MILLISECONDS)) { throw new IOException("Zookeeper took too long to connect"); } return zkc; }
Example 5
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 6
Source File: ZookeeperMonitor.java From arcusplatform with Apache License 2.0 | 6 votes |
@Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Expired: // TODO: move this elsewhere? logger.error("SHUTTING DOWN -- zookeeper session has been marked as expired"); System.err.println("SHUTTING DOWN -- zookeeper session has been marked as expired"); System.exit(-1); break; } } else { } }
Example 7
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 8
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 9
Source File: DataMonitor.java From bidder with Apache License 2.0 | 5 votes |
public void process(WatchedEvent event) { String path = event.getPath(); if (event.getType() == Event.EventType.None) { // We are are being told that the state of the // connection has changed switch (event.getState()) { case SyncConnected: // In this particular example we don't need to do anything // here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course) break; case Expired: // It's all over dead = true; listener.closing(KeeperException.Code.SessionExpired); break; } } else { if (path != null && path.equals(znode)) { // Something has changed on the node, let's find out zk.exists(znode, true, this, null); } } if (chainedWatcher != null) { chainedWatcher.process(event); } }
Example 10
Source File: ZKSessionLock.java From distributedlog with Apache License 2.0 | 5 votes |
@Override public void process(WatchedEvent event) { LOG.debug("Received event {} from lock {} at {} : watcher epoch {}, lock epoch {}.", new Object[] {event, lockPath, System.currentTimeMillis(), epoch, ZKSessionLock.this.epoch.get() }); if (event.getType() == Watcher.Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Expired: LOG.info("Session {} is expired for lock {} at {} : watcher epoch {}, lock epoch {}.", new Object[] { lockId.getRight(), lockPath, System.currentTimeMillis(), epoch, ZKSessionLock.this.epoch.get() }); handleSessionExpired(epoch); break; default: break; } } else if (event.getType() == Event.EventType.NodeDeleted) { // this handles the case where we have aborted a lock and deleted ourselves but still have a // watch on the nextLowestNode. This is a workaround since ZK doesn't support unsub. if (!event.getPath().equals(watchedNode)) { LOG.warn("{} (watching {}) ignored watched event from {} ", new Object[] { lockId, watchedNode, event.getPath() }); return; } handleNodeDelete(epoch, event); } else { LOG.warn("Unexpected ZK event: {}", event.getType().name()); } }
Example 11
Source File: GlobalZooKeeperCache.java From pulsar with Apache License 2.0 | 5 votes |
@Override public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) { synchronized (this) { if (LOG.isDebugEnabled()) { LOG.debug("[{}] Got Global ZooKeeper WatchdEvent: EventType: {}, KeeperState: {}, path: {}", this.hashCode(), event.getType(), event.getState(), event.getPath()); } if (event.getType() == Event.EventType.None) { switch (event.getState()) { case Expired: // in case of expired, the zkSession is no longer good for sure. // We need to restart the session immediately. // cancel any timer event since it is already bad ZooKeeper oldSession = this.zkSession.getAndSet(null); LOG.warn("Global ZK session lost. Triggering reconnection {}", oldSession); safeCloseZkSession(oldSession); asyncRestartZooKeeperSession(); return; case SyncConnected: case ConnectedReadOnly: checkNotNull(zkSession.get()); LOG.info("Global ZK session {} restored connection.", zkSession.get()); // dataCache.synchronous().invalidateAll(); childrenCache.synchronous().invalidateAll(); return; default: break; } } } // Other types of events super.process(event, updater); }
Example 12
Source File: TestFrameworkEdges.java From xian with Apache License 2.0 | 5 votes |
@Test public void testSessionKilled() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(1)); client.start(); try { client.create().forPath("/sessionTest"); final AtomicBoolean sessionDied = new AtomicBoolean(false); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if ( event.getState() == Event.KeeperState.Expired ) { sessionDied.set(true); } } }; client.checkExists().usingWatcher(watcher).forPath("/sessionTest"); KillSession.kill(client.getZookeeperClient().getZooKeeper(), server.getConnectString()); Assert.assertNotNull(client.checkExists().forPath("/sessionTest")); Assert.assertTrue(sessionDied.get()); } finally { CloseableUtils.closeQuietly(client); } }
Example 13
Source File: ZooKeeperConnection.java From javatech with Creative Commons Attribution Share Alike 4.0 International | 5 votes |
public ZooKeeper connect(String host) throws IOException, InterruptedException { zoo = new ZooKeeper(host, 5000, new Watcher() { @Override public void process(WatchedEvent we) { if (we.getState() == KeeperState.SyncConnected) { connectedSignal.countDown(); } } }); connectedSignal.await(); return zoo; }
Example 14
Source File: ZooKeeperConnection.java From Zebra with Apache License 2.0 | 5 votes |
public ZooKeeper connect(String host) throws IOException, InterruptedException { zooKeeper = new ZooKeeper(host, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if(watchedEvent.getState() == Event.KeeperState.SyncConnected) { connectedSignal.countDown(); } } }); connectedSignal.await(); return zooKeeper; }
Example 15
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 16
Source File: SolrCollectionConfigurer.java From ambari-logsearch with Apache License 2.0 | 5 votes |
private ZooKeeper openZookeeperConnection(final SolrPropsConfig solrPropsConfig) throws InterruptedException, IOException { final CountDownLatch connSignal = new CountDownLatch(1); ZooKeeper zooKeeper = new ZooKeeper(solrPropsConfig.getZkConnectString(), SESSION_TIMEOUT, new Watcher() { public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.SyncConnected) { connSignal.countDown(); } } }); connSignal.await(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); return zooKeeper; }
Example 17
Source File: ZooKeeperConnection.java From envelope with Apache License 2.0 | 4 votes |
@Override public void process(WatchedEvent event) { if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { latch.countDown(); } }
Example 18
Source File: ZKWatcher.java From zkclient with Apache License 2.0 | 4 votes |
/** * 事件处理 * @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 19
Source File: ZKDiscoveryService.java From twill with Apache License 2.0 | 4 votes |
private Watcher createConnectionWatcher() { return new Watcher() { // Watcher is invoked from single event thread, hence safe to use normal mutable variable. private boolean expired; @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.Expired) { LOG.warn("ZK Session expired: {}", zkClient.getConnectString()); expired = true; } else if (event.getState() == Event.KeeperState.SyncConnected && expired) { LOG.info("Reconnected after expiration: {}", zkClient.getConnectString()); expired = false; // Re-register all services lock.lock(); try { for (final Map.Entry<Discoverable, DiscoveryCancellable> entry : discoverables.entries()) { if (closed.get()) { entry.getValue().asyncCancel(); continue; } LOG.info("Re-registering service: {}", entry.getKey()); // Must be non-blocking in here. Futures.addCallback(doRegister(entry.getKey()), new FutureCallback<String>() { @Override public void onSuccess(String result) { // Updates the cancellable to the newly created sequential node. entry.getValue().setPath(result); LOG.debug("Service re-registered: {} {}", entry.getKey(), result); } @Override public void onFailure(Throwable t) { // When failed to create the node, there would be no retry and simply make the cancellable do nothing. entry.getValue().setPath(null); LOG.error("Failed to re-register service: {}", entry.getKey(), t); } }, Threads.SAME_THREAD_EXECUTOR); } } finally { lock.unlock(); } } } }; }
Example 20
Source File: ZkClient.java From DDMQ with Apache License 2.0 | 4 votes |
@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"); } }