Search in sources :

Example 66 with ManagedCursor

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

the class ManagedLedgerBkTest method asyncMarkDeleteAndClose.

@Test
public void asyncMarkDeleteAndClose() throws Exception {
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkc, zkc);
    ManagedLedgerConfig config = new ManagedLedgerConfig().setEnsembleSize(1).setWriteQuorumSize(1).setAckQuorumSize(1).setMetadataEnsembleSize(1).setMetadataWriteQuorumSize(1).setMetadataAckQuorumSize(1);
    ManagedLedger ledger = factory.open("my_test_ledger", config);
    ManagedCursor cursor = ledger.openCursor("c1");
    List<Position> positions = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        Position p = ledger.addEntry("entry".getBytes());
        positions.add(p);
    }
    final CountDownLatch counter = new CountDownLatch(positions.size());
    final AtomicBoolean gotException = new AtomicBoolean(false);
    for (Position p : positions) {
        cursor.asyncDelete(p, new DeleteCallback() {

            @Override
            public void deleteComplete(Object ctx) {
                // Ok
                counter.countDown();
            }

            @Override
            public void deleteFailed(ManagedLedgerException exception, Object ctx) {
                exception.printStackTrace();
                gotException.set(true);
                counter.countDown();
            }
        }, null);
    }
    cursor.close();
    ledger.close();
    counter.await();
    assertFalse(gotException.get());
    factory.shutdown();
}
Also used : Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) DeleteCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCallback) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Test(org.testng.annotations.Test)

Example 67 with ManagedCursor

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

the class ManagedLedgerBkTest method testSimpleRead.

@Test
public void testSimpleRead() throws Exception {
    ManagedLedgerFactoryConfig factoryConf = new ManagedLedgerFactoryConfig();
    factoryConf.setMaxCacheSize(0);
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkc, zkc, factoryConf);
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    config.setEnsembleSize(1).setWriteQuorumSize(1).setAckQuorumSize(1).setMetadataEnsembleSize(1).setMetadataAckQuorumSize(1);
    ManagedLedger ledger = factory.open("my-ledger", config);
    ManagedCursor cursor = ledger.openCursor("c1");
    int N = 1;
    for (int i = 0; i < N; i++) {
        String entry = "entry-" + i;
        ledger.addEntry(entry.getBytes());
    }
    List<Entry> entries = cursor.readEntries(N);
    assertEquals(N, entries.size());
    entries.forEach(e -> e.release());
    factory.shutdown();
}
Also used : Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerFactoryConfig(org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 68 with ManagedCursor

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

the class ManagedLedgerImpl method asyncOpenCursor.

@Override
public synchronized void asyncOpenCursor(final String cursorName, final OpenCursorCallback callback, final Object ctx) {
    try {
        checkManagedLedgerIsOpen();
        checkFenced();
    } catch (ManagedLedgerException e) {
        callback.openCursorFailed(e, ctx);
        return;
    }
    if (uninitializedCursors.containsKey(cursorName)) {
        uninitializedCursors.get(cursorName).thenAccept(cursor -> {
            callback.openCursorComplete(cursor, ctx);
        }).exceptionally(ex -> {
            callback.openCursorFailed((ManagedLedgerException) ex, ctx);
            return null;
        });
        return;
    }
    ManagedCursor cachedCursor = cursors.get(cursorName);
    if (cachedCursor != null) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Cursor was already created {}", name, cachedCursor);
        }
        callback.openCursorComplete(cachedCursor, ctx);
        return;
    }
    // Create a new one and persist it
    if (log.isDebugEnabled()) {
        log.debug("[{}] Creating new cursor: {}", name, cursorName);
    }
    final ManagedCursorImpl cursor = new ManagedCursorImpl(bookKeeper, config, this, cursorName);
    CompletableFuture<ManagedCursor> cursorFuture = new CompletableFuture<>();
    uninitializedCursors.put(cursorName, cursorFuture);
    cursor.initialize(getLastPosition(), new VoidCallback() {

        @Override
        public void operationComplete() {
            log.info("[{}] Opened new cursor: {}", name, cursor);
            cursor.setActive();
            // Update the ack position (ignoring entries that were written while the cursor was being created)
            cursor.initializeCursorPosition(getLastPositionAndCounter());
            synchronized (this) {
                cursors.add(cursor);
                uninitializedCursors.remove(cursorName).complete(cursor);
            }
            callback.openCursorComplete(cursor, ctx);
        }

        @Override
        public void operationFailed(ManagedLedgerException exception) {
            log.warn("[{}] Failed to open cursor: {}", name, cursor);
            synchronized (this) {
                uninitializedCursors.remove(cursorName).completeExceptionally(exception);
            }
            callback.openCursorFailed(exception, ctx);
        }
    });
}
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) VoidCallback(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl.VoidCallback) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor)

