Search in sources :

Example 96 with ManagedLedgerException

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

the class ManagedLedgerBkTest method testBookieFailure.

@Test
public void testBookieFailure() throws Exception {
    ManagedLedgerFactory factory = new ManagedLedgerFactoryImpl(bkc, zkc);
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    config.setEnsembleSize(2).setAckQuorumSize(2).setMetadataEnsembleSize(2);
    ManagedLedger ledger = factory.open("my-ledger", config);
    ManagedCursor cursor = ledger.openCursor("my-cursor");
    ledger.addEntry("entry-0".getBytes());
    killBookie(1);
    // Now we want to simulate that:
    // 1. The write operation fails because we only have 1 bookie available
    // 2. The bk client cannot properly close the ledger (finalizing the number of entries) because ZK is also
    // not available
    // 3. When we re-establish the service one, the ledger recovery will be triggered and the half-committed entry
    // is restored
    // Force to close the ZK client object so that BK will fail to close the ledger
    bkc.getZkHandle().close();
    try {
        ledger.addEntry("entry-1".getBytes());
        fail("should fail");
    } catch (ManagedLedgerException e) {
    // ok
    }
    bkc = new BookKeeperTestClient(baseClientConf);
    startNewBookie();
    // Reconnect a new bk client
    factory = new ManagedLedgerFactoryImpl(bkc, zkc);
    ledger = factory.open("my-ledger", config);
    cursor = ledger.openCursor("my-cursor");
    // Next add should succeed
    ledger.addEntry("entry-2".getBytes());
    assertEquals(3, cursor.getNumberOfEntriesInBacklog());
    List<Entry> entries = cursor.readEntries(1);
    assertEquals(1, entries.size());
    assertEquals("entry-0", new String(entries.get(0).getData()));
    entries.forEach(e -> e.release());
    // entry-1 which was half-committed will get fully committed during the recovery phase
    entries = cursor.readEntries(1);
    assertEquals(1, entries.size());
    assertEquals("entry-1", new String(entries.get(0).getData()));
    entries.forEach(e -> e.release());
    entries = cursor.readEntries(1);
    assertEquals(1, entries.size());
    assertEquals("entry-2", new String(entries.get(0).getData()));
    entries.forEach(e -> e.release());
    factory.shutdown();
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Entry(org.apache.bookkeeper.mledger.Entry) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) BookKeeperTestClient(org.apache.bookkeeper.client.BookKeeperTestClient) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 97 with ManagedLedgerException

use of org.apache.bookkeeper.mledger.ManagedLedgerException 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 98 with ManagedLedgerException

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

the class ManagedLedgerErrorsTest method closingManagedLedger.

@Test
public void closingManagedLedger() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger");
    ledger.openCursor("c1");
    ledger.addEntry("entry".getBytes());
    bkc.failNow(BKException.Code.NoSuchLedgerExistsException);
    try {
        ledger.close();
        fail("should fail");
    } catch (ManagedLedgerException e) {
    // ok
    }
    // ML should be closed even if it failed before
    try {
        ledger.addEntry("entry".getBytes());
        fail("managed ledger was closed");
    } catch (ManagedLedgerException e) {
    // ok
    }
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Test(org.testng.annotations.Test)

Example 99 with ManagedLedgerException

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

the class BrokerService method createPersistentTopic.

