Search in sources :

Example 11 with ReadEntryCallback

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

the class ManagedLedgerImpl method checkBackloggedCursors.

@Override
public void checkBackloggedCursors() {
    // activate caught up cursors
    cursors.forEach(cursor -> {
        if (cursor.getNumberOfEntries() < maxActiveCursorBacklogEntries) {
            cursor.setActive();
        }
    });
    // deactivate backlog cursors
    Iterator<ManagedCursor> cursors = activeCursors.iterator();
    while (cursors.hasNext()) {
        ManagedCursor cursor = cursors.next();
        long backlogEntries = cursor.getNumberOfEntries();
        if (backlogEntries > maxActiveCursorBacklogEntries) {
            PositionImpl readPosition = (PositionImpl) cursor.getReadPosition();
            readPosition = isValidPosition(readPosition) ? readPosition : getNextValidPosition(readPosition);
            if (readPosition == null) {
                if (log.isDebugEnabled()) {
                    log.debug("[{}] Couldn't find valid read position [{}] {}", name, cursor.getName(), cursor.getReadPosition());
                }
                continue;
            }
            try {
                asyncReadEntry(readPosition, new ReadEntryCallback() {

                    @Override
                    public void readEntryFailed(ManagedLedgerException e, Object ctx) {
                        log.warn("[{}] Failed while reading entries on [{}] {}", name, cursor.getName(), e.getMessage(), e);
                    }

                    @Override
                    public void readEntryComplete(Entry entry, Object ctx) {
                        MessageMetadata msgMetadata = null;
                        try {
                            msgMetadata = Commands.parseMessageMetadata(entry.getDataBuffer());
                            long msgTimeSincePublish = (System.currentTimeMillis() - msgMetadata.getPublishTime());
                            if (msgTimeSincePublish > maxMessageCacheRetentionTimeMillis) {
                                cursor.setInactive();
                            }
                        } finally {
                            if (msgMetadata != null) {
                                msgMetadata.recycle();
                            }
                            entry.release();
                        }
                    }
                }, null);
            } catch (Exception e) {
                log.warn("[{}] Failed while reading entries from cache on [{}] {}", name, cursor.getName(), e.getMessage(), e);
            }
        }
    }
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) BKException(org.apache.bookkeeper.client.BKException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) BadVersionException(org.apache.bookkeeper.mledger.ManagedLedgerException.BadVersionException) MetaStoreException(org.apache.bookkeeper.mledger.ManagedLedgerException.MetaStoreException) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor)

Example 12 with ReadEntryCallback

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

the class ManagedCursorImpl method getNthEntry.

@Override
public Entry getNthEntry(int N, IndividualDeletedEntries deletedEntries) throws InterruptedException, ManagedLedgerException {
    final CountDownLatch counter = new CountDownLatch(1);
    class Result {

        ManagedLedgerException exception = null;

        Entry entry = null;
    }
    final Result result = new Result();
    asyncGetNthEntry(N, deletedEntries, new ReadEntryCallback() {

        @Override
        public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
            result.exception = exception;
            counter.countDown();
        }

        @Override
        public void readEntryComplete(Entry entry, Object ctx) {
            result.entry = entry;
            counter.countDown();
        }
    }, null);
    counter.await();
    if (result.exception != null)
        throw result.exception;
    return result.entry;
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 13 with ReadEntryCallback

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

the class EntryCacheImpl method asyncReadEntry.

