List of usage examples for org.apache.zookeeper WatchedEvent getType
public EventType getType()
From source file:org.apache.twill.internal.kafka.client.ZKBrokerService.java
License:Apache License
/** * Checks exists of a given ZK path and execute the action when it exists. *///from w w w . java 2s . co m private void actOnExists(final String path, final Runnable action, final SettableFuture<?> readyFuture, final long retryTime, final TimeUnit retryUnit) { Futures.addCallback(zkClient.exists(path, new Watcher() { @Override public void process(WatchedEvent event) { if (!isRunning()) { return; } if (event.getType() == Event.EventType.NodeCreated) { action.run(); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(Stat result) { if (result != null) { action.run(); } else { // If the node doesn't exists, treat it as ready. When the node becomes available later, data will be // fetched by the watcher. readyFuture.set(null); } } @Override public void onFailure(Throwable t) { // Retry the operation based on the retry time. Thread retryThread = new Thread("zk-broker-service-retry") { @Override public void run() { try { retryUnit.sleep(retryTime); actOnExists(path, action, readyFuture, retryTime, retryUnit); } catch (InterruptedException e) { LOG.warn("ZK retry thread interrupted. Action not retried."); } } }; retryThread.setDaemon(true); retryThread.start(); } }, executorService); }
From source file:org.apache.twill.internal.state.ZKServiceDecoratorTest.java
License:Apache License
private void watchDataChange(final ZKClientService zkClient, final String path, final Semaphore semaphore, final AtomicReference<String> stateMatch) { Futures.addCallback(zkClient.getData(path, new Watcher() { @Override/*from ww w .ja v a 2 s .c o m*/ public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeDataChanged) { watchDataChange(zkClient, path, semaphore, stateMatch); } } }), new FutureCallback<NodeData>() { @Override public void onSuccess(NodeData result) { String content = new String(result.getData(), Charsets.UTF_8); JsonObject json = new Gson().fromJson(content, JsonElement.class).getAsJsonObject(); if (stateMatch.get().equals(json.get("state").getAsString())) { semaphore.release(); } } @Override public void onFailure(Throwable t) { exists(); } private void exists() { Futures.addCallback(zkClient.exists(path, new Watcher() { @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeCreated) { watchDataChange(zkClient, path, semaphore, stateMatch); } } }), new FutureCallback<Stat>() { @Override public void onSuccess(Stat result) { if (result != null) { watchDataChange(zkClient, path, semaphore, stateMatch); } } @Override public void onFailure(Throwable t) { LOG.error(t.getMessage(), t); } }); } }); }
From source file:org.apache.twill.zookeeper.ZKClientTest.java
License:Apache License
@Test public void testExpireRewatch() throws InterruptedException, IOException, ExecutionException { InMemoryZKServer zkServer = InMemoryZKServer.builder().setTickTime(1000).build(); zkServer.startAndWait();//from www . ja v a 2s. com try { final CountDownLatch expireReconnectLatch = new CountDownLatch(1); final AtomicBoolean expired = new AtomicBoolean(false); final ZKClientService client = ZKClientServices .delegate(ZKClients.reWatchOnExpire(ZKClientService.Builder.of(zkServer.getConnectionStr()) .setSessionTimeout(2000).setConnectionWatcher(new Watcher() { @Override public void process(WatchedEvent event) { if (event.getState() == Event.KeeperState.Expired) { expired.set(true); } else if (event.getState() == Event.KeeperState.SyncConnected && expired.compareAndSet(true, true)) { expireReconnectLatch.countDown(); } } }).build())); client.startAndWait(); try { final BlockingQueue<Watcher.Event.EventType> events = new LinkedBlockingQueue<>(); client.exists("/expireRewatch", new Watcher() { @Override public void process(final WatchedEvent event) { Futures.addCallback(client.exists("/expireRewatch", this), new FutureCallback<Stat>() { @Override public void onSuccess(Stat result) { events.add(event.getType()); } @Override public void onFailure(Throwable t) { LOG.error("Failed to call exists on /expireRewatch", t); } }); } }); client.create("/expireRewatch", null, CreateMode.PERSISTENT); Assert.assertEquals(Watcher.Event.EventType.NodeCreated, events.poll(60, TimeUnit.SECONDS)); KillZKSession.kill(client.getZooKeeperSupplier().get(), zkServer.getConnectionStr(), 10000); Assert.assertTrue(expireReconnectLatch.await(60, TimeUnit.SECONDS)); // Keep trying to delete the node until it succeed while (ZKOperations.ignoreError(client.delete("/expireRewatch"), KeeperException.class, null) .get() == null) { LOG.info("Delete failed. Retrying to delete /expireRewatch"); TimeUnit.MILLISECONDS.sleep(10); } Assert.assertEquals(Watcher.Event.EventType.NodeDeleted, events.poll(60, TimeUnit.SECONDS)); } finally { client.stopAndWait(); } } finally { zkServer.stopAndWait(); } }
From source file:org.bboxdb.distribution.zookeeper.ZookeeperClient.java
License:Apache License
/** * Process zooekeeper events//w w w .j a va 2 s . c o m * @param watchedEvent */ protected void processZookeeperEvent(final WatchedEvent watchedEvent) { // Ignore null parameter if (watchedEvent == null) { logger.warn("process called with an null argument"); return; } // Shutdown is pending, stop event processing if (shutdownPending == true) { return; } // Ignore type=none event if (watchedEvent.getType() == EventType.None) { return; } // Process events if (watchedEvent.getPath() != null) { if (watchedEvent.getPath().startsWith(getInstancesPath())) { readMembershipAndRegisterWatch(); } } else { logger.warn("Got unknown zookeeper event: {}", watchedEvent); } }
From source file:org.cloudata.core.commitlog.CommitLogServer.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Disconnected: LOG.warn("Disconnected:" + event); break; case Expired: LOG.info("Shutdown cause lock expired:" + event); stopCommitLogServer();/*from w w w . jav a2 s.co m*/ } } }
From source file:org.cloudata.core.master.CloudataMaster.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Disconnected: LOG.warn("Disconnected:" + event); break; case Expired: LOG.info("Shutdown cause lock expired:" + event); shutdown();/*from w ww. ja va 2 s . c o m*/ break; } } }
From source file:org.cloudata.core.tabletserver.TabletServer.java
License:Apache License
@Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case SyncConnected: break; case Disconnected: LOG.warn("Disconnected:" + event); break; case Expired: LOG.fatal("Shutdown cause lock expired:" + event); shutdown();/* w w w . j av a 2 s. com*/ break; } } }
From source file:org.eclipse.ecf.provider.zookeeper.node.internal.NodeReader.java
License:Open Source License
public void process(WatchedEvent event) { if (this.isDisposed) { // Already disposed return;//from w ww .j av a 2 s .co m } if (event.getState() == KeeperState.Disconnected || event.getState() == KeeperState.Expired || event.getType() == EventType.NodeDeleted) { /* * This node is deleted or the connection with the server we're * reading from is down. This discovered service wrapped by this * node is no more available. */ dispose(); } }
From source file:org.eclipse.ecf.provider.zookeeper.node.internal.ReadRoot.java
License:Open Source License
public void process(final WatchedEvent event) { ZooDiscoveryContainer.CACHED_THREAD_POOL.execute(new Runnable() { public void run() { synchronized (connectionLock) { if (watchManager.isDisposed()) return; switch (event.getState()) { case Disconnected: ReadRoot.this.isConnected = false; connect();//from w w w .j av a2 s . c om break; case Expired: ReadRoot.this.isConnected = false; connect(); break; case SyncConnected: if (!ReadRoot.this.isConnected) { ReadRoot.this.isConnected = true; ReadRoot.this.watchManager.addZooKeeper(ReadRoot.this.readKeeper); ReadRoot.this.readKeeper.exists(INode.ROOT, ReadRoot.this, null, null); ReadRoot.this.readKeeper.getChildren(INode.ROOT, ReadRoot.this, ReadRoot.this, null); } break; // ignore @deprecated cases } switch (event.getType()) { case NodeDeleted: if (event.getPath() == null || event.getPath().equals(INode.ROOT)) break; ReadRoot.this.nodeReaders.remove(event.getPath()); break; case NodeChildrenChanged: if (ReadRoot.this.isConnected) { ReadRoot.this.readKeeper.exists(INode.ROOT, ReadRoot.this, null, null); ReadRoot.this.readKeeper.getChildren(INode.ROOT, ReadRoot.this, ReadRoot.this, null); } break; } } } }); }
From source file:org.eclipse.gyrex.cloud.internal.admin.NodeConfigurer.java
License:Open Source License
@Override public IStatus configureConnection(final String connectString) { ZooKeeper zk = null;//from www.j a va 2s . com try { if (connectString != null) { // try connect // TODO: not sure if this makes sense when configuring a remote system final CountDownLatch connected = new CountDownLatch(1); zk = new ZooKeeper(connectString, 5000, new Watcher() { @Override public void process(final WatchedEvent event) { if ((event.getType() == EventType.None) && (event.getState() == KeeperState.SyncConnected)) { connected.countDown(); } } }); // wait at most 5 seconds for a connection connected.await(5000, TimeUnit.MILLISECONDS); if (zk.getState() != States.CONNECTED) { throw new IllegalStateException(String.format( "Timeout waiting for a connection to '%s'. Please verify the connect string.", connectString)); } // try reading some information from the cloud if (null == zk.exists(IZooKeeperLayout.PATH_GYREX_ROOT.toString(), false)) { // maybe a new cloud, try initialization final String path = IZooKeeperLayout.PATH_GYREX_ROOT.toString(); final String createdPath = zk.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); if (!path.equals(createdPath)) { throw new IllegalStateException(String .format("created path does not match expected path (%s != %s)", path, createdPath)); } } // at this point the connect string seems to be ok // TODO: store it in ZooKeeper and implement ZK to local sync } // store in instance preferences if local if (new NodeInfo().getNodeId().equals(nodeId)) { final Preferences preferences = InstanceScope.INSTANCE.getNode(CloudActivator.SYMBOLIC_NAME) .node(ZooKeeperGateConfig.PREF_NODE_ZOOKEEPER); if (connectString != null) { preferences.put(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING, connectString); } else { preferences.remove(ZooKeeperGateConfig.PREF_KEY_CLIENT_CONNECT_STRING); } preferences.flush(); // remove connection to cloud CloudState.unregisterNode(); // bring down ZooKeeper Gate ZooKeeperGateApplication.reconnect(); // register with new cloud CloudState.registerNode(); } } catch (final Exception e) { LOG.debug("Exception connecting to cloud using connect string {}.", connectString, e); return new Status(IStatus.ERROR, CloudActivator.SYMBOLIC_NAME, "Unable to connect to ZooKeeper. " + ExceptionUtils.getRootCauseMessage(e), e); } finally { if (zk != null) { try { zk.close(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } } } return Status.OK_STATUS; }