Java Code Examples for org.apache.zookeeper.KeeperException#create()

The following examples show how to use org.apache.zookeeper.KeeperException#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActiveStandbyElector.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Waits for the next event from ZooKeeper to arrive.
 * 
 * @param connectionTimeoutMs zookeeper connection timeout in milliseconds
 * @throws KeeperException if the connection attempt times out. This will
 * be a ZooKeeper ConnectionLoss exception code.
 * @throws IOException if interrupted while connecting to ZooKeeper
 */
private void waitForZKConnectionEvent(int connectionTimeoutMs)
    throws KeeperException, IOException {
  try {
    if (!hasReceivedEvent.await(connectionTimeoutMs, TimeUnit.MILLISECONDS)) {
      LOG.error("Connection timed out: couldn't connect to ZooKeeper in "
          + connectionTimeoutMs + " milliseconds");
      zk.close();
      throw KeeperException.create(Code.CONNECTIONLOSS);
    }
  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    throw new IOException(
        "Interrupted when connecting to zookeeper server", e);
  }
}
 
Example 2
Source File: ZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Override
protected void abortOpResult(Throwable t,
                             @Nullable OpResult opResult) {
    Throwable cause;
    if (null == opResult) {
        cause = t;
    } else {
        assert (opResult instanceof OpResult.ErrorResult);
        OpResult.ErrorResult errorResult = (OpResult.ErrorResult) opResult;
        if (KeeperException.Code.OK.intValue() == errorResult.getErr()) {
            cause = t;
        } else {
            cause = KeeperException.create(KeeperException.Code.get(errorResult.getErr()));
        }
    }
    if (null != listener) {
        listener.onAbort(cause);
    }
}
 
Example 3
Source File: ZKUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the specified node with the specified data and watches it.
 *
 * <p>Throws an exception if the node already exists.
 *
 * <p>The node created is persistent and open access.
 *
 * <p>Returns the version number of the created node if successful.
 *
 * @param zkw zk reference
 * @param znode path of node to create
 * @param data data of node to create
 * @return version of node created
 * @throws KeeperException if unexpected zookeeper exception
 * @throws KeeperException.NodeExistsException if node already exists
 */
public static int createAndWatch(ZKWatcher zkw,
    String znode, byte [] data)
  throws KeeperException, KeeperException.NodeExistsException {
  try {
    zkw.getRecoverableZooKeeper().create(znode, data, createACL(zkw, znode),
        CreateMode.PERSISTENT);
    Stat stat = zkw.getRecoverableZooKeeper().exists(znode, zkw);
    if (stat == null){
      // Likely a race condition. Someone deleted the znode.
      throw KeeperException.create(KeeperException.Code.SYSTEMERROR,
          "ZK.exists returned null (i.e.: znode does not exist) for znode=" + znode);
    }

    return stat.getVersion();
  } catch (InterruptedException e) {
    zkw.interruptedException(e);
    return -1;
  }
}
 
Example 4
Source File: TestZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testAbortNullOpResult() throws Exception {
    final AtomicReference<Throwable> exception =
            new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp =
            new ZKVersionedSetOp(mock(Op.class), new Transaction.OpListener<Version>() {
                @Override
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    versionedSetOp.abortOpResult(ke, null);
    latch.await();
    assertTrue(ke == exception.get());
}
 
Example 5
Source File: TestZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testAbortOpResult() throws Exception {
    final AtomicReference<Throwable> exception =
            new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp =
            new ZKVersionedSetOp(mock(Op.class), new Transaction.OpListener<Version>() {
                @Override
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    OpResult opResult = new OpResult.ErrorResult(KeeperException.Code.NONODE.intValue());
    versionedSetOp.abortOpResult(ke, opResult);
    latch.await();
    assertTrue(exception.get() instanceof KeeperException.NoNodeException);
}
 
Example 6
Source File: TestZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
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
        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();
}
 
Example 7
Source File: ZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Override
protected void abortOpResult(Throwable t,
                             @Nullable OpResult opResult) {
    Throwable cause;
    if (null == opResult) {
        cause = t;
    } else {
        assert (opResult instanceof OpResult.ErrorResult);
        OpResult.ErrorResult errorResult = (OpResult.ErrorResult) opResult;
        if (KeeperException.Code.OK.intValue() == errorResult.getErr()) {
            cause = t;
        } else {
            cause = KeeperException.create(KeeperException.Code.get(errorResult.getErr()));
        }
    }
    listener.onAbort(cause);
}
 
Example 8
Source File: TestZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testAbortNullOpResult() throws Exception {
    final AtomicReference<Throwable> exception =
            new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp =
            new ZKVersionedSetOp(mock(Op.class), new Transaction.OpListener<Version>() {
                @Override
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    versionedSetOp.abortOpResult(ke, null);
    latch.await();
    assertTrue(ke == exception.get());
}
 
Example 9
Source File: TestZKVersionedSetOp.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 60000)
public void testAbortOpResult() throws Exception {
    final AtomicReference<Throwable> exception =
            new AtomicReference<Throwable>();
    final CountDownLatch latch = new CountDownLatch(1);
    ZKVersionedSetOp versionedSetOp =
            new ZKVersionedSetOp(mock(Op.class), new Transaction.OpListener<Version>() {
                @Override
                public void onCommit(Version r) {
                    // no-op
                }

                @Override
                public void onAbort(Throwable t) {
                    exception.set(t);
                    latch.countDown();
                }
            });
    KeeperException ke = KeeperException.create(KeeperException.Code.SESSIONEXPIRED);
    OpResult opResult = new OpResult.ErrorResult(KeeperException.Code.NONODE.intValue());
    versionedSetOp.abortOpResult(ke, opResult);
    latch.await();
    assertTrue(exception.get() instanceof KeeperException.NoNodeException);
}
 
Example 10
Source File: TestZooKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
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
        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();
}
 
Example 11
Source File: AsyncResultImpl.java    From curator with Apache License 2.0 5 votes vote down vote up
@Override
public void checkError()
{
    checkException();
    if ( code != KeeperException.Code.OK )
    {
        throw new RuntimeException(KeeperException.create(code));
    }
}
 
Example 12
Source File: CuratorFrameworkImpl.java    From xian with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
private <DATA_TYPE> boolean checkBackgroundRetry(OperationAndData<DATA_TYPE> operationAndData, CuratorEvent event)
{
    boolean doRetry = false;
    if ( client.getRetryPolicy().allowRetry(operationAndData.getThenIncrementRetryCount(), operationAndData.getElapsedTimeMs(), operationAndData) )
    {
        doRetry = true;
    }
    else
    {
        if ( operationAndData.getErrorCallback() != null )
        {
            operationAndData.getErrorCallback().retriesExhausted(operationAndData);
        }

        if ( operationAndData.getCallback() != null )
        {
            sendToBackgroundCallback(operationAndData, event);
        }

        KeeperException.Code code = KeeperException.Code.get(event.getResultCode());
        Exception e = null;
        try
        {
            e = (code != null) ? KeeperException.create(code) : null;
        }
        catch ( Throwable t )
        {
            ThreadUtils.checkInterrupted(t);
        }
        if ( e == null )
        {
            e = new Exception("Unknown result codegetResultCode()");
        }

        validateConnection(codeToState(code));
        logError("Background operation retry gave up", e);
    }
    return doRetry;
}
 
Example 13
Source File: ZKMetadataStore.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static MetadataStoreException getException(Code code, String path) {
    KeeperException ex = KeeperException.create(code, path);

    switch (code) {
    case BADVERSION:
        return new BadVersionException(ex);
    case NONODE:
        return new NotFoundException(ex);
    default:
        return new MetadataStoreException(ex);
    }
}
 
Example 14
Source File: ZooKeeperChildrenCache.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public Set<String> get(String path) throws KeeperException, InterruptedException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getChildren called at: {}", path);
    }

    Set<String> children = cache.getChildrenAsync(path, this).join();
    if (children == null) {
        throw KeeperException.create(KeeperException.Code.NONODE);
    }

    return children;
}
 
Example 15
Source File: ZooKeeperManagedLedgerCache.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public Set<String> get(String path) throws KeeperException, InterruptedException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getChildren called at: {}", path);
    }

    Set<String> children = cache.getChildrenAsync(path, this).join();
    if (children == null) {
        throw KeeperException.create(KeeperException.Code.NONODE);
    }

    return children;
}
 
