Search in sources :

Example 76 with LedgerHandle

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

the class TestBKLogSegmentWriter method testAbortShouldFailAllWrites.

/**
 * Abort should wait for outstanding transmits to be completed and cancel buffered data.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testAbortShouldFailAllWrites() throws Exception {
    DistributedLogConfiguration confLocal = newLocalConf();
    confLocal.setImmediateFlushEnabled(false);
    confLocal.setOutputBufferSize(Integer.MAX_VALUE);
    confLocal.setPeriodicFlushFrequencyMilliSeconds(0);
    ZKDistributedLock lock = createLock("/test/lock-" + runtime.getMethodName(), zkc, true);
    BKLogSegmentWriter writer = createLogSegmentWriter(confLocal, 0L, -1L, lock);
    // Use another lock to wait for writer releasing lock
    ZKDistributedLock lock0 = createLock("/test/lock-" + runtime.getMethodName(), zkc0, false);
    CompletableFuture<ZKDistributedLock> lockFuture0 = lock0.asyncAcquire();
    // add 10 records
    int numRecords = 10;
    List<CompletableFuture<DLSN>> futureList = new ArrayList<CompletableFuture<DLSN>>(numRecords);
    for (int i = 0; i < numRecords; i++) {
        futureList.add(writer.asyncWrite(DLMTestUtil.getLogRecordInstance(i)));
    }
    assertEquals("Last tx id should be " + (numRecords - 1), numRecords - 1, writer.getLastTxId());
    assertEquals("Last acked tx id should be -1", -1L, writer.getLastTxIdAcknowledged());
    assertEquals("Last DLSN should be " + DLSN.InvalidDLSN, DLSN.InvalidDLSN, writer.getLastDLSN());
    assertEquals("Position should be " + numRecords, numRecords, writer.getPositionWithinLogSegment());
    final CountDownLatch deferLatch = new CountDownLatch(1);
    writer.getFuturePool().submit(() -> {
        try {
            deferLatch.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            LOG.warn("Interrupted on deferring completion : ", e);
        }
    });
    // transmit the buffered data
    Utils.ioResult(writer.flush());
    // add another 10 records
    List<CompletableFuture<DLSN>> anotherFutureList = new ArrayList<CompletableFuture<DLSN>>(numRecords);
    for (int i = numRecords; i < 2 * numRecords; i++) {
        anotherFutureList.add(writer.asyncWrite(DLMTestUtil.getLogRecordInstance(i)));
    }
    assertEquals("Last tx id should become " + (2 * numRecords - 1), 2 * numRecords - 1, writer.getLastTxId());
    assertEquals("Last acked tx id should become " + (numRecords - 1), (long) (numRecords - 1), writer.getLastTxIdAcknowledged());
    assertEquals("Last DLSN should still be " + DLSN.InvalidDLSN, DLSN.InvalidDLSN, writer.getLastDLSN());
    assertEquals("Position should become " + (2 * numRecords), 2 * numRecords, writer.getPositionWithinLogSegment());
    // abort the writer: it waits for outstanding transmits and abort buffered data
    abortWriterAndLock(writer, lock);
    Utils.ioResult(lockFuture0);
    lock0.checkOwnership();
    // release defer latch so completion would go through
    deferLatch.countDown();
    List<DLSN> dlsns = Utils.ioResult(FutureUtils.collect(futureList));
    assertEquals("All first 10 records should be written", numRecords, dlsns.size());
    for (int i = 0; i < numRecords; i++) {
        DLSN dlsn = dlsns.get(i);
        assertEquals("Incorrent ledger sequence number", 0L, dlsn.getLogSegmentSequenceNo());
        assertEquals("Incorrent entry id", 0L, dlsn.getEntryId());
        assertEquals("Inconsistent slot id", i, dlsn.getSlotId());
    }
    for (int i = 0; i < numRecords; i++) {
        try {
            Utils.ioResult(anotherFutureList.get(i));
            fail("Should be aborted record " + (numRecords + i) + " with transmit exception");
        } catch (WriteCancelledException wce) {
        // writes should be cancelled.
        }
    }
    assertEquals("Last tx id should still be " + (2 * numRecords - 1), 2 * numRecords - 1, writer.getLastTxId());
    assertEquals("Last acked tx id should be still " + (numRecords - 1), (long) (numRecords - 1), writer.getLastTxIdAcknowledged());
    assertEquals("Last DLSN should become " + futureList.get(futureList.size() - 1), dlsns.get(futureList.size() - 1), writer.getLastDLSN());
    assertEquals("Position should become " + 2 * numRecords, 2 * numRecords, writer.getPositionWithinLogSegment());
    // check only 1 entry were written
    LedgerHandle lh = getLedgerHandle(writer);
    LedgerHandle readLh = openLedgerNoRecovery(lh);
    assertTrue("Ledger " + lh.getId() + " should not be closed", readLh.isClosed());
    assertEquals("Only one entry is written for ledger " + lh.getId(), 0L, lh.getLastAddPushed());
    assertEquals("Only one entry is written for ledger " + lh.getId(), 0L, readLh.getLastAddConfirmed());
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) ZKDistributedLock(org.apache.distributedlog.lock.ZKDistributedLock) CompletableFuture(java.util.concurrent.CompletableFuture) WriteCancelledException(org.apache.distributedlog.exceptions.WriteCancelledException) Test(org.junit.Test)

Example 77 with LedgerHandle

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

the class TestBKLogSegmentWriter method testAbortShouldNotFlush.

/**
 * Abort a segment log writer should just abort pending writes and not flush buffered data.
 *
 * @throws Exception
 */
