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:org.apache.bookkeeper.zookeeper.ZooWorker.java

License:Apache License

public boolean allowRetry(int rc) {
    elapsedTimeMs = MathUtils.elapsedMSec(startTimeNanos);
    if (!ZooWorker.isRecoverableException(rc)) {
        if (KeeperException.Code.OK.intValue() == rc) {
            statsLogger.registerSuccessfulEvent(MathUtils.elapsedMicroSec(startTimeNanos),
                    TimeUnit.MICROSECONDS);
        } else {//  w w  w. jav  a 2  s  . c o  m
            statsLogger.registerFailedEvent(MathUtils.elapsedMicroSec(startTimeNanos), TimeUnit.MICROSECONDS);
        }
        return false;
    }
    ++attempts;
    return retryPolicy.allowRetry(attempts, elapsedTimeMs);
}

From source file:org.apache.curator.framework.imps.CreateBuilderImpl.java

License:Apache License

@Override
public void performBackgroundOperation(final OperationAndData<PathAndBytes> operationAndData) throws Exception {
    try {//w w  w .  j a v a2  s.  c o  m
        final OperationTrace trace = client.getZookeeperClient()
                .startAdvancedTracer("CreateBuilderImpl-Background");
        final byte[] data = operationAndData.getData().getData();
        client.getZooKeeper().create(operationAndData.getData().getPath(), data,
                acling.getAclList(operationAndData.getData().getPath()), createMode,
                new AsyncCallback.StringCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name) {
                        trace.setReturnCode(rc).setRequestBytesLength(data).setPath(path).commit();

                        if ((rc == KeeperException.Code.NONODE.intValue()) && createParentsIfNeeded) {
                            backgroundCreateParentsThenNode(client, operationAndData,
                                    operationAndData.getData().getPath(), backgrounding,
                                    createParentsAsContainers);
                        } else {
                            sendBackgroundResponse(rc, path, ctx, name, operationAndData);
                        }
                    }
                }, backgrounding.getContext());
    } catch (Throwable e) {
        backgrounding.checkError(e);
    }
}

From source file:org.apache.curator.framework.imps.CreateBuilderImpl.java

License:Apache License

private void pathInBackground(final String path, final byte[] data, final String givenPath) {
    final AtomicBoolean firstTime = new AtomicBoolean(true);
    OperationAndData<PathAndBytes> operationAndData = new OperationAndData<PathAndBytes>(this,
            new PathAndBytes(path, data), backgrounding.getCallback(),
            new OperationAndData.ErrorCallback<PathAndBytes>() {
                public void retriesExhausted(OperationAndData<PathAndBytes> operationAndData) {
                    if (doProtected) {
                        // all retries have failed, findProtectedNodeInForeground(..) included, schedule a clean up
                        new FindAndDeleteProtectedNodeInBackground(client,
                                ZKPaths.getPathAndNode(path).getPath(), protectedId).execute();
                        // assign a new id if this builder is used again later
                        protectedId = UUID.randomUUID().toString();
                    }//  w  w w  . j ava2  s.c  om
                }
            }, backgrounding.getContext()) {
        @Override
        void callPerformBackgroundOperation() throws Exception {
            boolean callSuper = true;
            boolean localFirstTime = firstTime.getAndSet(false) && !debugForceFindProtectedNode;
            if (!localFirstTime && doProtected) {
                debugForceFindProtectedNode = false;
                String createdPath = null;
                try {
                    createdPath = findProtectedNodeInForeground(path);
                } catch (KeeperException.ConnectionLossException e) {
                    sendBackgroundResponse(KeeperException.Code.CONNECTIONLOSS.intValue(), path,
                            backgrounding.getContext(), null, this);
                    callSuper = false;
                }
                if (createdPath != null) {
                    try {
                        sendBackgroundResponse(KeeperException.Code.OK.intValue(), createdPath,
                                backgrounding.getContext(), createdPath, this);
                    } catch (Exception e) {
                        ThreadUtils.checkInterrupted(e);
                        client.logError("Processing protected create for path: " + givenPath, e);
                    }
                    callSuper = false;
                }
            }

            if (failNextCreateForTesting) {
                pathInForeground(path, data); // simulate success on server without notification to client
                failNextCreateForTesting = false;
                throw new KeeperException.ConnectionLossException();
            }

            if (callSuper) {
                super.callPerformBackgroundOperation();
            }
        }
    };
    client.processBackgroundOperation(operationAndData, null);
}

