Example usage for org.apache.zookeeper KeeperException create

List of usage examples for org.apache.zookeeper KeeperException create

Introduction

In this page you can find the example usage for org.apache.zookeeper KeeperException create.

Prototype

public static KeeperException create(Code code) 

Source Link

Document

All non-specific keeper exceptions should be constructed via this factory method in order to guarantee consistency in error codes and such.

Usage

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Set <code>data</code> to zookeeper <code>path</code>.
 *
 * @param zk/*from   w w  w.j a va 2s . c  o m*/
 *          zookeeper client
 * @param path
 *          path to set data
 * @param data
 *          data to set
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static Future<ZkVersion> zkSetData(ZooKeeper zk, String path, byte[] data, ZkVersion version) {
    final Promise<ZkVersion> promise = new Promise<ZkVersion>();
    zk.setData(path, data, version.getZnodeVersion(), new AsyncCallback.StatCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, Stat stat) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.updateIfEmpty(new Return<ZkVersion>(new ZkVersion(stat.getVersion())));
                return;
            }
            promise.updateIfEmpty(new Throw<ZkVersion>(KeeperException.create(KeeperException.Code.get(rc))));
            return;
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Delete the given <i>path</i> from zookeeper.
 *
 * @param zk//from   ww w  .ja  v  a2 s. co  m
 *          zookeeper client
 * @param path
 *          path to delete
 * @param version
 *          version used to set data
 * @return future representing the version after this operation.
 */
public static Future<Void> zkDelete(ZooKeeper zk, String path, ZkVersion version) {
    final Promise<Void> promise = new Promise<Void>();
    zk.delete(path, version.getZnodeVersion(), new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (KeeperException.Code.OK.intValue() == rc) {
                promise.updateIfEmpty(new Return<Void>(null));
                return;
            }
            promise.updateIfEmpty(new Throw<Void>(KeeperException.create(KeeperException.Code.get(rc))));
            return;
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.zk.TestZKVersionedSetOp.java

License:Apache License

@Test(timeout = 60000)
public void testAbortNullOpResult() throws Exception {
    final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp = new ZKVersionedSetOp(mock(Op.class),
            new Transaction.OpListener<Version>() {
                @Override/*from  w  w w  .j av a2 s  .co  m*/
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    versionedSetOp.abortOpResult(ke, null);
    latch.await();
    assertTrue(ke == exception.get());
}

From source file:com.twitter.distributedlog.zk.TestZKVersionedSetOp.java

License:Apache License

@Test(timeout = 60000)
public void testAbortOpResult() throws Exception {
    final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp = new ZKVersionedSetOp(mock(Op.class),
            new Transaction.OpListener<Version>() {
                @Override//from  w  w  w.  j av  a2  s  . com
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    OpResult opResult = new OpResult.ErrorResult(KeeperException.Code.NONODE.intValue());
    versionedSetOp.abortOpResult(ke, opResult);
    latch.await();
    assertTrue(exception.get() instanceof KeeperException.NoNodeException);
}

From source file:com.twitter.distributedlog.zk.ZKTransaction.java

License:Apache License

@Override
public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
    if (KeeperException.Code.OK.intValue() == rc) { // transaction succeed
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).commitOpResult(results.get(i));
        }// w ww  . jav a  2s. c  om
        FutureUtils.setValue(result, null);
    } else {
        KeeperException ke = KeeperException.create(KeeperException.Code.get(rc));
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).abortOpResult(ke, null != results ? results.get(i) : null);
        }
        FutureUtils.setException(result, ke);
    }
}

From source file:com.twitter.distributedlog.zk.ZKVersionedSetOp.java

License:Apache License

@Override
protected void abortOpResult(Throwable t, @Nullable OpResult opResult) {
    Throwable cause;/*w  w  w  . j  a  v a  2 s  . c o  m*/
    if (null == opResult) {
        cause = t;
    } else {
        assert (opResult instanceof OpResult.ErrorResult);
        OpResult.ErrorResult errorResult = (OpResult.ErrorResult) opResult;
        if (KeeperException.Code.OK.intValue() == errorResult.getErr()) {
            cause = t;
        } else {
            cause = KeeperException.create(KeeperException.Code.get(errorResult.getErr()));
        }
    }
    listener.onAbort(cause);
}

From source file:com.twitter.distributedlog.ZooKeeperClientUtils.java

License:Apache License

/**
 * Expire given zookeeper client's session.
 *
 * @param zkc//from w  w  w  .j  a  v a2  s.c om
 *          zookeeper client
 * @param zkServers
 *          zookeeper servers
 * @param timeout
 *          timeout
 * @throws Exception
 */
public static void expireSession(ZooKeeperClient zkc, String zkServers, int timeout) throws Exception {
    final CountDownLatch expireLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1);
    ZooKeeper oldZk = zkc.get();
    oldZk.exists("/", new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            logger.debug("Receive event : {}", event);
            if (event.getType() == Event.EventType.None && event.getState() == Event.KeeperState.Expired) {
                expireLatch.countDown();
            }
        }
    });
    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (Event.EventType.None == event.getType()
                    && Event.KeeperState.SyncConnected == event.getState()) {
                latch.countDown();
            }
        }
    }, oldZk.getSessionId(), oldZk.getSessionPasswd());
    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }
    newZk.close();

    boolean done = false;
    Stopwatch expireWait = Stopwatch.createStarted();
    while (!done && expireWait.elapsed(TimeUnit.MILLISECONDS) < timeout * 2) {
        try {
            zkc.get().exists("/", false);
            done = true;
        } catch (KeeperException ke) {
            done = (ke.code() == KeeperException.Code.SESSIONEXPIRED);
        }
    }

    assertTrue("Client should receive session expired event.",
            expireLatch.await(timeout, TimeUnit.MILLISECONDS));
}