@Test(timeout = 60000)
public void testAbortShouldNotFlush() throws Exception {
    DistributedLogConfiguration confLocal = newLocalConf();
    confLocal.setImmediateFlushEnabled(false);
    confLocal.setOutputBufferSize(Integer.MAX_VALUE);
    confLocal.setPeriodicFlushFrequencyMilliSeconds(0);
    ZKDistributedLock lock = createLock("/test/lock-" + runtime.getMethodName(), zkc, true);
    BKLogSegmentWriter writer = createLogSegmentWriter(confLocal, 0L, -1L, lock);
    // Use another lock to wait for writer releasing lock
    ZKDistributedLock lock0 = createLock("/test/lock-" + runtime.getMethodName(), zkc0, false);
    CompletableFuture<ZKDistributedLock> lockFuture0 = lock0.asyncAcquire();
    // add 10 records
    int numRecords = 10;
    List<CompletableFuture<DLSN>> futureList = new ArrayList<CompletableFuture<DLSN>>(numRecords);
    for (int i = 0; i < numRecords; i++) {
        futureList.add(writer.asyncWrite(DLMTestUtil.getLogRecordInstance(i)));
    }
    assertEquals("Last tx id should be " + (numRecords - 1), numRecords - 1, writer.getLastTxId());
    assertEquals("Last acked tx id should be -1", -1L, writer.getLastTxIdAcknowledged());
    assertEquals("Last DLSN should be " + DLSN.InvalidDLSN, DLSN.InvalidDLSN, writer.getLastDLSN());
    assertEquals("Position should be " + numRecords, 10, writer.getPositionWithinLogSegment());
    // close the writer should flush buffered data and release lock
    abortWriterAndLock(writer, lock);
    Utils.ioResult(lockFuture0);
    lock0.checkOwnership();
    assertEquals("Last tx id should still be " + (numRecords - 1), numRecords - 1, writer.getLastTxId());
    assertEquals("Last acked tx id should still be " + (numRecords - 1), -1L, writer.getLastTxIdAcknowledged());
    assertEquals("Last DLSN should still be " + DLSN.InvalidDLSN, DLSN.InvalidDLSN, writer.getLastDLSN());
    assertEquals("Position should still be " + numRecords, 10, writer.getPositionWithinLogSegment());
    for (int i = 0; i < numRecords; i++) {
        try {
            Utils.ioResult(futureList.get(i));
            fail("Should be aborted record " + i + " with transmit exception");
        } catch (WriteCancelledException wce) {
            assertTrue("Record " + i + " should be aborted because of ledger fenced", wce.getCause() instanceof BKTransmitException);
            BKTransmitException bkte = (BKTransmitException) wce.getCause();
            assertEquals("Record " + i + " should be aborted", BKException.Code.InterruptedException, bkte.getBKResultCode());
        }
    }
    // check no entries were written
    LedgerHandle lh = getLedgerHandle(writer);
    LedgerHandle readLh = openLedgerNoRecovery(lh);
    assertTrue("Ledger " + lh.getId() + " should not be closed", readLh.isClosed());
    assertEquals("There should be no entries in ledger " + lh.getId(), LedgerHandle.INVALID_ENTRY_ID, readLh.getLastAddConfirmed());
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) WriteCancelledException(org.apache.distributedlog.exceptions.WriteCancelledException) BKTransmitException(org.apache.distributedlog.exceptions.BKTransmitException) ArrayList(java.util.ArrayList) ZKDistributedLock(org.apache.distributedlog.lock.ZKDistributedLock) Test(org.junit.Test)

Example 78 with LedgerHandle

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

the class TestLedgerAllocatorPool method testConcurrentAllocation.

