List of usage examples for org.apache.zookeeper KeeperException code
Code code
To view the source code for org.apache.zookeeper KeeperException code.
Click Source Link
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/*from www . j av a2s . co m*/ * 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
private void deleteLockNode(final Promise<BoxedUnit> promise) { if (null == currentNode) { promise.setValue(BoxedUnit.UNIT); return;/*from ww w . ja v a 2s .co m*/ } 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.setValue(BoxedUnit.UNIT); } }); } }, null); }
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 www . j a va 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 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 ww w .j av a 2s.c om*/ * 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 {//w ww .ja va2s.c om 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.subscription.ZKSubscriptionsStore.java
License:Apache License
@Override public Future<Map<String, DLSN>> getLastCommitPositions() { final Promise<Map<String, DLSN>> result = new Promise<Map<String, DLSN>>(); try {//from w w w . j ava2 s . c o m this.zkc.get().getChildren(this.zkPath, false, new AsyncCallback.Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { if (KeeperException.Code.NONODE.intValue() == rc) { result.setValue(new HashMap<String, DLSN>()); } else if (KeeperException.Code.OK.intValue() != rc) { result.setException(KeeperException.create(KeeperException.Code.get(rc), path)); } else { getLastCommitPositions(result, children); } } }, null); } catch (ZooKeeperClient.ZooKeeperConnectionException zkce) { result.setException(zkce); } catch (InterruptedException ie) { result.setException(new DLInterruptedException("getLastCommitPositions was interrupted", ie)); } return result; }
From source file:com.twitter.distributedlog.subscription.ZKSubscriptionStateStore.java
License:Apache License
Future<DLSN> getLastCommitPositionFromZK() { final Promise<DLSN> result = new Promise<DLSN>(); try {/*from w w w . ja v a2 s . c o m*/ logger.debug("Reading last commit position from path {}", zkPath); zooKeeperClient.get().getData(zkPath, false, new AsyncCallback.DataCallback() { @Override public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { logger.debug("Read last commit position from path {}: rc = {}", zkPath, rc); if (KeeperException.Code.NONODE.intValue() == rc) { result.setValue(DLSN.NonInclusiveLowerBound); } else if (KeeperException.Code.OK.intValue() != rc) { result.setException(KeeperException.create(KeeperException.Code.get(rc), path)); } else { try { DLSN dlsn = DLSN.deserialize(new String(data, Charsets.UTF_8)); result.setValue(dlsn); } catch (Exception t) { logger.warn("Invalid last commit position found from path {}", zkPath, t); // invalid dlsn recorded in subscription state store result.setValue(DLSN.NonInclusiveLowerBound); } } } }, null); } catch (ZooKeeperClient.ZooKeeperConnectionException zkce) { result.setException(zkce); } catch (InterruptedException ie) { result.setException(new DLInterruptedException("getLastCommitPosition was interrupted", ie)); } return result; }
From source file:com.twitter.distributedlog.TestBKDistributedLogNamespace.java
License:Apache License
@Test(timeout = 60000) public void testAclModifyPermsDlmConflict() throws Exception { String streamName = "test-stream"; // Reopening and writing again with the same un will succeed. initDlogMeta("/" + runtime.getMethodName(), "test-un", streamName); try {//from w w w . j ava 2s . c o m // Reopening and writing again with a different un will fail. initDlogMeta("/" + runtime.getMethodName(), "not-test-un", streamName); fail("write should have failed due to perms"); } catch (ZKException ex) { LOG.info("caught exception trying to write with no perms {}", ex); assertEquals(KeeperException.Code.NOAUTH, ex.getKeeperExceptionCode()); } catch (Exception ex) { LOG.info("caught wrong exception trying to write with no perms {}", ex); fail("wrong exception " + ex.getClass().getName() + " expected " + LockingException.class.getName()); } // Should work again. initDlogMeta("/" + runtime.getMethodName(), "test-un", streamName); }
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/*from ww w.ja v a 2s . c o 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.tools.TestDistributedLogTool.java
License:Apache License
@Test(timeout = 60000) public void testToolCreateZkAclId() throws Exception { createStream(defaultUri, "0", "CreateAclStream", defaultPrivilegedZkAclId); try {/*from w ww .j ava 2 s . c o m*/ DistributedLogManager dlm = DLMTestUtil.createNewDLM("0CreateAclStream", conf, defaultUri); DLMTestUtil.generateCompletedLogSegments(dlm, conf, 3, 1000); dlm.close(); } catch (ZKException ex) { assertEquals(KeeperException.Code.NOAUTH, ex.getKeeperExceptionCode()); } }