Search in sources :

Example 51 with Producer

use of org.apache.pulsar.client.api.Producer in project incubator-pulsar by apache.

the class BrokerServiceTest method testBrokerServiceNamespaceStats.

@Test
public void testBrokerServiceNamespaceStats() throws Exception {
    final int numBundles = 4;
    final String ns1 = "prop/use/stats1";
    final String ns2 = "prop/use/stats2";
    List<String> nsList = Lists.newArrayList(ns1, ns2);
    List<Producer<byte[]>> producerList = Lists.newArrayList();
    BrokerStats brokerStatsClient = admin.brokerStats();
    for (String ns : nsList) {
        admin.namespaces().createNamespace(ns, numBundles);
        String topic1 = String.format("persistent://%s/topic1", ns);
        producerList.add(pulsarClient.newProducer().topic(topic1).create());
        String topic2 = String.format("persistent://%s/topic2", ns);
        producerList.add(pulsarClient.newProducer().topic(topic2).create());
    }
    rolloverPerIntervalStats();
    JsonObject topicStats = brokerStatsClient.getTopics();
    assertEquals(topicStats.size(), 2, topicStats.toString());
    for (String ns : nsList) {
        JsonObject nsObject = topicStats.getAsJsonObject(ns);
        List<String> topicList = admin.namespaces().getTopics(ns);
        for (String topic : topicList) {
            NamespaceBundle bundle = (NamespaceBundle) pulsar.getNamespaceService().getBundle(TopicName.get(topic));
            JsonObject bundleObject = nsObject.getAsJsonObject(bundle.getBundleRange());
            JsonObject topicObject = bundleObject.getAsJsonObject("persistent");
            AtomicBoolean topicPresent = new AtomicBoolean();
            topicObject.entrySet().iterator().forEachRemaining(persistentTopic -> {
                if (persistentTopic.getKey().equals(topic)) {
                    topicPresent.set(true);
                }
            });
            assertTrue(topicPresent.get());
        }
    }
    for (Producer<?> producer : producerList) {
        producer.close();
    }
    for (String ns : nsList) {
        List<String> topics = admin.namespaces().getTopics(ns);
        for (String dest : topics) {
            admin.persistentTopics().delete(dest);
        }
        admin.namespaces().deleteNamespace(ns);
    }
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Producer(org.apache.pulsar.client.api.Producer) JsonObject(com.google.gson.JsonObject) BrokerStats(org.apache.pulsar.client.admin.BrokerStats) Test(org.testng.annotations.Test)

Example 52 with Producer

use of org.apache.pulsar.client.api.Producer in project incubator-pulsar by apache.

the class BrokerServiceTest method testTopicFailureShouldNotHaveDeadLock.

/**
 * Verifies brokerService should not have deadlock and successfully remove topic from topicMap on topic-failure and
 * it should not introduce deadlock while performing it.
 */
@Test(timeOut = 3000)
public void testTopicFailureShouldNotHaveDeadLock() {
    final String namespace = "prop/usw/my-ns";
    final String deadLockTestTopic = "persistent://" + namespace + "/deadLockTestTopic";
    // let this broker own this namespace bundle by creating a topic
    try {
        final String successfulTopic = "persistent://" + namespace + "/ownBundleTopic";
        Producer<byte[]> producer = pulsarClient.newProducer().topic(successfulTopic).create();
        producer.close();
    } catch (Exception e) {
        fail(e.getMessage());
    }
    ExecutorService executor = Executors.newSingleThreadExecutor();
    BrokerService service = spy(pulsar.getBrokerService());
    // create topic will fail to get managedLedgerConfig
    CompletableFuture<ManagedLedgerConfig> failedManagedLedgerConfig = new CompletableFuture<>();
    failedManagedLedgerConfig.completeExceptionally(new NullPointerException("failed to peristent policy"));
    doReturn(failedManagedLedgerConfig).when(service).getManagedLedgerConfig(anyObject());
    CompletableFuture<Void> topicCreation = new CompletableFuture<Void>();
    // create topic async and wait on the future completion
    executor.submit(() -> {
        service.getTopic(deadLockTestTopic).thenAccept(topic -> topicCreation.complete(null)).exceptionally(e -> {
            topicCreation.completeExceptionally(e.getCause());
            return null;
        });
    });
    // future-result should be completed with exception
    try {
        topicCreation.get(1, TimeUnit.SECONDS);
    } catch (TimeoutException | InterruptedException e) {
        fail("there is a dead-lock and it should have been prevented");
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof NullPointerException);
    } finally {
        executor.shutdownNow();
    }
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) JsonObject(com.google.gson.JsonObject) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) Producer(org.apache.pulsar.client.api.Producer) TimeoutException(java.util.concurrent.TimeoutException) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) URI(java.net.URI) Mockito.doReturn(org.mockito.Mockito.doReturn) BeforeClass(org.testng.annotations.BeforeClass) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies) Assert.assertNotNull(org.testng.Assert.assertNotNull) PulsarWebResource.joinPath(org.apache.pulsar.broker.web.PulsarWebResource.joinPath) Executors(java.util.concurrent.Executors) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) JsonArray(com.google.gson.JsonArray) Optional(java.util.Optional) TopicName(org.apache.pulsar.common.naming.TopicName) LOCAL_POLICIES_ROOT(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService.LOCAL_POLICIES_ROOT) Assert.assertEquals(org.testng.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.apache.pulsar.client.api.Message) Mockito.spy(org.mockito.Mockito.spy) HashSet(java.util.HashSet) AuthenticationTls(org.apache.pulsar.client.impl.auth.AuthenticationTls) Lists(com.google.common.collect.Lists) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) Matchers.anyObject(org.mockito.Matchers.anyObject) PulsarClient(org.apache.pulsar.client.api.PulsarClient) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) ExecutorService(java.util.concurrent.ExecutorService) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) AfterClass(org.testng.annotations.AfterClass) Assert.fail(org.testng.Assert.fail) IOException(java.io.IOException) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Field(java.lang.reflect.Field) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Authentication(org.apache.pulsar.client.api.Authentication) Assert.assertTrue(org.testng.Assert.assertTrue) BrokerStats(org.apache.pulsar.client.admin.BrokerStats) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) IOException(java.io.IOException) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) ExecutionException(java.util.concurrent.ExecutionException) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test)

