Search in sources :

Example 6 with BookKeeper

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

the class LedgerReadBenchmark method benchmark.

@Override
protected void benchmark(DistributedLogNamespace namespace, String logName, StatsLogger statsLogger) {
    DistributedLogManager dlm = null;
    while (null == dlm) {
        try {
            dlm = namespace.openLog(streamName);
        } catch (IOException ioe) {
            logger.warn("Failed to create dlm for stream {} : ", streamName, ioe);
        }
        if (null == dlm) {
            try {
                TimeUnit.MILLISECONDS.sleep(conf.getZKSessionTimeoutMilliseconds());
            } catch (InterruptedException e) {
            }
        }
    }
    logger.info("Created dlm for stream {}.", streamName);
    List<LogSegmentMetadata> segments = null;
    while (null == segments) {
        try {
            segments = dlm.getLogSegments();
        } catch (IOException ioe) {
            logger.warn("Failed to get log segments for stream {} : ", streamName, ioe);
        }
        if (null == segments) {
            try {
                TimeUnit.MILLISECONDS.sleep(conf.getZKSessionTimeoutMilliseconds());
            } catch (InterruptedException e) {
            }
        }
    }
    final Counter readCounter = statsLogger.getCounter("reads");
    logger.info("Reading from log segments : {}", segments);
    ZooKeeperClient zkc = ZooKeeperClientBuilder.newBuilder().uri(uri).name("benchmark-zkc").sessionTimeoutMs(conf.getZKSessionTimeoutMilliseconds()).zkAclId(null).build();
    BKDLConfig bkdlConfig;
    try {
        bkdlConfig = BKDLConfig.resolveDLConfig(zkc, uri);
    } catch (IOException e) {
        return;
    }
    BookKeeper bk;
    try {
        bk = BookKeeperClientBuilder.newBuilder().name("benchmark-bkc").dlConfig(conf).zkServers(bkdlConfig.getBkZkServersForReader()).ledgersPath(bkdlConfig.getBkLedgersPath()).build().get();
    } catch (IOException e) {
        return;
    }
    final int readConcurrency = conf.getInt("ledger_read_concurrency", 1000);
    boolean streamRead = conf.getBoolean("ledger_stream_read", true);
    try {
        for (LogSegmentMetadata segment : segments) {
            Stopwatch stopwatch = Stopwatch.createStarted();
            long lid = segment.getLedgerId();
            LedgerHandle lh = bk.openLedgerNoRecovery(lid, BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8));
            logger.info("It took {} ms to open log segment {}", new Object[] { stopwatch.elapsed(TimeUnit.MILLISECONDS), (lh.getLastAddConfirmed() + 1), segment });
            stopwatch.reset().start();
            Runnable reader;
            if (streamRead) {
                reader = new LedgerStreamReader(lh, new BookkeeperInternalCallbacks.ReadEntryListener() {

                    @Override
                    public void onEntryComplete(int rc, LedgerHandle lh, LedgerEntry entry, Object ctx) {
                        readCounter.inc();
                    }
                }, readConcurrency);
            } else {
                reader = new LedgerStreamReader(lh, new BookkeeperInternalCallbacks.ReadEntryListener() {

                    @Override
                    public void onEntryComplete(int rc, LedgerHandle lh, LedgerEntry entry, Object ctx) {
                        readCounter.inc();
                    }
                }, readConcurrency);
            }
            reader.run();
            logger.info("It took {} ms to complete reading {} entries from log segment {}", new Object[] { stopwatch.elapsed(TimeUnit.MILLISECONDS), (lh.getLastAddConfirmed() + 1), segment });
        }
    } catch (Exception e) {
        logger.error("Error on reading bk ", e);
    }
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) LogSegmentMetadata(com.twitter.distributedlog.LogSegmentMetadata) Stopwatch(com.google.common.base.Stopwatch) BookKeeper(org.apache.bookkeeper.client.BookKeeper) IOException(java.io.IOException) IOException(java.io.IOException) Counter(org.apache.bookkeeper.stats.Counter) ZooKeeperClient(com.twitter.distributedlog.ZooKeeperClient) DistributedLogManager(com.twitter.distributedlog.DistributedLogManager) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) BKDLConfig(com.twitter.distributedlog.metadata.BKDLConfig)

Example 7 with BookKeeper

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

the class DistributedLogInputFormat method getSplits.

