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.distributedlog.impl.ZKLogSegmentMetadataStore.java

License:Apache License

@Override
public void deleteLogSegment(Transaction<Object> txn, final LogSegmentMetadata segment,
        final OpListener<Void> listener) {
    Op deleteOp = Op.delete(segment.getZkPath(), -1);
    logger.info("Delete segment : {}", segment);
    txn.addOp(DefaultZKOp.of(deleteOp, new OpListener<Void>() {
        @Override/*from  ww  w.  j  a va  2 s. c om*/
        public void onCommit(Void r) {
            if (null != listener) {
                listener.onCommit(r);
            }
        }

        @Override
        public void onAbort(Throwable t) {
            logger.info("Aborted transaction on deleting segment {}", segment);
            KeeperException.Code kc;
            if (t instanceof KeeperException) {
                kc = ((KeeperException) t).code();
            } else if (t instanceof ZKException) {
                kc = ((ZKException) t).getKeeperExceptionCode();
            } else {
                abortListener(t);
                return;
            }
            if (KeeperException.Code.NONODE == kc) {
                abortListener(new LogSegmentNotFoundException(segment.getZkPath()));
                return;
            }
            abortListener(t);
        }

        private void abortListener(Throwable t) {
            if (null != listener) {
                listener.onAbort(t);
            }
        }
    }));
}

From source file:org.apache.distributedlog.impl.ZKLogSegmentMetadataStore.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
    CompletableFuture<Versioned<List<String>>> result = ((CompletableFuture<Versioned<List<String>>>) ctx);
    if (KeeperException.Code.OK.intValue() == rc) {
        /** cversion: the number of changes to the children of this znode **/
        LongVersion zkVersion = new LongVersion(stat.getCversion());
        result.complete(new Versioned(children, zkVersion));
    } else if (KeeperException.Code.NONODE.intValue() == rc) {
        result.completeExceptionally(new LogNotFoundException("Log " + path + " not found"));
    } else {// w  w w . j  av a  2 s. c  om
        result.completeExceptionally(
                new ZKException("Failed to get log segments from " + path, KeeperException.Code.get(rc)));
    }
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Creates a distributed lock using the given {@code zkClient} to coordinate locking.
 *
 * @param zkClient The ZooKeeper client to use.
 * @param lockPath The path used to manage the lock under.
 * @param clientId client id use for lock.
 * @param lockStateExecutor executor to execute all lock state changes.
 * @param lockOpTimeout timeout of lock operations
 * @param statsLogger stats logger//  w w  w  . j a v a 2 s .c  o  m
 */
