Search in sources :

Example 46 with BookKeeper

use of org.apache.bookkeeper.client.BookKeeper in project distributedlog by twitter.

the class BookKeeperClient method deleteLedger.

public Future<Void> deleteLedger(long lid, final boolean ignoreNonExistentLedger) {
    BookKeeper bk;
    try {
        bk = get();
    } catch (IOException ioe) {
        return Future.exception(ioe);
    }
    final Promise<Void> promise = new Promise<Void>();
    bk.asyncDeleteLedger(lid, new AsyncCallback.DeleteCallback() {

        @Override
        public void deleteComplete(int rc, Object ctx) {
            if (BKException.Code.OK == rc) {
                promise.updateIfEmpty(new Return<Void>(null));
            } else if (BKException.Code.NoSuchLedgerExistsException == rc) {
                if (ignoreNonExistentLedger) {
                    promise.updateIfEmpty(new Return<Void>(null));
                } else {
                    promise.updateIfEmpty(new Throw<Void>(BKException.create(rc)));
                }
            } else {
                promise.updateIfEmpty(new Throw<Void>(BKException.create(rc)));
            }
        }
    }, null);
    return promise;
}
Also used : Return(com.twitter.util.Return) AsyncCallback(org.apache.bookkeeper.client.AsyncCallback) BookKeeper(org.apache.bookkeeper.client.BookKeeper) IOException(java.io.IOException) Promise(com.twitter.util.Promise)

Example 47 with BookKeeper

use of org.apache.bookkeeper.client.BookKeeper in project pravega by pravega.

the class BookKeeperLogReconcileCommand method execute.

@Override
public void execute() throws Exception {
    ensureArgCount(1);
    int logId = getIntArg(0);
    // Ensure that the Bookkeeper log is disabled; abort otherwise.
    @Cleanup val context = createContext();
    @Cleanup val log = context.logFactory.createDebugLogWrapper(logId);
    // Display a summary of the BookKeeperLog.
    val m = log.fetchMetadata();
    outputLogSummary(logId, m);
    if (m == null || m.isEnabled()) {
        String message = (m == null) ? "BookKeeperLog '%s' does not exist." : "BookKeeperLog '%s' is enabled. Please, disable it before executing this command.";
        output(message, logId);
        return;
    }
    // Once the Bookkeeper log is disabled, list all ledgers from this log. This implies to query all the ledgers
    // in Bookkeeper and filter out the ones related to BookkeeperLog id passed by parameter.
    ClientConfiguration config = new ClientConfiguration().setMetadataServiceUri("zk://" + this.getServiceConfig().getZkURL() + context.bookKeeperConfig.getBkLedgerPath());
    @Cleanup BookKeeper bkClient = BookKeeper.forConfig(config).build();
    @Cleanup LedgerManager manager = bkClient.getLedgerManager();
    LedgerManager.LedgerRangeIterator ledgerRangeIterator = manager.getLedgerRanges(Long.MAX_VALUE);
    List<ReadHandle> candidateLedgers = new ArrayList<>();
    try {
        while (ledgerRangeIterator.hasNext()) {
            LedgerManager.LedgerRange lr = ledgerRangeIterator.next();
            for (long ledgerId : lr.getLedgers()) {
                ReadHandle readHandle = Ledgers.openRead(ledgerId, bkClient, context.bookKeeperConfig);
                if (Ledgers.getBookKeeperLogId(readHandle) == logId) {
                    candidateLedgers.add(readHandle);
                }
            }
        }
        // If there are no candidate ledgers, just return.
        if (candidateLedgers.isEmpty()) {
            output("No candidate ledgers to reconcile.");
            return;
        }
        // Confirm with user prior executing the command.
        output("Candidate ledgers for reconciliation: %s", candidateLedgers.stream().map(String::valueOf).collect(Collectors.joining(",")));
        output("BookKeeperLog '%s' reconciliation is about to be executed.", logId);
        if (!confirmContinue()) {
            output("Not reconciling anything at this time.");
            return;
        }
        // Executing BookkeeperLog reconciliation.
        output("BookKeeperLog '%s': starting ledger reconciliation.", logId);
        log.reconcileLedgers(candidateLedgers);
        output("BookKeeperLog '%s': ledger reconciliation completed.", logId);
    } finally {
        // Closing opened ledgers.
        closeBookkeeperReadHandles(candidateLedgers);
    }
}
Also used : lombok.val(lombok.val) LedgerManager(org.apache.bookkeeper.meta.LedgerManager) ArrayList(java.util.ArrayList) BookKeeper(org.apache.bookkeeper.client.BookKeeper) Cleanup(lombok.Cleanup) ReadHandle(org.apache.bookkeeper.client.api.ReadHandle) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration)

Example 48 with BookKeeper

use of org.apache.bookkeeper.client.BookKeeper in project pravega by pravega.

the class BookKeeperCleanupCommand method execute.

