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.acl.ZKAccessControl.java

License:Apache License

public static Future<ZKAccessControl> read(final ZooKeeperClient zkc, final String zkPath, Watcher watcher) {
    final Promise<ZKAccessControl> promise = new Promise<ZKAccessControl>();

    try {/*from www. j  a  va2  s.c  o  m*/
        zkc.get().getData(zkPath, watcher, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                if (KeeperException.Code.OK.intValue() == rc) {
                    try {
                        AccessControlEntry ace = deserialize(zkPath, data);
                        promise.setValue(new ZKAccessControl(ace, zkPath, stat.getVersion()));
                    } catch (IOException ioe) {
                        promise.setException(ioe);
                    }
                } else {
                    promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }
    return promise;
}

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

License:Apache License

public static Future<Void> delete(final ZooKeeperClient zkc, final String zkPath) {
    final Promise<Void> promise = new Promise<Void>();

    try {// w ww  .j a v  a 2 s  .  co  m
        zkc.get().delete(zkPath, -1, new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx) {
                if (KeeperException.Code.OK.intValue() == rc || KeeperException.Code.NONODE.intValue() == rc) {
                    promise.setValue(null);
                } else {
                    promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }
    return promise;
}

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

License:Apache License

private void fetchAccessControlEntries(final Promise<Void> promise) {
    try {/*from www .j  a  v a  2 s .c  o m*/
        zkc.get().getChildren(zkRootPath, this, new AsyncCallback.Children2Callback() {
            @Override
            public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
                if (KeeperException.Code.OK.intValue() != rc) {
                    promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                    return;
                }
                Set<String> streamsReceived = new HashSet<String>();
                streamsReceived.addAll(children);
                Set<String> streamsCached = streamEntries.keySet();
                Set<String> streamsRemoved = Sets.difference(streamsCached, streamsReceived).immutableCopy();
                for (String s : streamsRemoved) {
                    ZKAccessControl accessControl = streamEntries.remove(s);
                    if (null != accessControl) {
                        logger.info("Removed Access Control Entry for stream {} : {}", s,
                                accessControl.getAccessControlEntry());
                    }
                }
                if (streamsReceived.isEmpty()) {
                    promise.setValue(null);
                    return;
                }
                final AtomicInteger numPendings = new AtomicInteger(streamsReceived.size());
                final AtomicInteger numFailures = new AtomicInteger(0);
                for (String s : streamsReceived) {
                    final String streamName = s;
                    ZKAccessControl.read(zkc, zkRootPath + "/" + streamName, null)
                            .addEventListener(new FutureEventListener<ZKAccessControl>() {

                                @Override
                                public void onSuccess(ZKAccessControl accessControl) {
                                    streamEntries.put(streamName, accessControl);
                                    logger.info("Added overrided access control for stream {} : {}", streamName,
                                            accessControl.getAccessControlEntry());
                                    complete();
                                }

                                @Override
                                public void onFailure(Throwable cause) {
                                    if (cause instanceof KeeperException.NoNodeException) {
                                        streamEntries.remove(streamName);
                                    } else if (cause instanceof ZKAccessControl.CorruptedAccessControlException) {
                                        logger.warn(
                                                "Access control is corrupted for stream {} @ {}, skipped it ...",
                                                new Object[] { streamName, zkRootPath, cause });
                                        streamEntries.remove(streamName);
                                    } else {
                                        if (1 == numFailures.incrementAndGet()) {
                                            promise.setException(cause);
                                        }
                                    }
                                    complete();
                                }

                                private void complete() {
                                    if (0 == numPendings.decrementAndGet() && numFailures.get() == 0) {
                                        promise.setValue(null);
                                    }
                                }
                            });
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }
}

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

License:Apache License

private void createDefaultAccessControlEntryIfNeeded(final Promise<ZKAccessControl> promise) {
    ZooKeeper zk;//w  ww .j  ava 2 s . c  o m
    try {
        zk = zkc.get();
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
        return;
    } catch (InterruptedException e) {
        promise.setException(e);
        return;
    }
    ZkUtils.asyncCreateFullPathOptimistic(zk, zkRootPath, new byte[0], 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) {
                        logger.info("Created zk path {} for default ACL.", zkRootPath);
                        fetchDefaultAccessControlEntry(promise);
                    } else {
                        promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
                    }
                }
            }, null);
}

From source file:com.twitter.distributedlog.bk.SimpleLedgerAllocator.java

License:Apache License

private static Future<Versioned<byte[]>> createAllocationData(final String allocatePath,
        final ZooKeeperClient zkc) {
    try {//from ww  w. j  a  v  a 2 s. c  o m
        final Promise<Versioned<byte[]>> promise = new Promise<Versioned<byte[]>>();
        zkc.get().create(allocatePath, DistributedLogConstants.EMPTY_BYTES, zkc.getDefaultACL(),
                CreateMode.PERSISTENT, new org.apache.zookeeper.AsyncCallback.Create2Callback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            promise.setValue(new Versioned<byte[]>(DistributedLogConstants.EMPTY_BYTES,
                                    new ZkVersion(stat.getVersion())));
                        } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {
                            Utils.zkGetData(zkc, allocatePath, false).proxyTo(promise);
                        } else {
                            promise.setException(FutureUtils.zkException(
                                    KeeperException.create(KeeperException.Code.get(rc)), allocatePath));
                        }
                    }
                }, null);
        return promise;
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        return Future.exception(FutureUtils.zkException(e, allocatePath));
    } catch (InterruptedException e) {
        return Future.exception(FutureUtils.zkException(e, allocatePath));
    }
}

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

License:Apache License

Future<Void> checkLogStreamExistsAsync() {
    final Promise<Void> promise = new Promise<Void>();
    try {// w  w w  .j a va2s .  c o m
        final ZooKeeper zk = zooKeeperClient.get();
        zk.sync(logMetadata.getLogSegmentsPath(), new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int syncRc, String path, Object syncCtx) {
                if (KeeperException.Code.NONODE.intValue() == syncRc) {
                    promise.setException(new LogNotFoundException(String
                            .format("Log %s does not exist or has been deleted", getFullyQualifiedName())));
                    return;
                } else if (KeeperException.Code.OK.intValue() != syncRc) {
                    promise.setException(
                            new ZKException("Error on checking log existence for " + getFullyQualifiedName(),
                                    KeeperException.create(KeeperException.Code.get(syncRc))));
                    return;
                }
                zk.exists(logMetadata.getLogSegmentsPath(), false, new AsyncCallback.StatCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, Stat stat) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            promise.setValue(null);
                        } else if (KeeperException.Code.NONODE.intValue() == rc) {
                            promise.setException(new LogNotFoundException(String.format(
                                    "Log %s does not exist or has been deleted", getFullyQualifiedName())));
                        } else {
                            promise.setException(new ZKException(
                                    "Error on checking log existence for " + getFullyQualifiedName(),
                                    KeeperException.create(KeeperException.Code.get(rc))));
                        }
                    }
                }, null);
            }
        }, null);

    } catch (InterruptedException ie) {
        LOG.error("Interrupted while reading {}", logMetadata.getLogSegmentsPath(), ie);
        promise.setException(new DLInterruptedException(
                "Interrupted while checking " + logMetadata.getLogSegmentsPath(), ie));
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    }
    return promise;
}

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