public ZKSessionLock(ZooKeeperClient zkClient, String lockPath, String clientId,
        OrderedScheduler lockStateExecutor, long lockOpTimeout, StatsLogger statsLogger,
        DistributedLockContext lockContext) throws IOException {
    this.zkClient = zkClient;
    try {
        this.zk = zkClient.get();
    } catch (ZooKeeperClient.ZooKeeperConnectionException zce) {
        throw new ZKException("Failed to get zookeeper client for lock " + lockPath,
                KeeperException.Code.CONNECTIONLOSS);
    } catch (InterruptedException e) {
        throw new DLInterruptedException("Interrupted on getting zookeeper client for lock " + lockPath, e);
    }
    this.lockPath = lockPath;
    this.lockId = Pair.of(clientId, this.zk.getSessionId());
    this.lockContext = lockContext;
    this.lockStateExecutor = lockStateExecutor;
    this.lockState = new StateManagement();
    this.lockOpTimeout = lockOpTimeout;

    this.tryStats = statsLogger.getOpStatsLogger("tryAcquire");
    this.tryTimeouts = statsLogger.getCounter("tryTimeouts");
    this.unlockStats = statsLogger.getOpStatsLogger("unlock");

    // Attach interrupt handler to acquire future so clients can abort the future.
    this.acquireFuture = FutureUtils.createFuture();
    this.acquireFuture.whenComplete((value, cause) -> {
        if (null != cause) {
            // This will set the lock state to closed, and begin to cleanup the zk lock node.
            // We have to be careful not to block here since doing so blocks the ordered lock
            // state executor which can cause deadlocks depending on how futures are chained.
            ZKSessionLock.this.asyncUnlock(cause);
            // Note re. logging and exceptions: errors are already logged by unlockAsync.
        }
    });
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Get client id and its ephemeral owner.
 *
 * @param zkClient/* w w  w  . j a  v  a 2 s. co  m*/
 *          zookeeper client
 * @param lockPath
 *          lock path
 * @param nodeName
 *          node name
 * @return client id and its ephemeral owner.
 */
static CompletableFuture<Pair<String, Long>> asyncParseClientID(ZooKeeper zkClient, String lockPath,
        String nodeName) {
    String[] parts = nodeName.split("_");
    // member_<clientid>_s<owner_session>_
    if (4 == parts.length && parts[2].startsWith("s")) {
        long sessionOwner = Long.parseLong(parts[2].substring(1));
        String clientId;
        try {
            clientId = URLDecoder.decode(parts[1], UTF_8.name());
            return FutureUtils.value(Pair.of(clientId, sessionOwner));
        } catch (UnsupportedEncodingException e) {
            // if failed to parse client id, we have to get client id by zookeeper#getData.
        }
    }
    final CompletableFuture<Pair<String, Long>> promise = new CompletableFuture<Pair<String, Long>>();
    zkClient.getData(lockPath + "/" + nodeName, false, new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (KeeperException.Code.OK.intValue() != rc) {
                promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
            } else {
                promise.complete(Pair.of(deserializeClientId(data), stat.getEphemeralOwner()));
            }
        }
    }, null);
    return promise;
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