@Override
public void execute() throws Exception {
    ensureArgCount(0);
    @Cleanup val context = createContext();
    // Get all BK ledger ids.
    output("Searching for all the ledgers ...");
    @Cleanup val bkAdmin = new BookKeeperAdmin((BookKeeper) context.logFactory.getBookKeeperClient());
    val allLedgerIds = new ArrayList<Long>();
    bkAdmin.listLedgers().forEach(allLedgerIds::add);
    output("Searching for all referenced ledgers ...");
    // We will not be deleting any ledger id above the highest referenced Ledger Id since we may be inadvertently
    // deleting freshly created Ledgers that have not yet been added to a Ledger Metadata yet (BookKeeperLog.initialize
    // first creates a new Ledger and then updates the Metadata in ZK with its existence).
    AtomicLong highestReferencedLedgerId = new AtomicLong();
    val referencedLedgerIds = new HashSet<Long>();
    collectAllReferencedLedgerIds(referencedLedgerIds, context);
    highestReferencedLedgerId.set(referencedLedgerIds.stream().max(Long::compareTo).orElse(-1L));
    // We want to do our due diligence and verify there are no more other BookKeeperLogs that the user hasn't told us about.
    output("Searching for possible other BookKeeperLogs ...");
    checkForExtraLogs(context);
    // Determine deletion candidates.
    val deletionCandidates = allLedgerIds.stream().filter(id -> id < highestReferencedLedgerId.get() && !referencedLedgerIds.contains(id)).collect(Collectors.toList());
    output("\nTotal Count: %d, Referenced Count: %d, Highest Referenced Id: %s, To Delete Count: %d.", allLedgerIds.size(), referencedLedgerIds.size(), highestReferencedLedgerId, deletionCandidates.size());
    if (deletionCandidates.isEmpty()) {
        output("There are no Ledgers eligible for deletion at this time.");
        return;
    }
    output("\nDeletion candidates:");
    listCandidates(deletionCandidates, context);
    if (!confirmContinue()) {
        output("Not deleting anything at this time.");
        return;
    }
    // Search again for referenced ledger ids, in case any new ones were just referenced.
    collectAllReferencedLedgerIds(referencedLedgerIds, context);
    highestReferencedLedgerId.set(referencedLedgerIds.stream().max(Long::compareTo).orElse(-1L));
    deleteCandidates(deletionCandidates, referencedLedgerIds, context);
}
Also used : lombok.val(lombok.val) AdminCommand(io.pravega.cli.admin.AdminCommand) Collection(java.util.Collection) Exceptions(io.pravega.common.Exceptions) lombok.val(lombok.val) Cleanup(lombok.Cleanup) BookKeeper(org.apache.bookkeeper.client.BookKeeper) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) BookKeeperAdmin(org.apache.bookkeeper.client.BookKeeperAdmin) DebugBookKeeperLogWrapper(io.pravega.segmentstore.storage.impl.bookkeeper.DebugBookKeeperLogWrapper) VisibleForTesting(com.google.common.annotations.VisibleForTesting) CommandArgs(io.pravega.cli.admin.CommandArgs) AtomicLong(java.util.concurrent.atomic.AtomicLong) ArrayList(java.util.ArrayList) AtomicLong(java.util.concurrent.atomic.AtomicLong) Cleanup(lombok.Cleanup) BookKeeperAdmin(org.apache.bookkeeper.client.BookKeeperAdmin) HashSet(java.util.HashSet)

Example 49 with BookKeeper

use of org.apache.bookkeeper.client.BookKeeper 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 50 with BookKeeper

use of org.apache.bookkeeper.client.BookKeeper in project bookkeeper by apache.

the class BenchBookie method getValidLedgerId.

private static long getValidLedgerId(String zkServers) throws IOException, BKException, KeeperException, InterruptedException {
    BookKeeper bkc = null;
    LedgerHandle lh = null;
    long id = 0;
    try {
        bkc = new BookKeeper(zkServers);
        lh = bkc.createLedger(1, 1, BookKeeper.DigestType.CRC32, new byte[20]);
        id = lh.getId();
        return id;
    } finally {
        if (lh != null) {
            lh.close();
        }
        if (bkc != null) {
            bkc.close();
        }
    }
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) BookKeeper(org.apache.bookkeeper.client.BookKeeper)

Aggregations

BookKeeper (org.apache.bookkeeper.client.BookKeeper)76 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)48 Test (org.junit.Test)25 ClientConfiguration (org.apache.bookkeeper.conf.ClientConfiguration)24 BKException (org.apache.bookkeeper.client.BKException)18 IOException (java.io.IOException)17 ServerConfiguration (org.apache.bookkeeper.conf.ServerConfiguration)12 List (java.util.List)11 CompletableFuture (java.util.concurrent.CompletableFuture)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 LedgerEntry (org.apache.bookkeeper.client.LedgerEntry)10 ArrayList (java.util.ArrayList)9 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)8 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)7 AsyncCallback (org.apache.bookkeeper.client.AsyncCallback)7 HttpServiceResponse (org.apache.bookkeeper.http.service.HttpServiceResponse)7 BookkeeperCommitLog (herddb.cluster.BookkeeperCommitLog)6 TableSpaceManager (herddb.core.TableSpaceManager)6 DataScanner (herddb.model.DataScanner)6 StatementExecutionException (herddb.model.StatementExecutionException)6