Search in sources :

Example 6 with Position

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

the class ManagedCursorImpl method asyncReplayEntries.

/**
     * Async replays given positions: 
     * a. before reading it filters out already-acked messages 
     * b. reads remaining entries async and gives it to given ReadEntriesCallback
     * c. returns all already-acked messages which are not replayed so, those messages can be removed by
     * caller(Dispatcher)'s replay-list and it won't try to replay it again
     * 
     */
@Override
public Set<? extends Position> asyncReplayEntries(final Set<? extends Position> positions, ReadEntriesCallback callback, Object ctx) {
    List<Entry> entries = Lists.newArrayListWithExpectedSize(positions.size());
    if (positions.isEmpty()) {
        callback.readEntriesComplete(entries, ctx);
    }
    // filters out messages which are already acknowledged
    Set<Position> alreadyAcknowledgedPositions = Sets.newHashSet();
    lock.readLock().lock();
    try {
        positions.stream().filter(position -> individualDeletedMessages.contains((PositionImpl) position) || ((PositionImpl) position).compareTo(markDeletePosition) < 0).forEach(alreadyAcknowledgedPositions::add);
    } finally {
        lock.readLock().unlock();
    }
    final int totalValidPositions = positions.size() - alreadyAcknowledgedPositions.size();
    final AtomicReference<ManagedLedgerException> exception = new AtomicReference<>();
    ReadEntryCallback cb = new ReadEntryCallback() {

        int pendingCallbacks = totalValidPositions;

        @Override
        public synchronized void readEntryComplete(Entry entry, Object ctx) {
            if (exception.get() != null) {
                // if there is already a failure for a different position, we should release the entry straight away
                // and not add it to the list
                entry.release();
                if (--pendingCallbacks == 0) {
                    callback.readEntriesFailed(exception.get(), ctx);
                }
            } else {
                entries.add(entry);
                if (--pendingCallbacks == 0) {
                    callback.readEntriesComplete(entries, ctx);
                }
            }
        }

        @Override
        public synchronized void readEntryFailed(ManagedLedgerException mle, Object ctx) {
            log.warn("[{}][{}] Error while replaying entries", ledger.getName(), name, mle);
            if (exception.compareAndSet(null, mle)) {
                // release the entries just once, any further read success will release the entry straight away
                entries.forEach(Entry::release);
            }
            if (--pendingCallbacks == 0) {
                callback.readEntriesFailed(exception.get(), ctx);
            }
        }
    };
    positions.stream().filter(position -> !alreadyAcknowledgedPositions.contains(position)).forEach(p -> ledger.asyncReadEntry((PositionImpl) p, cb, ctx));
    return alreadyAcknowledgedPositions;
}
Also used : ZNodeProtobufFormat(org.apache.bookkeeper.mledger.impl.MetaStoreImplZookeeper.ZNodeProtobufFormat) RangeSet(com.google.common.collect.RangeSet) PositionBound(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.PositionBound) LoggerFactory(org.slf4j.LoggerFactory) MetaStoreCallback(org.apache.bookkeeper.mledger.impl.MetaStore.MetaStoreCallback) Collections2(com.google.common.collect.Collections2) Pair(org.apache.bookkeeper.mledger.util.Pair) ManagedCursorInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedCursorInfo) FindEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.FindEntryCallback) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ClearBacklogCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ClearBacklogCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Objects(com.google.common.base.Objects) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) AtomicReferenceFieldUpdater(java.util.concurrent.atomic.AtomicReferenceFieldUpdater) Range(com.google.common.collect.Range) Set(java.util.Set) Position(org.apache.bookkeeper.mledger.Position) MLDataFormats(org.apache.bookkeeper.mledger.proto.MLDataFormats) BookKeeper(org.apache.bookkeeper.client.BookKeeper) Collectors(java.util.stream.Collectors) BKException(org.apache.bookkeeper.client.BKException) SkipEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.SkipEntriesCallback) Sets(com.google.common.collect.Sets) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Predicate(com.google.common.base.Predicate) Stat(org.apache.bookkeeper.mledger.impl.MetaStore.Stat) DeleteCallback(org.apache.bookkeeper.client.AsyncCallback.DeleteCallback) AsyncCallbacks(org.apache.bookkeeper.mledger.AsyncCallbacks) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) Entry(org.apache.bookkeeper.mledger.Entry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) AtomicReference(java.util.concurrent.atomic.AtomicReference) TreeRangeSet(com.google.common.collect.TreeRangeSet) 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) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) Logger(org.slf4j.Logger) CursorAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.CursorAlreadyClosedException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) TimeUnit(java.util.concurrent.TimeUnit) PositionInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.PositionInfo) CloseCallback(org.apache.bookkeeper.client.AsyncCallback.CloseCallback) MarkDeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) Position(org.apache.bookkeeper.mledger.Position) AtomicReference(java.util.concurrent.atomic.AtomicReference) Entry(org.apache.bookkeeper.mledger.Entry) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException)

