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.curator.x.async.TestBasicOperations.java

License:Apache License

@Test
public void testException() {
    CountDownLatch latch = new CountDownLatch(1);
    client.getData().forPath("/woop").exceptionally(e -> {
        Assert.assertTrue(e instanceof KeeperException);
        Assert.assertEquals(((KeeperException) e).code(), KeeperException.Code.NONODE);
        latch.countDown();/*  w  ww. j  a  v  a  2s  .  c  o  m*/
        return null;
    });
    Assert.assertTrue(timing.awaitLatch(latch));
}

From source file:org.apache.curator.x.async.TestBasicOperations.java

License:Apache License

@Test
public void testResultWrapper() throws Exception {
    CompletionStage<AsyncResult<String>> resultStage = AsyncResult.of(client.create().forPath("/first"));
    complete(resultStage, (v, e) -> {
        Assert.assertNull(e);//from   w ww  .j a  va2s .  c  om
        Assert.assertEquals(v.getRawValue(), "/first");
        Assert.assertNull(v.getRawException());
        Assert.assertEquals(v.getCode(), KeeperException.Code.OK);
    });

    resultStage = AsyncResult.of(client.create().forPath("/foo/bar"));
    complete(resultStage, (v, e) -> {
        Assert.assertNull(e);
        Assert.assertNull(v.getRawValue());
        Assert.assertNull(v.getRawException());
        Assert.assertEquals(v.getCode(), KeeperException.Code.NONODE);
    });

    resultStage = AsyncResult.of(client.create().forPath("illegal path"));
    complete(resultStage, (v, e) -> {
        Assert.assertNull(e);
        Assert.assertNull(v.getRawValue());
        Assert.assertNotNull(v.getRawException());
        Assert.assertTrue(v.getRawException() instanceof IllegalArgumentException);
        Assert.assertEquals(v.getCode(), KeeperException.Code.SYSTEMERROR);
    });

    server.stop();
    resultStage = AsyncResult.of(client.create().forPath("/second"));
    complete(resultStage, (v, e) -> {
        Assert.assertNull(e);
        Assert.assertNull(v.getRawValue());
        Assert.assertNull(v.getRawException());
        Assert.assertEquals(v.getCode(), KeeperException.Code.CONNECTIONLOSS);
    });
}

From source file:org.apache.curator.x.rpc.idl.exceptions.RpcException.java

License:Apache License

public RpcException(Exception e) {
    this.message = e.getLocalizedMessage();
    if (this.message == null) {
        StringWriter str = new StringWriter();
        e.printStackTrace(new PrintWriter(str));
        this.message = str.toString();
    }/*from  w w w.  j  a v a 2  s. c  om*/

    if (KeeperException.class.isAssignableFrom(e.getClass())) {
        KeeperException keeperException = (KeeperException) e;
        switch (keeperException.code()) {
        default: {
            type = ExceptionType.ZOOKEEPER;
            zooKeeperException = ZooKeeperExceptionType.valueOf(keeperException.code().name());
            nodeException = null;
            break;
        }

        case NONODE:
        case NODEEXISTS:
        case NOTEMPTY:
        case BADVERSION: {
            type = ExceptionType.NODE;
            zooKeeperException = null;
            nodeException = NodeExceptionType.valueOf(keeperException.code().name());
            break;
        }
        }
    } else {
        type = ExceptionType.GENERAL;
    }
}

From source file:org.apache.distributedlog.auditor.DLAuditor.java

License:Apache License