Example 69 with ManagedCursor

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

the class ManagedLedgerImpl method asyncClose.

@Override
public synchronized void asyncClose(final CloseCallback callback, final Object ctx) {
    State state = STATE_UPDATER.get(this);
    if (state == State.Fenced) {
        factory.close(this);
        callback.closeFailed(new ManagedLedgerFencedException(), ctx);
        return;
    } else if (state == State.Closed) {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Ignoring request to close a closed managed ledger", name);
        }
        callback.closeComplete(ctx);
        return;
    }
    log.info("[{}] Closing managed ledger", name);
    factory.close(this);
    STATE_UPDATER.set(this, State.Closed);
    LedgerHandle lh = currentLedger;
    if (log.isDebugEnabled()) {
        log.debug("[{}] Closing current writing ledger {}", name, lh.getId());
    }
    mbean.startDataLedgerCloseOp();
    lh.asyncClose((rc, lh1, ctx1) -> {
        if (log.isDebugEnabled()) {
            log.debug("[{}] Close complete for ledger {}: rc = {}", name, lh.getId(), rc);
        }
        mbean.endDataLedgerCloseOp();
        if (rc != BKException.Code.OK) {
            callback.closeFailed(new ManagedLedgerException(BKException.getMessage(rc)), ctx);
            return;
        }
        // Close all cursors in parallel
        List<CompletableFuture<Void>> futures = Lists.newArrayList();
        for (ManagedCursor cursor : cursors) {
            Futures.CloseFuture closeFuture = new Futures.CloseFuture();
            cursor.asyncClose(closeFuture, null);
            futures.add(closeFuture);
        }
        Futures.waitForAll(futures).thenRun(() -> {
            callback.closeComplete(ctx);
        }).exceptionally(exception -> {
            callback.closeFailed(new ManagedLedgerException(exception), ctx);
            return null;
        });
    }, null);
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CompletableFuture(java.util.concurrent.CompletableFuture) Futures(org.apache.bookkeeper.mledger.util.Futures) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ManagedLedgerFencedException(org.apache.bookkeeper.mledger.ManagedLedgerException.ManagedLedgerFencedException) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor)

Example 70 with ManagedCursor

use of org.apache.bookkeeper.mledger.ManagedCursor 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)

Aggregations

ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)135 Test (org.testng.annotations.Test)126 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)102 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)66 Position (org.apache.bookkeeper.mledger.Position)59 Entry (org.apache.bookkeeper.mledger.Entry)57 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)52 CountDownLatch (java.util.concurrent.CountDownLatch)32 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)28 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)17 CyclicBarrier (java.util.concurrent.CyclicBarrier)15 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)12 ManagedLedgerFactoryConfig (org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig)12 List (java.util.List)10 BKException (org.apache.bookkeeper.client.BKException)10 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)10 Future (java.util.concurrent.Future)9 TimeUnit (java.util.concurrent.TimeUnit)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 MarkDeleteCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback)9