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.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

@Override
public void put(final String prop, final T value, final Callback<None> callback) {
    _putStats.inc();//from  www  .  j  ava 2s. c om

    trace(_log, "put ", prop, ": ", value);

    final String path = getPath(prop);
    _zkConn.ensurePersistentNodeExists(path, new Callback<None>() {
        @Override
        public void onSuccess(None none) {
            final String ephemeralPath = path + "/ephemoral-";

            AsyncCallback.StringCallback stringCallback = new AsyncCallback.StringCallback() {
                @Override
                public void processResult(int rc, String path, Object ctx, String name) {
                    KeeperException.Code code = KeeperException.Code.get(rc);
                    switch (code) {
                    case OK:
                        callback.onSuccess(None.none());
                        break;
                    default:
                        callback.onError(KeeperException.create(code));
                        break;
                    }
                }
            };

            if (_zk instanceof RetryZooKeeper) {
                ((RetryZooKeeper) _zk).createUniqueSequential(ephemeralPath, _serializer.toBytes(value),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, stringCallback, null);
            } else {
                _zk.create(ephemeralPath, _serializer.toBytes(value), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL, stringCallback, null);
            }
        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    });
}

From source file:com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

public void removePartial(final String prop, final T value, final Callback<None> callback) {
    final String path = getPath(prop);

    trace(_log, "remove partial ", prop, ": ", value);

    final Callback<Map<String, T>> childrenCallback = new Callback<Map<String, T>>() {
        @Override//w w  w .ja  va 2  s  . co  m
        public void onSuccess(Map<String, T> children) {
            String delete = _merger.unmerge(prop, value, children);
            _zkConn.removeNodeUnsafe(path + "/" + delete.toString(), callback);

        }

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }
    };

    _zk.getChildren(path, false, new AsyncCallback.ChildrenCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<String> children) {
            KeeperException.Code code = KeeperException.Code.get(rc);
            switch (code) {
            case OK:
                if (children.size() > 0) {
                    ChildCollector collector = new ChildCollector(children.size(), childrenCallback);
                    for (String child : children) {
                        _zk.getData(path + "/" + child, false, collector, null);
                    }
                } else {
                    _log.warn("Ignoring request to removePartial with no children: {}", path);
                    callback.onSuccess(None.none());
                }
                break;
            default:
                callback.onError(KeeperException.create(code));
                break;
            }

        }
    }, null);
}

From source file:com.linkedin.d2.discovery.stores.zk.ZooKeeperEphemeralStore.java

License:Apache License

@Override
public void get(final String listenTo, final Callback<T> callback) {
    String path = getPath(listenTo);
    // Note ChildrenCallback is compatible with a ZK 3.2 server; Children2Callback is
    // compatible only with ZK 3.3+ server.
    AsyncCallback.ChildrenCallback zkCallback = new AsyncCallback.ChildrenCallback() {
        @Override//from   w ww . j  a va 2 s  .c  o m
        public void processResult(int rc, String path, Object context, List<String> children) {
            KeeperException.Code result = KeeperException.Code.get(rc);
            switch (result) {
            case NONODE:
                callback.onSuccess(null);
                break;

            case OK:
                getMergedChildren(path, children, null, callback);
                break;

            default:
                callback.onError(KeeperException.create(result));
                break;
            }
        }
    };
    _zk.getChildren(path, null, zkCallback, null);
}

From source file:com.linkedin.parseq.zk.client.TestReaper.java

License:Apache License

@Test
public void testReaperRetry() throws InterruptedException {
    final int MAX_RETRY = 3;
    final CountDownLatch failure = new CountDownLatch(MAX_RETRY);
    final CountDownLatch success = new CountDownLatch(1);

    Reaper.Zombie zombie = new Reaper.Zombie() {
        private int count = 0;

        @Override/*from w  ww  . j av  a  2s  .  c o  m*/
        public Task<Void> reap() {
            if (count++ < MAX_RETRY) {
                return Task.action(() -> failure.countDown())
                        .andThen(Task.failure(KeeperException.create(KeeperException.Code.CONNECTIONLOSS)));
            } else {
                return Task.action(() -> success.countDown());
            }
        }
    };
    _reaper.submit(zombie);

    Assert.assertTrue(failure.await(10, TimeUnit.SECONDS));
    Assert.assertTrue(success.await(10, TimeUnit.SECONDS));
}

From source file:com.netflix.curator.framework.imps.CuratorFrameworkImpl.java

License:Apache License

@SuppressWarnings({ "ThrowableResultOfMethodCallIgnored" })
<DATA_TYPE> void processBackgroundOperation(OperationAndData<DATA_TYPE> operationAndData, CuratorEvent event) {
    boolean isInitialExecution = (event == null);
    if (isInitialExecution) {
        performBackgroundOperation(operationAndData);
        return;//from   w ww .j a  va 2  s .  c o m
    }

    boolean queueOperation = false;
    do {
        if (RetryLoop.shouldRetry(event.getResultCode())) {
            if (client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(),
                    operationAndData.getElapsedTimeMs(), operationAndData)) {
                queueOperation = true;
            } else {
                if (operationAndData.getErrorCallback() != null) {
                    operationAndData.getErrorCallback().retriesExhausted(operationAndData);
                }

                KeeperException.Code code = KeeperException.Code.get(event.getResultCode());
                Exception e = null;
                try {
                    e = (code != null) ? KeeperException.create(code) : null;
                } catch (Throwable ignore) {
                }
                if (e == null) {
                    e = new Exception("Unknown result code: " + event.getResultCode());
                }
                logError("Background operation retry gave up", e);
            }
            break;
        }

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

        processEvent(event);
    } while (false);

    if (queueOperation) {
        backgroundOperations.offer(operationAndData);
    }
}

