Search in sources :

Example 96 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project incubator-pulsar by apache.

the class ManagedCursorTest method testNumberOfEntries.

@Test(timeOut = 20000)
void testNumberOfEntries() throws Exception {
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
    ManagedCursor c1 = ledger.openCursor("c1");
    ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    ManagedCursor c2 = ledger.openCursor("c2");
    ledger.addEntry("dummy-entry-2".getBytes(Encoding));
    ManagedCursor c3 = ledger.openCursor("c3");
    ledger.addEntry("dummy-entry-3".getBytes(Encoding));
    ManagedCursor c4 = ledger.openCursor("c4");
    ledger.addEntry("dummy-entry-4".getBytes(Encoding));
    ManagedCursor c5 = ledger.openCursor("c5");
    assertEquals(c1.getNumberOfEntries(), 4);
    assertEquals(c1.hasMoreEntries(), true);
    assertEquals(c2.getNumberOfEntries(), 3);
    assertEquals(c2.hasMoreEntries(), true);
    assertEquals(c3.getNumberOfEntries(), 2);
    assertEquals(c3.hasMoreEntries(), true);
    assertEquals(c4.getNumberOfEntries(), 1);
    assertEquals(c4.hasMoreEntries(), true);
    assertEquals(c5.getNumberOfEntries(), 0);
    assertEquals(c5.hasMoreEntries(), false);
    List<Entry> entries = c1.readEntries(2);
    assertEquals(entries.size(), 2);
    c1.markDelete(entries.get(1).getPosition());
    assertEquals(c1.getNumberOfEntries(), 2);
    entries.forEach(e -> e.release());
}
Also used : Entry(org.apache.bookkeeper.mledger.Entry) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 97 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project incubator-pulsar by apache.

the class ManagedCursorTest method internalTestFindNewestMatchingAllEntries.

void internalTestFindNewestMatchingAllEntries(final String name, final int entriesPerLedger, final int expectedEntryId) throws Exception {
    final String ledgerAndCursorName = name;
    ManagedLedgerConfig config = new ManagedLedgerConfig();
    config.setRetentionSizeInMB(10);
    config.setMaxEntriesPerLedger(entriesPerLedger);
    config.setRetentionTime(1, TimeUnit.HOURS);
    ManagedLedger ledger = factory.open(ledgerAndCursorName, config);
    ManagedCursorImpl c1 = (ManagedCursorImpl) ledger.openCursor(ledgerAndCursorName);
    ledger.addEntry(getEntryPublishTime("retained1"));
    // space apart message publish times
    Thread.sleep(100);
    ledger.addEntry(getEntryPublishTime("retained2"));
    Thread.sleep(100);
    ledger.addEntry(getEntryPublishTime("retained3"));
    Thread.sleep(100);
    Position newPosition = ledger.addEntry(getEntryPublishTime("expectedresetposition"));
    long timestamp = System.currentTimeMillis();
    long ledgerId = ((PositionImpl) newPosition).getLedgerId();
    Thread.sleep(2);
    ledger.addEntry(getEntryPublishTime("not-read"));
    List<Entry> entries = c1.readEntries(3);
    c1.markDelete(entries.get(2).getPosition());
    c1.close();
    ledger.close();
    entries.forEach(e -> e.release());
    // give timed ledger trimming a chance to run
    Thread.sleep(100);
    ledger = factory.open(ledgerAndCursorName, config);
    c1 = (ManagedCursorImpl) ledger.openCursor(ledgerAndCursorName);
    PositionImpl found = (PositionImpl) findPositionFromAllEntries(c1, timestamp);
    assertEquals(found.getLedgerId(), ledgerId);
    assertEquals(found.getEntryId(), expectedEntryId);
}
Also used : Entry(org.apache.bookkeeper.mledger.Entry) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig)

Example 98 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project incubator-pulsar by apache.

the class ManagedCursorTest method readWithCacheDisabled.