private void collectLedgersFromAllocator(final URI uri, final Namespace namespace,
        final List<String> allocationPaths, final Set<Long> ledgers) throws IOException {
    final LinkedBlockingQueue<String> poolQueue = new LinkedBlockingQueue<String>();
    for (String allocationPath : allocationPaths) {
        String rootPath = uri.getPath() + "/" + allocationPath;
        try {/*from ww  w  .j a v a 2s. com*/
            List<String> pools = getZooKeeperClient(namespace).get().getChildren(rootPath, false);
            for (String pool : pools) {
                poolQueue.add(rootPath + "/" + pool);
            }
        } catch (KeeperException e) {
            throw new ZKException("Failed to get list of pools from " + rootPath, e);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new DLInterruptedException("Interrupted on getting list of pools from " + rootPath, e);
        }
    }

    logger.info("Collecting ledgers from allocators for {} : {}", uri, poolQueue);

    executeAction(poolQueue, 10, new Action<String>() {
        @Override
        public void execute(String poolPath) throws IOException {
            try {
                collectLedgersFromPool(poolPath);
            } catch (InterruptedException e) {
                throw new DLInterruptedException(
                        "Interrupted on collecting" + " ledgers from allocation pool " + poolPath, e);
            } catch (KeeperException e) {
                throw new ZKException("Failed to collect ledgers from allocation pool " + poolPath, e.code());
            }
        }

        private void collectLedgersFromPool(String poolPath)
                throws InterruptedException, ZooKeeperClient.ZooKeeperConnectionException, KeeperException {
            List<String> allocators = getZooKeeperClient(namespace).get().getChildren(poolPath, false);
            for (String allocator : allocators) {
                String allocatorPath = poolPath + "/" + allocator;
                byte[] data = getZooKeeperClient(namespace).get().getData(allocatorPath, false, new Stat());
                if (null != data && data.length > 0) {
                    try {
                        long ledgerId = DLUtils.bytes2LogSegmentId(data);
                        synchronized (ledgers) {
                            ledgers.add(ledgerId);
                        }
                    } catch (NumberFormatException nfe) {
                        logger.warn("Invalid ledger found in allocator path {} : ", allocatorPath, nfe);
                    }
                }
            }
        }
    });

    logger.info("Collected ledgers from allocators for {}.", uri);
}

From source file:org.apache.distributedlog.bk.LedgerAllocatorPool.java

License:Apache License

/**
 * Initialize simple allocators with given list of allocator names <i>allocators</i>.
 * It initializes a simple allocator with its simple allocator path.
 *//*w  w w  .ja  v a2s  . co  m*/
private void initializeAllocators(List<String> allocators) throws IOException, InterruptedException {
    final AtomicInteger numPendings = new AtomicInteger(allocators.size());
    final AtomicInteger numFailures = new AtomicInteger(0);
    final CountDownLatch latch = new CountDownLatch(numPendings.get() > 0 ? 1 : 0);
    AsyncCallback.DataCallback dataCallback = new AsyncCallback.DataCallback() {
        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (KeeperException.Code.OK.intValue() != rc) {
                numFailures.incrementAndGet();
                latch.countDown();
                return;
            }
            Versioned<byte[]> allocatorData = new Versioned<byte[]>(data, new LongVersion(stat.getVersion()));
            SimpleLedgerAllocator allocator = new SimpleLedgerAllocator(path, allocatorData,
                    quorumConfigProvider, zkc, bkc);
            allocator.start();
            pendingList.add(allocator);
            if (numPendings.decrementAndGet() == 0 && numFailures.get() == 0) {
                latch.countDown();
            }
        }
    };
    for (String name : allocators) {
        String path = poolPath + "/" + name;
        zkc.get().getData(path, false, dataCallback, null);
    }
    latch.await();
    if (numFailures.get() > 0) {
        throw new IOException("Failed to initialize allocators : " + allocators);
    }
}

From source file:org.apache.distributedlog.bk.LedgerAllocatorPool.java

License:Apache License

/**
 * Rescue a ledger allocator from an ERROR state.
 * @param ledgerAllocator/*from w ww  .  j  a v a  2  s.co m*/
 *          ledger allocator to rescue
 */