Example 7 with Position

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

the class ManagedCursorImpl method findNewestMatching.

@Override
public Position findNewestMatching(Predicate<Entry> condition) throws InterruptedException, ManagedLedgerException {
    final CountDownLatch counter = new CountDownLatch(1);
    class Result {

        ManagedLedgerException exception = null;

        Position position = null;
    }
    final Result result = new Result();
    asyncFindNewestMatching(FindPositionConstraint.SearchActiveEntries, condition, new FindEntryCallback() {

        @Override
        public void findEntryComplete(Position position, Object ctx) {
            result.position = position;
            counter.countDown();
        }

        @Override
        public void findEntryFailed(ManagedLedgerException exception, Object ctx) {
            result.exception = exception;
            counter.countDown();
        }
    }, null);
    counter.await();
    if (result.exception != null)
        throw result.exception;
    return result.position;
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Position(org.apache.bookkeeper.mledger.Position) FindEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.FindEntryCallback) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 8 with Position

use of org.apache.bookkeeper.mledger.Position 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 9 with Position

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

the class ManagedCursorTest method testOutOfOrderDeletePersistenceAfterCrash.

@Test(timeOut = 20000)
public void testOutOfOrderDeletePersistenceAfterCrash() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig());
    ManagedCursor c1 = ledger.openCursor("c1");
    List<Position> addedPositions = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        Position p = ledger.addEntry(("dummy-entry-" + i).getBytes(Encoding));
        addedPositions.add(p);
    }
    // Acknowledge few messages leaving holes
    c1.delete(addedPositions.get(2));
    c1.delete(addedPositions.get(5));
    c1.delete(addedPositions.get(7));
    c1.delete(addedPositions.get(8));
    c1.delete(addedPositions.get(9));
    assertEquals(c1.getNumberOfEntriesInBacklog(), 20 - 5);
    // Re-Open
    ManagedLedgerFactory factory2 = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle());
    ledger = factory2.open("my_test_ledger", new ManagedLedgerConfig());
    c1 = ledger.openCursor("c1");
    assertEquals(c1.getNumberOfEntriesInBacklog(), 20 - 5);
    List<Entry> entries = c1.readEntries(20);
    assertEquals(entries.size(), 20 - 5);
    List<String> entriesStr = entries.stream().map(e -> new String(e.getDataAndRelease(), Encoding)).collect(Collectors.toList());
    assertEquals(entriesStr.get(0), "dummy-entry-0");
    assertEquals(entriesStr.get(1), "dummy-entry-1");
    // Entry-2 was deleted
    assertEquals(entriesStr.get(2), "dummy-entry-3");
    assertEquals(entriesStr.get(3), "dummy-entry-4");
    // Entry-6 was deleted
    assertEquals(entriesStr.get(4), "dummy-entry-6");
    assertFalse(c1.hasMoreEntries());
    factory2.shutdown();
}
Also used : 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) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ArrayList(java.util.ArrayList) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Test(org.testng.annotations.Test)

Example 10 with Position

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

the class ManagedCursorTest method errorRecoveringCursor3.

@Test(timeOut = 20000)
void errorRecoveringCursor3() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger");
    Position p1 = ledger.addEntry("entry".getBytes());
    ledger.addEntry("entry".getBytes());
    ManagedCursor c1 = ledger.openCursor("c1");
    Position p3 = ledger.addEntry("entry".getBytes());
    assertEquals(c1.getReadPosition(), p3);
    ManagedLedgerFactory factory2 = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle());
    bkc.failAfter(4, BKException.Code.ReadException);
    ledger = factory2.open("my_test_ledger");
    c1 = ledger.openCursor("c1");
    // Verify the ManagedCursor was rewind back to the snapshotted position
    assertEquals(c1.getReadPosition(), p3);
    factory2.shutdown();
}
Also used : Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Aggregations

Position (org.apache.bookkeeper.mledger.Position)201 Test (org.testng.annotations.Test)169 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)168 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)167 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)127 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)115 Entry (org.apache.bookkeeper.mledger.Entry)104 CountDownLatch (java.util.concurrent.CountDownLatch)97 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)72 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)68 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)58 BKException (org.apache.bookkeeper.client.BKException)56 List (java.util.List)55 MarkDeleteCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback)53 AtomicReference (java.util.concurrent.atomic.AtomicReference)52 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)52 Logger (org.slf4j.Logger)52 LoggerFactory (org.slf4j.LoggerFactory)52 Lists (com.google.common.collect.Lists)51 TimeUnit (java.util.concurrent.TimeUnit)51