Search in sources :

Example 26 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException in project pulsar by yahoo.

the class ManagedLedgerImpl method asyncAddEntry.

@Override
public synchronized void asyncAddEntry(ByteBuf buffer, AddEntryCallback callback, Object ctx) {
    if (log.isDebugEnabled()) {
        log.debug("[{}] asyncAddEntry size={} state={}", name, buffer.readableBytes(), state);
    }
    final State state = STATE_UPDATER.get(this);
    if (state == State.Fenced) {
        callback.addFailed(new ManagedLedgerFencedException(), ctx);
        return;
    } else if (state == State.Closed) {
        callback.addFailed(new ManagedLedgerException("Managed ledger was already closed"), ctx);
        return;
    }
    OpAddEntry addOperation = OpAddEntry.create(this, buffer, callback, ctx);
    pendingAddEntries.add(addOperation);
    if (state == State.ClosingLedger || state == State.CreatingLedger) {
        // We are waiting for a new ledger to be created
        if (log.isDebugEnabled()) {
            log.debug("[{}] Queue addEntry request", name);
        }
    } else if (state == State.ClosedLedger) {
        long now = System.currentTimeMillis();
        if (now < lastLedgerCreationFailureTimestamp + WaitTimeAfterLedgerCreationFailureMs) {
            // Deny the write request, since we haven't waited enough time since last attempt to create a new ledger
            pendingAddEntries.remove(addOperation);
            callback.addFailed(new ManagedLedgerException("Waiting for new ledger creation to complete"), ctx);
            return;
        }
        // No ledger and no pending operations. Create a new ledger
        if (log.isDebugEnabled()) {
            log.debug("[{}] Creating a new ledger", name);
        }
        if (STATE_UPDATER.compareAndSet(this, State.ClosedLedger, State.CreatingLedger)) {
            this.lastLedgerCreationInitiationTimestamp = System.nanoTime();
            mbean.startDataLedgerCreateOp();
            bookKeeper.asyncCreateLedger(config.getEnsembleSize(), config.getWriteQuorumSize(), config.getAckQuorumSize(), config.getDigestType(), config.getPassword(), this, ctx);
        }
    } else {
        checkArgument(state == State.LedgerOpened);
        // Write into lastLedger
        addOperation.setLedger(currentLedger);
        ++currentLedgerEntries;
        currentLedgerSize += buffer.readableBytes();
        if (log.isDebugEnabled()) {
            log.debug("[{}] Write into current ledger lh={} entries={}", name, currentLedger.getId(), currentLedgerEntries);
        }
        if (currentLedgerIsFull()) {
            if (log.isDebugEnabled()) {
                log.debug("[{}] Closing current ledger lh={}", name, currentLedger.getId());
            }
            // This entry will be the last added to current ledger
            addOperation.setCloseWhenDone(true);
            STATE_UPDATER.set(this, State.ClosingLedger);
        }
        addOperation.initiate();
    }
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException)

Example 27 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException in project pulsar by yahoo.

the class ManagedLedgerImpl method initializeBookKeeper.