@Test(timeOut = 20000)
void readWithCacheDisabled() throws Exception {
    ManagedLedgerFactoryConfig config = new ManagedLedgerFactoryConfig();
    config.setMaxCacheSize(0);
    factory = new ManagedLedgerFactoryImpl(bkc, bkc.getZkHandle(), config);
    ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(1));
    ManagedCursor c1 = ledger.openCursor("c1");
    ManagedCursor c2 = ledger.openCursor("c2");
    ledger.addEntry("entry-1".getBytes(Encoding));
    ledger.addEntry("entry-2".getBytes(Encoding));
    List<Entry> entries = c1.readEntries(2);
    assertEquals(entries.size(), 2);
    assertEquals(new String(entries.get(0).getData(), Encoding), "entry-1");
    assertEquals(new String(entries.get(1).getData(), Encoding), "entry-2");
    entries.forEach(e -> e.release());
    entries = c1.readEntries(2);
    assertEquals(entries.size(), 0);
    entries.forEach(e -> e.release());
    entries = c2.readEntries(2);
    assertEquals(entries.size(), 2);
    entries.forEach(e -> e.release());
    entries = c2.readEntries(2);
    assertEquals(entries.size(), 0);
    entries.forEach(e -> e.release());
}
Also used : Entry(org.apache.bookkeeper.mledger.Entry) LedgerEntry(org.apache.bookkeeper.client.LedgerEntry) ManagedLedgerFactoryConfig(org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 99 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project incubator-pulsar by apache.

the class ManagedCursorTest method testSkipEntriesWithIndividualDeletedMessages.

@Test(timeOut = 20000)
void testSkipEntriesWithIndividualDeletedMessages() throws Exception {
    ManagedLedger ledger = factory.open("testSkipEntriesWithIndividualDeletedMessages", new ManagedLedgerConfig().setMaxEntriesPerLedger(5));
    ManagedCursor c1 = ledger.openCursor("c1");
    Position pos1 = ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    Position pos2 = ledger.addEntry("dummy-entry-2".getBytes(Encoding));
    Position pos3 = ledger.addEntry("dummy-entry-3".getBytes(Encoding));
    Position pos4 = ledger.addEntry("dummy-entry-4".getBytes(Encoding));
    Position pos5 = ledger.addEntry("dummy-entry-5".getBytes(Encoding));
    // delete individual messages
    c1.delete(pos2);
    c1.delete(pos4);
    c1.skipEntries(3, IndividualDeletedEntries.Exclude);
    assertEquals(c1.getNumberOfEntries(), 0);
    assertEquals(c1.getReadPosition(), pos5.getNext());
    assertEquals(c1.getMarkDeletedPosition(), pos5);
    pos1 = ledger.addEntry("dummy-entry-1".getBytes(Encoding));
    pos2 = ledger.addEntry("dummy-entry-2".getBytes(Encoding));
    pos3 = ledger.addEntry("dummy-entry-3".getBytes(Encoding));
    pos4 = ledger.addEntry("dummy-entry-4".getBytes(Encoding));
    pos5 = ledger.addEntry("dummy-entry-5".getBytes(Encoding));
    c1.delete(pos2);
    c1.delete(pos4);
    c1.skipEntries(4, IndividualDeletedEntries.Include);
    assertEquals(c1.getNumberOfEntries(), 1);
    assertEquals(c1.getReadPosition(), pos5);
    assertEquals(c1.getMarkDeletedPosition(), pos4);
}
Also used : Position(org.apache.bookkeeper.mledger.Position) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Example 100 with ManagedLedgerConfig

use of org.apache.bookkeeper.mledger.ManagedLedgerConfig in project incubator-pulsar by apache.

the class BrokerService method createPersistentTopic.

private void createPersistentTopic(final String topic, CompletableFuture<Topic> topicFuture) {
    final long topicCreateTimeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    TopicName topicName = TopicName.get(topic);
    if (!pulsar.getNamespaceService().isServiceUnitActive(topicName)) {
        // namespace is being unloaded
        String msg = String.format("Namespace is being unloaded, cannot add topic %s", topic);
        log.warn(msg);
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(new ServiceUnitNotReadyException(msg));
        return;
    }
    getManagedLedgerConfig(topicName).thenAccept(managedLedgerConfig -> {
        // Once we have the configuration, we can proceed with the async open operation
        managedLedgerFactory.asyncOpen(topicName.getPersistenceNamingEncoding(), managedLedgerConfig, new OpenLedgerCallback() {

            @Override
            public void openLedgerComplete(ManagedLedger ledger, Object ctx) {
                try {
                    PersistentTopic persistentTopic = new PersistentTopic(topic, ledger, BrokerService.this);
                    CompletableFuture<Void> replicationFuture = persistentTopic.checkReplication();
                    replicationFuture.thenCompose(v -> {
                        // Also check dedup status
                        return persistentTopic.checkDeduplicationStatus();
                    }).thenRun(() -> {
                        log.info("Created topic {} - dedup is {}", topic, persistentTopic.isDeduplicationEnabled() ? "enabled" : "disabled");
                        long topicLoadLatencyMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) - topicCreateTimeMs;
                        pulsarStats.recordTopicLoadTimeValue(topic, topicLoadLatencyMs);
                        addTopicToStatsMaps(topicName, persistentTopic);
                        topicFuture.complete(persistentTopic);
                    }).exceptionally((ex) -> {
                        log.warn("Replication or dedup check failed. Removing topic from topics list {}, {}", topic, ex);
                        persistentTopic.stopReplProducers().whenComplete((v, exception) -> {
                            topics.remove(topic, topicFuture);
                            topicFuture.completeExceptionally(ex);
                        });
                        return null;
                    });
                } catch (NamingException e) {
                    log.warn("Failed to create topic {}-{}", topic, e.getMessage());
                    pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
                    topicFuture.completeExceptionally(e);
                }
            }

            @Override
            public void openLedgerFailed(ManagedLedgerException exception, Object ctx) {
                log.warn("Failed to create topic {}", topic, exception);
                pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
                topicFuture.completeExceptionally(new PersistenceException(exception));
            }
        }, null);
    }).exceptionally((exception) -> {
        log.warn("[{}] Failed to get topic configuration: {}", topic, exception.getMessage(), exception);
        // remove topic from topics-map in different thread to avoid possible deadlock if
        // createPersistentTopic-thread only tries to handle this future-result
        pulsar.getExecutor().submit(() -> topics.remove(topic, topicFuture));
        topicFuture.completeExceptionally(exception);
        return null;
    });
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) PulsarClientImpl(org.apache.pulsar.client.impl.PulsarClientImpl) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) FieldContext(org.apache.pulsar.common.configuration.FieldContext) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) ZooKeeperDataCache(org.apache.pulsar.zookeeper.ZooKeeperDataCache) PersistentOfflineTopicStats(org.apache.pulsar.common.policies.data.PersistentOfflineTopicStats) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) PersistencePolicies(org.apache.pulsar.common.policies.data.PersistencePolicies) Set(java.util.Set) ZooKeeperCacheListener(org.apache.pulsar.zookeeper.ZooKeeperCacheListener) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) Executors(java.util.concurrent.Executors) ZkUtils(org.apache.bookkeeper.util.ZkUtils) NamespaceBundleFactory(org.apache.pulsar.common.naming.NamespaceBundleFactory) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) ClientBuilderImpl(org.apache.pulsar.client.impl.ClientBuilderImpl) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ChannelOption(io.netty.channel.ChannelOption) AuthenticationService(org.apache.pulsar.broker.authentication.AuthenticationService) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) EventType(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect.EventType) ServerMetadataException(org.apache.pulsar.broker.service.BrokerServiceException.ServerMetadataException) Lists(com.google.common.collect.Lists) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PulsarClient(org.apache.pulsar.client.api.PulsarClient) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) PersistentDispatcherMultipleConsumers(org.apache.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) ClientCnxnAspect(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect) PulsarWebResource(org.apache.pulsar.broker.web.PulsarWebResource) SslContext(io.netty.handler.ssl.SslContext) IOException(java.io.IOException) Field(java.lang.reflect.Field) PulsarService(org.apache.pulsar.broker.PulsarService) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) AuthorizationService(org.apache.pulsar.broker.authorization.AuthorizationService) Metrics(org.apache.pulsar.common.stats.Metrics) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) Ids(org.apache.zookeeper.ZooDefs.Ids) AdminResource(org.apache.pulsar.broker.admin.AdminResource) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) Stat(org.apache.zookeeper.data.Stat) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) URI(java.net.URI) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) DigestType(org.apache.bookkeeper.client.BookKeeper.DigestType) EventLoopUtil(org.apache.pulsar.common.util.netty.EventLoopUtil) OrderedScheduler(org.apache.bookkeeper.common.util.OrderedScheduler) Predicate(java.util.function.Predicate) InetSocketAddress(java.net.InetSocketAddress) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) FutureUtil(org.apache.pulsar.common.util.FutureUtil) Queues(com.google.common.collect.Queues) ClientConfigurationData(org.apache.pulsar.client.impl.conf.ClientConfigurationData) EventListner(org.apache.pulsar.broker.zookeeper.aspectj.ClientCnxnAspect.EventListner) ClientBuilder(org.apache.pulsar.client.api.ClientBuilder) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) LongAdder(java.util.concurrent.atomic.LongAdder) TopicName(org.apache.pulsar.common.naming.TopicName) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) ByteBuf(io.netty.buffer.ByteBuf) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) TopicDomain(org.apache.pulsar.common.naming.TopicDomain) ClusterReplicationMetrics(org.apache.pulsar.broker.stats.ClusterReplicationMetrics) FieldParser(org.apache.pulsar.common.util.FieldParser) RetentionPolicies(org.apache.pulsar.common.policies.data.RetentionPolicies) Logger(org.slf4j.Logger) EventLoopGroup(io.netty.channel.EventLoopGroup) KeeperException(org.apache.zookeeper.KeeperException) Semaphore(java.util.concurrent.Semaphore) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Maps(com.google.common.collect.Maps) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Policies(org.apache.pulsar.common.policies.data.Policies) Closeable(java.io.Closeable) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Collections(java.util.Collections) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) TopicName(org.apache.pulsar.common.naming.TopicName) ServiceUnitNotReadyException(org.apache.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) NamingException(org.apache.pulsar.broker.service.BrokerServiceException.NamingException) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback)

Aggregations

ManagedLedgerConfig (org.apache.bookkeeper.mledger.ManagedLedgerConfig)194 Test (org.testng.annotations.Test)182 ManagedLedger (org.apache.bookkeeper.mledger.ManagedLedger)159 ManagedCursor (org.apache.bookkeeper.mledger.ManagedCursor)147 Position (org.apache.bookkeeper.mledger.Position)85 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)77 Entry (org.apache.bookkeeper.mledger.Entry)63 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)54 CountDownLatch (java.util.concurrent.CountDownLatch)52 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)33 CyclicBarrier (java.util.concurrent.CyclicBarrier)20 ManagedLedgerFactoryConfig (org.apache.bookkeeper.mledger.ManagedLedgerFactoryConfig)19 AddEntryCallback (org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)18 List (java.util.List)17 AtomicReference (java.util.concurrent.atomic.AtomicReference)16 LedgerEntry (org.apache.bookkeeper.client.LedgerEntry)16 TimeUnit (java.util.concurrent.TimeUnit)15 AsyncCallbacks (org.apache.bookkeeper.mledger.AsyncCallbacks)15 BKException (org.apache.bookkeeper.client.BKException)14 Lists (com.google.common.collect.Lists)13