Example 53 with Producer

use of org.apache.pulsar.client.api.Producer in project incubator-pulsar by apache.

the class BrokerServiceTest method testLedgerOpenFailureShouldNotHaveDeadLock.

@Test
public void testLedgerOpenFailureShouldNotHaveDeadLock() throws Exception {
    final String namespace = "prop/usw/my-ns";
    final String deadLockTestTopic = "persistent://" + namespace + "/deadLockTestTopic";
    // let this broker own this namespace bundle by creating a topic
    try {
        final String successfulTopic = "persistent://" + namespace + "/ownBundleTopic";
        Producer<byte[]> producer = pulsarClient.newProducer().topic(successfulTopic).create();
        producer.close();
    } catch (Exception e) {
        fail(e.getMessage());
    }
    ExecutorService executor = Executors.newSingleThreadExecutor();
    BrokerService service = spy(pulsar.getBrokerService());
    // create topic will fail to get managedLedgerConfig
    CompletableFuture<ManagedLedgerConfig> failedManagedLedgerConfig = new CompletableFuture<>();
    failedManagedLedgerConfig.complete(null);
    doReturn(failedManagedLedgerConfig).when(service).getManagedLedgerConfig(anyObject());
    CompletableFuture<Void> topicCreation = new CompletableFuture<Void>();
    // fail managed-ledger future
    Field ledgerField = ManagedLedgerFactoryImpl.class.getDeclaredField("ledgers");
    ledgerField.setAccessible(true);
    @SuppressWarnings("unchecked") ConcurrentHashMap<String, CompletableFuture<ManagedLedgerImpl>> ledgers = (ConcurrentHashMap<String, CompletableFuture<ManagedLedgerImpl>>) ledgerField.get(pulsar.getManagedLedgerFactory());
    CompletableFuture<ManagedLedgerImpl> future = new CompletableFuture<>();
    future.completeExceptionally(new ManagedLedgerException("ledger opening failed"));
    ledgers.put(namespace + "/persistent/deadLockTestTopic", future);
    // create topic async and wait on the future completion
    executor.submit(() -> {
        service.getTopic(deadLockTestTopic).thenAccept(topic -> topicCreation.complete(null)).exceptionally(e -> {
            topicCreation.completeExceptionally(e.getCause());
            return null;
        });
    });
    // future-result should be completed with exception
    try {
        topicCreation.get(1, TimeUnit.SECONDS);
    } catch (TimeoutException | InterruptedException e) {
        fail("there is a dead-lock and it should have been prevented");
    } catch (ExecutionException e) {
        assertTrue(e.getCause() instanceof PersistenceException);
    } finally {
        executor.shutdownNow();
        ledgers.clear();
    }
}
Also used : SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) JsonObject(com.google.gson.JsonObject) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) Producer(org.apache.pulsar.client.api.Producer) TimeoutException(java.util.concurrent.TimeoutException) Cleanup(lombok.Cleanup) Test(org.testng.annotations.Test) ManagedLedgerFactoryImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerFactoryImpl) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) URI(java.net.URI) Mockito.doReturn(org.mockito.Mockito.doReturn) BeforeClass(org.testng.annotations.BeforeClass) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) LocalPolicies(org.apache.pulsar.common.policies.data.LocalPolicies) Assert.assertNotNull(org.testng.Assert.assertNotNull) PulsarWebResource.joinPath(org.apache.pulsar.broker.web.PulsarWebResource.joinPath) Executors(java.util.concurrent.Executors) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) CountDownLatch(java.util.concurrent.CountDownLatch) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) JsonArray(com.google.gson.JsonArray) Optional(java.util.Optional) TopicName(org.apache.pulsar.common.naming.TopicName) LOCAL_POLICIES_ROOT(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService.LOCAL_POLICIES_ROOT) Assert.assertEquals(org.testng.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Message(org.apache.pulsar.client.api.Message) Mockito.spy(org.mockito.Mockito.spy) HashSet(java.util.HashSet) AuthenticationTls(org.apache.pulsar.client.impl.auth.AuthenticationTls) Lists(com.google.common.collect.Lists) BundlesData(org.apache.pulsar.common.policies.data.BundlesData) Matchers.anyObject(org.mockito.Matchers.anyObject) PulsarClient(org.apache.pulsar.client.api.PulsarClient) NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) ExecutorService(java.util.concurrent.ExecutorService) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) AfterClass(org.testng.annotations.AfterClass) Assert.fail(org.testng.Assert.fail) IOException(java.io.IOException) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) Field(java.lang.reflect.Field) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Authentication(org.apache.pulsar.client.api.Authentication) Assert.assertTrue(org.testng.Assert.assertTrue) BrokerStats(org.apache.pulsar.client.admin.BrokerStats) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) IOException(java.io.IOException) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) ExecutionException(java.util.concurrent.ExecutionException) Field(java.lang.reflect.Field) ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ExecutorService(java.util.concurrent.ExecutorService) PersistenceException(org.apache.pulsar.broker.service.BrokerServiceException.PersistenceException) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test)

