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.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  . java 2 s . co m*/
        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.BKLogWriteHandler.java

License:Apache License

private void deleteLogSegmentMetadata(final LogSegmentMetadata segmentMetadata,
        final Promise<LogSegmentMetadata> promise) {
    Transaction<Object> deleteTxn = metadataStore.transaction();
    metadataStore.deleteLogSegment(deleteTxn, segmentMetadata);
    deleteTxn.execute().addEventListener(new FutureEventListener<Void>() {
        @Override/*from  www .j  av a 2 s . c  o  m*/
        public void onSuccess(Void result) {
            // purge log segment
            removeLogSegmentFromCache(segmentMetadata.getZNodeName());
            promise.setValue(segmentMetadata);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (cause instanceof ZKException) {
                ZKException zke = (ZKException) cause;
                if (KeeperException.Code.NONODE == zke.getKeeperExceptionCode()) {
                    LOG.error("No log segment {} found for {}.", segmentMetadata, getFullyQualifiedName());
                    // purge log segment
                    removeLogSegmentFromCache(segmentMetadata.getZNodeName());
                    promise.setValue(segmentMetadata);
                    return;
                }
            }
            LOG.error("Couldn't purge {} for {}: with error {}",
                    new Object[] { segmentMetadata, getFullyQualifiedName(), cause });
            promise.setException(cause);
        }
    });
}

From source file:com.twitter.distributedlog.exceptions.ZKException.java

License:Apache License

public ZKException(String msg, KeeperException exception) {
    super(StatusCode.ZOOKEEPER_ERROR, msg, exception);
    this.code = exception.code();
}

From source file:com.twitter.distributedlog.exceptions.ZKException.java

License:Apache License

public static boolean isRetryableZKException(ZKException zke) {
    KeeperException.Code code = zke.getKeeperExceptionCode();
    return KeeperException.Code.CONNECTIONLOSS == code || KeeperException.Code.OPERATIONTIMEOUT == code
            || KeeperException.Code.SESSIONEXPIRED == code || KeeperException.Code.SESSIONMOVED == code;
}

From source file:com.twitter.distributedlog.impl.metadata.ZKLogMetadataForWriter.java

License:Apache License

