Example usage for org.apache.zookeeper KeeperException code

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

Introduction

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

Prototype

Code code

To view the source code for org.apache.zookeeper KeeperException code.

Click Source Link

Usage

From source file:com.cloudera.flume.master.ZKClient.java

License:Apache License

/**
 * Ensure that the given path is deleted, whether or not we did it.
 *//*ww w .  ja v a 2  s .  c o  m*/
public void ensureDeleted(final String path, final int version)
        throws KeeperException, IOException, InterruptedException {
    Preconditions.checkArgument(zk != null);
    final FixedRetryPolicy policy = new FixedRetryPolicy(3);
    ZKRetryable<Void> retry = new ZKRetryable<Void>() {
        public boolean doTry() throws Exception {
            try {
                zk.delete(path, version);
                return true;
            } catch (KeeperException k) {
                if (k.code() == Code.NONODE) {
                    return true;
                }
                defaultHandleException(k);
            }
            return false;
        }
    };

    ZKRetryHarness harness = new ZKRetryHarness(retry, policy);
    harness.attempt();
}

From source file:com.continuuity.weave.internal.state.ZKServiceDecorator.java

License:Open Source License

@Override
protected void doStart() {
    callbackExecutor = Executors.newSingleThreadExecutor(Threads.createDaemonThreadFactory("message-callback"));
    zkClient.addConnectionWatcher(createConnectionWatcher());

    // Create nodes for states and messaging
    StateNode stateNode = new StateNode(ServiceController.State.STARTING, null);

    final List<OperationFuture<String>> futures = ImmutableList.of(
            zkClient.create(getZKPath("messages"), null, CreateMode.PERSISTENT),
            zkClient.create(getZKPath("state"), encodeStateNode(stateNode), CreateMode.PERSISTENT));
    final ListenableFuture<List<String>> createFuture = Futures.successfulAsList(futures);

    createFuture.addListener(new Runnable() {
        @Override// w w  w .  jav  a  2 s  .co  m
        public void run() {
            try {
                for (OperationFuture<String> future : futures) {
                    try {
                        future.get();
                    } catch (ExecutionException e) {
                        Throwable cause = e.getCause();
                        if (cause instanceof KeeperException
                                && ((KeeperException) cause).code() == KeeperException.Code.NODEEXISTS) {
                            LOG.warn("Node already exists: {}", future.getRequestPath());
                        } else {
                            throw Throwables.propagate(cause);
                        }
                    }
                }

                // Starts the decorated service
                decoratedService.addListener(createListener(), Threads.SAME_THREAD_EXECUTOR);
                decoratedService.start();
            } catch (Exception e) {
                notifyFailed(e);
            }
        }
    }, Threads.SAME_THREAD_EXECUTOR);
}

From source file:com.continuuity.weave.internal.zookeeper.DefaultZKClientService.java

License:Open Source License