Example 54 with Producer

use of org.apache.pulsar.client.api.Producer in project incubator-pulsar by apache.

the class CompactionTest method testWholeBatchCompactedOut.

@Test
public void testWholeBatchCompactedOut() throws Exception {
    String topic = "persistent://my-property/use/my-ns/my-topic1";
    // subscribe before sending anything, so that we get all messages
    pulsarClient.newConsumer().topic(topic).subscriptionName("sub1").readCompacted(true).subscribe().close();
    try (Producer producerNormal = pulsarClient.newProducer().topic(topic).create();
        Producer producerBatch = pulsarClient.newProducer().topic(topic).maxPendingMessages(3).enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).create()) {
        producerBatch.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-message-1".getBytes()).build());
        producerBatch.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-message-2".getBytes()).build());
        producerBatch.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-message-3".getBytes()).build()).get();
        producerNormal.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-message-4".getBytes()).build()).get();
    }
    // compact the topic
    Compactor compactor = new TwoPhaseCompactor(conf, pulsarClient, bk, compactionScheduler);
    compactor.compact(topic).get();
    try (Consumer consumer = pulsarClient.newConsumer().topic(topic).subscriptionName("sub1").readCompacted(true).subscribe()) {
        Message message = consumer.receive();
        Assert.assertEquals(message.getKey(), "key1");
        Assert.assertEquals(new String(message.getData()), "my-message-4");
    }
}
Also used : Producer(org.apache.pulsar.client.api.Producer) Consumer(org.apache.pulsar.client.api.Consumer) Message(org.apache.pulsar.client.api.Message) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 55 with Producer