License:Apache License

private Future<Void> ensureReadLockPathExist() {
    final Promise<Void> promise = new Promise<Void>();
    promise.setInterruptHandler(new com.twitter.util.Function<Throwable, BoxedUnit>() {
        @Override/*from w  w  w.j a  v  a2s .  c  om*/
        public BoxedUnit apply(Throwable t) {
            FutureUtils.setException(promise,
                    new LockCancelledException(readLockPath, "Could not ensure read lock path", t));
            return null;
        }
    });
    Optional<String> parentPathShouldNotCreate = Optional.of(logMetadata.getLogRootPath());
    Utils.zkAsyncCreateFullPathOptimisticRecursive(zooKeeperClient, readLockPath, parentPathShouldNotCreate,
            new byte[0], zooKeeperClient.getDefaultACL(), CreateMode.PERSISTENT,
            new org.apache.zookeeper.AsyncCallback.StringCallback() {
                @Override
                public void processResult(final int rc, final String path, Object ctx, String name) {
                    scheduler.submit(new Runnable() {
                        @Override
                        public void run() {
                            if (KeeperException.Code.NONODE.intValue() == rc) {
                                FutureUtils.setException(promise, new LogNotFoundException(String.format(
                                        "Log %s does not exist or has been deleted", getFullyQualifiedName())));
                            } else if (KeeperException.Code.OK.intValue() == rc) {
                                FutureUtils.setValue(promise, null);
                                LOG.trace("Created path {}.", path);
                            } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {
                                FutureUtils.setValue(promise, null);
                                LOG.trace("Path {} is already existed.", path);
                            } else if (DistributedLogConstants.ZK_CONNECTION_EXCEPTION_RESULT_CODE == rc) {
                                FutureUtils.setException(promise,
                                        new ZooKeeperClient.ZooKeeperConnectionException(path));
                            } else if (DistributedLogConstants.DL_INTERRUPTED_EXCEPTION_RESULT_CODE == rc) {
                                FutureUtils.setException(promise, new DLInterruptedException(path));
                            } else {
                                FutureUtils.setException(promise,
                                        KeeperException.create(KeeperException.Code.get(rc)));
                            }
                        }
                    });
                }
            }, null);
    return promise;
}

