Search in sources :

Example 6 with Producer

use of com.yahoo.pulsar.client.api.Producer in project pulsar by yahoo.

the class ResendRequestTest method testExclusiveSingleAckedNormalTopic.

@Test(timeOut = testTimeout)
public void testExclusiveSingleAckedNormalTopic() throws Exception {
    String key = "testExclusiveSingleAckedNormalTopic";
    final String topicName = "persistent://prop/use/ns-abc/topic-" + key;
    final String subscriptionName = "my-ex-subscription-" + key;
    final String messagePredicate = "my-message-" + key + "-";
    final int totalMessages = 10;
    HashSet<MessageId> messageIdHashSet = new HashSet<MessageId>();
    HashSet<String> messageDataHashSet = new HashSet<String>();
    // 1. producer connect
    Producer producer = pulsarClient.createProducer(topicName);
    PersistentTopic topicRef = (PersistentTopic) pulsar.getBrokerService().getTopicReference(topicName);
    assertNotNull(topicRef);
    assertEquals(topicRef.getProducers().size(), 1);
    // 2. Create consumer
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setReceiverQueueSize(7);
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName, conf);
    // 3. producer publish messages
    for (int i = 0; i < totalMessages; i++) {
        String message = messagePredicate + i;
        producer.send(message.getBytes());
    }
    // 4. Receive messages
    Message message = consumer.receive();
    log.info("Message received " + new String(message.getData()));
    for (int i = 1; i < totalMessages; i++) {
        Message msg = consumer.receive();
        log.info("Message received " + new String(msg.getData()));
        messageDataHashSet.add(new String(msg.getData()));
    }
    printIncomingMessageQueue(consumer);
    // 5. Ack 1st message and ask for resend
    consumer.acknowledge(message);
    log.info("Message acked " + new String(message.getData()));
    messageIdHashSet.add(message.getMessageId());
    messageDataHashSet.add(new String(message.getData()));
    consumer.redeliverUnacknowledgedMessages();
    log.info("Resend Messages Request sent");
    // 6. Check if messages resent in correct order
    for (int i = 0; i < totalMessages - 1; i++) {
        message = consumer.receive();
        log.info("Message received " + new String(message.getData()));
        if (i < 2) {
            messageIdHashSet.add(message.getMessageId());
            consumer.acknowledge(message);
        }
        log.info("Message acked " + new String(message.getData()));
        assertTrue(messageDataHashSet.contains(new String(message.getData())));
    }
    assertEquals(messageIdHashSet.size(), 3);
    assertEquals(messageDataHashSet.size(), totalMessages);
    printIncomingMessageQueue(consumer);
    // 7. Request resend 2nd time - you should receive 4 messages
    consumer.redeliverUnacknowledgedMessages();
    log.info("Resend Messages Request sent");
    message = consumer.receive(2000, TimeUnit.MILLISECONDS);
    while (message != null) {
        log.info("Message received " + new String(message.getData()));
        consumer.acknowledge(message);
        log.info("Message acked " + new String(message.getData()));
        messageIdHashSet.add(message.getMessageId());
        messageDataHashSet.add(new String(message.getData()));
        message = consumer.receive(5000, TimeUnit.MILLISECONDS);
    }
    assertEquals(messageIdHashSet.size(), totalMessages);
    assertEquals(messageDataHashSet.size(), totalMessages);
    printIncomingMessageQueue(consumer);
    // 9. Calling resend after acking all messages - expectin 0 messages
    consumer.redeliverUnacknowledgedMessages();
    assertEquals(consumer.receive(2000, TimeUnit.MILLISECONDS), null);
    // 10. Checking message contents
    for (int i = 0; i < totalMessages; i++) {
        assertTrue(messageDataHashSet.contains(messagePredicate + i));
    }
}
Also used : Producer(com.yahoo.pulsar.client.api.Producer) Consumer(com.yahoo.pulsar.client.api.Consumer) Message(com.yahoo.pulsar.client.api.Message) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) HashSet(java.util.HashSet) MessageId(com.yahoo.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Example 7 with Producer

use of com.yahoo.pulsar.client.api.Producer in project pulsar by yahoo.

the class ReplicatorTest method testConcurrentReplicator.

@Test
public void testConcurrentReplicator() throws Exception {
    log.info("--- Starting ReplicatorTest::testConcurrentReplicator ---");
    final DestinationName dest = DestinationName.get(String.format("persistent://pulsar/global/ns1/topic-%d", 0));
    ClientConfiguration conf = new ClientConfiguration();
    conf.setStatsInterval(0, TimeUnit.SECONDS);
    Producer producer = PulsarClient.create(url1.toString(), conf).createProducer(dest.toString());
    producer.close();
    PersistentTopic topic = (PersistentTopic) pulsar1.getBrokerService().getTopic(dest.toString()).get();
    PulsarClientImpl pulsarClient = spy((PulsarClientImpl) pulsar1.getBrokerService().getReplicationClient("r3"));
    final Method startRepl = PersistentTopic.class.getDeclaredMethod("startReplicator", String.class);
    startRepl.setAccessible(true);
    Field replClientField = BrokerService.class.getDeclaredField("replicationClients");
    replClientField.setAccessible(true);
    ConcurrentOpenHashMap<String, PulsarClient> replicationClients = (ConcurrentOpenHashMap<String, PulsarClient>) replClientField.get(pulsar1.getBrokerService());
    replicationClients.put("r3", pulsarClient);
    ExecutorService executor = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executor.submit(() -> {
            try {
                startRepl.invoke(topic, "r3");
            } catch (Exception e) {
                fail("setting replicator failed", e);
            }
        });
    }
    Thread.sleep(3000);
    Mockito.verify(pulsarClient, Mockito.times(1)).createProducerAsync(Mockito.anyString(), Mockito.anyObject(), Mockito.anyString());
}
Also used : ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) Method(java.lang.reflect.Method) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) CursorAlreadyClosedException(org.apache.bookkeeper.mledger.ManagedLedgerException.CursorAlreadyClosedException) Field(java.lang.reflect.Field) Producer(com.yahoo.pulsar.client.api.Producer) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ExecutorService(java.util.concurrent.ExecutorService) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) Test(org.testng.annotations.Test)

