List of usage examples for org.apache.zookeeper WatchedEvent getType
public EventType getType()
From source file:com.talis.platform.sequencing.zookeeper.ZooKeeperProvider.java
License:Apache License
@Override public void process(WatchedEvent event) { switch (event.getType()) { case None://from w w w. j av a 2 s .c om processNoneTypeEvent(event.getState()); default: // do nothing } }
From source file:com.taobao.adfs.zookeeper.ZookeeperClientManager.java
License:Apache License
public synchronized ZooKeeper create(String connectString, int sessionTimeout) throws IOException { ZooKeeper zookeeper = zookeeperRepository.get(connectString); if (zookeeper != null) { Utilities.logDebug(logger, "reuse zookeeper client, address=", connectString); return zookeeper; }//www .ja v a 2s. c o m this.timeout = sessionTimeout; Watcher watcher = new Watcher() { public void process(WatchedEvent event) { switch (event.getType()) { case None: { connectionEvent(event); break; } } } }; zookeeper = new ZooKeeper(connectString, sessionTimeout, watcher); try { connectedSignal.await(); } catch (InterruptedException e) { Utilities.logDebug(logger, "notify by SynConnected."); } zookeeperRepository.put(connectString, zookeeper); Utilities.logDebug(logger, "create zookeeper client, address=", connectString); return zookeeper; }
From source file:com.twitter.common.zookeeper.SingletonServiceTest.java
License:Apache License
@Test public void testNonLeaderDisconnect() throws Exception { CountDownLatch elected = new CountDownLatch(1); listener.onLeading(EasyMock.<LeaderControl>anyObject()); expectLastCall().andAnswer(countDownAnswer(elected)); listener.onDefeated(null);// w w w .ja v a2 s. co m expectLastCall().anyTimes(); control.replay(); ZooKeeperClient zkClient = createZkClient(); String path = "/fake/path"; // Create a fake leading candidate node to ensure that the leader in this test is never // elected. ZooKeeperUtils.ensurePath(zkClient, ZooKeeperUtils.OPEN_ACL_UNSAFE, path); String leaderNode = zkClient.get().create(path + "/" + SingletonService.LEADER_ELECT_NODE_PREFIX, "fake_leader".getBytes(), ZooKeeperUtils.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); serverSet = new ServerSetImpl(zkClient, path); candidate = SingletonService.createSingletonCandidate(zkClient, path, ZooKeeperUtils.OPEN_ACL_UNSAFE); DefeatOnDisconnectLeader leader = new DefeatOnDisconnectLeader(zkClient, listener); service = new SingletonService(serverSet, candidate); service.lead(InetSocketAddress.createUnresolved("foo", PORT_A), ImmutableMap.of("http-admin", InetSocketAddress.createUnresolved("foo", PORT_B)), leader); final CountDownLatch disconnected = new CountDownLatch(1); zkClient.register(new Watcher() { @Override public void process(WatchedEvent event) { if ((event.getType() == EventType.None) && (event.getState() == KeeperState.Disconnected)) { disconnected.countDown(); } } }); shutdownNetwork(); disconnected.await(); restartNetwork(); zkClient.get().delete(leaderNode, ZooKeeperUtils.ANY_VERSION); // Upon deletion of the fake leader node, the candidate should become leader. elected.await(); }
From source file:com.twitter.common.zookeeper.ZooKeeperClient.java
License:Apache License
/** * Returns the current active ZK connection or establishes a new one if none has yet been * established or a previous connection was disconnected or had its session time out. This * method will attempt to re-use sessions when possible. * * @param connectionTimeout the maximum amount of time to wait for the connection to the ZK * cluster to be established; 0 to wait forever * @return a connected ZooKeeper client/* ww w .ja v a 2 s . co m*/ * @throws ZooKeeperConnectionException if there was a problem connecting to the ZK cluster * @throws InterruptedException if interrupted while waiting for a connection to be established * @throws TimeoutException if a connection could not be established within the configured * session timeout */ public synchronized ZooKeeper get(Amount<Long, Time> connectionTimeout) throws ZooKeeperConnectionException, InterruptedException, TimeoutException { if (zooKeeper == null) { final CountDownLatch connected = new CountDownLatch(1); Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { switch (event.getType()) { // Guard the None type since this watch may be used as the default watch on calls by // the client outside our control. case None: switch (event.getState()) { case Expired: LOG.info("Zookeeper session expired. Event: " + event); close(); break; case SyncConnected: connected.countDown(); break; } } eventQueue.offer(event); } }; try { zooKeeper = (sessionState != null) ? new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher, sessionState.sessionId, sessionState.sessionPasswd) : new ZooKeeper(zooKeeperServers, sessionTimeoutMs, watcher); } catch (IOException e) { throw new ZooKeeperConnectionException("Problem connecting to servers: " + zooKeeperServers, e); } if (connectionTimeout.getValue() > 0) { if (!connected.await(connectionTimeout.as(Time.MILLISECONDS), TimeUnit.MILLISECONDS)) { close(); throw new TimeoutException("Timed out waiting for a ZK connection after " + connectionTimeout); } } else { try { connected.await(); } catch (InterruptedException ex) { LOG.info("Interrupted while waiting to connect to zooKeeper"); close(); throw ex; } } credentials.authenticate(zooKeeper); sessionState = new SessionState(zooKeeper.getSessionId(), zooKeeper.getSessionPasswd()); } return zooKeeper; }
From source file:com.twitter.common.zookeeper.ZooKeeperClient.java
License:Apache License
/** * 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.//from w ww. j av a2 s . c o m */ public Watcher registerExpirationHandler(final Command onExpired) { Watcher watcher = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == EventType.None && event.getState() == KeeperState.Expired) { onExpired.execute(); } } }; register(watcher); return watcher; }
From source file:com.twitter.common.zookeeper.ZooKeeperMap.java
License:Apache License
private synchronized void watchChildren() throws InterruptedException, KeeperException, ZooKeeperConnectionException { /*//from www. j a va 2s. co m * Add a watch on the parent node itself, and attempt to rewatch if it * gets deleted */ zkClient.get().exists(nodePath, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.NodeDeleted) { // If the parent node no longer exists localMap.clear(); try { tryWatchChildren(); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while trying to watch children.", e); Thread.currentThread().interrupt(); } } } }); final Watcher childWatcher = new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.NodeChildrenChanged) { try { tryWatchChildren(); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while trying to watch children.", e); Thread.currentThread().interrupt(); } } } }; List<String> children = zkClient.get().getChildren(nodePath, childWatcher); updateChildren(Sets.newHashSet(children)); }
From source file:com.twitter.common.zookeeper.ZooKeeperMap.java
License:Apache License
private void addChild(final String child) throws InterruptedException, KeeperException, ZooKeeperConnectionException { final Watcher nodeWatcher = new Watcher() { @Override// w ww . jav a2 s. c om public void process(WatchedEvent event) { if (event.getType() == Watcher.Event.EventType.NodeDataChanged) { try { tryAddChild(child); } catch (InterruptedException e) { LOG.log(Level.WARNING, "Interrupted while trying to add a child.", e); Thread.currentThread().interrupt(); } } else if (event.getType() == Watcher.Event.EventType.NodeDeleted) { removeEntry(child); } } }; try { V value = deserializer.apply(zkClient.get().getData(makePath(child), nodeWatcher, null)); putEntry(child, value); } catch (KeeperException.NoNodeException e) { // This node doesn't exist anymore, remove it from the map and we're done. removeEntry(child); } }
From source file:com.twitter.distributedlog.acl.ZKAccessControlManager.java
License:Apache License
@Override public void process(WatchedEvent event) { if (Event.EventType.None.equals(event.getType())) { if (event.getState() == Event.KeeperState.Expired) { refetchAllAccessControlEntries(0); }// ww w . ja va2 s.c om } else if (Event.EventType.NodeDataChanged.equals(event.getType())) { logger.info("Default ACL for {} is changed, refetching ...", zkRootPath); refetchDefaultAccessControlEntry(0); } else if (Event.EventType.NodeChildrenChanged.equals(event.getType())) { logger.info("List of ACLs for {} are changed, refetching ...", zkRootPath); refetchAccessControlEntries(0); } }
From source file:com.twitter.distributedlog.BKLogHandler.java
License:Apache License
@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); }/*from ww w . j a v a 2 s . c om*/ } 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())); } }
From source file:com.twitter.distributedlog.impl.federated.FederatedZKLogMetadataStore.java
License:Apache License
@Override public void process(WatchedEvent watchedEvent) { if (Event.EventType.None == watchedEvent.getType() && Event.KeeperState.Expired == watchedEvent.getState()) { scheduleTask(this, conf.getZKSessionTimeoutMilliseconds()); return;//from w ww . j a va 2s.c o m } if (Event.EventType.NodeChildrenChanged == watchedEvent.getType()) { // fetch the namespace fetchSubNamespaces(this).addEventListener(this); } }