@Test(timeout = 60000)
public void testConcurrentAllocation() throws Exception {
    final int numAllocators = 5;
    String allocationPath = "/concurrentAllocation";
    final LedgerAllocatorPool pool = new LedgerAllocatorPool(allocationPath, numAllocators, dlConf, zkc, bkc, allocationExecutor);
    final ConcurrentMap<Long, LedgerHandle> allocatedLedgers = new ConcurrentHashMap<Long, LedgerHandle>();
    final AtomicInteger numFailures = new AtomicInteger(0);
    Thread[] allocationThreads = new Thread[numAllocators];
    for (int i = 0; i < numAllocators; i++) {
        final int tid = i;
        allocationThreads[i] = new Thread() {

            int numLedgers = 50;

            @Override
            public void run() {
                try {
                    for (int i = 0; i < numLedgers; i++) {
                        pool.allocate();
                        ZKTransaction txn = newTxn();
                        LedgerHandle lh = Utils.ioResult(pool.tryObtain(txn, NULL_LISTENER));
                        Utils.ioResult(txn.execute());
                        lh.close();
                        allocatedLedgers.putIfAbsent(lh.getId(), lh);
                        logger.info("[thread {}] allocate {}th ledger {}", new Object[] { tid, i, lh.getId() });
                    }
                } catch (Exception ioe) {
                    numFailures.incrementAndGet();
                }
            }
        };
    }
    for (Thread t : allocationThreads) {
        t.start();
    }
    for (Thread t : allocationThreads) {
        t.join();
    }
    assertEquals(0, numFailures.get());
    assertEquals(50 * numAllocators, allocatedLedgers.size());
    Utils.close(pool);
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) ZKTransaction(org.apache.distributedlog.zk.ZKTransaction) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.junit.Test)

Example 79 with LedgerHandle

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

the class NetworkLessBookieTest method testUseLocalBookie.

@Test
public void testUseLocalBookie() throws Exception {
    ClientConfiguration conf = new ClientConfiguration();
    conf.setZkServers(zkUtil.getZooKeeperConnectString());
    conf.setZkTimeout(20000);
    try (BookKeeper bkc = new BookKeeper(conf)) {
        try (LedgerHandle h = bkc.createLedger(1, 1, DigestType.CRC32, "testPasswd".getBytes())) {
            h.addEntry("test".getBytes());
        }
    }
    for (BookieServer bk : bs) {
        for (Channel channel : bk.nettyServer.allChannels) {
            if (!(channel instanceof LocalChannel)) {
                fail();
            }
        }
    }
}
Also used : LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) LocalChannel(io.netty.channel.local.LocalChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) BookKeeper(org.apache.bookkeeper.client.BookKeeper) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) Test(org.junit.Test)

Example 80 with LedgerHandle

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

the class BookKeeperBuildersTest method testDefaultWriteFlagsEmpty.

@Test
public void testDefaultWriteFlagsEmpty() throws Exception {
    setNewGeneratedLedgerId(ledgerId);
    WriteHandle writer = newCreateLedgerOp().withAckQuorumSize(ackQuorumSize).withEnsembleSize(ensembleSize).withPassword(password).withWriteQuorumSize(writeQuorumSize).withCustomMetadata(customMetadata).execute().get();
    assertEquals(ledgerId, writer.getId());
    LedgerMetadata metadata = getLedgerMetadata(ledgerId);
    assertEquals(ensembleSize, metadata.getEnsembleSize());
    assertEquals(ackQuorumSize, metadata.getAckQuorumSize());
    assertEquals(writeQuorumSize, metadata.getWriteQuorumSize());
    assertArrayEquals(password, metadata.getPassword());
    LedgerHandle lh = (LedgerHandle) writer;
    assertEquals(EnumSet.noneOf(WriteFlag.class), lh.getWriteFlags());
}
Also used : LedgerMetadata(org.apache.bookkeeper.client.LedgerMetadata) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) Test(org.junit.Test)

Aggregations

LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)238 Test (org.junit.Test)140 CountDownLatch (java.util.concurrent.CountDownLatch)54 BookKeeper (org.apache.bookkeeper.client.BookKeeper)52 LedgerEntry (org.apache.bookkeeper.client.LedgerEntry)49 BKException (org.apache.bookkeeper.client.BKException)39 ArrayList (java.util.ArrayList)31 IOException (java.io.IOException)28 ServerConfiguration (org.apache.bookkeeper.conf.ServerConfiguration)28 File (java.io.File)27 BookieSocketAddress (org.apache.bookkeeper.net.BookieSocketAddress)23 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)22 List (java.util.List)18 CompletableFuture (java.util.concurrent.CompletableFuture)18 BookieServer (org.apache.bookkeeper.proto.BookieServer)18 Test (org.testng.annotations.Test)17 Entry (org.apache.bookkeeper.mledger.Entry)16 ZKTransaction (com.twitter.distributedlog.zk.ZKTransaction)13 ByteBuffer (java.nio.ByteBuffer)13 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)13