List of usage examples for org.apache.zookeeper KeeperException create
public static KeeperException create(Code code)
From source file:com.yahoo.pulsar.broker.namespace.NamespaceService.java
License:Apache License
/** * 1. split the given bundle into two bundles 2. assign ownership of both the bundles to current broker 3. update * policies with newly created bundles into LocalZK 4. disable original bundle and refresh the cache * * @param bundle//from w ww .j a v a 2 s.c o m * @return * @throws Exception */ public CompletableFuture<Void> splitAndOwnBundle(NamespaceBundle bundle) throws Exception { final CompletableFuture<Void> future = new CompletableFuture<>(); Pair<NamespaceBundles, List<NamespaceBundle>> splittedBundles = bundleFactory.splitBundles(bundle, 2 /* by default split into 2 */); if (splittedBundles != null) { checkNotNull(splittedBundles.getLeft()); checkNotNull(splittedBundles.getRight()); checkArgument(splittedBundles.getRight().size() == 2, "bundle has to be split in two bundles"); NamespaceName nsname = bundle.getNamespaceObject(); try { // take ownership of newly split bundles for (NamespaceBundle sBundle : splittedBundles.getRight()) { checkNotNull(ownershipCache.tryAcquiringOwnership(sBundle)); } updateNamespaceBundles(nsname, splittedBundles.getLeft(), (rc, path, zkCtx, stat) -> pulsar.getOrderedExecutor().submit(safeRun(() -> { if (rc == KeeperException.Code.OK.intValue()) { // disable old bundle try { ownershipCache.disableOwnership(bundle); // invalidate cache as zookeeper has new split // namespace bundle bundleFactory.invalidateBundleCache(nsname); // update bundled_topic cache for load-report-generation pulsar.getBrokerService().refreshTopicToStatsMaps(bundle); loadManager.setLoadReportForceUpdateFlag(); future.complete(null); } catch (Exception e) { String msg1 = format( "failed to disable bundle %s under namespace [%s] with error %s", nsname.toString(), bundle.toString(), e.getMessage()); LOG.warn(msg1, e); future.completeExceptionally(new ServiceUnitNotReadyException(msg1)); } } else { String msg2 = format("failed to update namespace [%s] policies due to %s", nsname.toString(), KeeperException.create(KeeperException.Code.get(rc)).getMessage()); LOG.warn(msg2); future.completeExceptionally(new ServiceUnitNotReadyException(msg2)); } }))); } catch (Exception e) { String msg = format("failed to aquire ownership of split bundle for namespace [%s], %s", nsname.toString(), e.getMessage()); LOG.warn(msg, e); future.completeExceptionally(new ServiceUnitNotReadyException(msg)); } } else { String msg = format("bundle %s not found under namespace", bundle.toString()); future.completeExceptionally(new ServiceUnitNotReadyException(msg)); } return future; }
From source file:com.yahoo.pulsar.zookeeper.ZooKeeperCache.java
License:Apache License
@SuppressWarnings({ "unchecked", "deprecation" }) public <T> CompletableFuture<Optional<Entry<T, Stat>>> getDataAsync(final String path, final Watcher watcher, final Deserializer<T> deserializer) { checkNotNull(path);/*from ww w. ja v a 2 s . co m*/ checkNotNull(deserializer); CompletableFuture<Optional<Entry<T, Stat>>> future = new CompletableFuture<>(); dataCache.get(path, (p, executor) -> { // Return a future for the z-node to be fetched from ZK CompletableFuture<Entry<Object, Stat>> zkFuture = new CompletableFuture<>(); this.zkSession.get().getData(path, watcher, (rc, path1, ctx, content, stat) -> { if (rc == Code.OK.intValue()) { try { T obj = deserializer.deserialize(path, content); zkFuture.complete(new AbstractMap.SimpleImmutableEntry<Object, Stat>(obj, stat)); } catch (Exception e) { zkFuture.completeExceptionally(e); } } else if (rc == Code.NONODE.intValue()) { // Return null values for missing z-nodes, as this is not "exceptional" condition zkFuture.complete(null); } else { zkFuture.completeExceptionally(KeeperException.create(rc)); } }, null); return zkFuture; }).thenAccept(result -> { if (result != null) { future.complete(Optional.of((Entry<T, Stat>) result)); } else { future.complete(Optional.empty()); } }).exceptionally(ex -> { future.completeExceptionally(ex); return null; }); return future; }
From source file:com.yahoo.pulsar.zookeeper.ZookeeperClientFactoryImpl.java
License:Apache License
@Override public CompletableFuture<ZooKeeper> create(String serverList, SessionType sessionType, int zkSessionTimeoutMillis) { // Create a normal ZK client boolean canBeReadOnly = sessionType == SessionType.AllowReadOnly; CompletableFuture<ZooKeeper> future = new CompletableFuture<>(); try {// ww w .ja va2 s .c o m CompletableFuture<Void> internalFuture = new CompletableFuture<>(); ZooKeeper zk = new ZooKeeper(serverList, zkSessionTimeoutMillis, event -> { if (event.getType() == Event.EventType.None) { switch (event.getState()) { case ConnectedReadOnly: checkArgument(canBeReadOnly); // Fall through case SyncConnected: // ZK session is ready to use internalFuture.complete(null); break; case Expired: internalFuture .completeExceptionally(KeeperException.create(KeeperException.Code.SESSIONEXPIRED)); break; default: log.warn("Unexpected ZK event received: {}", event); break; } } }, canBeReadOnly); internalFuture.thenRun(() -> { log.info("ZooKeeper session established: {}", zk); future.complete(zk); }).exceptionally((exception) -> { log.error("Failed to establish ZooKeeper session: {}", exception.getMessage()); future.completeExceptionally(exception); return null; }); } catch (IOException e) { future.completeExceptionally(e); } return future; }
From source file:dmg.cells.zookeeper.PathChildrenCache.java
License:Apache License
void refresh(RefreshMode mode) throws Exception { final BackgroundCallback callback = (client, event) -> { if (PathChildrenCache.this.state.get() != State.CLOSED) { if (event.getResultCode() == KeeperException.Code.OK.intValue()) { processChildren(event.getChildren(), mode); } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { ensurePathAndThenRefresh(mode); } else if (event.getResultCode() == KeeperException.Code.CONNECTIONLOSS.intValue() || event.getResultCode() == KeeperException.Code.SESSIONEXPIRED.intValue()) { log.debug("Refresh callback ignored {}", event); } else { handleException(KeeperException.create(event.getResultCode())); }/*w w w . java 2 s.c o m*/ } }; client.getChildren().usingWatcher(childrenWatcher).inBackground(callback).forPath(path); }
From source file:io.vertx.config.zookeeper.ZookeeperConfigStoreTest.java
License:Apache License
private void dataWrittenCallback(Handler<AsyncResult<Void>> handler, Context context, CuratorEvent event) { context.runOnContext((x) -> {//ww w .j a va 2 s. c o m if (event.getResultCode() == 0) { handler.handle(Future.succeededFuture()); } else { handler.handle(Future .failedFuture(KeeperException.create(KeeperException.Code.get(event.getResultCode())))); } }); }
From source file:org.apache.accumulo.fate.zookeeper.ZooReader.java
License:Apache License
@Override public void sync(final String path) throws KeeperException, InterruptedException { final AtomicInteger rc = new AtomicInteger(); final CountDownLatch waiter = new CountDownLatch(1); getZooKeeper().sync(path, new VoidCallback() { @Override/*w w w. jav a2 s . com*/ public void processResult(int code, String arg1, Object arg2) { rc.set(code); waiter.countDown(); } }, null); waiter.await(); Code code = Code.get(rc.get()); if (code != KeeperException.Code.OK) { throw KeeperException.create(code); } }
From source file:org.apache.accumulo.fate.zookeeper.ZooReaderWriterTest.java
License:Apache License
@Test(expected = NoNodeException.class) public void testDeleteFailOnInitialNoNode() throws Exception { final String path = "/foo"; final int version = -1; zk.delete(path, version);// www . j a va2 s .co m EasyMock.expectLastCall().andThrow(KeeperException.create(Code.NONODE)); EasyMock.expect(retry.hasRetried()).andReturn(false); EasyMock.replay(zk, zrw, retryFactory, retry); zrw.delete(path, version); }
From source file:org.apache.accumulo.fate.zookeeper.ZooReaderWriterTest.java
License:Apache License
@Test public void testDeleteFailOnRetry() throws Exception { final String path = "/foo"; final int version = -1; zk.delete(path, version);/*from w w w .j a v a 2 s . c o m*/ EasyMock.expectLastCall().andThrow(KeeperException.create(Code.CONNECTIONLOSS)); EasyMock.expect(retry.canRetry()).andReturn(true); retry.useRetry(); EasyMock.expectLastCall().once(); retry.waitForNextAttempt(); EasyMock.expectLastCall().once(); zk.delete(path, version); EasyMock.expectLastCall().andThrow(KeeperException.create(Code.NONODE)); EasyMock.expect(retry.hasRetried()).andReturn(true); EasyMock.replay(zk, zrw, retryFactory, retry); zrw.delete(path, version); EasyMock.verify(zk, zrw, retryFactory, retry); }
From source file:org.apache.bookkeeper.client.BookieWatcher.java
License:Apache License
/** * Blocks until bookies are read from zookeeper, used in the {@link BookKeeper} constructor. * @throws InterruptedException//from w ww.j a v a2s .c o m * @throws KeeperException */ public void readBookiesBlocking() throws InterruptedException, KeeperException { final LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<Integer>(); readBookies(new ChildrenCallback() { public void processResult(int rc, String path, Object ctx, List<String> children) { try { BookieWatcher.this.processResult(rc, path, ctx, children); queue.put(rc); } catch (InterruptedException e) { logger.error("Interruped when trying to read bookies in a blocking fashion"); throw new RuntimeException(e); } } }); int rc = queue.take(); if (rc != KeeperException.Code.OK.intValue()) { throw KeeperException.create(Code.get(rc)); } }
From source file:org.apache.bookkeeper.client.TestBookieWatcher.java
License:Apache License
private void expireZooKeeperSession(ZooKeeper zk, int timeout) throws IOException, InterruptedException, KeeperException { final CountDownLatch latch = new CountDownLatch(1); ZooKeeper newZk = new ZooKeeper(zkUtil.getZooKeeperConnectString(), timeout, new Watcher() { @Override//from w w w .j a va 2 s. c o m 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(); }