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);
}
}
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;
}
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();
}
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;
}
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);
}
});
}
Aggregations