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

@Deprecated
public static KeeperException create(int code, String path) 

Source Link

Usage

From source file:org.apache.hadoop.contrib.bkjournal.BookKeeperJournalManager.java

License:Apache License

/**
 * Pre-creating bookkeeper metadata path in zookeeper.
 *//* w  ww . j  a v  a2 s  . c  o  m*/
private void prepareBookKeeperEnv() throws IOException {
    // create bookie available path in zookeeper if it doesn't exists
    final String zkAvailablePath = conf.get(BKJM_ZK_LEDGERS_AVAILABLE_PATH,
            BKJM_ZK_LEDGERS_AVAILABLE_PATH_DEFAULT);
    final CountDownLatch zkPathLatch = new CountDownLatch(1);

    final AtomicBoolean success = new AtomicBoolean(false);
    StringCallback callback = new StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            if (KeeperException.Code.OK.intValue() == rc || KeeperException.Code.NODEEXISTS.intValue() == rc) {
                LOG.info("Successfully created bookie available path : " + zkAvailablePath);
                success.set(true);
            } else {
                KeeperException.Code code = KeeperException.Code.get(rc);
                LOG.error("Error : " + KeeperException.create(code, path).getMessage()
                        + ", failed to create bookie available path : " + zkAvailablePath);
            }
            zkPathLatch.countDown();
        }
    };
    ZkUtils.asyncCreateFullPathOptimistic(zkc, zkAvailablePath, new byte[0], Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT, callback, null);

    try {
        if (!zkPathLatch.await(zkc.getSessionTimeout(), TimeUnit.MILLISECONDS) || !success.get()) {
            throw new IOException("Couldn't create bookie available path :" + zkAvailablePath + ", timed out "
                    + zkc.getSessionTimeout() + " millis");
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Interrupted when creating the bookie available path : " + zkAvailablePath, e);
    }
}

From source file:org.apache.hadoop.hbase.zookeeper.ZKUtil.java

License:Apache License

/**
 * Creates the specified node with the specified data and watches it.
 *
 * <p>Throws an exception if the node already exists.
 *
 * <p>The node created is persistent and open access.
 *
 * <p>Returns the version number of the created node if successful.
 *
 * @param zkw zk reference/*w  w w .ja  v  a 2 s  .c o m*/
 * @param znode path of node to create
 * @param data data of node to create
 * @return version of node created
 * @throws KeeperException if unexpected zookeeper exception
 * @throws KeeperException.NodeExistsException if node already exists
 */
public static int createAndWatch(ZooKeeperWatcher zkw, String znode, byte[] data)
        throws KeeperException, KeeperException.NodeExistsException {
    try {
        zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode), CreateMode.PERSISTENT);
        Stat stat = zkw.getRecoverableZooKeeper().exists(znode, zkw);
        if (stat == null) {
            // Likely a race condition. Someone deleted the znode.
            throw KeeperException.create(KeeperException.Code.SYSTEMERROR,
                    "ZK.exists returned null (i.e.: znode does not exist) for znode=" + znode);
        }
        return stat.getVersion();
    } catch (InterruptedException e) {
        zkw.interruptedException(e);
        return -1;
    }
}

From source file:org.apache.hadoop.hdfs.server.namenode.bookkeeper.BookKeeperJournalManager.java

License:Apache License

/**
 * Create parent ZNode under which available BookKeeper bookie servers will
 * register themselves. Will create parent ZNodes for that path as well.
 * @see ZkUtils#createFullPathOptimistic(ZooKeeper, String, byte[], List, CreateMode, StringCallback, Object)
 * @param availablePath Full ZooKeeper path for bookies to register
 *                      themselves./*from   ww  w.java2s  .  c o  m*/
 * @param zooKeeper Fully instantiated ZooKeeper instance.
 * @throws IOException If we are unable to successfully create the path
 *                     during the time specified as the ZooKeeper session
 *                     timeout.
 */
@VisibleForTesting
public static void prepareBookKeeperEnv(final String availablePath, ZooKeeper zooKeeper) throws IOException {
    final CountDownLatch availablePathLatch = new CountDownLatch(1);
    StringCallback cb = new StringCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, String name) {
            if (Code.OK.intValue() == rc || Code.NODEEXISTS.intValue() == rc) {
                availablePathLatch.countDown();
                LOG.info("Successfully created bookie available path:" + availablePath);
            } else {
                Code code = Code.get(rc);
                LOG.error("Failed to create available bookie path (" + availablePath + ")",
                        KeeperException.create(code, path));
            }
        }
    };
    ZkUtils.createFullPathOptimistic(zooKeeper, availablePath, new byte[0], Ids.OPEN_ACL_UNSAFE,
            CreateMode.PERSISTENT, cb, null);
    try {
        int timeoutMs = zooKeeper.getSessionTimeout();
        if (!availablePathLatch.await(timeoutMs, TimeUnit.MILLISECONDS)) {
            throw new IOException("Couldn't create the bookie available path : " + availablePath
                    + ", timed out after " + timeoutMs + " ms.");
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new IOException("Interrupted when creating the bookie available " + "path: " + availablePath, e);
    }
}

From source file:org.apache.hedwig.zookeeper.ZkUtils.java

License:Apache License