@Override
public CompletableFuture<LockWaiter> asyncTryLock(final long timeout, final TimeUnit unit) {
    final CompletableFuture<String> result = new CompletableFuture<String>();
    final boolean wait = DistributedLogConstants.LOCK_IMMEDIATE != timeout;
    if (wait) {/*from w ww  .  j  av a  2s .  c  o  m*/
        asyncTryLock(wait, result);
    } else {
        // try to check locks first
        zk.getChildren(lockPath, null, new AsyncCallback.Children2Callback() {
            @Override
            public void processResult(final int rc, String path, Object ctx, final List<String> children,
                    Stat stat) {
                lockStateExecutor.submit(lockPath, new SafeRunnable() {
                    @Override
                    public void safeRun() {
                        if (!lockState.inState(State.INIT)) {
                            result.completeExceptionally(new LockStateChangedException(lockPath, lockId,
                                    State.INIT, lockState.getState()));
                            return;
                        }
                        if (KeeperException.Code.OK.intValue() != rc) {
                            result.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
                            return;
                        }

                        FailpointUtils.checkFailPointNoThrow(FailpointUtils.FailPointName.FP_LockTryAcquire);

                        Collections.sort(children, MEMBER_COMPARATOR);
                        if (children.size() > 0) {
                            asyncParseClientID(zk, lockPath, children.get(0))
                                    .whenCompleteAsync(new FutureEventListener<Pair<String, Long>>() {
                                        @Override
                                        public void onSuccess(Pair<String, Long> owner) {
                                            if (!checkOrClaimLockOwner(owner, result)) {
                                                acquireFuture.complete(false);
                                            }
                                        }

                                        @Override
                                        public void onFailure(final Throwable cause) {
                                            result.completeExceptionally(cause);
                                        }
                                    }, lockStateExecutor.chooseExecutor(lockPath));
                        } else {
                            asyncTryLock(wait, result);
                        }
                    }
                });
            }
        }, null);
    }

    final CompletableFuture<Boolean> waiterAcquireFuture = FutureUtils.createFuture();
    waiterAcquireFuture.whenComplete((value, cause) -> acquireFuture.completeExceptionally(cause));
    return result.thenApply(new Function<String, LockWaiter>() {
        @Override
        public LockWaiter apply(final String currentOwner) {
            final Exception acquireException = new OwnershipAcquireFailedException(lockPath, currentOwner);
            FutureUtils.within(acquireFuture, timeout, unit, acquireException, lockStateExecutor, lockPath)
                    .whenComplete(new FutureEventListener<Boolean>() {

                        @Override
                        public void onSuccess(Boolean acquired) {
                            completeOrFail(acquireException);
                        }

                        @Override
                        public void onFailure(final Throwable acquireCause) {
                            completeOrFail(acquireException);
                        }

                        private void completeOrFail(final Throwable acquireCause) {
                            if (isLockHeld()) {
                                waiterAcquireFuture.complete(true);
                            } else {
                                asyncUnlock().whenComplete(new FutureEventListener<Void>() {
                                    @Override
                                    public void onSuccess(Void value) {
                                        waiterAcquireFuture.completeExceptionally(acquireCause);
                                    }

                                    @Override
                                    public void onFailure(Throwable cause) {
                                        waiterAcquireFuture.completeExceptionally(acquireCause);
                                    }
                                });
                            }
                        }
                    });
            return new LockWaiter(lockId.getLeft(), currentOwner, waiterAcquireFuture);
        }
    });
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Try lock. If wait is true, it would wait and watch sibling to acquire lock when
 * the sibling is dead. <i>acquireCompletableFuture</i> will be notified either it locked successfully
 * or the lock failed. The promise will only satisfy with current lock owner.
 *
 * <p>NOTE: the <i>promise</i> is only satisfied on <i>lockStateExecutor</i>, so any
 * transformations attached on promise will be executed in order.</p>
 *
 * @param wait/*from w  w w .j  a  v a  2 s. c o m*/
 *          whether to wait for ownership.
 * @param promise
 *          promise to satisfy with current lock owner.
 */
private void asyncTryLockWithoutCleanup(final boolean wait, final CompletableFuture<String> promise) {
    executeLockAction(epoch.get(), new LockAction() {
        @Override
        public void execute() {
            if (!lockState.inState(State.INIT)) {
                promise.completeExceptionally(
                        new LockStateChangedException(lockPath, lockId, State.INIT, lockState.getState()));
                return;
            }
            lockState.transition(State.PREPARING);

            final int curEpoch = epoch.incrementAndGet();
            watcher = new LockWatcher(curEpoch);
            // register watcher for session expires
            zkClient.register(watcher);
            // Encode both client id and session in the lock node
            String myPath;
            try {
                // member_<clientid>_s<owner_session>_
                myPath = getLockPathPrefixV3(lockPath, lockId.getLeft(), lockId.getRight());
            } catch (UnsupportedEncodingException uee) {
                myPath = getLockPathPrefixV1(lockPath);
            }
            zk.create(myPath, serializeClientId(lockId.getLeft()), zkClient.getDefaultACL(),
                    CreateMode.EPHEMERAL_SEQUENTIAL, new AsyncCallback.StringCallback() {
                        @Override
                        public void processResult(final int rc, String path, Object ctx, final String name) {
                            executeLockAction(curEpoch, new LockAction() {
                                @Override
                                public void execute() {
                                    if (KeeperException.Code.OK.intValue() != rc) {
                                        KeeperException ke = KeeperException
                                                .create(KeeperException.Code.get(rc));
                                        promise.completeExceptionally(ke);
                                        return;
                                    }

                                    if (FailpointUtils.checkFailPointNoThrow(
                                            FailpointUtils.FailPointName.FP_LockTryCloseRaceCondition)) {
                                        lockState.transition(State.CLOSING);
                                        lockState.transition(State.CLOSED);
                                    }

                                    if (null != currentNode) {
                                        LOG.error("Current node for {} overwritten current = {} new = {}",
                                                new Object[] { lockPath, lockId,
                                                        getLockIdFromPath(currentNode) });
                                    }

                                    currentNode = name;
                                    currentId = getLockIdFromPath(currentNode);
                                    LOG.trace("{} received member id for lock {}", lockId, currentId);

                                    if (lockState.isExpiredOrClosing()) {
                                        // Delete node attempt may have come after PREPARING but before create node,
                                        // in which case we'd be left with a dangling node unless we clean up.
                                        CompletableFuture<Void> deletePromise = new CompletableFuture<Void>();
                                        deleteLockNode(deletePromise);
                                        FutureUtils
                                                .ensure(deletePromise,
                                                        () -> promise.completeExceptionally(
                                                                new LockClosedException(lockPath, lockId,
                                                                        lockState.getState())));
                                        return;
                                    }

                                    lockState.transition(State.PREPARED);
                                    checkLockOwnerAndWaitIfPossible(watcher, wait, promise);
                                }

                                @Override
                                public String getActionName() {
                                    return "postPrepare(wait=" + wait + ")";
                                }
                            });
                        }
                    }, null);
        }

        @Override
        public String getActionName() {
            return "prepare(wait=" + wait + ")";
        }
    }, promise);
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

private void deleteLockNode(final CompletableFuture<Void> promise) {
    if (null == currentNode) {
        promise.complete(null);/*from   ww w .  j av  a  2s .  c om*/
        return;
    }

    zk.delete(currentNode, -1, new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(final int rc, final String path, Object ctx) {
            lockStateExecutor.submit(lockPath, new SafeRunnable() {
                @Override
                public void safeRun() {
                    if (KeeperException.Code.OK.intValue() == rc) {
                        LOG.info("Deleted lock node {} for {} successfully.", path, lockId);
                    } else if (KeeperException.Code.NONODE.intValue() == rc
                            || KeeperException.Code.SESSIONEXPIRED.intValue() == rc) {
                        LOG.info("Delete node failed. Node already gone for node {} id {}, rc = {}",
                                new Object[] { path, lockId, KeeperException.Code.get(rc) });
                    } else {
                        LOG.error("Failed on deleting lock node {} for {} : {}",
                                new Object[] { path, lockId, KeeperException.Code.get(rc) });
                    }

                    FailpointUtils.checkFailPointNoThrow(FailpointUtils.FailPointName.FP_LockUnlockCleanup);
                    promise.complete(null);
                }
            });
        }
    }, null);
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Check Lock Owner Phase 2 : check all lock waiters to get current owner and wait for ownership if necessary.
 *
 * @param lockWatcher/*from  w w  w  .jav  a  2 s  .  com*/
 *          lock watcher.
 * @param wait
 *          whether to wait for ownership.
 * @param getChildrenRc
 *          result of getting all lock waiters
 * @param children
 *          current lock waiters.
 * @param promise
 *          promise to satisfy with current lock owner.
 */
private void processLockWaiters(final LockWatcher lockWatcher, final boolean wait, final int getChildrenRc,
        final List<String> children, final CompletableFuture<String> promise) {
    executeLockAction(lockWatcher.epoch, new LockAction() {
        @Override
        public void execute() {
            if (!lockState.inState(State.PREPARED)) { // e.g. lock closed or session expired after prepared
                promise.completeExceptionally(
                        new LockStateChangedException(lockPath, lockId, State.PREPARED, lockState.getState()));
                return;
            }

            if (KeeperException.Code.OK.intValue() != getChildrenRc) {
                promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(getChildrenRc)));
                return;
            }
            if (children.isEmpty()) {
                LOG.error("Error, member list is empty for lock {}.", lockPath);
                promise.completeExceptionally(
                        new UnexpectedException("Empty member list for lock " + lockPath));
                return;
            }

            // sort the children
            Collections.sort(children, MEMBER_COMPARATOR);
            final String cid = currentId;
            final int memberIndex = children.indexOf(cid);
            if (LOG.isDebugEnabled()) {
                LOG.debug("{} is the number {} member in the list.", cid, memberIndex);
            }
            // If we hold the lock
            if (memberIndex == 0) {
                LOG.info("{} acquired the lock {}.", cid, lockPath);
                claimOwnership(lockWatcher.epoch);
                promise.complete(cid);
            } else if (memberIndex > 0) { // we are in the member list but we didn't hold the lock
                // get ownership of current owner
                asyncParseClientID(zk, lockPath, children.get(0))
                        .whenComplete(new FutureEventListener<Pair<String, Long>>() {
                            @Override
                            public void onSuccess(Pair<String, Long> currentOwner) {
                                watchLockOwner(lockWatcher, wait, cid, children.get(memberIndex - 1),
                                        children.get(0), currentOwner, promise);
                            }

                            @Override
                            public void onFailure(final Throwable cause) {
                                // ensure promise is satisfied in lock thread
                                executeLockAction(lockWatcher.epoch, new LockAction() {
                                    @Override
                                    public void execute() {
                                        promise.completeExceptionally(cause);
                                    }

                                    @Override
                                    public String getActionName() {
                                        return "handleFailureOnParseClientID(lockPath=" + lockPath + ")";
                                    }
                                }, promise);
                            }
                        });
            } else {
                LOG.error("Member {} doesn't exist in the members list {} for lock {}.",
                        new Object[] { cid, children, lockPath });
                promise.completeExceptionally(new UnexpectedException("Member " + cid
                        + " doesn't exist in member list " + children + " for lock " + lockPath));
            }
        }

        @Override
        public String getActionName() {
            return "processLockWaiters(rc=" + getChildrenRc + ", waiters=" + children + ")";
        }
    }, promise);
}

