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.impl.TestZKLogSegmentMetadataStore.java
License:Apache License
@Test(timeout = 60000) public void testDeleteNonExistentLogSegment() throws Exception { LogSegmentMetadata segment = createLogSegment(1L); Transaction<Object> deleteTxn = lsmStore.transaction(); lsmStore.deleteLogSegment(deleteTxn, segment); try {/*from w w w.j ava 2 s . c o m*/ FutureUtils.result(deleteTxn.execute()); fail("Should fail deletion if log segment doesn't exist"); } catch (Throwable t) { assertTrue("Should throw NoNodeException if log segment doesn't exist", t instanceof ZKException); ZKException zke = (ZKException) t; assertEquals("Should throw NoNodeException if log segment doesn't exist", KeeperException.Code.NONODE, zke.getKeeperExceptionCode()); } }
From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java
License:Apache License
@Test(timeout = 60000) public void testUpdateNonExistentLogSegment() throws Exception { LogSegmentMetadata segment = createLogSegment(1L); Transaction<Object> updateTxn = lsmStore.transaction(); lsmStore.updateLogSegment(updateTxn, segment); try {//from ww w. j a v a 2 s . c om FutureUtils.result(updateTxn.execute()); fail("Should fail update if log segment doesn't exist"); } catch (Throwable t) { assertTrue("Should throw NoNodeException if log segment doesn't exist", t instanceof ZKException); ZKException zke = (ZKException) t; assertEquals("Should throw NoNodeException if log segment doesn't exist", KeeperException.Code.NONODE, zke.getKeeperExceptionCode()); } }
From source file:com.twitter.distributedlog.impl.TestZKLogSegmentMetadataStore.java
License:Apache License
@Test(timeout = 60000) public void testCreateDeleteLogSegmentFailure() throws Exception { LogSegmentMetadata segment1 = createLogSegment(1L); LogSegmentMetadata segment2 = createLogSegment(2L); LogSegmentMetadata segment3 = createLogSegment(3L); // create log segment 1 Transaction<Object> createTxn = lsmStore.transaction(); lsmStore.createLogSegment(createTxn, segment1); FutureUtils.result(createTxn.execute()); // the log segment should be created assertNotNull("LogSegment " + segment1 + " should be created", zkc.get().exists(segment1.getZkPath(), false)); // delete log segment 1 and delete log segment 2 Transaction<Object> createDeleteTxn = lsmStore.transaction(); lsmStore.deleteLogSegment(createDeleteTxn, segment1); lsmStore.deleteLogSegment(createDeleteTxn, segment2); lsmStore.createLogSegment(createDeleteTxn, segment3); try {//from w w w . ja v a 2 s .co m FutureUtils.result(createDeleteTxn.execute()); fail("Should fail transaction if one operation failed"); } catch (Throwable t) { assertTrue("Transaction is aborted", t instanceof ZKException); ZKException zke = (ZKException) t; assertEquals("Transaction is aborted", KeeperException.Code.NONODE, zke.getKeeperExceptionCode()); } // segment 1 should not be deleted assertNotNull("LogSegment " + segment1 + " should not be deleted", zkc.get().exists(segment1.getZkPath(), false)); // segment 3 should not be created assertNull("LogSegment " + segment3 + " should be created", zkc.get().exists(segment3.getZkPath(), false)); }
From source file:com.twitter.distributedlog.impl.ZKLogMetadataStore.java
License:Apache License
@Override public Future<Iterator<String>> getLogs() { final Promise<Iterator<String>> promise = new Promise<Iterator<String>>(); final String nsRootPath = namespace.getPath(); try {/*from ww w . j a v a2 s. c o m*/ final ZooKeeper zk = zkc.get(); zk.sync(nsRootPath, new AsyncCallback.VoidCallback() { @Override public void processResult(int syncRc, String syncPath, Object ctx) { if (KeeperException.Code.OK.intValue() == syncRc) { zk.getChildren(nsRootPath, false, new AsyncCallback.Children2Callback() { @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { if (KeeperException.Code.OK.intValue() == rc) { List<String> results = Lists.newArrayListWithExpectedSize(children.size()); for (String child : children) { if (!isReservedStreamName(child)) { results.add(child); } } promise.setValue(results.iterator()); } else if (KeeperException.Code.NONODE.intValue() == rc) { List<String> streams = Lists.newLinkedList(); promise.setValue(streams.iterator()); } else { promise.setException(new ZKException("Error reading namespace " + nsRootPath, KeeperException.Code.get(rc))); } } }, null); } else if (KeeperException.Code.NONODE.intValue() == syncRc) { List<String> streams = Lists.newLinkedList(); promise.setValue(streams.iterator()); } else { promise.setException(new ZKException("Error reading namespace " + nsRootPath, KeeperException.Code.get(syncRc))); } } }, null); zkc.get(); } catch (ZooKeeperClient.ZooKeeperConnectionException e) { promise.setException(e); } catch (InterruptedException e) { promise.setException(e); } return promise; }
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);/*from w w w . j a v a 2 s . c o m*/ } else { result.setException(KeeperException.create(KeeperException.Code.get(rc))); } }
From source file:com.twitter.distributedlog.impl.ZKNamespaceWatcher.java
License:Apache License
@Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { if (KeeperException.Code.OK.intValue() == rc) { logger.info("Received updated logs under {} : {}", uri, children); List<String> result = new ArrayList<String>(children.size()); for (String s : children) { if (isReservedStreamName(s)) { continue; }/* w ww.j ava 2 s. c o m*/ result.add(s); } for (NamespaceListener listener : listeners) { listener.onStreamsChanged(result.iterator()); } } else { scheduleTask(this, conf.getZKSessionTimeoutMilliseconds()); } }
From source file:com.twitter.distributedlog.lock.TestZKSessionLock.java
License:Apache License
/** * Test lock on non existed lock./*from w w w . ja v a2 s .c o m*/ * * - lock should fail on a non existed lock. * * @throws Exception */ @Test(timeout = 60000) public void testLockOnNonExistedLock() throws Exception { String lockPath = "/test-lock-on-non-existed-lock"; String clientId = "test-lock-on-non-existed-lock"; ZKSessionLock lock = new ZKSessionLock(zkc, lockPath, clientId, lockStateExecutor); // lock try { lock.tryLock(0, TimeUnit.MILLISECONDS); fail("Should fail on locking a non-existed lock."); } catch (LockingException le) { Throwable cause = le.getCause(); assertTrue(cause instanceof KeeperException); assertEquals(KeeperException.Code.NONODE, ((KeeperException) cause).code()); } assertEquals(State.CLOSED, lock.getLockState()); // lock should failed on a failure lock try { lock.tryLock(0, TimeUnit.MILLISECONDS); fail("Should fail on locking a failure lock."); } catch (LockStateChangedException lsce) { // expected } assertEquals(State.CLOSED, lock.getLockState()); }
From source file:com.twitter.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/*from w ww.j a v a 2s . co 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 = new Promise<Boolean>(new com.twitter.util.Function<Throwable, BoxedUnit>() { @Override public BoxedUnit apply(Throwable t) { // 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(t); // Note re. logging and exceptions: errors are already logged by unlockAsync. return BoxedUnit.UNIT; } }); }
From source file:com.twitter.distributedlog.lock.ZKSessionLock.java
License:Apache License
/** * Get client id and its ephemeral owner. * * @param zkClient//from www. j a va 2s. com * 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 w w w. jav a 2 s . 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.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); } }); }