Example 16
Source File: AdminResource.java    From pulsar with Apache License 2.0 5 votes vote down vote up
protected void zkSync(String path) throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    AtomicInteger rc = new AtomicInteger(KeeperException.Code.OK.intValue());
    globalZk().sync(path, (rc2, s, ctx) -> {
        if (KeeperException.Code.OK.intValue() != rc2) {
            rc.set(rc2);
        }
        latch.countDown();
    }, null);
    latch.await();
    if (KeeperException.Code.OK.intValue() != rc.get()) {
        throw KeeperException.create(KeeperException.Code.get(rc.get()));
    }
}
 
Example 17
Source File: FutureUtils.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the <i>throwable</i> to zookeeper related exceptions.
 *
 * @param throwable cause
 * @param path zookeeper path
 * @return zookeeper related exceptions
 */
public static Throwable zkException(Throwable throwable, String path) {
    if (throwable instanceof KeeperException) {
        return throwable;
    } else if (throwable instanceof ZooKeeperClient.ZooKeeperConnectionException) {
        return KeeperException.create(KeeperException.Code.CONNECTIONLOSS, path);
    } else if (throwable instanceof InterruptedException) {
        return new DLInterruptedException("Interrupted on operating " + path, throwable);
    } else {
        return new UnexpectedException("Encountered unexpected exception on operatiing " + path, throwable);
    }
}
 
Example 18
Source File: ZKTransaction.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
    if (KeeperException.Code.OK.intValue() == rc) { // transaction succeed
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).commitOpResult(results.get(i));
        }
        FutureUtils.setValue(result, null);
    } else {
        KeeperException ke = KeeperException.create(KeeperException.Code.get(rc));
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).abortOpResult(ke, null != results ? results.get(i) : null);
        }
        FutureUtils.setException(result, ke);
    }
}
 
Example 19
Source File: ZKTransaction.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
public void processResult(int rc, String path, Object ctx, List<OpResult> results) {
    if (KeeperException.Code.OK.intValue() == rc) { // transaction succeed
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).commitOpResult(results.get(i));
        }
        FutureUtils.complete(result, null);
    } else {
        KeeperException ke = KeeperException.create(KeeperException.Code.get(rc));
        for (int i = 0; i < ops.size(); i++) {
            ops.get(i).abortOpResult(ke, null != results ? results.get(i) : null);
        }
        FutureUtils.completeExceptionally(result, ke);
    }
}
 
Example 20
Source File: CuratorAsyncManager.java    From Singularity with Apache License 2.0 5 votes vote down vote up
private void checkLatch(CountDownLatch latch, String path) throws InterruptedException {
  if (!latch.await(configuration.getZookeeperAsyncTimeout(), TimeUnit.MILLISECONDS)) {
    throw new IllegalStateException(
      String.format(
        "Timed out waiting response for objects from %s, waited %s millis",
        path,
        configuration.getZookeeperAsyncTimeout()
      ),
      KeeperException.create(Code.OPERATIONTIMEOUT, path)
    );
  }
}