Search in sources :

Example 1 with ReadEntryCallback

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

the class ManagedCursorConcurrencyTest method testConcurrentIndividualDeletesWithGetNthEntry.

@Test(timeOut = 30000)
public void testConcurrentIndividualDeletesWithGetNthEntry() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(100).setThrottleMarkDelete(0.5));
    final ManagedCursor cursor = ledger.openCursor("c1");
    final int N = 1000;
    final List<Position> addedEntries = Lists.newArrayListWithExpectedSize(N);
    for (int i = 0; i < N; i++) {
        Position pos = ledger.addEntry("entry".getBytes());
        addedEntries.add(pos);
    }
    final int deleteEntries = 100;
    final CountDownLatch counter = new CountDownLatch(deleteEntries);
    final AtomicBoolean gotException = new AtomicBoolean(false);
    final AtomicInteger iteration = new AtomicInteger(0);
    for (int i = 0; i < deleteEntries; i++) {
        executor.submit(safeRun(() -> {
            try {
                cursor.asyncDelete(addedEntries.get(iteration.getAndIncrement()), new DeleteCallback() {

                    @Override
                    public void deleteComplete(Object ctx) {
                    // Ok
                    }

                    @Override
                    public void deleteFailed(ManagedLedgerException exception, Object ctx) {
                        exception.printStackTrace();
                        gotException.set(true);
                    }
                }, null);
            } catch (Exception e) {
                e.printStackTrace();
                gotException.set(true);
            } finally {
                counter.countDown();
            }
        }));
    }
    counter.await();
    final int readEntries = N - deleteEntries;
    final CountDownLatch readCounter = new CountDownLatch(readEntries);
    final AtomicInteger successReadEntries = new AtomicInteger(0);
    for (int i = 1; i <= readEntries; i++) {
        try {
            cursor.asyncGetNthEntry(i, IndividualDeletedEntries.Exclude, new ReadEntryCallback() {

                @Override
                public void readEntryComplete(Entry entry, Object ctx) {
                    successReadEntries.getAndIncrement();
                    entry.release();
                    readCounter.countDown();
                }

                @Override
                public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
                    exception.printStackTrace();
                    gotException.set(true);
                }
            }, null);
        } catch (Exception e) {
            e.printStackTrace();
            gotException.set(true);
        }
    }
    readCounter.await();
    assertFalse(gotException.get());
    assertEquals(successReadEntries.get(), readEntries);
}
Also used : ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) DeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Test(org.testng.annotations.Test)

Example 2 with ReadEntryCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback 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 3 with ReadEntryCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback 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 4 with ReadEntryCallback

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

the class PersistentSubscription method peekNthMessage.

@Override
public CompletableFuture<Entry> peekNthMessage(int messagePosition) {
    CompletableFuture<Entry> future = new CompletableFuture<>();
    if (log.isDebugEnabled()) {
        log.debug("[{}][{}] Getting message at position {}", topicName, subName, messagePosition);
    }
    cursor.asyncGetNthEntry(messagePosition, IndividualDeletedEntries.Exclude, new ReadEntryCallback() {

        @Override
        public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
            future.completeExceptionally(exception);
        }

        @Override
        public void readEntryComplete(Entry entry, Object ctx) {
            future.complete(entry);
        }
    }, null);
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback)

Example 5 with ReadEntryCallback

use of org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback in project incubator-pulsar by apache.

the class ManagedCursorConcurrencyTest method testConcurrentIndividualDeletesWithGetNthEntry.

@Test(timeOut = 30000)
public void testConcurrentIndividualDeletesWithGetNthEntry() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(100).setThrottleMarkDelete(0.5));
    final ManagedCursor cursor = ledger.openCursor("c1");
    final int N = 1000;
    final List<Position> addedEntries = Lists.newArrayListWithExpectedSize(N);
    for (int i = 0; i < N; i++) {
        Position pos = ledger.addEntry("entry".getBytes());
        addedEntries.add(pos);
    }
    final int deleteEntries = 100;
    final CountDownLatch counter = new CountDownLatch(deleteEntries);
    final AtomicBoolean gotException = new AtomicBoolean(false);
    final AtomicInteger iteration = new AtomicInteger(0);
    for (int i = 0; i < deleteEntries; i++) {
        executor.submit(safeRun(() -> {
            try {
                cursor.asyncDelete(addedEntries.get(iteration.getAndIncrement()), new DeleteCallback() {

                    @Override
                    public void deleteComplete(Object ctx) {
                    // Ok
                    }

                    @Override
                    public void deleteFailed(ManagedLedgerException exception, Object ctx) {
                        exception.printStackTrace();
                        gotException.set(true);
                    }
                }, null);
            } catch (Exception e) {
                e.printStackTrace();
                gotException.set(true);
            } finally {
                counter.countDown();
            }
        }));
    }
    counter.await();
    final int readEntries = N - deleteEntries;
    final CountDownLatch readCounter = new CountDownLatch(readEntries);
    final AtomicInteger successReadEntries = new AtomicInteger(0);
    for (int i = 1; i <= readEntries; i++) {
        try {
            cursor.asyncGetNthEntry(i, IndividualDeletedEntries.Exclude, new ReadEntryCallback() {

                @Override
                public void readEntryComplete(Entry entry, Object ctx) {
                    successReadEntries.getAndIncrement();
                    entry.release();
                    readCounter.countDown();
                }

                @Override
                public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
                    exception.printStackTrace();
                    gotException.set(true);
                }
            }, null);
        } catch (Exception e) {
            e.printStackTrace();
            gotException.set(true);
        }
    }
    readCounter.await();
    assertFalse(gotException.get());
    assertEquals(successReadEntries.get(), readEntries);
}
Also used : ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) DeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Test(org.testng.annotations.Test)

Aggregations

ReadEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback)15 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)15 Entry (org.apache.bookkeeper.mledger.Entry)14 CountDownLatch (java.util.concurrent.CountDownLatch)8 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)8 BKException (org.apache.bookkeeper.client.BKException)7 CompletableFuture (java.util.concurrent.CompletableFuture)6 MetaStoreException (org.apache.bookkeeper.mledger.ManagedLedgerException.MetaStoreException)6 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)5 Lists (com.google.common.collect.Lists)5 List (java.util.List)5 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)5 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)5 Position (org.apache.bookkeeper.mledger.Position)5 Pair (org.apache.bookkeeper.mledger.util.Pair)5 SafeRun.safeRun (org.apache.bookkeeper.mledger.util.SafeRun.safeRun)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 Range (com.google.common.collect.Range)4 RateLimiter (com.google.common.util.concurrent.RateLimiter)4