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.impl.federated.FederatedZKLogMetadataStore.java

License:Apache License

private Future<Optional<URI>> fetchLogLocation(final URI uri, String logName) {
    final Promise<Optional<URI>> fetchPromise = new Promise<Optional<URI>>();
    final String logRootPath = uri.getPath() + "/" + logName;
    try {// www  .ja v  a 2 s .c  om
        zkc.get().exists(logRootPath, false, new AsyncCallback.StatCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, Stat stat) {
                if (Code.OK.intValue() == rc) {
                    fetchPromise.setValue(Optional.of(uri));
                } else if (Code.NONODE.intValue() == rc) {
                    fetchPromise.setValue(Optional.<URI>absent());
                } else {
                    fetchPromise.setException(KeeperException.create(Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        fetchPromise.setException(e);
    } catch (InterruptedException e) {
        fetchPromise.setException(e);
    }
    return fetchPromise;
}

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

License:Apache License

@Override
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
    Promise<List<String>> result = ((Promise<List<String>>) ctx);
    if (KeeperException.Code.OK.intValue() == rc) {
        result.setValue(children);/*  w  w  w.  j  a  v a 2s.  c  o m*/
    } else {
        result.setException(KeeperException.create(KeeperException.Code.get(rc)));
    }
}

From source file:com.twitter.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Get client id and its ephemeral owner.
 *
 * @param zkClient/*from w w  w  .j  av  a2  s.  c o m*/
 *          zookeeper client
 * @param lockPath
 *          lock path
 * @param nodeName
 *          node name
 * @return client id and its ephemeral owner.
 */
static Future<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 Future.value(Pair.of(clientId, sessionOwner));
        } catch (UnsupportedEncodingException e) {
            // if failed to parse client id, we have to get client id by zookeeper#getData.
        }
    }
    final Promise<Pair<String, Long>> promise = new Promise<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.setException(KeeperException.create(KeeperException.Code.get(rc)));
            } else {
                promise.setValue(Pair.of(deserializeClientId(data), stat.getEphemeralOwner()));
            }
        }
    }, null);
    return promise;
}

From source file:com.twitter.distributedlog.lock.ZKSessionLock.java

License:Apache License

