Search in sources :

Example 1 with BKException

use of org.apache.bookkeeper.client.BKException in project distributedlog by twitter.

the class LedgerBatchReader method run.

@Override
public void run() {
    long lac = lh.getLastAddConfirmed();
    long entryId = 0L;
    while (entryId <= lac) {
        long startEntryId = entryId;
        long endEntryId = Math.min(startEntryId + batchSize - 1, lac);
        Enumeration<LedgerEntry> entries = null;
        while (null == entries) {
            try {
                entries = lh.readEntries(startEntryId, endEntryId);
            } catch (BKException bke) {
                logger.error("Encountered exceptions on reading [ {} - {} ] ", new Object[] { startEntryId, endEntryId, bke });
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                break;
            }
        }
        if (null == entries) {
            break;
        }
        while (entries.hasMoreElements()) {
            LedgerEntry entry = entries.nextElement();
            readEntryListener.onEntryComplete(BKException.Code.OK, lh, entry, null);
        }
        entryId = endEntryId + 1;
    }
}
Also used : LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) BKException(org.apache.bookkeeper.client.BKException)

Example 2 with BKException

use of org.apache.bookkeeper.client.BKException in project distributedlog by twitter.

the class BKLogWriteHandler method deleteLogSegment.

private Future<LogSegmentMetadata> deleteLogSegment(final LogSegmentMetadata ledgerMetadata) {
    LOG.info("Deleting ledger {} for {}", ledgerMetadata, getFullyQualifiedName());
    final Promise<LogSegmentMetadata> promise = new Promise<LogSegmentMetadata>();
    final Stopwatch stopwatch = Stopwatch.createStarted();
    promise.addEventListener(new FutureEventListener<LogSegmentMetadata>() {

        @Override
        public void onSuccess(LogSegmentMetadata segment) {
            deleteOpStats.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }

        @Override
        public void onFailure(Throwable cause) {
            deleteOpStats.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
        }
    });
    try {
        bookKeeperClient.get().asyncDeleteLedger(ledgerMetadata.getLedgerId(), new AsyncCallback.DeleteCallback() {

            @Override
            public void deleteComplete(int rc, Object ctx) {
                if (BKException.Code.NoSuchLedgerExistsException == rc) {
                    LOG.warn("No ledger {} found to delete for {} : {}.", new Object[] { ledgerMetadata.getLedgerId(), getFullyQualifiedName(), ledgerMetadata });
                } else if (BKException.Code.OK != rc) {
                    BKException bke = BKException.create(rc);
                    LOG.error("Couldn't delete ledger {} from bookkeeper for {} : ", new Object[] { ledgerMetadata.getLedgerId(), getFullyQualifiedName(), bke });
                    promise.setException(bke);
                    return;
                }
                // after the ledger is deleted, we delete the metadata znode
                scheduler.submit(new Runnable() {

                    @Override
                    public void run() {
                        deleteLogSegmentMetadata(ledgerMetadata, promise);
                    }
                });
            }
        }, null);
    } catch (IOException e) {
        promise.setException(BKException.create(BKException.Code.BookieHandleNotAvailableException));
    }
    return promise;
}
Also used : AsyncCallback(org.apache.bookkeeper.client.AsyncCallback) Stopwatch(com.google.common.base.Stopwatch) IOException(java.io.IOException) Promise(com.twitter.util.Promise) FutureEventListenerRunnable(com.twitter.distributedlog.util.FutureUtils.FutureEventListenerRunnable) BKException(org.apache.bookkeeper.client.BKException)

Example 3 with BKException

use of org.apache.bookkeeper.client.BKException in project distributedlog by twitter.

the class TestLedgerAllocator method testSuccessAllocatorShouldDeleteUnusedledger.

@Test(timeout = 60000)
public void testSuccessAllocatorShouldDeleteUnusedledger() throws Exception {
    String allocationPath = "/allocation-delete-unused-ledger";
    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 ZkVersion(stat.getVersion()));
    SimpleLedgerAllocator allocator1 = new SimpleLedgerAllocator(allocationPath, allocationData, newQuorumConfigProvider(dlConf), zkc, bkc);
    allocator1.allocate();
    // wait until allocated
    ZKTransaction txn1 = newTxn();
    LedgerHandle lh1 = FutureUtils.result(allocator1.tryObtain(txn1, NULL_LISTENER));
    // Second allocator kicks in
    stat = new Stat();
    data = zkc.get().getData(allocationPath, false, stat);
    allocationData = new Versioned<byte[]>(data, new ZkVersion(stat.getVersion()));
    SimpleLedgerAllocator allocator2 = new SimpleLedgerAllocator(allocationPath, allocationData, newQuorumConfigProvider(dlConf), zkc, bkc);
    allocator2.allocate();
    // wait until allocated
    ZKTransaction txn2 = newTxn();
    LedgerHandle lh2 = FutureUtils.result(allocator2.tryObtain(txn2, NULL_LISTENER));
    // should fail to commit txn1 as version is changed by second allocator
    try {
        FutureUtils.result(txn1.execute());
        fail("Should fail commit obtaining ledger handle from first allocator as allocator is modified by second allocator.");
    } catch (ZKException ke) {
    // as expected
    }
    FutureUtils.result(txn2.execute());
    Utils.close(allocator1);
    Utils.close(allocator2);
    // ledger handle should be deleted
    try {
        lh1.close();
        fail("LedgerHandle allocated by allocator1 should be deleted.");
    } catch (BKException bke) {
    // as expected
    }
    try {
        bkc.get().openLedger(lh1.getId(), BookKeeper.DigestType.CRC32, dlConf.getBKDigestPW().getBytes());
        fail("LedgerHandle allocated by allocator1 should be deleted.");
    } catch (BKException.BKNoSuchLedgerExistsException nslee) {
    // as expected
    }
    long eid = lh2.addEntry("hello world".getBytes());
    lh2.close();
    LedgerHandle readLh = bkc.get().openLedger(lh2.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);
}
Also used : Versioned(org.apache.bookkeeper.versioning.Versioned) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ZKTransaction(com.twitter.distributedlog.zk.ZKTransaction) ZKException(com.twitter.distributedlog.exceptions.ZKException) Stat(org.apache.zookeeper.data.Stat) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) BKException(org.apache.bookkeeper.client.BKException) ZkVersion(org.apache.bookkeeper.meta.ZkVersion) Test(org.junit.Test)