From source file:com.netflix.curator.framework.imps.CuratorTransactionImpl.java

License:Apache License

private List<OpResult> doOperation(AtomicBoolean firstTime) throws Exception {
    boolean localFirstTime = firstTime.getAndSet(false);
    if (!localFirstTime) {

    }/* w ww. j a v a  2 s.  c  o  m*/

    List<OpResult> opResults = client.getZooKeeper().multi(transaction);
    if (opResults.size() > 0) {
        OpResult firstResult = opResults.get(0);
        if (firstResult.getType() == ZooDefs.OpCode.error) {
            OpResult.ErrorResult error = (OpResult.ErrorResult) firstResult;
            KeeperException.Code code = KeeperException.Code.get(error.getErr());
            if (code == null) {
                code = KeeperException.Code.UNIMPLEMENTED;
            }
            throw KeeperException.create(code);
        }
    }
    return opResults;
}

From source file:com.proofpoint.zookeeper.RetryHandler.java

License:Apache License

private boolean shouldRetry(KeeperException.Code code) {
    if ((code == KeeperException.Code.CONNECTIONLOSS) || (code == KeeperException.Code.OPERATIONTIMEOUT)) {
        try {/*www  . j a va  2  s  . c  om*/
            //noinspection ThrowableResultOfMethodCallIgnored
            if (policy.shouldRetry(KeeperException.create(code), retries++)) {
                client.getState().close();
                return true;
            } else {
                log.info("Connection lost on retries for call %s", proc.getClass().getName());
                client.errorConnectionLost();
                client.getState().close();
            }
        } catch (Exception e) {
            log.error(e, "for call %s", proc.getClass().getName());
        }
    }
    return false;
}

From source file:com.splicemachine.ddl.ZooKeeperDDLWatchChecker.java

License:Apache License

@Override
public void notifyProcessed(Collection<Pair<DDLMessage.DDLChange, String>> processedChanges)
        throws IOException {
    /*//from  w ww .java2s. co  m
     * Notify the relevant controllers that their change has been processed
     */
    List<Op> ops = Lists.newArrayListWithExpectedSize(processedChanges.size());
    List<DDLMessage.DDLChange> changeList = Lists.newArrayList();
    for (Pair<DDLMessage.DDLChange, String> pair : processedChanges) {
        DDLMessage.DDLChange change = pair.getFirst();
        String errorMessage = pair.getSecond();
        // Tag Errors for handling on the client, will allow us to understand what node failed and why...
        String path = zkClient.changePath + "/" + change.getChangeId() + "/"
                + (errorMessage == null ? "" : DDLConfiguration.ERROR_TAG) + id;
        Op op = Op.create(path,
                (errorMessage == null ? new byte[] {}
                        : (String.format("server [%s] failed with error [%s]", id, errorMessage).getBytes())),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        ops.add(op);
        changeList.add(change);
    }
    try {
        List<OpResult> multi = ZkUtils.getRecoverableZooKeeper().getZooKeeper().multi(ops);
        for (int i = 0; i < multi.size(); i++) {
            OpResult result = multi.get(i);
            if (!(result instanceof OpResult.ErrorResult))
                processedChanges.remove(changeList.get(i));
            else {
                OpResult.ErrorResult err = (OpResult.ErrorResult) result;
                KeeperException.Code code = KeeperException.Code.get(err.getErr());
                switch (code) {
                case NODEEXISTS: //we may have already set the value, so ignore node exists issues
                case NONODE: // someone already removed the notification, it's obsolete
                    // ignore
                    break;
                default:
                    throw Exceptions.getIOException(KeeperException.create(code));
                }
            }
        }
    } catch (InterruptedException e) {
        throw Exceptions.getIOException(e);
    } catch (KeeperException e) {
        switch (e.code()) {
        case NODEEXISTS: //we may have already set the value, so ignore node exists issues
        case NONODE: // someone already removed the notification, it's obsolete
            // ignore
            break;
        default:
            throw Exceptions.getIOException(e);
        }
    }
}

From source file:com.twitter.distributedlog.acl.ZKAccessControl.java

License:Apache License

public Future<ZKAccessControl> create(ZooKeeperClient zkc) {
    final Promise<ZKAccessControl> promise = new Promise<ZKAccessControl>();
    try {/*from   w  w w  .  ja va 2  s.co  m*/
        zkc.get().create(zkPath, serialize(accessControlEntry), zkc.getDefaultACL(), CreateMode.PERSISTENT,
                new AsyncCallback.StringCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            ZKAccessControl.this.zkVersion = 0;
                            promise.setValue(ZKAccessControl.this);
                        } else {
                            promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                        }
                    }
                }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    } catch (IOException e) {
        promise.setException(e);
    }
    return promise;
}

From source file:com.twitter.distributedlog.acl.ZKAccessControl.java

License:Apache License

public Future<ZKAccessControl> update(ZooKeeperClient zkc) {
    final Promise<ZKAccessControl> promise = new Promise<ZKAccessControl>();
    try {// w  w w .ja  va 2  s.c o  m
        zkc.get().setData(zkPath, serialize(accessControlEntry), zkVersion, new AsyncCallback.StatCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, Stat stat) {
                if (KeeperException.Code.OK.intValue() == rc) {
                    ZKAccessControl.this.zkVersion = stat.getVersion();
                    promise.setValue(ZKAccessControl.this);
                } else {
                    promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    } catch (IOException e) {
        promise.setException(e);
    }
    return promise;
}