public static void createFullPathOptimistic(final ZooKeeper zk, final String originalPath, final byte[] data,
        final List<ACL> acl, final CreateMode createMode)
        throws KeeperException, IOException, InterruptedException {
    final SyncObject syncObj = new SyncObject();

    createFullPathOptimistic(zk, originalPath, data, acl, createMode, new SafeAsyncZKCallback.StringCallback() {
        @Override/*from  ww w  . ja  v a 2 s.  c o m*/
        public void safeProcessResult(final int rc, String path, Object ctx, String name) {
            synchronized (syncObj) {
                syncObj.rc = rc;
                syncObj.path = path;
                syncObj.called = true;
                syncObj.notify();
            }
        }
    }, syncObj);

    synchronized (syncObj) {
        while (!syncObj.called) {
            syncObj.wait();
        }
    }

    if (Code.OK.intValue() != syncObj.rc) {
        throw KeeperException.create(KeeperException.Code.get(syncObj.rc), syncObj.path);
    }
}

From source file:org.apache.hedwig.zookeeper.ZkUtils.java

License:Apache License

public static KeeperException logErrorAndCreateZKException(String msg, String path, int rc) {
    KeeperException ke = KeeperException.create(Code.get(rc), path);
    logger.error(msg + ",zkPath: " + path, ke);
    return ke;/*from  w ww.java 2  s .  com*/
}

From source file:org.apache.pulsar.broker.admin.impl.PersistentTopicsBase.java

License:Apache License

private CompletableFuture<Void> updatePartitionedTopic(TopicName topicName, int numPartitions) {
    final String path = ZkAdminPaths.partitionedTopicPath(topicName);

    CompletableFuture<Void> updatePartition = new CompletableFuture<>();
    createSubscriptions(topicName, numPartitions).thenAccept(res -> {
        try {/*from w  w  w. j  av  a 2 s  .  c om*/
            byte[] data = jsonMapper().writeValueAsBytes(new PartitionedTopicMetadata(numPartitions));
            globalZk().setData(path, data, -1, (rc, path1, ctx, stat) -> {
                if (rc == KeeperException.Code.OK.intValue()) {
                    updatePartition.complete(null);
                } else {
                    updatePartition.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc),
                            "failed to create update partitions"));
                }
            }, null);
        } catch (Exception e) {
            updatePartition.completeExceptionally(e);
        }
    }).exceptionally(ex -> {
        updatePartition.completeExceptionally(ex);
        return null;
    });

    return updatePartition;
}

From source file:org.apache.pulsar.broker.admin.PersistentTopics.java

License:Apache License

private CompletableFuture<Void> updatePartitionedTopic(DestinationName dn, int numPartitions) {
    String path = path(PARTITIONED_TOPIC_PATH_ZNODE, dn.getProperty(), dn.getCluster(),
            dn.getNamespacePortion(), domain(), dn.getEncodedLocalName());

    CompletableFuture<Void> updatePartition = new CompletableFuture<>();
    createSubscriptions(dn, numPartitions).thenAccept(res -> {
        try {//from  www  .  j  ava  2 s.  com
            byte[] data = jsonMapper().writeValueAsBytes(new PartitionedTopicMetadata(numPartitions));
            globalZk().setData(path, data, -1, (rc, path1, ctx, stat) -> {
                if (rc == KeeperException.Code.OK.intValue()) {
                    updatePartition.complete(null);
                } else {
                    updatePartition.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc),
                            "failed to create update partitions"));
                }
            }, null);
        } catch (Exception e) {
            updatePartition.completeExceptionally(e);
        }
    }).exceptionally(ex -> {
        updatePartition.completeExceptionally(ex);
        return null;
    });

    return updatePartition;
}

From source file:org.apache.twill.internal.AbstractZKServiceController.java

License:Apache License

protected final void watchInstanceNode() {
    if (!shouldProcessZKEvent()) {
        return;//  w  w w  .ja  v a 2 s.co m
    }
    Futures.addCallback(zkClient.getData(getInstancePath(), new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (!shouldProcessZKEvent()) {
                return;
            }
            switch (event.getType()) {
            case NodeDataChanged:
                watchInstanceNode();
                break;
            case NodeDeleted:
                instanceNodeFailed(KeeperException.create(KeeperException.Code.NONODE, getInstancePath()));
                break;
            default:
                LOG.info("Ignore ZK event for instance node: {}", event);
            }
        }
    }), instanceNodeDataCallback, Threads.SAME_THREAD_EXECUTOR);
}

From source file:org.midonet.cluster.backend.zookeeper.ZkDirectory.java

License:Apache License

@Override
public void asyncAdd(String relativePath, final byte[] data, CreateMode mode,
        final DirectoryCallback<String> cb, Object context) {

    final String absPath = getAbsolutePath(relativePath);

    zk.create(absPath, data, acl, mode, new AsyncCallback.StringCallback() {
        @Override//from w w  w.j  a  v a  2s .  com
        public void processResult(int rc, String path, Object ctx, String name) {
            if (rc == KeeperException.Code.OK.intValue()) {
                cb.onSuccess(name.substring(basePath.length()), null, ctx);
            } else {
                cb.onError(KeeperException.create(KeeperException.Code.get(rc), path), ctx);
            }
        }
    }, context);
}

From source file:org.midonet.cluster.backend.zookeeper.ZkDirectory.java

License:Apache License

@Override
public void asyncGet(String relativePath, DirectoryCallback<byte[]> dataCallback, Watcher watcher,
        Object context) {/*from   w ww  .j a va  2 s.  c o  m*/
    zk.getData(getAbsolutePath(relativePath), watcher, new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (rc == KeeperException.Code.OK.intValue()) {
                dataCallback.onSuccess(data, stat, ctx);
            } else {
                dataCallback.onError(KeeperException.create(KeeperException.Code.get(rc), path), ctx);
            }
        }
    }, context);
}