From source file:org.apache.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Check Lock Owner Phase 3: watch sibling node for lock ownership.
 *
 * @param lockWatcher//  ww  w .jav  a2 s. co m
 *          lock watcher.
 * @param wait
 *          whether to wait for ownership.
 * @param myNode
 *          my lock node.
 * @param siblingNode
 *          my sibling lock node.
 * @param ownerNode
 *          owner lock node.
 * @param currentOwner
 *          current owner info.
 * @param promise
 *          promise to satisfy with current lock owner.
 */
private void watchLockOwner(final LockWatcher lockWatcher, final boolean wait, final String myNode,
        final String siblingNode, final String ownerNode, final Pair<String, Long> currentOwner,
        final CompletableFuture<String> promise) {
    executeLockAction(lockWatcher.epoch, new LockAction() {
        @Override
        public void execute() {
            boolean shouldWatch;
            final boolean shouldClaimOwnership;
            if (lockContext.hasLockId(currentOwner) && siblingNode.equals(ownerNode)) {
                // if the current owner is the znode left from previous session
                // we should watch it and claim ownership
                shouldWatch = true;
                shouldClaimOwnership = true;
                LOG.info(
                        "LockWatcher {} for {} found its previous session {} held lock,"
                                + " watch it to claim ownership.",
                        new Object[] { myNode, lockPath, currentOwner });
            } else if (lockId.compareTo(currentOwner) == 0
                    && areLockWaitersInSameSession(siblingNode, ownerNode)) {
                // I found that my sibling is the current owner with same lock id (client id & session id)
                // It must be left by any race condition from same zookeeper client
                shouldWatch = true;
                shouldClaimOwnership = true;
                LOG.info(
                        "LockWatcher {} for {} found itself {} already held lock at sibling node {},"
                                + " watch it to claim ownership.",
                        new Object[] { myNode, lockPath, lockId, siblingNode });
            } else {
                shouldWatch = wait;
                if (wait) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "Current LockWatcher for {} with ephemeral node {}, "
                                        + "is waiting for {} to release lock at {}.",
                                new Object[] { lockPath, myNode, siblingNode, System.currentTimeMillis() });
                    }
                }
                shouldClaimOwnership = false;
            }

            // watch sibling for lock ownership
            if (shouldWatch) {
                watchedNode = String.format("%s/%s", lockPath, siblingNode);
                zk.exists(watchedNode, lockWatcher, new AsyncCallback.StatCallback() {
                    @Override
                    public void processResult(final int rc, String path, Object ctx, final Stat stat) {
                        executeLockAction(lockWatcher.epoch, new LockAction() {
                            @Override
                            public void execute() {
                                if (!lockState.inState(State.PREPARED)) {
                                    promise.completeExceptionally(new LockStateChangedException(lockPath,
                                            lockId, State.PREPARED, lockState.getState()));
                                    return;
                                }

                                if (KeeperException.Code.OK.intValue() == rc) {
                                    if (shouldClaimOwnership) {
                                        // watch owner successfully
                                        LOG.info(
                                                "LockWatcher {} claimed ownership for {} after set watcher on {}.",
                                                new Object[] { myNode, lockPath, ownerNode });
                                        claimOwnership(lockWatcher.epoch);
                                        promise.complete(currentOwner.getLeft());
                                    } else {
                                        // watch sibling successfully
                                        lockState.transition(State.WAITING);
                                        promise.complete(currentOwner.getLeft());
                                    }
                                } else if (KeeperException.Code.NONODE.intValue() == rc) {
                                    // sibling just disappeared, it might be the chance to claim ownership
                                    checkLockOwnerAndWaitIfPossible(lockWatcher, wait, promise);
                                } else {
                                    promise.completeExceptionally(
                                            KeeperException.create(KeeperException.Code.get(rc)));
                                }
                            }

                            @Override
                            public String getActionName() {
                                StringBuilder sb = new StringBuilder();
                                sb.append("postWatchLockOwner(myNode=").append(myNode).append(", siblingNode=")
                                        .append(siblingNode).append(", ownerNode=").append(ownerNode)
                                        .append(")");
                                return sb.toString();
                            }
                        }, promise);
                    }
                }, null);
            } else {
                promise.complete(currentOwner.getLeft());
            }
        }

        @Override
        public String getActionName() {
            StringBuilder sb = new StringBuilder();
            sb.append("watchLockOwner(myNode=").append(myNode).append(", siblingNode=").append(siblingNode)
                    .append(", ownerNode=").append(ownerNode).append(")");
            return sb.toString();
        }
    }, promise);
}