@Override
public void asyncReadEntry(LedgerHandle lh, PositionImpl position, final ReadEntryCallback callback, final Object ctx) {
    if (log.isDebugEnabled()) {
        log.debug("[{}] Reading entry ledger {}: {}", ml.getName(), lh.getId(), position.getEntryId());
    }
    EntryImpl entry = entries.get(position);
    if (entry != null) {
        EntryImpl cachedEntry = new EntryImpl(entry);
        entry.release();
        manager.mlFactoryMBean.recordCacheHit(cachedEntry.getLength());
        callback.readEntryComplete(cachedEntry, ctx);
    } else {
        ReadCallback readCallback = (rc, ledgerHandle, sequence, obj) -> {
            if (rc != BKException.Code.OK) {
                ml.invalidateLedgerHandle(ledgerHandle, rc);
                callback.readEntryFailed(new ManagedLedgerException(BKException.create(rc)), obj);
                return;
            }
            if (sequence.hasMoreElements()) {
                EntryImpl returnEntry = new EntryImpl(sequence.nextElement());
                manager.mlFactoryMBean.recordCacheMiss(1, returnEntry.getLength());
                ml.mbean.addReadEntriesSample(1, returnEntry.getLength());
                callback.readEntryComplete(returnEntry, obj);
            } else {
                // got an empty sequence
                callback.readEntryFailed(new ManagedLedgerException("Could not read given position"), obj);
            }
        };
        lh.asyncReadEntries(position.getEntryId(), position.getEntryId(), readCallback, ctx);
    }
}
Also used : Longs(com.google.common.primitives.Longs) Logger(org.slf4j.Logger) Weighter(org.apache.bookkeeper.mledger.util.RangeCache.Weighter) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) LoggerFactory(org.slf4j.LoggerFactory) ReadEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Pair(org.apache.bookkeeper.mledger.util.Pair) BKException(org.apache.bookkeeper.client.BKException) TooManyRequestsException(org.apache.bookkeeper.mledger.ManagedLedgerException.TooManyRequestsException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) List(java.util.List) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) RangeCache(org.apache.bookkeeper.mledger.util.RangeCache) ReadCallback(org.apache.bookkeeper.client.AsyncCallback.ReadCallback) ReadEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ReadCallback(org.apache.bookkeeper.client.AsyncCallback.ReadCallback)

Example 14 with ReadEntryCallback

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

the class PersistentReplicator method peekNthMessage.

public CompletableFuture<Entry> peekNthMessage(int messagePosition) {
    CompletableFuture<Entry> future = new CompletableFuture<>();
    if (log.isDebugEnabled()) {
        log.debug("[{}][{} -> {}] Getting message at position {}", topicName, localCluster, remoteCluster, 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 15 with ReadEntryCallback

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

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 : RangeSet(com.google.common.collect.RangeSet) PositionBound(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.PositionBound) LoggerFactory(org.slf4j.LoggerFactory) Collections2(com.google.common.collect.Collections2) MetaStoreCallback(org.apache.bookkeeper.mledger.impl.MetaStore.MetaStoreCallback) Pair(org.apache.bookkeeper.mledger.util.Pair) ManagedCursorInfo(org.apache.bookkeeper.mledger.proto.MLDataFormats.ManagedCursorInfo) FindEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.FindEntryCallback) LongProperty(org.apache.bookkeeper.mledger.proto.MLDataFormats.LongProperty) 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) DEFAULT_LEDGER_DELETE_RETRIES(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.DEFAULT_LEDGER_DELETE_RETRIES) Map(java.util.Map) 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) Sets(com.google.common.collect.Sets) BKException(org.apache.bookkeeper.client.BKException) SkipEntriesCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.SkipEntriesCallback) 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) TreeRangeSet(com.google.common.collect.TreeRangeSet) RateLimiter(com.google.common.util.concurrent.RateLimiter) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) Lists(com.google.common.collect.Lists) MetaStoreException(org.apache.bookkeeper.mledger.ManagedLedgerException.MetaStoreException) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) ManagedLedgerException.getManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException.getManagedLedgerException) Logger(org.slf4j.Logger) CursorAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.CursorAlreadyClosedException) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ManagedLedgerImpl.createManagedLedgerException(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.createManagedLedgerException) MoreObjects(com.google.common.base.MoreObjects) Maps(com.google.common.collect.Maps) 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) DEFAULT_LEDGER_DELETE_BACKOFF_TIME_SEC(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.DEFAULT_LEDGER_DELETE_BACKOFF_TIME_SEC) NoMoreEntriesToReadException(org.apache.bookkeeper.mledger.ManagedLedgerException.NoMoreEntriesToReadException) 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) ManagedLedgerException.getManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException.getManagedLedgerException) ManagedLedgerImpl.createManagedLedgerException(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl.createManagedLedgerException)

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