From source file:org.apache.curator.framework.imps.CuratorFrameworkImpl.java

License:Apache License

Watcher.Event.KeeperState codeToState(KeeperException.Code code) {
    switch (code) {
    case AUTHFAILED:
    case NOAUTH: {
        return Watcher.Event.KeeperState.AuthFailed;
    }//from w ww  .j a v a  2 s.  co m

    case CONNECTIONLOSS:
    case OPERATIONTIMEOUT: {
        return Watcher.Event.KeeperState.Disconnected;
    }

    case SESSIONEXPIRED: {
        return Watcher.Event.KeeperState.Expired;
    }

    case OK:
    case SESSIONMOVED: {
        return Watcher.Event.KeeperState.SyncConnected;
    }
    }
    return Watcher.Event.KeeperState.fromInt(-1);
}

From source file:org.apache.curator.framework.imps.CuratorFrameworkImpl.java

License:Apache License

@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
private <DATA_TYPE> boolean checkBackgroundRetry(OperationAndData<DATA_TYPE> operationAndData,
        CuratorEvent event) {/* ww  w .ja  v a  2 s .  c om*/
    boolean doRetry = false;
    if (client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(),
            operationAndData.getElapsedTimeMs(), operationAndData)) {
        doRetry = true;
    } else {
        if (operationAndData.getErrorCallback() != null) {
            operationAndData.getErrorCallback().retriesExhausted(operationAndData);
        }

        if (operationAndData.getCallback() != null) {
            sendToBackgroundCallback(operationAndData, event);
        }

        KeeperException.Code code = KeeperException.Code.get(event.getResultCode());
        Exception e = null;
        try {
            e = (code != null) ? KeeperException.create(code) : null;
        } catch (Throwable t) {
            ThreadUtils.checkInterrupted(t);
        }
        if (e == null) {
            e = new Exception("Unknown result codegetResultCode()");
        }

        validateConnection(codeToState(code));
        logError("Background operation retry gave up", e);
    }
    return doRetry;
}

From source file:org.apache.curator.framework.imps.CuratorFrameworkImpl.java

License:Apache License

private void performBackgroundOperation(OperationAndData<?> operationAndData) {
    try {/*from ww w  . j  av  a 2s.  c  o  m*/
        if (client.isConnected()) {
            operationAndData.callPerformBackgroundOperation();
        } else {
            client.getZooKeeper(); // important - allow connection resets, timeouts, etc. to occur
            if (operationAndData.getElapsedTimeMs() >= client.getConnectionTimeoutMs()) {
                throw new CuratorConnectionLossException();
            }
            operationAndData.sleepFor(1, TimeUnit.SECONDS);
            queueOperation(operationAndData);
        }
    } catch (Throwable e) {
        ThreadUtils.checkInterrupted(e);

        /**
         * Fix edge case reported as CURATOR-52. ConnectionState.checkTimeouts() throws KeeperException.ConnectionLossException
         * when the initial (or previously failed) connection cannot be re-established. This needs to be run through the retry policy
         * and callbacks need to get invoked, etc.
         */
        if (e instanceof CuratorConnectionLossException) {
            WatchedEvent watchedEvent = new WatchedEvent(Watcher.Event.EventType.None,
                    Watcher.Event.KeeperState.Disconnected, null);
            CuratorEvent event = new CuratorEventImpl(this, CuratorEventType.WATCHED,
                    KeeperException.Code.CONNECTIONLOSS.intValue(), null, null, operationAndData.getContext(),
                    null, null, null, watchedEvent, null);
            if (checkBackgroundRetry(operationAndData, event)) {
                queueOperation(operationAndData);
            } else {
                logError("Background retry gave up", e);
            }
        } else {
            handleBackgroundOperationException(operationAndData, e);
        }
    }
}

From source file:org.apache.curator.framework.imps.DeleteBuilderImpl.java

License:Apache License

@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception {
    try {/* w w  w . ja va2 s .  com*/
        final OperationTrace trace = client.getZookeeperClient()
                .startAdvancedTracer("DeleteBuilderImpl-Background");
        client.getZooKeeper().delete(operationAndData.getData(), version, new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx) {
                trace.setReturnCode(rc).setPath(path).commit();
                if ((rc == KeeperException.Code.NOTEMPTY.intValue()) && deletingChildrenIfNeeded) {
                    backgroundDeleteChildrenThenNode(operationAndData);
                } else {
                    CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.DELETE, rc, path, null,
                            ctx, null, null, null, null, null);
                    client.processBackgroundOperation(operationAndData, event);
                }
            }
        }, backgrounding.getContext());
    } catch (Throwable e) {
        backgrounding.checkError(e);
    }
}