use of org.apache.pulsar.client.api.Producer in project incubator-pulsar by apache.

the class RawReaderTest method testBatchingRebatch.

@Test
public void testBatchingRebatch() throws Exception {
    String topic = "persistent://my-property/use/my-ns/my-raw-topic";
    try (Producer producer = pulsarClient.newProducer().topic(topic).maxPendingMessages(3).enableBatching(true).batchingMaxMessages(3).batchingMaxPublishDelay(1, TimeUnit.HOURS).create()) {
        producer.sendAsync(MessageBuilder.create().setKey("key1").setContent("my-content-1".getBytes()).build());
        producer.sendAsync(MessageBuilder.create().setKey("key2").setContent("my-content-2".getBytes()).build());
        producer.sendAsync(MessageBuilder.create().setKey("key3").setContent("my-content-3".getBytes()).build()).get();
    }
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    try {
        RawMessage m1 = reader.readNextAsync().get();
        RawMessage m2 = RawBatchConverter.rebatchMessage(m1, (key, id) -> key.equals("key2")).get();
        List<ImmutablePair<MessageId, String>> idsAndKeys = RawBatchConverter.extractIdsAndKeys(m2);
        Assert.assertEquals(idsAndKeys.size(), 1);
        Assert.assertEquals(idsAndKeys.get(0).getRight(), "key2");
        m2.close();
    } finally {
        reader.closeAsync().get();
    }
}
Also used : RawMessage(org.apache.pulsar.client.api.RawMessage) Producer(org.apache.pulsar.client.api.Producer) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) RawReader(org.apache.pulsar.client.api.RawReader) Test(org.testng.annotations.Test) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) AfterMethod(org.testng.annotations.AfterMethod) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Future(java.util.concurrent.Future) Lists(com.google.common.collect.Lists) Assert(org.testng.Assert) ByteBuf(io.netty.buffer.ByteBuf) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Map(java.util.Map) MessageMetadata(org.apache.pulsar.common.api.proto.PulsarApi.MessageMetadata) Commands(org.apache.pulsar.common.api.Commands) PropertyAdmin(org.apache.pulsar.common.policies.data.PropertyAdmin) CancellationException(java.util.concurrent.CancellationException) MessageBuilder(org.apache.pulsar.client.api.MessageBuilder) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) MessageId(org.apache.pulsar.client.api.MessageId) Producer(org.apache.pulsar.client.api.Producer) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) RawReader(org.apache.pulsar.client.api.RawReader) RawMessage(org.apache.pulsar.client.api.RawMessage) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Aggregations

Producer (org.apache.pulsar.client.api.Producer)56 Test (org.testng.annotations.Test)47 Message (org.apache.pulsar.client.api.Message)39 Consumer (org.apache.pulsar.client.api.Consumer)36 ProducerConfiguration (org.apache.pulsar.client.api.ProducerConfiguration)32 ConsumerConfiguration (org.apache.pulsar.client.api.ConsumerConfiguration)29 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)20 IOException (java.io.IOException)18 ExecutionException (java.util.concurrent.ExecutionException)17 CompletableFuture (java.util.concurrent.CompletableFuture)16 MessageId (org.apache.pulsar.client.api.MessageId)16 Map (java.util.Map)14 PulsarClient (org.apache.pulsar.client.api.PulsarClient)13 CountDownLatch (java.util.concurrent.CountDownLatch)11 List (java.util.List)10 Future (java.util.concurrent.Future)10 TimeUnit (java.util.concurrent.TimeUnit)10 Lists (com.google.common.collect.Lists)9 ExecutorService (java.util.concurrent.ExecutorService)9 ConsumerImpl (org.apache.pulsar.client.impl.ConsumerImpl)9