private synchronized void initializeBookKeeper(final ManagedLedgerInitializeLedgerCallback callback) {
    if (log.isDebugEnabled()) {
        log.debug("[{}] initializing bookkeeper; ledgers {}", name, ledgers);
    }
    // Calculate total entries and size
    Iterator<LedgerInfo> iterator = ledgers.values().iterator();
    while (iterator.hasNext()) {
        LedgerInfo li = iterator.next();
        if (li.getEntries() > 0) {
            NUMBER_OF_ENTRIES_UPDATER.addAndGet(this, li.getEntries());
            TOTAL_SIZE_UPDATER.addAndGet(this, li.getSize());
        } else {
            iterator.remove();
            bookKeeper.asyncDeleteLedger(li.getLedgerId(), (rc, ctx) -> {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] Deleted empty ledger ledgerId={} rc={}", name, li.getLedgerId(), rc);
                }
            }, null);
        }
    }
    final MetaStoreCallback<Void> storeLedgersCb = new MetaStoreCallback<Void>() {

        @Override
        public void operationComplete(Void v, Stat stat) {
            ledgersStat = stat;
            initializeCursors(callback);
        }

        @Override
        public void operationFailed(MetaStoreException e) {
            callback.initializeFailed(new ManagedLedgerException(e));
        }
    };
    // Create a new ledger to start writing
    this.lastLedgerCreationInitiationTimestamp = System.nanoTime();
    mbean.startDataLedgerCreateOp();
    bookKeeper.asyncCreateLedger(config.getEnsembleSize(), config.getWriteQuorumSize(), config.getAckQuorumSize(), config.getDigestType(), config.getPassword(), (rc, lh, ctx) -> {
        executor.submitOrdered(name, safeRun(() -> {
            mbean.endDataLedgerCreateOp();
            if (rc != BKException.Code.OK) {
                callback.initializeFailed(new ManagedLedgerException(BKException.getMessage(rc)));
                return;
            }
            log.info("[{}] Created ledger {}", name, lh.getId());
            STATE_UPDATER.set(this, State.LedgerOpened);
            lastLedgerCreatedTimestamp = System.currentTimeMillis();
            currentLedger = lh;
            lastConfirmedEntry = new PositionImpl(lh.getId(), -1);
            LedgerInfo info = LedgerInfo.newBuilder().setLedgerId(lh.getId()).setTimestamp(0).build();
            ledgers.put(lh.getId(), info);
            // Save it back to ensure all nodes exist
            ManagedLedgerInfo mlInfo = ManagedLedgerInfo.newBuilder().addAllLedgerInfo(ledgers.values()).build();
            store.asyncUpdateLedgerIds(name, mlInfo, ledgersStat, storeLedgersCb);
        }));
    }, null);
}
Also used : ManagedLedgerInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo) LedgerInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo) MetaStoreException(org.apache.bookkeeper.mledger.ManagedLedgerException.MetaStoreException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Stat(org.apache.bookkeeper.mledger.impl.MetaStore.Stat) MetaStoreCallback(org.apache.bookkeeper.mledger.impl.MetaStore.MetaStoreCallback) ManagedLedgerInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo)

Example 28 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException in project pulsar by yahoo.

the class ManagedLedgerImpl method asyncReadEntry.

void asyncReadEntry(PositionImpl position, ReadEntryCallback callback, Object ctx) {
    LedgerHandle currentLedger = this.currentLedger;
    if (log.isDebugEnabled()) {
        log.debug("[{}] Reading entry ledger {}: {}", name, position.getLedgerId(), position.getEntryId());
    }
    if (position.getLedgerId() == currentLedger.getId()) {
        LedgerHandle ledger = currentLedger;
        entryCache.asyncReadEntry(ledger, position, callback, ctx);
    } else {
        getLedgerHandle(position.getLedgerId()).thenAccept(ledger -> {
            entryCache.asyncReadEntry(ledger, position, callback, ctx);
        }).exceptionally(ex -> {
            log.error("[{}] Error opening ledger for reading at position {} - {}", name, position, ex.getMessage());
            callback.readEntryFailed(new ManagedLedgerException(ex), ctx);
            return null;
        });
    }
}
Also used : OpenCallback(org.apache.bookkeeper.client.AsyncCallback.OpenCallback) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) MetaStoreCallback(org.apache.bookkeeper.mledger.impl.MetaStore.MetaStoreCallback) Pair(org.apache.bookkeeper.mledger.util.Pair) Unpooled(io.netty.buffer.Unpooled) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) ManagedLedgerMXBean(org.apache.bookkeeper.mledger.ManagedLedgerMXBean) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) Commands(com.yahoo.pulsar.common.api.Commands) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ManagedLedgerInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo) LedgerInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedLedgerInfo.LedgerInfo) Range(com.google.common.collect.Range) Futures(org.apache.bookkeeper.mledger.util.Futures) Math.min(java.lang.Math.min) Position(org.apache.bookkeeper.mledger.Position) NavigableMap(java.util.NavigableMap) BookKeeper(org.apache.bookkeeper.client.BookKeeper) BKException(org.apache.bookkeeper.client.BKException) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Queues(com.google.common.collect.Queues) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) BoundType(com.google.common.collect.BoundType) Stat(org.apache.bookkeeper.mledger.impl.MetaStore.Stat) ConcurrentLongHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentLongHashMap) Queue(java.util.Queue) BadVersionException(org.apache.bookkeeper.mledger.ManagedLedgerException.BadVersionException) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CreateCallback(org.apache.bookkeeper.client.AsyncCallback.CreateCallback) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) Entry(org.apache.bookkeeper.mledger.Entry) CompletableFuture(java.util.concurrent.CompletableFuture) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) RateLimiter(com.google.common.util.concurrent.RateLimiter) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) MetaStoreException(org.apache.bookkeeper.mledger.ManagedLedgerException.MetaStoreException) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) OrderedSafeExecutor(org.apache.bookkeeper.util.OrderedSafeExecutor) java.util.concurrent.atomic(java.util.concurrent.atomic) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) CallbackMutex(org.apache.bookkeeper.mledger.util.CallbackMutex) VoidCallback(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl.VoidCallback) UnboundArrayBlockingQueue(org.apache.bookkeeper.util.UnboundArrayBlockingQueue) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle)