From source file:org.apache.curator.framework.imps.EnsembleTracker.java

License:Apache License

private void reset() throws Exception {
    if ((client.getState() == CuratorFrameworkState.STARTED) && (state.get() == State.STARTED)) {
        BackgroundCallback backgroundCallback = new BackgroundCallback() {
            @Override/*from  w w  w.j a va2  s.c  o m*/
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                outstanding.decrementAndGet();
                if ((event.getType() == CuratorEventType.GET_CONFIG)
                        && (event.getResultCode() == KeeperException.Code.OK.intValue())) {
                    processConfigData(event.getData());
                }
            }
        };
        outstanding.incrementAndGet();
        try {
            client.getConfig().usingWatcher(this).inBackground(backgroundCallback).forEnsemble();
            outstanding.incrementAndGet(); // finally block will decrement
        } finally {
            outstanding.decrementAndGet();
        }
    }
}

From source file:org.apache.curator.framework.imps.FindAndDeleteProtectedNodeInBackground.java

License:Apache License

@Override
public void performBackgroundOperation(final OperationAndData<Void> operationAndData) throws Exception {
    final OperationTrace trace = client.getZookeeperClient()
            .startAdvancedTracer("FindAndDeleteProtectedNodeInBackground");
    AsyncCallback.Children2Callback callback = new AsyncCallback.Children2Callback() {
        @Override/*from   w w  w.j a va  2 s  . com*/
        public void processResult(int rc, String path, Object o, List<String> strings, Stat stat) {
            trace.setReturnCode(rc).setPath(path).setStat(stat).commit();

            if (debugInsertError.compareAndSet(true, false)) {
                rc = KeeperException.Code.CONNECTIONLOSS.intValue();
            }

            if (rc == KeeperException.Code.OK.intValue()) {
                final String node = CreateBuilderImpl.findNode(strings, "/", protectedId); // due to namespacing, don't let CreateBuilderImpl.findNode adjust the path
                if (node != null) {
                    try {
                        String deletePath = client
                                .unfixForNamespace(ZKPaths.makePath(namespaceAdjustedParentPath, node));
                        client.delete().guaranteed().inBackground().forPath(deletePath);
                    } catch (Exception e) {
                        ThreadUtils.checkInterrupted(e);
                        log.error("Could not start guaranteed delete for node: " + node);
                        rc = KeeperException.Code.CONNECTIONLOSS.intValue();
                    }
                }
            }

            if (rc != KeeperException.Code.OK.intValue()) {
                CuratorEventImpl event = new CuratorEventImpl(client, CuratorEventType.CHILDREN, rc, path, null,
                        o, stat, null, strings, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        }
    };
    client.getZooKeeper().getChildren(namespaceAdjustedParentPath, false, callback, null);
}

From source file:org.apache.curator.framework.imps.GetDataBuilderImpl.java

License:Apache License

@Override
public void performBackgroundOperation(final OperationAndData<String> operationAndData) throws Exception {
    try {/*from  w w w.j  a  v  a2s . com*/
        final OperationTrace trace = client.getZookeeperClient()
                .startAdvancedTracer("GetDataBuilderImpl-Background");
        AsyncCallback.DataCallback callback = new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                trace.setReturnCode(rc).setResponseBytesLength(data).setPath(path)
                        .setWithWatcher(watching.getWatcher() != null).setStat(stat).commit();
                if (decompress && (data != null)) {
                    try {
                        data = client.getCompressionProvider().decompress(path, data);
                    } catch (Exception e) {
                        ThreadUtils.checkInterrupted(e);
                        log.error("Decompressing for path: " + path, e);
                        rc = KeeperException.Code.DATAINCONSISTENCY.intValue();
                    }
                }
                CuratorEvent event = new CuratorEventImpl(client, CuratorEventType.GET_DATA, rc, path, null,
                        ctx, stat, data, null, null, null);
                client.processBackgroundOperation(operationAndData, event);
            }
        };
        if (watching.isWatched()) {
            client.getZooKeeper().getData(operationAndData.getData(), true, callback,
                    backgrounding.getContext());
        } else {
            client.getZooKeeper().getData(operationAndData.getData(), watching.getWatcher(), callback,
                    backgrounding.getContext());
        }
    } catch (Throwable e) {
        backgrounding.checkError(e);
    }
}