private OperationFuture<String> doCreate(final String path, @Nullable final byte[] data,
        final CreateMode createMode, final boolean createParent, final boolean ignoreNodeExists) {
    final SettableOperationFuture<String> createFuture = SettableOperationFuture.create(path, eventExecutor);
    getZooKeeper().create(path, data, aclMapper.apply(path), createMode, Callbacks.STRING, createFuture);
    if (!createParent) {
        return createFuture;
    }//from ww w  .ja  v  a  2s  .  co m

    // If create parent is request, return a different future
    final SettableOperationFuture<String> result = SettableOperationFuture.create(path, eventExecutor);
    // Watch for changes in the original future
    Futures.addCallback(createFuture, new FutureCallback<String>() {
        @Override
        public void onSuccess(String path) {
            // Propagate if creation was successful
            result.set(path);
        }

        @Override
        public void onFailure(Throwable t) {
            // See if the failure can be handled
            if (updateFailureResult(t, result, path, ignoreNodeExists)) {
                return;
            }
            // Create the parent node
            String parentPath = getParent(path);
            if (parentPath.isEmpty()) {
                result.setException(t);
                return;
            }
            // Watch for parent creation complete
            Futures.addCallback(doCreate(parentPath, null, CreateMode.PERSISTENT, createParent, true),
                    new FutureCallback<String>() {
                        @Override
                        public void onSuccess(String parentPath) {
                            // Create the requested path again
                            Futures.addCallback(doCreate(path, data, createMode, false, ignoreNodeExists),
                                    new FutureCallback<String>() {
                                        @Override
                                        public void onSuccess(String pathResult) {
                                            result.set(pathResult);
                                        }

                                        @Override
                                        public void onFailure(Throwable t) {
                                            // handle the failure
                                            updateFailureResult(t, result, path, ignoreNodeExists);
                                        }
                                    });
                        }

                        @Override
                        public void onFailure(Throwable t) {
                            result.setException(t);
                        }
                    });
        }

        /**
         * Updates the result future based on the given {@link Throwable}.
         * @param t Cause of the failure
         * @param result Future to be updated
         * @param path Request path for the operation
         * @return {@code true} if it is a failure, {@code false} otherwise.
         */
        private boolean updateFailureResult(Throwable t, SettableOperationFuture<String> result, String path,
                boolean ignoreNodeExists) {
            // Propagate if there is error
            if (!(t instanceof KeeperException)) {
                result.setException(t);
                return true;
            }
            KeeperException.Code code = ((KeeperException) t).code();
            // Node already exists, simply return success if it allows for ignoring node exists (for parent node creation).
            if (ignoreNodeExists && code == KeeperException.Code.NODEEXISTS) {
                // The requested path could be used because it only applies to non-sequential node
                result.set(path);
                return false;
            }
            if (code != KeeperException.Code.NONODE) {
                result.setException(t);
                return true;
            }
            return false;
        }

        /**
         * Gets the parent of the given path.
         * @param path Path for computing its parent
         * @return Parent of the given path, or empty string if the given path is the root path already.
         */
        private String getParent(String path) {
            String parentPath = path.substring(0, path.lastIndexOf('/'));
            return (parentPath.isEmpty() && !"/".equals(path)) ? "/" : parentPath;
        }
    });

    return result;
}

From source file:com.continuuity.weave.internal.zookeeper.RetryUtils.java

License:Open Source License

/**
 * Tells if a given operation error code can be retried or not.
 * @param code The error code of the operation.
 * @return {@code true} if the operation can be retried.
 *///from w  w w  . j  a  v a 2s.  co m
public static boolean canRetry(KeeperException.Code code) {
    return (code == KeeperException.Code.CONNECTIONLOSS || code == KeeperException.Code.OPERATIONTIMEOUT
            || code == KeeperException.Code.SESSIONEXPIRED || code == KeeperException.Code.SESSIONMOVED);
}

From source file:com.continuuity.weave.internal.zookeeper.RewatchOnExpireWatcher.java

License:Open Source License