From source file:com.twitter.distributedlog.impl.federated.FederatedZKLogMetadataStore.java

License:Apache License

Future<Set<URI>> fetchSubNamespaces(final Watcher watcher) {
    final Promise<Set<URI>> promise = new Promise<Set<URI>>();
    try {/* w  w  w  .  ja v a  2 s  . co  m*/
        zkc.get().sync(this.zkSubnamespacesPath, new AsyncCallback.VoidCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx) {
                if (Code.OK.intValue() == rc) {
                    fetchSubNamespaces(watcher, promise);
                } else {
                    promise.setException(KeeperException.create(Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }
    return promise;
}

From source file:com.twitter.distributedlog.impl.federated.FederatedZKLogMetadataStore.java

License:Apache License

Future<URI> createSubNamespace() {
    final Promise<URI> promise = new Promise<URI>();

    final String nsPath = namespace.getPath() + "/" + ZNODE_SUB_NAMESPACES + "/" + SUB_NAMESPACE_PREFIX;
    try {/*  w ww  .j  ava2 s. c o  m*/
        zkc.get().create(nsPath, new byte[0], zkc.getDefaultACL(), CreateMode.PERSISTENT_SEQUENTIAL,
                new AsyncCallback.StringCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name) {
                        if (Code.OK.intValue() == rc) {
                            try {
                                URI newUri = getSubNamespaceURI(getNamespaceFromZkPath(name));
                                logger.info("Created sub namespace {}", newUri);
                                promise.setValue(newUri);
                            } catch (UnexpectedException ue) {
                                promise.setException(ue);
                            } catch (URISyntaxException e) {
                                promise.setException(
                                        new UnexpectedException("Invalid namespace " + name + " is created."));
                            }
                        } else {
                            promise.setException(KeeperException.create(Code.get(rc)));
                        }
                    }
                }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.setException(e);
    } catch (InterruptedException e) {
        promise.setException(e);
    }

    return promise;
}

From source file:com.twitter.distributedlog.impl.federated.FederatedZKLogMetadataStore.java

License:Apache License

void createLogInNamespaceSync(URI uri, String logName)
        throws InterruptedException, IOException, KeeperException {
    Transaction txn = zkc.get().transaction();
    // we don't have the zk version yet. set it to 0 instead of -1, to prevent non CAS operation.
    int zkVersion = null == zkSubnamespacesVersion.get() ? 0 : zkSubnamespacesVersion.get();
    txn.setData(zkSubnamespacesPath, uri.getPath().getBytes(UTF_8), zkVersion);
    String logPath = uri.getPath() + "/" + logName;
    txn.create(logPath, new byte[0], zkc.getDefaultACL(), CreateMode.PERSISTENT);
    try {/*from  w  w w  .  j  a va2  s .c  o  m*/
        txn.commit();
        // if the transaction succeed, the zk version is advanced
        setZkSubnamespacesVersion(zkVersion + 1);
    } catch (KeeperException ke) {
        List<OpResult> opResults = ke.getResults();
        OpResult createResult = opResults.get(1);
        if (createResult instanceof OpResult.ErrorResult) {
            OpResult.ErrorResult errorResult = (OpResult.ErrorResult) createResult;
            if (Code.NODEEXISTS.intValue() == errorResult.getErr()) {
                throw new LogExistsException("Log " + logName + " already exists");
            }
        }
        OpResult setResult = opResults.get(0);
        if (setResult instanceof OpResult.ErrorResult) {
            OpResult.ErrorResult errorResult = (OpResult.ErrorResult) setResult;
            if (Code.BADVERSION.intValue() == errorResult.getErr()) {
                throw KeeperException.create(Code.BADVERSION);
            }
        }
        throw new ZKException("ZK exception in creating log " + logName + " in " + uri, ke);
    }
}