@Override
public Future<LockWaiter> asyncTryLock(final long timeout, final TimeUnit unit) {
    final Promise<String> result = new Promise<String>();
    final boolean wait = DistributedLogConstants.LOCK_IMMEDIATE != timeout;
    if (wait) {/*from  www. j a  v  a 2 s  .co  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.setException(new LockStateChangedException(lockPath, lockId, State.INIT,
                                    lockState.getState()));
                            return;
                        }
                        if (KeeperException.Code.OK.intValue() != rc) {
                            result.setException(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))
                                    .addEventListener(new FutureEventListener<Pair<String, Long>>() {
                                        @Override
                                        public void onSuccess(Pair<String, Long> owner) {
                                            if (!checkOrClaimLockOwner(owner, result)) {
                                                acquireFuture.updateIfEmpty(new Return<Boolean>(false));
                                            }
                                        }

                                        @Override
                                        public void onFailure(final Throwable cause) {
                                            lockStateExecutor.submit(lockPath, new SafeRunnable() {
                                                @Override
                                                public void safeRun() {
                                                    result.setException(cause);
                                                }
                                            });
                                        }
                                    });
                        } else {
                            asyncTryLock(wait, result);
                        }
                    }
                });
            }
        }, null);
    }

    final Promise<Boolean> waiterAcquireFuture = new Promise<Boolean>(
            new com.twitter.util.Function<Throwable, BoxedUnit>() {
                @Override
                public BoxedUnit apply(Throwable t) {
                    acquireFuture.raise(t);
                    return BoxedUnit.UNIT;
                }
            });
    return result.map(new AbstractFunction1<String, LockWaiter>() {
        @Override
        public LockWaiter apply(final String currentOwner) {
            final Exception acquireException = new OwnershipAcquireFailedException(lockPath, currentOwner);
            FutureUtils.within(acquireFuture, timeout, unit, acquireException, lockStateExecutor, lockPath)
                    .addEventListener(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.setValue(true);
                            } else {
                                asyncUnlock().addEventListener(new FutureEventListener<BoxedUnit>() {
                                    @Override
                                    public void onSuccess(BoxedUnit value) {
                                        waiterAcquireFuture.setException(acquireCause);
                                    }

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

From source file:com.twitter.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>acquireFuture</i> will be notified either it locked successfully
 * or the lock failed. The promise will only satisfy with current lock owner.
 *
 * NOTE: the <i>promise</i> is only satisfied on <i>lockStateExecutor</i>, so any
 * transformations attached on promise will be executed in order.
 *
 * @param wait/* w  w w. j a va  2 s . c om*/
 *          whether to wait for ownership.
 * @param promise
 *          promise to satisfy with current lock owner.
 */
private void asyncTryLockWithoutCleanup(final boolean wait, final Promise<String> promise) {
    executeLockAction(epoch.get(), new LockAction() {
        @Override
        public void execute() {
            if (!lockState.inState(State.INIT)) {
                promise.setException(
                        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.setException(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.
                                        Promise<BoxedUnit> deletePromise = new Promise<BoxedUnit>();
                                        deleteLockNode(deletePromise);
                                        deletePromise.ensure(new Function0<BoxedUnit>() {
                                            public BoxedUnit apply() {
                                                promise.setException(new LockClosedException(lockPath, lockId,
                                                        lockState.getState()));
                                                return BoxedUnit.UNIT;
                                            }
                                        });
                                        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:com.twitter.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  ww.j  a v a2 s .  c  o m*/
 *          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 Promise<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.setException(
                        new LockStateChangedException(lockPath, lockId, State.PREPARED, lockState.getState()));
                return;
            }

            if (KeeperException.Code.OK.intValue() != getChildrenRc) {
                promise.setException(KeeperException.create(KeeperException.Code.get(getChildrenRc)));
                return;
            }
            if (children.isEmpty()) {
                LOG.error("Error, member list is empty for lock {}.", lockPath);
                promise.setException(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.setValue(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))
                        .addEventListener(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.setException(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.setException(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:com.twitter.distributedlog.lock.ZKSessionLock.java

License:Apache License

/**
 * Check Lock Owner Phase 3: watch sibling node for lock ownership.
 *
 * @param lockWatcher//from  w w w  . jav  a 2 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 Promise<String> promise) {
    executeLockAction(lockWatcher.epoch, new LockAction() {
        @Override
        public void execute() {
            boolean shouldWatch;
            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;
                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 && siblingNode.equals(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
                // I would watch owner instead of sibling
                shouldWatch = 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() });
                    }
                }
            }

            // 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.setException(new LockStateChangedException(lockPath, lockId,
                                            State.PREPARED, lockState.getState()));
                                    return;
                                }

                                if (KeeperException.Code.OK.intValue() == rc) {
                                    if (siblingNode.equals(ownerNode) && (lockId.compareTo(currentOwner) == 0
                                            || lockContext.hasLockId(currentOwner))) {
                                        // watch owner successfully
                                        LOG.info(
                                                "LockWatcher {} claimed ownership for {} after set watcher on {}.",
                                                new Object[] { myNode, lockPath, ownerNode });
                                        claimOwnership(lockWatcher.epoch);
                                        promise.setValue(currentOwner.getLeft());
                                    } else {
                                        // watch sibling successfully
                                        lockState.transition(State.WAITING);
                                        promise.setValue(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.setException(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.setValue(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:com.twitter.distributedlog.LogSegmentMetadata.java

License:Apache License

public static Future<LogSegmentMetadata> read(ZooKeeperClient zkc, String path,
        final boolean skipMinVersionCheck) {
    final Promise<LogSegmentMetadata> result = new Promise<LogSegmentMetadata>();
    try {/*from   www .j  av  a 2s .com*/
        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) {
                    result.setException(KeeperException.create(KeeperException.Code.get(rc)));
                    return;
                }
                try {
                    LogSegmentMetadata metadata = parseData(path, data, skipMinVersionCheck);
                    result.setValue(metadata);
                } catch (IOException ie) {
                    LOG.error("Error on parsing log segment metadata from {} : ", path, ie);
                    result.setException(ie);
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        result.setException(FutureUtils.zkException(e, path));
    } catch (InterruptedException e) {
        result.setException(FutureUtils.zkException(e, path));
    }
    return result;
}

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

License:Apache License

private void expireZooKeeperSession(ZooKeeper zk, int timeout)
        throws IOException, InterruptedException, KeeperException {
    final CountDownLatch latch = new CountDownLatch(1);

    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override/* w  w w  . j  ava 2s  .co  m*/
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.None && event.getState() == KeeperState.SyncConnected) {
                latch.countDown();
            }
        }
    }, zk.getSessionId(), zk.getSessionPasswd());

    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }

    newZk.close();
}

From source file:com.twitter.distributedlog.util.Utils.java

License:Apache License

/**
 * Retrieve data from zookeeper <code>path</code>.
 *
 * @param path/*  ww  w.  jav a2  s.  c  o  m*/
 *          zookeeper path to retrieve data
 * @param watch
 *          whether to watch the path
 * @return future representing the versioned value. null version or null value means path doesn't exist.
 */
public static Future<Versioned<byte[]>> zkGetData(ZooKeeper zk, String path, boolean watch) {
    final Promise<Versioned<byte[]>> promise = new Promise<Versioned<byte[]>>();
    zk.getData(path, watch, new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (KeeperException.Code.OK.intValue() == rc) {
                if (null == stat) {
                    promise.setValue(new Versioned<byte[]>(null, null));
                } else {
                    promise.setValue(new Versioned<byte[]>(data, new ZkVersion(stat.getVersion())));
                }
            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                promise.setValue(new Versioned<byte[]>(null, null));
            } else {
                promise.setException(KeeperException.create(KeeperException.Code.get(rc)));
            }
        }
    }, null);
    return promise;
}