private void rescueAllocator(final SimpleLedgerAllocator ledgerAllocator) throws DLInterruptedException {
    SimpleLedgerAllocator oldAllocator;
    synchronized (this) {
        oldAllocator = rescueMap.put(ledgerAllocator.allocatePath, ledgerAllocator);
    }
    if (oldAllocator != null) {
        logger.info("ledger allocator {} is being rescued.", ledgerAllocator.allocatePath);
        return;
    }
    try {
        zkc.get().getData(ledgerAllocator.allocatePath, false, new AsyncCallback.DataCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
                boolean retry = false;
                SimpleLedgerAllocator newAllocator = null;
                if (KeeperException.Code.OK.intValue() == rc) {
                    Versioned<byte[]> allocatorData = new Versioned<byte[]>(data,
                            new LongVersion(stat.getVersion()));
                    logger.info("Rescuing ledger allocator {}.", path);
                    newAllocator = new SimpleLedgerAllocator(path, allocatorData, quorumConfigProvider, zkc,
                            bkc);
                    newAllocator.start();
                    logger.info("Rescued ledger allocator {}.", path);
                } else if (KeeperException.Code.NONODE.intValue() == rc) {
                    logger.info("Ledger allocator {} doesn't exist, skip rescuing it.", path);
                } else {
                    retry = true;
                }
                synchronized (LedgerAllocatorPool.this) {
                    rescueMap.remove(ledgerAllocator.allocatePath);
                    if (null != newAllocator) {
                        pendingList.addLast(newAllocator);
                    }
                }
                if (retry) {
                    scheduleAllocatorRescue(ledgerAllocator);
                }
            }
        }, null);
    } catch (InterruptedException ie) {
        logger.warn("Interrupted on rescuing ledger allocator {} : ", ledgerAllocator.allocatePath, ie);
        synchronized (LedgerAllocatorPool.this) {
            rescueMap.remove(ledgerAllocator.allocatePath);
        }
        throw new DLInterruptedException(
                "Interrupted on rescuing ledger allocator " + ledgerAllocator.allocatePath, ie);
    } catch (IOException ioe) {
        logger.warn("Failed to rescue ledger allocator {}, retry rescuing it later : ",
                ledgerAllocator.allocatePath, ioe);
        synchronized (LedgerAllocatorPool.this) {
            rescueMap.remove(ledgerAllocator.allocatePath);
        }
        scheduleAllocatorRescue(ledgerAllocator);
    }
}

From source file:org.apache.distributedlog.bk.SimpleLedgerAllocator.java

License:Apache License

private static CompletableFuture<Versioned<byte[]>> createAllocationData(final String allocatePath,
        final ZooKeeperClient zkc) {
    try {/*from   w  w  w  . ja v  a 2 s .  com*/
        final CompletableFuture<Versioned<byte[]>> promise = new CompletableFuture<Versioned<byte[]>>();
        zkc.get().create(allocatePath, DistributedLogConstants.EMPTY_BYTES, zkc.getDefaultACL(),
                CreateMode.PERSISTENT, new org.apache.zookeeper.AsyncCallback.Create2Callback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name, Stat stat) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            promise.complete(new Versioned<byte[]>(DistributedLogConstants.EMPTY_BYTES,
                                    new LongVersion(stat.getVersion())));
                        } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {
                            FutureUtils.proxyTo(Utils.zkGetData(zkc, allocatePath, false), promise);
                        } else {
                            promise.completeExceptionally(Utils.zkException(
                                    KeeperException.create(KeeperException.Code.get(rc)), allocatePath));
                        }
                    }
                }, null);
        return promise;
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        return FutureUtils.exception(Utils.zkException(e, allocatePath));
    } catch (InterruptedException e) {
        return FutureUtils.exception(Utils.zkException(e, allocatePath));
    }
}

From source file:org.apache.distributedlog.bk.TestLedgerAllocator.java

License:Apache License