Example 8 with Producer

use of com.yahoo.pulsar.client.api.Producer in project pulsar by yahoo.

the class BrokerClientIntegrationTest method testResetCursor.

@Test(timeOut = 10000, dataProvider = "subType")
public void testResetCursor(SubscriptionType subType) throws Exception {
    final RetentionPolicies policy = new RetentionPolicies(60, 52 * 1024);
    final DestinationName destName = DestinationName.get("persistent://my-property/use/my-ns/unacked-topic");
    final int warmup = 20;
    final int testSize = 150;
    final List<Message> received = new ArrayList<Message>();
    final ConsumerConfiguration consConfig = new ConsumerConfiguration();
    final String subsId = "sub";
    final NavigableMap<Long, TimestampEntryCount> publishTimeIdMap = new ConcurrentSkipListMap<>();
    consConfig.setSubscriptionType(subType);
    consConfig.setMessageListener((MessageListener) (Consumer consumer, Message msg) -> {
        try {
            synchronized (received) {
                received.add(msg);
            }
            consumer.acknowledge(msg);
            long publishTime = ((MessageImpl) msg).getPublishTime();
            log.info(" publish time is " + publishTime + "," + msg.getMessageId());
            TimestampEntryCount timestampEntryCount = publishTimeIdMap.computeIfAbsent(publishTime, (k) -> new TimestampEntryCount(publishTime));
            timestampEntryCount.incrementAndGet();
        } catch (final PulsarClientException e) {
            log.warn("Failed to ack!");
        }
    });
    admin.namespaces().setRetention(destName.getNamespace(), policy);
    Consumer consumer = pulsarClient.subscribe(destName.toString(), subsId, consConfig);
    final Producer producer = pulsarClient.createProducer(destName.toString());
    log.info("warm up started for " + destName.toString());
    // send warmup msgs
    byte[] msgBytes = new byte[1000];
    for (Integer i = 0; i < warmup; i++) {
        producer.send(msgBytes);
    }
    log.info("warm up finished.");
    // sleep to ensure receiving of msgs
    for (int n = 0; n < 10 && received.size() < warmup; n++) {
        Thread.sleep(100);
    }
    // validate received msgs
    Assert.assertEquals(received.size(), warmup);
    received.clear();
    // publish testSize num of msgs
    log.info("Sending more messages.");
    for (Integer n = 0; n < testSize; n++) {
        producer.send(msgBytes);
        Thread.sleep(1);
    }
    log.info("Sending more messages done.");
    Thread.sleep(3000);
    long begints = publishTimeIdMap.firstEntry().getKey();
    long endts = publishTimeIdMap.lastEntry().getKey();
    // find reset timestamp
    long timestamp = (endts - begints) / 2 + begints;
    timestamp = publishTimeIdMap.floorKey(timestamp);
    NavigableMap<Long, TimestampEntryCount> expectedMessages = new ConcurrentSkipListMap<>();
    expectedMessages.putAll(publishTimeIdMap.tailMap(timestamp, true));
    received.clear();
    log.info("reset cursor to " + timestamp + " for topic " + destName.toString() + " for subs " + subsId);
    log.info("issuing admin operation on " + admin.getServiceUrl().toString());
    List<String> subList = admin.persistentTopics().getSubscriptions(destName.toString());
    for (String subs : subList) {
        log.info("got sub " + subs);
    }
    publishTimeIdMap.clear();
    // reset the cursor to this timestamp
    Assert.assertTrue(subList.contains(subsId));
    admin.persistentTopics().resetCursor(destName.toString(), subsId, timestamp);
    consumer = pulsarClient.subscribe(destName.toString(), subsId, consConfig);
    Thread.sleep(3000);
    int totalExpected = 0;
    for (TimestampEntryCount tec : expectedMessages.values()) {
        totalExpected += tec.numMessages;
    }
    // validate that replay happens after the timestamp
    Assert.assertTrue(publishTimeIdMap.firstEntry().getKey() >= timestamp);
    consumer.close();
    producer.close();
    // validate that expected and received counts match
    int totalReceived = 0;
    for (TimestampEntryCount tec : publishTimeIdMap.values()) {
        totalReceived += tec.numMessages;
    }
    Assert.assertEquals(totalReceived, totalExpected, "did not receive all messages on replay after reset");
}
Also used : RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) Assert.assertNull(org.testng.Assert.assertNull) DataProvider(org.testng.annotations.DataProvider) Consumer(com.yahoo.pulsar.client.api.Consumer) LoggerFactory(org.slf4j.LoggerFactory) Test(org.testng.annotations.Test) Mockito.spy(org.mockito.Mockito.spy) AfterMethod(org.testng.annotations.AfterMethod) OwnershipCache(com.yahoo.pulsar.broker.namespace.OwnershipCache) SubscriptionType(com.yahoo.pulsar.client.api.SubscriptionType) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) ArrayList(java.util.ArrayList) State(com.yahoo.pulsar.client.impl.HandlerBase.State) Assert(org.testng.Assert) ProducerConsumerBase(com.yahoo.pulsar.client.api.ProducerConsumerBase) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) Matchers.anyObject(org.mockito.Matchers.anyObject) Mockito.doAnswer(org.mockito.Mockito.doAnswer) MessageListener(com.yahoo.pulsar.client.api.MessageListener) URI(java.net.URI) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) Assert.assertFalse(org.testng.Assert.assertFalse) ExecutorService(java.util.concurrent.ExecutorService) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Logger(org.slf4j.Logger) Producer(com.yahoo.pulsar.client.api.Producer) Assert.fail(org.testng.Assert.fail) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) BeforeMethod(org.testng.annotations.BeforeMethod) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) Set(java.util.Set) PulsarHandler(com.yahoo.pulsar.common.api.PulsarHandler) Field(java.lang.reflect.Field) NavigableMap(java.util.NavigableMap) Executors(java.util.concurrent.Executors) Sets(com.google.common.collect.Sets) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) Topic(com.yahoo.pulsar.broker.service.Topic) Mockito.never(org.mockito.Mockito.never) List(java.util.List) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) ConcurrentLongHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentLongHashMap) Assert.assertTrue(org.testng.Assert.assertTrue) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Message(com.yahoo.pulsar.client.api.Message) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) Message(com.yahoo.pulsar.client.api.Message) ArrayList(java.util.ArrayList) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Test(org.testng.annotations.Test)