private void children() {
    Futures.addCallback(client.getChildren(path, this), new FutureCallback<NodeChildren>() {
        @Override/*from  w w  w . ja va2 s  . c o  m*/
        public void onSuccess(NodeChildren result) {
            Object oldResult = lastResult.getReference();
            lastResult.compareAndSet(oldResult, null, true, false);

            if (result.equals(oldResult)) {
                return;
            }

            if (!(oldResult instanceof NodeChildren)) {
                // Something very wrong
                LOG.error("The same watcher has been used for different event type.");
                return;
            }

            NodeChildren oldNodeChildren = (NodeChildren) oldResult;
            if (!result.getChildren().equals(oldNodeChildren.getChildren())) {
                process(new WatchedEvent(Event.EventType.NodeChildrenChanged, Event.KeeperState.SyncConnected,
                        path));
            } else {
                process(new WatchedEvent(Event.EventType.NodeDataChanged, Event.KeeperState.SyncConnected,
                        path));
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (RetryUtils.canRetry(t)) {
                children();
                return;
            }

            lastResult.set(null, false);
            if (t instanceof KeeperException) {
                KeeperException.Code code = ((KeeperException) t).code();
                if (code == KeeperException.Code.NONODE) {
                    // Node deleted
                    process(new WatchedEvent(Event.EventType.NodeDeleted, Event.KeeperState.SyncConnected,
                            path));
                    return;
                }
            }
            LOG.error("Fail to re-set watch on getChildren for path " + path, t);
        }
    });
}

From source file:com.continuuity.weave.internal.zookeeper.RewatchOnExpireWatcher.java

License:Open Source License

private void data() {
    Futures.addCallback(client.getData(path, this), new FutureCallback<NodeData>() {
        @Override//from  w ww . j  av  a 2  s  . c  o  m
        public void onSuccess(NodeData result) {
            Object oldResult = lastResult.getReference();
            lastResult.compareAndSet(oldResult, null, true, false);

            if (!result.equals(oldResult)) {
                // Whenever something changed, treated it as data changed.
                process(new WatchedEvent(Event.EventType.NodeDataChanged, Event.KeeperState.SyncConnected,
                        path));
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (RetryUtils.canRetry(t)) {
                data();
                return;
            }

            lastResult.set(null, false);
            if (t instanceof KeeperException) {
                KeeperException.Code code = ((KeeperException) t).code();
                if (code == KeeperException.Code.NONODE) {
                    // Node deleted
                    process(new WatchedEvent(Event.EventType.NodeDeleted, Event.KeeperState.SyncConnected,
                            path));
                    return;
                }
            }
            LOG.error("Fail to re-set watch on getData for path " + path, t);
        }
    });
}

From source file:com.continuuity.weave.yarn.YarnWeaveRunnerService.java

License:Open Source License

@Override
protected void startUp() throws Exception {
    yarnClient.start();/*w w w .  j  a  v a 2 s .c  o m*/
    zkClientService.startAndWait();
    try {
        // Create the root node, so that the namespace root would get created if it is missing
        zkClientService.create("/", null, CreateMode.PERSISTENT).get();
    } catch (Exception e) {
        // If the exception is caused by node exists, then it's ok. Otherwise propagate the exception.
        Throwable cause = e.getCause();
        if (!(cause instanceof KeeperException)
                || ((KeeperException) cause).code() != KeeperException.Code.NODEEXISTS) {
            throw Throwables.propagate(e);
        }
    }
}

From source file:com.continuuity.weave.zookeeper.ZKOperations.java

License:Open Source License

private static <T> void watchChanges(final Operation<T> operation, final String path,
        final Callback<T> callback, final AtomicBoolean cancelled) {
    Futures.addCallback(operation.exec(path, new Watcher() {
        @Override/*from  ww  w .j  ava 2 s .c om*/
        public void process(WatchedEvent event) {
            if (!cancelled.get()) {
                watchChanges(operation, path, callback, cancelled);
            }
        }
    }), new FutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            if (!cancelled.get()) {
                callback.updated(result);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            if (t instanceof KeeperException && ((KeeperException) t).code() == KeeperException.Code.NONODE) {
                final SettableFuture<String> existCompletion = SettableFuture.create();
                existCompletion.addListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            if (!cancelled.get()) {
                                watchChanges(operation, existCompletion.get(), callback, cancelled);
                            }
                        } catch (Exception e) {
                            LOG.error("Failed to watch children for path " + path, e);
                        }
                    }
                }, Threads.SAME_THREAD_EXECUTOR);
                watchExists(operation.getZKClient(), path, existCompletion);
                return;
            }
            LOG.error("Failed to watch data for path " + path + " " + t, t);
        }
    });
}

From source file:com.deem.zkui.utils.ZooKeeperUtil.java

License:Open Source License

private void createIfDoesntExist(String path, byte[] data, boolean force, ZooKeeper zooKeeper)
        throws InterruptedException, KeeperException {
    try {/* ww w. ja  v a  2 s  .  co  m*/
        zooKeeper.create(path, data, defaultAcl(), CreateMode.PERSISTENT);
    } catch (KeeperException ke) {
        //Explicit Overwrite
        if (KeeperException.Code.NODEEXISTS.equals(ke.code())) {
            if (force) {
                zooKeeper.delete(path, -1);
                zooKeeper.create(path, data, defaultAcl(), CreateMode.PERSISTENT);
            }
        } else {
            throw ke;
        }
    }
}

From source file:com.edmunds.etm.common.impl.UrlTokenRepository.java

License:Apache License

/**
 * Gets the UrlToken with the specified name.
 *
 * @param name name of the token to fetch
 * @return the requested token or null if not found
 *///from  w ww . jav a  2s.  c  om
public UrlToken getToken(String name) {
    byte[] data;
    try {
        data = connection.getData(controllerPaths.getUrlToken(name), null, null);
    } catch (KeeperException e) {
        if (e.code() == Code.NONODE) {
            return null;
        } else {
            logger.error(String.format("Error fetching URL token: %s", name), e);
            return null;
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    try {
        UrlTokenDto dto = objectSerializer.readValue(data, UrlTokenDto.class);
        return UrlToken.readDto(dto);
    } catch (IOException e) {
        return null;
    }
}