@Override
public List<InputSplit> getSplits(JobContext jobContext) throws IOException, InterruptedException {
    List<LogSegmentMetadata> segments = dlm.getLogSegments();
    List<InputSplit> inputSplits = Lists.newArrayListWithCapacity(segments.size());
    BookKeeper bk = namespace.getReaderBKC().get();
    LedgerManager lm = BookKeeperAccessor.getLedgerManager(bk);
    final AtomicInteger rcHolder = new AtomicInteger(0);
    final AtomicReference<LedgerMetadata> metadataHolder = new AtomicReference<LedgerMetadata>(null);
    for (LogSegmentMetadata segment : segments) {
        final CountDownLatch latch = new CountDownLatch(1);
        lm.readLedgerMetadata(segment.getLedgerId(), new BookkeeperInternalCallbacks.GenericCallback<LedgerMetadata>() {

            @Override
            public void operationComplete(int rc, LedgerMetadata ledgerMetadata) {
                metadataHolder.set(ledgerMetadata);
                rcHolder.set(rc);
                latch.countDown();
            }
        });
        latch.await();
        if (BKException.Code.OK != rcHolder.get()) {
            throw new IOException("Faild to get log segment metadata for " + segment + " : " + BKException.getMessage(rcHolder.get()));
        }
        inputSplits.add(new LogSegmentSplit(segment, metadataHolder.get()));
    }
    return inputSplits;
}
Also used : LedgerManager(org.apache.bookkeeper.meta.LedgerManager) LogSegmentMetadata(com.twitter.distributedlog.LogSegmentMetadata) BookKeeper(org.apache.bookkeeper.client.BookKeeper) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) LedgerMetadata(org.apache.bookkeeper.client.LedgerMetadata) BookkeeperInternalCallbacks(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InputSplit(org.apache.hadoop.mapreduce.InputSplit)

Example 8 with BookKeeper

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

the class DLAuditor method calculateLedgerSpaceUsage.

private long calculateLedgerSpaceUsage(BookKeeperClient bkc, final ExecutorService executorService) throws IOException {
    final AtomicLong totalBytes = new AtomicLong(0);
    final AtomicLong totalEntries = new AtomicLong(0);
    final AtomicLong numLedgers = new AtomicLong(0);
    LedgerManager lm = BookKeeperAccessor.getLedgerManager(bkc.get());
    final SettableFuture<Void> doneFuture = SettableFuture.create();
    final BookKeeper bk = bkc.get();
    BookkeeperInternalCallbacks.Processor<Long> collector = new BookkeeperInternalCallbacks.Processor<Long>() {

        @Override
        public void process(final Long lid, final AsyncCallback.VoidCallback cb) {
            numLedgers.incrementAndGet();
            executorService.submit(new Runnable() {

                @Override
                public void run() {
                    bk.asyncOpenLedgerNoRecovery(lid, BookKeeper.DigestType.CRC32, conf.getBKDigestPW().getBytes(UTF_8), new org.apache.bookkeeper.client.AsyncCallback.OpenCallback() {

                        @Override
                        public void openComplete(int rc, LedgerHandle lh, Object ctx) {
                            final int cbRc;
                            if (BKException.Code.OK == rc) {
                                totalBytes.addAndGet(lh.getLength());
                                totalEntries.addAndGet(lh.getLastAddConfirmed() + 1);
                                cbRc = rc;
                            } else {
                                cbRc = BKException.Code.ZKException;
                            }
                            executorService.submit(new Runnable() {

                                @Override
                                public void run() {
                                    cb.processResult(cbRc, null, null);
                                }
                            });
                        }
                    }, null);
                }
            });
        }
    };
    AsyncCallback.VoidCallback finalCb = new AsyncCallback.VoidCallback() {

        @Override
        public void processResult(int rc, String path, Object ctx) {
            if (BKException.Code.OK == rc) {
                doneFuture.set(null);
            } else {
                doneFuture.setException(BKException.create(rc));
            }
        }
    };
    lm.asyncProcessLedgers(collector, finalCb, null, BKException.Code.OK, BKException.Code.ZKException);
    try {
        doneFuture.get();
        logger.info("calculated {} ledgers\n\ttotal bytes = {}\n\ttotal entries = {}", new Object[] { numLedgers.get(), totalBytes.get(), totalEntries.get() });
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new DLInterruptedException("Interrupted on calculating ledger space : ", e);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) (e.getCause());
        } else {
            throw new IOException("Failed to calculate ledger space : ", e.getCause());
        }
    }
    return totalBytes.get();
}
Also used : LedgerManager(org.apache.bookkeeper.meta.LedgerManager) AsyncCallback(org.apache.zookeeper.AsyncCallback) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException) ExecutionException(java.util.concurrent.ExecutionException) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) BookKeeper(org.apache.bookkeeper.client.BookKeeper) IOException(java.io.IOException) AtomicLong(java.util.concurrent.atomic.AtomicLong) BookkeeperInternalCallbacks(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks) AtomicLong(java.util.concurrent.atomic.AtomicLong) DLInterruptedException(com.twitter.distributedlog.exceptions.DLInterruptedException)

Example 9 with BookKeeper

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

the class BookKeeperClient method createLedger.

// Util functions
public Future<LedgerHandle> createLedger(int ensembleSize, int writeQuorumSize, int ackQuorumSize) {
    BookKeeper bk;
    try {
        bk = get();
    } catch (IOException ioe) {
        return Future.exception(ioe);
    }
    final Promise<LedgerHandle> promise = new Promise<LedgerHandle>();
    bk.asyncCreateLedger(ensembleSize, writeQuorumSize, ackQuorumSize, BookKeeper.DigestType.CRC32, passwd, new AsyncCallback.CreateCallback() {

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

Example 10 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)

Aggregations

BookKeeper (org.apache.bookkeeper.client.BookKeeper)10 IOException (java.io.IOException)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)5 BKException (org.apache.bookkeeper.client.BKException)3 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)3 Maps (com.google.common.collect.Maps)2 Range (com.google.common.collect.Range)2 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)2 LogSegmentMetadata (com.twitter.distributedlog.LogSegmentMetadata)2 Promise (com.twitter.util.Promise)2 Return (com.twitter.util.Return)2 List (java.util.List)2 Map (java.util.Map)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 TimeUnit (java.util.concurrent.TimeUnit)2 AsyncCallback (org.apache.bookkeeper.client.AsyncCallback)2 ClientConfiguration (org.apache.bookkeeper.conf.ClientConfiguration)2 LedgerManager (org.apache.bookkeeper.meta.LedgerManager)2