Example 9 with Producer

use of com.yahoo.pulsar.client.api.Producer in project pulsar by yahoo.

the class ManagedLedgerMetricsTest method testManagedLedgerMetrics.

@Test
public void testManagedLedgerMetrics() throws Exception {
    ManagedLedgerMetrics metrics = new ManagedLedgerMetrics(pulsar);
    final String addEntryRateKey = "brk_ml_AddEntryMessagesRate";
    List<Metrics> list1 = metrics.generate();
    Assert.assertTrue(list1.isEmpty());
    Producer producer = pulsarClient.createProducer("persistent://my-property/use/my-ns/my-topic1");
    for (int i = 0; i < 10; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    for (Entry<String, ManagedLedgerImpl> ledger : ((ManagedLedgerFactoryImpl) pulsar.getManagedLedgerFactory()).getManagedLedgers().entrySet()) {
        ManagedLedgerMBeanImpl stats = (ManagedLedgerMBeanImpl) ledger.getValue().getStats();
        stats.refreshStats(1, TimeUnit.SECONDS);
    }
    List<Metrics> list2 = metrics.generate();
    Assert.assertEquals(list2.get(0).getMetrics().get(addEntryRateKey), 10.0D);
    for (int i = 0; i < 5; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    for (Entry<String, ManagedLedgerImpl> ledger : ((ManagedLedgerFactoryImpl) pulsar.getManagedLedgerFactory()).getManagedLedgers().entrySet()) {
        ManagedLedgerMBeanImpl stats = (ManagedLedgerMBeanImpl) ledger.getValue().getStats();
        stats.refreshStats(1, TimeUnit.SECONDS);
    }
    List<Metrics> list3 = metrics.generate();
    Assert.assertEquals(list3.get(0).getMetrics().get(addEntryRateKey), 5.0D);
}
Also used : ManagedLedgerImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl) ManagedLedgerMetrics(com.yahoo.pulsar.broker.stats.metrics.ManagedLedgerMetrics) Producer(com.yahoo.pulsar.client.api.Producer) ManagedLedgerMBeanImpl(org.apache.bookkeeper.mledger.impl.ManagedLedgerMBeanImpl) ManagedLedgerMetrics(com.yahoo.pulsar.broker.stats.metrics.ManagedLedgerMetrics) Test(org.testng.annotations.Test)

Example 10 with Producer

use of com.yahoo.pulsar.client.api.Producer in project pulsar by yahoo.

the class ClientErrorsTest method producerCreateFailAfterRetryTimeout.

private void producerCreateFailAfterRetryTimeout(String topic) throws Exception {
    ClientConfiguration conf = new ClientConfiguration();
    conf.setOperationTimeout(1, TimeUnit.SECONDS);
    PulsarClient client = PulsarClient.create("http://127.0.0.1:" + WEB_SERVICE_PORT, conf);
    final AtomicInteger counter = new AtomicInteger(0);
    mockBrokerService.setHandleProducer((ctx, producer) -> {
        if (counter.incrementAndGet() == 2) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            // do nothing
            }
        }
        ctx.writeAndFlush(Commands.newError(producer.getRequestId(), ServerError.ServiceNotReady, "msg"));
    });
    try {
        Producer producer = client.createProducer(topic);
        fail("Should have failed");
    } catch (Exception e) {
        // we fail even on the retriable error
        assertTrue(e instanceof PulsarClientException.LookupException);
    }
    mockBrokerService.resetHandleProducer();
    client.close();
}
Also used : LookupException(com.yahoo.pulsar.client.api.PulsarClientException.LookupException) Producer(com.yahoo.pulsar.client.api.Producer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) LookupException(com.yahoo.pulsar.client.api.PulsarClientException.LookupException) ExecutionException(java.util.concurrent.ExecutionException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException)

Aggregations

Producer (com.yahoo.pulsar.client.api.Producer)105 Test (org.testng.annotations.Test)90 Consumer (com.yahoo.pulsar.client.api.Consumer)71 Message (com.yahoo.pulsar.client.api.Message)57 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)51 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)35 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)32 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)30 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)27 CompletableFuture (java.util.concurrent.CompletableFuture)20 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)15 MessageId (com.yahoo.pulsar.client.api.MessageId)12 PulsarAdminException (com.yahoo.pulsar.client.admin.PulsarAdminException)11 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)10 PersistentTopicStats (com.yahoo.pulsar.common.policies.data.PersistentTopicStats)10 BacklogQuota (com.yahoo.pulsar.common.policies.data.BacklogQuota)9 HashSet (java.util.HashSet)9 MockedPulsarServiceBaseTest (com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)8 Field (java.lang.reflect.Field)7