static void createMissingMetadata(final ZooKeeper zk, final String logRootPath,
        final List<Versioned<byte[]>> metadatas, final List<ACL> acl, final boolean ownAllocator,
        final boolean createIfNotExists, final Promise<List<Versioned<byte[]>>> promise) {
    final List<byte[]> pathsToCreate = Lists.newArrayListWithExpectedSize(metadatas.size());
    final List<Op> zkOps = Lists.newArrayListWithExpectedSize(metadatas.size());
    CreateMode createMode = CreateMode.PERSISTENT;

    // log root parent path
    if (pathExists(metadatas.get(MetadataIndex.LOG_ROOT_PARENT))) {
        pathsToCreate.add(null);/*from  ww w.  ja  v  a2s  .c o m*/
    } else {
        String logRootParentPath = new File(logRootPath).getParent();
        pathsToCreate.add(DistributedLogConstants.EMPTY_BYTES);
        zkOps.add(Op.create(logRootParentPath, DistributedLogConstants.EMPTY_BYTES, acl, createMode));
    }

    // log root path
    if (pathExists(metadatas.get(MetadataIndex.LOG_ROOT))) {
        pathsToCreate.add(null);
    } else {
        pathsToCreate.add(DistributedLogConstants.EMPTY_BYTES);
        zkOps.add(Op.create(logRootPath, DistributedLogConstants.EMPTY_BYTES, acl, createMode));
    }

    // max id
    if (pathExists(metadatas.get(MetadataIndex.MAX_TXID))) {
        pathsToCreate.add(null);
    } else {
        byte[] zeroTxnIdData = DLUtils.serializeTransactionId(0L);
        pathsToCreate.add(zeroTxnIdData);
        zkOps.add(Op.create(logRootPath + MAX_TXID_PATH, zeroTxnIdData, acl, createMode));
    }
    // version
    if (pathExists(metadatas.get(MetadataIndex.VERSION))) {
        pathsToCreate.add(null);
    } else {
        byte[] versionData = intToBytes(LAYOUT_VERSION);
        pathsToCreate.add(versionData);
        zkOps.add(Op.create(logRootPath + VERSION_PATH, versionData, acl, createMode));
    }
    // lock path
    if (pathExists(metadatas.get(MetadataIndex.LOCK))) {
        pathsToCreate.add(null);
    } else {
        pathsToCreate.add(DistributedLogConstants.EMPTY_BYTES);
        zkOps.add(Op.create(logRootPath + LOCK_PATH, DistributedLogConstants.EMPTY_BYTES, acl, createMode));
    }
    // read lock path
    if (pathExists(metadatas.get(MetadataIndex.READ_LOCK))) {
        pathsToCreate.add(null);
    } else {
        pathsToCreate.add(DistributedLogConstants.EMPTY_BYTES);
        zkOps.add(
                Op.create(logRootPath + READ_LOCK_PATH, DistributedLogConstants.EMPTY_BYTES, acl, createMode));
    }
    // log segments path
    if (pathExists(metadatas.get(MetadataIndex.LOGSEGMENTS))) {
        pathsToCreate.add(null);
    } else {
        byte[] logSegmentsData = DLUtils
                .serializeLogSegmentSequenceNumber(DistributedLogConstants.UNASSIGNED_LOGSEGMENT_SEQNO);
        pathsToCreate.add(logSegmentsData);
        zkOps.add(Op.create(logRootPath + LOGSEGMENTS_PATH, logSegmentsData, acl, createMode));
    }
    // allocation path
    if (ownAllocator) {
        if (pathExists(metadatas.get(MetadataIndex.ALLOCATION))) {
            pathsToCreate.add(null);
        } else {
            pathsToCreate.add(DistributedLogConstants.EMPTY_BYTES);
            zkOps.add(Op.create(logRootPath + ALLOCATION_PATH, DistributedLogConstants.EMPTY_BYTES, acl,
                    createMode));
        }
    }
    if (zkOps.isEmpty()) {
        // nothing missed
        promise.setValue(metadatas);
        return;
    }
    if (!createIfNotExists) {
        promise.setException(new LogNotFoundException("Log " + logRootPath + " not found"));
        return;
    }

    zk.multi(zkOps, new AsyncCallback.MultiCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, List<OpResult> resultList) {
            if (KeeperException.Code.OK.intValue() == rc) {
                List<Versioned<byte[]>> finalMetadatas = Lists.newArrayListWithExpectedSize(metadatas.size());
                for (int i = 0; i < pathsToCreate.size(); i++) {
                    byte[] dataCreated = pathsToCreate.get(i);
                    if (null == dataCreated) {
                        finalMetadatas.add(metadatas.get(i));
                    } else {
                        finalMetadatas.add(new Versioned<byte[]>(dataCreated, new ZkVersion(0)));
                    }
                }
                promise.setValue(finalMetadatas);
            } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {
                promise.setException(new LogExistsException("Someone just created log " + logRootPath));
            } else {
                if (LOG.isDebugEnabled()) {
                    StringBuilder builder = new StringBuilder();
                    for (OpResult result : resultList) {
                        if (result instanceof OpResult.ErrorResult) {
                            OpResult.ErrorResult errorResult = (OpResult.ErrorResult) result;
                            builder.append(errorResult.getErr()).append(",");
                        } else {
                            builder.append(0).append(",");
                        }
                    }
                    String resultCodeList = builder.substring(0, builder.length() - 1);
                    LOG.debug("Failed to create log, full rc list = {}", resultCodeList);
                }

                promise.setException(
                        new ZKException("Failed to create log " + logRootPath, KeeperException.Code.get(rc)));
            }
        }
    }, null);
}

From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java

License:Apache License

@Test(timeout = 60000)
public void testStoreMaxLogSegmentSequenceNumberBadVersion() throws Exception {
    Transaction<Object> updateTxn = lsmStore.transaction();
    Versioned<Long> value = new Versioned<Long>(999L, new ZkVersion(10));
    final Promise<Version> result = new Promise<Version>();
    lsmStore.storeMaxLogSegmentSequenceNumber(updateTxn, rootZkPath, value,
            new Transaction.OpListener<Version>() {
                @Override//from   w  w  w  . j  a  v a  2 s .co m
                public void onCommit(Version r) {
                    result.setValue(r);
                }

                @Override
                public void onAbort(Throwable t) {
                    result.setException(t);
                }
            });
    try {
        FutureUtils.result(updateTxn.execute());
        fail("Should fail on storing log segment sequence number if providing bad version");
    } catch (ZKException zke) {
        assertEquals(KeeperException.Code.BADVERSION, zke.getKeeperExceptionCode());
    }
    try {
        Await.result(result);
        fail("Should fail on storing log segment sequence number if providing bad version");
    } catch (KeeperException ke) {
        assertEquals(KeeperException.Code.BADVERSION, ke.code());
    }
    Stat stat = new Stat();
    byte[] data = zkc.get().getData(rootZkPath, false, stat);
    assertEquals(0, stat.getVersion());
    assertEquals(0, data.length);
}

From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java

License:Apache License