From source file:com.vmware.photon.controller.common.zookeeper.ServiceNodeMembership.java

License:Open Source License

/**
 * Creates a new membership node in Zookeeper and sets the provided future when creation is complete.
 *
 * @param leasePromise promise that gets fulfilled when node is created
 * @return a listenable future to get notified when the znode gets created
 * @throws Exception// w  w w. ja  v a  2s . co  m
 */
public synchronized ListenableFuture<Void> create(final SettableFuture<ServiceNode.Lease> leasePromise)
        throws Exception {
    logger.debug("Creating membership node for {}", membershipNode);

    final SettableFuture<Void> future = SettableFuture.create();
    BackgroundCallback callback = new BackgroundCallback() {
        @Override
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                leasePromise.set(new ServiceNode.Lease() {
                    @Override
                    public ListenableFuture<Void> getExpirationFuture() {
                        return expirationPromise;
                    }
                });
                future.set(null);
            } else {
                logger.error("Failed to create node {}: {}", membershipNode, event.getResultCode());
                future.setException(KeeperException.create(KeeperException.Code.get(event.getResultCode())));
                leasePromise
                        .setException(KeeperException.create(KeeperException.Code.get(event.getResultCode())));
            }
        }
    };

    zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(callback)
            .forPath(membershipNode, getSerializedAddress());
    return future;
}

From source file:com.vmware.photon.controller.common.zookeeper.ServiceNodeMembership.java

License:Open Source License

public synchronized void delete(final SettableFuture<Void> donePromise) throws Exception {
    logger.debug("Deleting membership node for {}", membershipNode);

    BackgroundCallback callback = new BackgroundCallback() {
        @Override/*from w  w  w  .jav a 2 s .c  om*/
        public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
            if (event.getResultCode() == KeeperException.Code.OK.intValue()) {
                donePromise.set(VOID);
                logger.debug("Membership node deleted");
            } else {
                logger.error("Error deleting the node {}: {}", membershipNode, event.getResultCode());
                donePromise
                        .setException(KeeperException.create(KeeperException.Code.get(event.getResultCode())));
            }
        }
    };

    zkClient.delete().guaranteed().inBackground(callback).forPath(membershipNode);
}

From source file:com.yahoo.pulsar.broker.cache.LocalZooKeeperCacheService.java

License:Apache License

/**
 * Create LocalPolicies with bundle-data in LocalZookeeper by fetching it from GlobalZookeeper
 *
 * @param path//from w  ww  .ja v  a2 s  .  co  m
 *            znode path
 * @param readFromGlobal
 *            if true copy policies from global zk to local zk else create a new znode with empty {@link Policies}
 * @throws Exception
 */
@SuppressWarnings("deprecation")
public CompletableFuture<Optional<LocalPolicies>> createPolicies(String path, boolean readFromGlobal) {
    checkNotNull(path, "path can't be null");
    checkArgument(path.startsWith(LOCAL_POLICIES_ROOT), "Invalid path of local policies");

    CompletableFuture<Optional<LocalPolicies>> future = new CompletableFuture<>();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating local namespace policies for {} - readFromGlobal: {}", path, readFromGlobal);
    }

    CompletableFuture<Optional<LocalPolicies>> readFromGlobalFuture = new CompletableFuture<>();

    if (readFromGlobal) {
        String globalPath = joinPath(POLICIES_ROOT,
                path.substring(path.indexOf(LOCAL_POLICIES_ROOT) + LOCAL_POLICIES_ROOT.length() + 1));
        checkNotNull(configurationCacheService);
        checkNotNull(configurationCacheService.policiesCache());
        checkNotNull(configurationCacheService.policiesCache().getAsync(globalPath));
        configurationCacheService.policiesCache().getAsync(globalPath).thenAccept(policies -> {
            if (policies.isPresent()) {
                // Copying global bundles information to local policies
                LocalPolicies localPolicies = new LocalPolicies();
                localPolicies.bundles = policies.get().bundles;
                readFromGlobalFuture.complete(Optional.of(localPolicies));
            } else {
                // Policies are not present in global zk
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Global policies not found at {}", globalPath);
                }
                readFromGlobalFuture.complete(Optional.empty());
            }
        }).exceptionally(ex -> {
            future.completeExceptionally(ex);
            return null;
        });
    } else {
        // Use default local policies
        readFromGlobalFuture.complete(Optional.of(new LocalPolicies()));
    }

    readFromGlobalFuture.thenAccept(localPolicies -> {
        if (!localPolicies.isPresent()) {
            future.complete(Optional.empty());
        }

        // When we have the updated localPolicies, we can write them back in local ZK
        byte[] content;
        try {
            content = ObjectMapperFactory.getThreadLocal().writeValueAsBytes(localPolicies.get());
        } catch (Throwable t) {
            // Failed to serialize to json
            future.completeExceptionally(t);
            return;
        }

        ZkUtils.asyncCreateFullPathOptimistic(cache.getZooKeeper(), path, content, Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT, (rc, path1, ctx, name) -> {
                    if (rc == KeeperException.Code.OK.intValue()
                            || rc == KeeperException.Code.NODEEXISTS.intValue()) {
                        LOG.info("Successfully copyied bundles data to local zk at {}", path);
                        future.complete(localPolicies);
                    } else {
                        LOG.error("Failed to create policies for {} in local zookeeper: {}", path,
                                KeeperException.Code.get(rc));
                        future.completeExceptionally(new PulsarServerException(KeeperException.create(rc)));
                    }
                }, null);
    }).exceptionally(ex -> {
        future.completeExceptionally(ex);
        return null;
    });

    return future;
}