@Test(timeout = 60000)
public void testBadVersionOnTwoAllocators() throws Exception {
    String allocationPath = "/allocation-bad-version";
    zkc.get().create(allocationPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    Stat stat = new Stat();
    byte[] data = zkc.get().getData(allocationPath, false, stat);
    Versioned<byte[]> allocationData = new Versioned<byte[]>(data, new LongVersion(stat.getVersion()));

    SimpleLedgerAllocator allocator1 = new SimpleLedgerAllocator(allocationPath, allocationData,
            newQuorumConfigProvider(dlConf), zkc, bkc);
    SimpleLedgerAllocator allocator2 = new SimpleLedgerAllocator(allocationPath, allocationData,
            newQuorumConfigProvider(dlConf), zkc, bkc);
    allocator1.allocate();/*from w w  w  . j  a v a 2s .c o m*/
    // wait until allocated
    ZKTransaction txn1 = newTxn();
    LedgerHandle lh = Utils.ioResult(allocator1.tryObtain(txn1, NULL_LISTENER));
    allocator2.allocate();
    ZKTransaction txn2 = newTxn();
    try {
        Utils.ioResult(allocator2.tryObtain(txn2, NULL_LISTENER));
        fail("Should fail allocating on second allocator as allocator1 is starting allocating something.");
    } catch (ZKException ke) {
        assertEquals(KeeperException.Code.BADVERSION, ke.getKeeperExceptionCode());
    }
    Utils.ioResult(txn1.execute());
    Utils.close(allocator1);
    Utils.close(allocator2);

    long eid = lh.addEntry("hello world".getBytes());
    lh.close();
    LedgerHandle readLh = bkc.get().openLedger(lh.getId(), BookKeeper.DigestType.CRC32,
            dlConf.getBKDigestPW().getBytes());
    Enumeration<LedgerEntry> entries = readLh.readEntries(eid, eid);
    int i = 0;
    while (entries.hasMoreElements()) {
        LedgerEntry entry = entries.nextElement();
        assertEquals("hello world", new String(entry.getEntry(), UTF_8));
        ++i;
    }
    assertEquals(1, i);
}

From source file:org.apache.distributedlog.impl.acl.ZKAccessControl.java

License:Apache License

public CompletableFuture<ZKAccessControl> create(ZooKeeperClient zkc) {
    final CompletableFuture<ZKAccessControl> promise = new CompletableFuture<ZKAccessControl>();
    try {//from w  ww . j a v  a 2  s  .  c  om
        zkc.get().create(zkPath, serialize(accessControlEntry), zkc.getDefaultACL(), CreateMode.PERSISTENT,
                new AsyncCallback.StringCallback() {
                    @Override
                    public void processResult(int rc, String path, Object ctx, String name) {
                        if (KeeperException.Code.OK.intValue() == rc) {
                            ZKAccessControl.this.zkVersion = 0;
                            promise.complete(ZKAccessControl.this);
                        } else {
                            promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
                        }
                    }
                }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.completeExceptionally(e);
    } catch (InterruptedException e) {
        promise.completeExceptionally(e);
    } catch (IOException e) {
        promise.completeExceptionally(e);
    }
    return promise;
}

From source file:org.apache.distributedlog.impl.acl.ZKAccessControl.java

License:Apache License

public CompletableFuture<ZKAccessControl> update(ZooKeeperClient zkc) {
    final CompletableFuture<ZKAccessControl> promise = new CompletableFuture<ZKAccessControl>();
    try {/* w w  w .  j av a 2s.c o  m*/
        zkc.get().setData(zkPath, serialize(accessControlEntry), zkVersion, new AsyncCallback.StatCallback() {
            @Override
            public void processResult(int rc, String path, Object ctx, Stat stat) {
                if (KeeperException.Code.OK.intValue() == rc) {
                    ZKAccessControl.this.zkVersion = stat.getVersion();
                    promise.complete(ZKAccessControl.this);
                } else {
                    promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
                }
            }
        }, null);
    } catch (ZooKeeperClient.ZooKeeperConnectionException e) {
        promise.completeExceptionally(e);
    } catch (InterruptedException e) {
        promise.completeExceptionally(e);
    } catch (IOException e) {
        promise.completeExceptionally(e);
    }
    return promise;
}