@Test(timeout = 60000)
public void testStoreMaxLogSegmentSequenceNumberOnNonExistentPath() throws Exception {
    Transaction<Object> updateTxn = lsmStore.transaction();
    Versioned<Long> value = new Versioned<Long>(999L, new ZkVersion(10));
    final Promise<Version> result = new Promise<Version>();
    String nonExistentPath = rootZkPath + "/non-existent";
    lsmStore.storeMaxLogSegmentSequenceNumber(updateTxn, nonExistentPath, value,
            new Transaction.OpListener<Version>() {
                @Override//from   www .  j a  va2  s.co  m
                public void onCommit(Version r) {
                    result.setValue(r);
                }

                @Override
                public void onAbort(Throwable t) {
                    result.setException(t);
                }
            });
    try {
        FutureUtils.result(updateTxn.execute());
        fail("Should fail on storing log segment sequence number if path doesn't exist");
    } catch (ZKException zke) {
        assertEquals(KeeperException.Code.NONODE, zke.getKeeperExceptionCode());
    }
    try {
        Await.result(result);
        fail("Should fail on storing log segment sequence number if path doesn't exist");
    } catch (KeeperException ke) {
        assertEquals(KeeperException.Code.NONODE, ke.code());
    }
}

From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java

License:Apache License

@Test(timeout = 60000)
public void testStoreMaxTxnIdBadVersion() throws Exception {
    Transaction<Object> updateTxn = lsmStore.transaction();
    Versioned<Long> value = new Versioned<Long>(999L, new ZkVersion(10));
    final Promise<Version> result = new Promise<Version>();
    lsmStore.storeMaxTxnId(updateTxn, rootZkPath, value, new Transaction.OpListener<Version>() {
        @Override/*from www .j av  a  2  s .com*/
        public void onCommit(Version r) {
            result.setValue(r);
        }

        @Override
        public void onAbort(Throwable t) {
            result.setException(t);
        }
    });
    try {
        FutureUtils.result(updateTxn.execute());
        fail("Should fail on storing log record transaction id if providing bad version");
    } catch (ZKException zke) {
        assertEquals(KeeperException.Code.BADVERSION, zke.getKeeperExceptionCode());
    }
    try {
        Await.result(result);
        fail("Should fail on storing log record transaction id if providing bad version");
    } catch (KeeperException ke) {
        assertEquals(KeeperException.Code.BADVERSION, ke.code());
    }
    Stat stat = new Stat();
    byte[] data = zkc.get().getData(rootZkPath, false, stat);
    assertEquals(0, stat.getVersion());
    assertEquals(0, data.length);
}

From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java

License:Apache License

@Test(timeout = 60000)
public void testStoreMaxTxnIdOnNonExistentPath() throws Exception {
    Transaction<Object> updateTxn = lsmStore.transaction();
    Versioned<Long> value = new Versioned<Long>(999L, new ZkVersion(10));
    final Promise<Version> result = new Promise<Version>();
    String nonExistentPath = rootZkPath + "/non-existent";
    lsmStore.storeMaxLogSegmentSequenceNumber(updateTxn, nonExistentPath, value,
            new Transaction.OpListener<Version>() {
                @Override//w ww. j a va2 s.c o m
                public void onCommit(Version r) {
                    result.setValue(r);
                }

                @Override
                public void onAbort(Throwable t) {
                    result.setException(t);
                }
            });
    try {
        FutureUtils.result(updateTxn.execute());
        fail("Should fail on storing log record transaction id if path doesn't exist");
    } catch (ZKException zke) {
        assertEquals(KeeperException.Code.NONODE, zke.getKeeperExceptionCode());
    }
    try {
        Await.result(result);
        fail("Should fail on storing log record transaction id if path doesn't exist");
    } catch (KeeperException ke) {
        assertEquals(KeeperException.Code.NONODE, ke.code());
    }
}

From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java

License:Apache License

@Test(timeout = 60000)
public void testCreateLogSegment() throws Exception {
    LogSegmentMetadata segment = createLogSegment(1L);
    Transaction<Object> createTxn = lsmStore.transaction();
    lsmStore.createLogSegment(createTxn, segment);
    FutureUtils.result(createTxn.execute());
    // the log segment should be created
    assertNotNull("LogSegment " + segment + " should be created", zkc.get().exists(segment.getZkPath(), false));
    LogSegmentMetadata segment2 = createLogSegment(1L);
    Transaction<Object> createTxn2 = lsmStore.transaction();
    lsmStore.createLogSegment(createTxn2, segment2);
    try {//from  w w w .j  av a 2 s .co  m
        FutureUtils.result(createTxn2.execute());
        fail("Should fail if log segment exists");
    } catch (Throwable t) {
        // expected
        assertTrue("Should throw NodeExistsException if log segment exists", t instanceof ZKException);
        ZKException zke = (ZKException) t;
        assertEquals("Should throw NodeExistsException if log segment exists", KeeperException.Code.NODEEXISTS,
                zke.getKeeperExceptionCode());
    }
}