Example 29 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException in project pulsar by yahoo.

the class ManagedCursorTest method asyncReadWithErrors.

@Test(timeOut = 20000)
void asyncReadWithErrors() throws Exception {
    ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger");
    ManagedCursor cursor = ledger.openCursor("c1");
    ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    final CountDownLatch counter = new CountDownLatch(1);
    stopBookKeeper();
    cursor.asyncReadEntries(100, new ReadEntriesCallback() {

        public void readEntriesComplete(List<Entry> entries, Object ctx) {
            entries.forEach(e -> e.release());
            counter.countDown();
        }

        public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
            fail("async-call should not have failed");
        }
    }, null);
    counter.await();
    cursor.rewind();
    // Clear the cache to force reading from BK
    ledger.entryCache.clear();
    final CountDownLatch counter2 = new CountDownLatch(1);
    cursor.asyncReadEntries(100, new ReadEntriesCallback() {

        public void readEntriesComplete(List<Entry> entries, Object ctx) {
            fail("async-call should have failed");
        }

        public void readEntriesFailed(ManagedLedgerException exception, Object ctx) {
            counter2.countDown();
        }
    }, null);
    counter2.await();
}
Also used : ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) ZNodeProtobufFormat(org.apache.bookkeeper.mledger.impl.MetaStoreImplZookeeper.ZNodeProtobufFormat) Arrays(java.util.Arrays) Assert.assertNull(org.testng.Assert.assertNull) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) MockedBookKeeperTestCase(org.apache.bookkeeper.test.MockedBookKeeperTestCase) Entry(org.apache.bookkeeper.mledger.Entry) LoggerFactory(org.slf4j.LoggerFactory) Assert.assertEquals(org.testng.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callable(java.util.concurrent.Callable) Test(org.testng.annotations.Test) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Lists(com.google.common.collect.Lists) Charset(java.nio.charset.Charset) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedLedgerFactoryConfig(org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig) Assert.assertFalse(org.testng.Assert.assertFalse) ExecutorService(java.util.concurrent.ExecutorService) Charsets(com.google.common.base.Charsets) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) CyclicBarrier(java.util.concurrent.CyclicBarrier) Logger(org.slf4j.Logger) Factory(org.testng.annotations.Factory) Assert.fail(org.testng.Assert.fail) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) IndividualDeletedEntries(org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) BKException(org.apache.bookkeeper.client.BKException) Sets(com.google.common.collect.Sets) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) TimeUnit(java.util.concurrent.TimeUnit) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) MarkDeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback) Assert.assertTrue(org.testng.Assert.assertTrue) Collections(java.util.Collections) ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 30 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException in project pulsar by yahoo.

the class ManagedCursorTest method deleteCursor.

@Test(timeOut = 20000)
void deleteCursor() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger");
    ManagedCursor c1 = ledger.openCursor("c1");
    ledger.addEntry("entry-1".getBytes(Encoding));
    Position p2 = ledger.addEntry("entry-2".getBytes(Encoding));
    assertEquals(c1.getNumberOfEntries(), 2);
    // Remove and recreate the same cursor
    ledger.deleteCursor("c1");
    try {
        c1.readEntries(10);
        fail("must fail, the cursor should be closed");
    } catch (ManagedLedgerException e) {
    // ok
    }
    try {
        c1.markDelete(p2);
        fail("must fail, the cursor should be closed");
    } catch (ManagedLedgerException e) {
    // ok
    }
    c1 = ledger.openCursor("c1");
    assertEquals(c1.getNumberOfEntries(), 0);
    c1.close();
    try {
        c1.readEntries(10);
        fail("must fail, the cursor should be closed");
    } catch (ManagedLedgerException e) {
    // ok
    }
    c1.close();
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Aggregations

ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)133 Test (org.testng.annotations.Test)70 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)65 CountDownLatch (java.util.concurrent.CountDownLatch)63 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)46 Entry (org.apache.bookkeeper.mledger.Entry)36 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)33 Position (org.apache.bookkeeper.mledger.Position)33 CompletableFuture (java.util.concurrent.CompletableFuture)23 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)21 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)19 List (java.util.List)18 ReadEntriesCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback)18 BKException (org.apache.bookkeeper.client.BKException)15 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)13 CloseCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback)13 MarkDeleteCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback)13 Logger (org.slf4j.Logger)13 LoggerFactory (org.slf4j.LoggerFactory)13