From source file:org.apache.distributedlog.LogSegmentMetadata.java

License:Apache License

public static CompletableFuture<LogSegmentMetadata> read(ZooKeeperClient zkc, String path,
        final boolean skipMinVersionCheck) {
    final CompletableFuture<LogSegmentMetadata> result = new CompletableFuture<LogSegmentMetadata>();
    try {//from   w  w w .ja va2s  .  c o  m
        zkc.get().getData(path, false, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                if (KeeperException.Code.OK.intValue() != rc) {
                    if (KeeperException.Code.NONODE.intValue() == rc) {
                        FutureUtils.completeExceptionally(result, new LogSegmentNotFoundException(path));
                    } else {
                        FutureUtils.completeExceptionally(result,
                                new ZKException("Failed to read log segment metadata from " + path,
                                        KeeperException.Code.get(rc)));
                    }
                    return;
                }
                try {
                    LogSegmentMetadata metadata = parseData(path, data, skipMinVersionCheck);
                    FutureUtils.complete(result, metadata);
                } catch (IOException ie) {
                    LOG.error("Error on parsing log segment metadata from {} : ", path, ie);
                    result.completeExceptionally(ie);
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        result.completeExceptionally(Utils.zkException(e, path));
    } catch (InterruptedException e) {
        result.completeExceptionally(Utils.zkException(e, path));
    }
    return result;
}