private CompletableFuture<Topic> createPersistentTopic(final String topic) throws RuntimeException {
    checkTopicNsOwnership(topic);
    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    DestinationName destinationName = DestinationName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(destinationName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        throw new RuntimeException(new ServiceUnitNotReadyException(msg));
    }
    final CompletableFuture<Topic> topicFuture = new CompletableFuture<>();
    getManagedLedgerConfig(destinationName).thenAccept(config -> {
        managedLedgerFactory.asyncOpen(destinationName.getPersistenceNamingEncoding(), config, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                PersistentTopic persistentTopic = new PersistentTopic(topic, ledger, BrokerService.this);
                CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                replicationFuture.thenRun(() -> {
                    log.info("Created topic {}", topic);
                    long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - topicCreateTimeMs;
                    pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                    addTopicToStatsMaps(destinationName, persistentTopic);
                    topicFuture.complete(persistentTopic);
                });
                replicationFuture.exceptionally((ex) -> {
                    log.warn("Replication check failed. Removing topic from topics list {}, {}", topic, ex);
                    persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                        topics.remove(topic, topicFuture);
                        topicFuture.completeExceptionally(ex);
                    });
                    return null;
                });
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                log.warn("Failed to create topic {}", topic, exception);
                topics.remove(topic, topicFuture);
                topicFuture.completeExceptionally(new PersistenceException(exception));
            }
        }, null);
    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        topics.remove(topic, topicFuture);
        topicFuture.completeExceptionally(exception);
        return null;
    });
    return topicFuture;
}
Also used : DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) LoggerFactory(org.slf4j.LoggerFactory) NamespaceBundleStats(com.yahoo.pulsar.common.policies.data.loadbalancer.NamespaceBundleStats) Stat(org.apache.zookeeper.data.Stat) Policies(com.yahoo.pulsar.common.policies.data.Policies) EpollMode(io.netty.channel.epoll.EpollMode) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PersistentOfflineTopicStats(com.yahoo.pulsar.common.policies.data.PersistentOfflineTopicStats) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) ZooKeeperCacheListener(com.yahoo.pulsar.zookeeper.ZooKeeperCacheListener) PulsarService(com.yahoo.pulsar.broker.PulsarService) FieldParser(com.yahoo.pulsar.common.util.FieldParser) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) FutureUtil(com.yahoo.pulsar.client.util.FutureUtil) URI(java.net.URI) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) SystemUtils(org.apache.commons.lang.SystemUtils) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) DigestType(org.apache.bookkeeper.client.BookKeeper.DigestType) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) Set(java.util.Set) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ObjectMapperFactory(com.yahoo.pulsar.common.util.ObjectMapperFactory) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Metrics(com.yahoo.pulsar.broker.stats.Metrics) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Optional(java.util.Optional) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ChannelOption(io.netty.channel.ChannelOption) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) EpollChannelOption(io.netty.channel.epoll.EpollChannelOption) Lists(com.google.common.collect.Lists) FieldContext(com.yahoo.pulsar.common.configuration.FieldContext) ByteBuf(io.netty.buffer.ByteBuf) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) ConcurrentOpenHashSet(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashSet) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) NamespaceBundleFactory(com.yahoo.pulsar.common.naming.NamespaceBundleFactory) PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) ClusterReplicationMetrics(com.yahoo.pulsar.broker.stats.ClusterReplicationMetrics) Logger(org.slf4j.Logger) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) EventLoopGroup(io.netty.channel.EventLoopGroup) KeeperException(org.apache.zookeeper.KeeperException) Semaphore(java.util.concurrent.Semaphore) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) IOException(java.io.IOException) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Field(java.lang.reflect.Field) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) PulsarWebResource(com.yahoo.pulsar.broker.web.PulsarWebResource) Closeable(java.io.Closeable) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) AuthorizationManager(com.yahoo.pulsar.broker.authorization.AuthorizationManager) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) AuthenticationService(com.yahoo.pulsar.broker.authentication.AuthenticationService) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)

Example 100 with ManagedLedgerException

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

the class PersistentTopicTest method testPublishMessageMLFailure.

@Test
public void testPublishMessageMLFailure() throws Exception {
    final String successTopicName = "persistent://prop/use/ns-abc/successTopic";
    final ManagedLedger ledgerMock = mock(ManagedLedger.class);
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService);
    MessageMetadata.Builder messageMetadata = MessageMetadata.newBuilder();
    messageMetadata.setPublishTime(System.currentTimeMillis());
    messageMetadata.setProducerName("prod-name");
    messageMetadata.setSequenceId(1);
    ByteBuf payload = Unpooled.wrappedBuffer("content".getBytes());
    final CountDownLatch latch = new CountDownLatch(1);
    // override asyncAddEntry callback to return error
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((AddEntryCallback) invocationOnMock.getArguments()[1]).addFailed(new ManagedLedgerException("Managed ledger failure"), invocationOnMock.getArguments()[2]);
            return null;
        }
    }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
    topic.publishMessage(payload, (exception, ledgerId, entryId) -> {
        if (exception == null) {
            fail("publish should have failed");
        } else {
            latch.countDown();
        }
    });
    assertTrue(latch.await(1, TimeUnit.SECONDS));
}
Also used : ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Matchers.anyString(org.mockito.Matchers.anyString) ByteBuf(io.netty.buffer.ByteBuf) CountDownLatch(java.util.concurrent.CountDownLatch) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Matchers.anyObject(org.mockito.Matchers.anyObject) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) Test(org.testng.annotations.Test)

Aggregations

ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)133 Test (org.testng.annotations.Test)70 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)65 CountDownLatch (java.util.concurrent.CountDownLatch)63 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)46 Entry (org.apache.bookkeeper.mledger.Entry)36 ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)33 Position (org.apache.bookkeeper.mledger.Position)33 CompletableFuture (java.util.concurrent.CompletableFuture)23 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)21 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)19 List (java.util.List)18 ReadEntriesCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntriesCallback)18 BKException (org.apache.bookkeeper.client.BKException)15 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 LedgerHandle (org.apache.bookkeeper.client.LedgerHandle)13 CloseCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback)13 MarkDeleteCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.MarkDeleteCallback)13 Logger (org.slf4j.Logger)13 LoggerFactory (org.slf4j.LoggerFactory)13