Example 4 with BKException

use of org.apache.bookkeeper.client.BKException in project distributedlog by twitter.

the class DLAuditor method calculateStreamSpaceUsage.

private long calculateStreamSpaceUsage(final com.twitter.distributedlog.DistributedLogManagerFactory factory, final String stream) throws IOException {
    DistributedLogManager dlm = factory.createDistributedLogManager(stream, com.twitter.distributedlog.DistributedLogManagerFactory.ClientSharingOption.SharedClients);
    long totalBytes = 0;
    try {
        List<LogSegmentMetadata> segments = dlm.getLogSegments();
        for (LogSegmentMetadata segment : segments) {
            try {
                LedgerHandle lh = getBookKeeperClient(factory).get().openLedgerNoRecovery(segment.getLedgerId(), BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8));
                totalBytes += lh.getLength();
                lh.close();
            } catch (BKException e) {
                logger.error("Failed to open ledger {} : ", segment.getLedgerId(), e);
                throw new IOException("Failed to open ledger " + segment.getLedgerId(), e);
            } catch (InterruptedException e) {
                logger.warn("Interrupted on opening ledger {} : ", segment.getLedgerId(), e);
                Thread.currentThread().interrupt();
                throw new DLInterruptedException("Interrupted on opening ledger " + segment.getLedgerId(), e);
            }
        }
    } finally {
        dlm.close();
    }
    return totalBytes;
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) DistributedLogManager(com.twitter.distributedlog.DistributedLogManager) LogSegmentMetadata(com.twitter.distributedlog.LogSegmentMetadata) BKException(org.apache.bookkeeper.client.BKException) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException) IOException(java.io.IOException) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException)

Example 5 with BKException

use of org.apache.bookkeeper.client.BKException in project distributedlog by twitter.

the class LogSegmentReader method nextKeyValue.

@Override
public boolean nextKeyValue() throws IOException, InterruptedException {
    LogRecordWithDLSN record;
    currentRecord = null;
    if (null != reader) {
        record = reader.nextRecord();
        if (null != record) {
            currentRecord = record;
            readPos = record.getPositionWithinLogSegment();
            return true;
        } else {
            return false;
        }
    }
    ++entryId;
    if (entryId > lh.getLastAddConfirmed()) {
        return false;
    }
    try {
        Enumeration<LedgerEntry> entries = lh.readEntries(entryId, entryId);
        if (entries.hasMoreElements()) {
            LedgerEntry entry = entries.nextElement();
            reader = Entry.newBuilder().setLogSegmentInfo(metadata.getLogSegmentSequenceNumber(), metadata.getStartSequenceId()).setEntryId(entry.getEntryId()).setEnvelopeEntry(LogSegmentMetadata.supportsEnvelopedEntries(metadata.getVersion())).deserializeRecordSet(true).setInputStream(entry.getEntryInputStream()).buildReader();
        }
        return nextKeyValue();
    } catch (BKException e) {
        throw new IOException(e);
    }
}
Also used : LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) BKException(org.apache.bookkeeper.client.BKException) IOException(java.io.IOException)

Aggregations

BKException (org.apache.bookkeeper.client.BKException)8 IOException (java.io.IOException)4 LedgerEntry (org.apache.bookkeeper.client.LedgerEntry)3 Promise (com.twitter.util.Promise)2 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)2 Optional (com.google.common.base.Optional)1 Stopwatch (com.google.common.base.Stopwatch)1 DistributedLogManager (com.twitter.distributedlog.DistributedLogManager)1 LedgerDescriptor (com.twitter.distributedlog.LedgerDescriptor)1 LogSegmentMetadata (com.twitter.distributedlog.LogSegmentMetadata)1 DLInterruptedException (com.twitter.distributedlog.exceptions.DLInterruptedException)1 ZKException (com.twitter.distributedlog.exceptions.ZKException)1 FirstTxIdNotLessThanSelector (com.twitter.distributedlog.selector.FirstTxIdNotLessThanSelector)1 FutureEventListenerRunnable (com.twitter.distributedlog.util.FutureUtils.FutureEventListenerRunnable)1 ZKTransaction (com.twitter.distributedlog.zk.ZKTransaction)1 FutureEventListener (com.twitter.util.FutureEventListener)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AsyncCallback (org.apache.bookkeeper.client.AsyncCallback)1 ZkVersion (org.apache.bookkeeper.meta.ZkVersion)1 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)1