Search in sources :

Example 11 with PulsarClientException

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

the class BacklogQuotaManagerTest method testProducerExceptionAndThenUnblock.

@Test
public void testProducerExceptionAndThenUnblock() throws Exception {
    assertEquals(admin.namespaces().getBacklogQuotaMap("prop/usc/quotahold"), Maps.newTreeMap());
    admin.namespaces().setBacklogQuota("prop/usc/quotahold", new BacklogQuota(10 * 1024, BacklogQuota.RetentionPolicy.producer_exception));
    final ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setStatsInterval(0, TimeUnit.SECONDS);
    final PulsarClient client = PulsarClient.create(adminUrl.toString(), clientConf);
    final String topic1 = "persistent://prop/usc/quotahold/exceptandunblock";
    final String subName1 = "c1except";
    boolean gotException = false;
    Consumer consumer = client.subscribe(topic1, subName1);
    ProducerConfiguration producerConfiguration = new ProducerConfiguration();
    producerConfiguration.setSendTimeout(2, TimeUnit.SECONDS);
    byte[] content = new byte[1024];
    Producer producer = client.createProducer(topic1, producerConfiguration);
    for (int i = 0; i < 10; i++) {
        producer.send(content);
    }
    Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000);
    try {
        // try to send over backlog quota and make sure it fails
        producer.send(content);
        producer.send(content);
        Assert.fail("backlog quota did not exceed");
    } catch (PulsarClientException ce) {
        Assert.assertTrue(ce instanceof PulsarClientException.ProducerBlockedQuotaExceededException || ce instanceof PulsarClientException.TimeoutException, ce.getMessage());
        gotException = true;
    }
    Assert.assertTrue(gotException, "backlog exceeded exception did not occur");
    // now remove backlog and ensure that producer is unblockedrolloverStats();
    PersistentTopicStats stats = admin.persistentTopics().getStats(topic1);
    int backlog = (int) stats.subscriptions.get(subName1).msgBacklog;
    for (int i = 0; i < backlog; i++) {
        Message msg = consumer.receive();
        consumer.acknowledge(msg);
    }
    Thread.sleep((TIME_TO_CHECK_BACKLOG_QUOTA + 1) * 1000);
    // publish should work now
    Exception sendException = null;
    gotException = false;
    try {
        for (int i = 0; i < 5; i++) {
            producer.send(content);
        }
    } catch (Exception e) {
        gotException = true;
        sendException = e;
    }
    Assert.assertFalse(gotException, "unable to publish due to " + sendException);
    client.close();
}
Also used : Message(com.yahoo.pulsar.client.api.Message) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) BacklogQuota(com.yahoo.pulsar.common.policies.data.BacklogQuota) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Consumer(com.yahoo.pulsar.client.api.Consumer) Producer(com.yahoo.pulsar.client.api.Producer) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) Test(org.testng.annotations.Test)

Example 12 with PulsarClientException

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

the class PersistentTopicE2ETest method testMultipleClientsMultipleSubscriptions.

@Test
public void testMultipleClientsMultipleSubscriptions() throws Exception {
    final String topicName = "persistent://prop/use/ns-abc/topic7";
    final String subName = "sub7";
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setSubscriptionType(SubscriptionType.Exclusive);
    PulsarClient client1 = PulsarClient.create(brokerUrl.toString());
    PulsarClient client2 = PulsarClient.create(brokerUrl.toString());
    try {
        client1.subscribe(topicName, subName, conf);
        client1.createProducer(topicName);
        client2.createProducer(topicName);
        client2.subscribe(topicName, subName, conf);
        fail("Should have thrown an exception since one consumer is already connected");
    } catch (PulsarClientException cce) {
        Assert.assertTrue(cce.getMessage().contains("Exclusive consumer is already connected"));
    } finally {
        client2.shutdown();
        client1.shutdown();
    }
}
Also used : ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) Test(org.testng.annotations.Test)

Example 13 with PulsarClientException

use of com.yahoo.pulsar.client.api.PulsarClientException 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 14 with PulsarClientException

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

the class ConsumeBaseExceptionTest method testListener.

@Test
public void testListener() throws PulsarClientException {
    Consumer consumer = null;
    ConsumerConfiguration conf = new ConsumerConfiguration();
    conf.setMessageListener((Consumer c, Message msg) -> {
    });
    consumer = pulsarClient.subscribe("persistent://prop/cluster/ns/topicName", "my-subscription", conf);
    Assert.assertTrue(consumer.receiveAsync().isCompletedExceptionally());
    try {
        consumer.receiveAsync().exceptionally(e -> {
            Assert.assertTrue(e instanceof PulsarClientException.InvalidConfigurationException);
            return null;
        }).get();
    } catch (Exception e) {
        Assert.fail();
    }
}
Also used : Assert(org.testng.Assert) ProducerConsumerBase(com.yahoo.pulsar.client.api.ProducerConsumerBase) Consumer(com.yahoo.pulsar.client.api.Consumer) BeforeMethod(org.testng.annotations.BeforeMethod) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Test(org.testng.annotations.Test) Message(com.yahoo.pulsar.client.api.Message) AfterMethod(org.testng.annotations.AfterMethod) Consumer(com.yahoo.pulsar.client.api.Consumer) Message(com.yahoo.pulsar.client.api.Message) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Test(org.testng.annotations.Test)

Example 15 with PulsarClientException

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

the class MessageIdTest method producerSendAsync.

@Test(timeOut = 10000)
public void producerSendAsync() throws PulsarClientException {
    // 1. Basic Config
    String key = "producerSendAsync";
    final String topicName = "persistent://prop/cluster/namespace/topic-" + key;
    final String subscriptionName = "my-subscription-" + key;
    final String messagePredicate = "my-message-" + key + "-";
    final int numberOfMessages = 30;
    // 2. Create Producer
    Producer producer = pulsarClient.createProducer(topicName);
    // 3. Create Consumer
    Consumer consumer = pulsarClient.subscribe(topicName, subscriptionName);
    // 4. Publish message and get message id
    Set<MessageId> messageIds = new HashSet();
    List<Future<MessageId>> futures = new ArrayList();
    for (int i = 0; i < numberOfMessages; i++) {
        String message = messagePredicate + i;
        futures.add(producer.sendAsync(message.getBytes()));
    }
    MessageIdImpl previousMessageId = null;
    for (Future<MessageId> f : futures) {
        try {
            MessageIdImpl currentMessageId = (MessageIdImpl) f.get();
            if (previousMessageId != null) {
                Assert.assertTrue(currentMessageId.compareTo(previousMessageId) > 0, "Message Ids should be in ascending order");
            }
            messageIds.add(currentMessageId);
            previousMessageId = currentMessageId;
        } catch (Exception e) {
            Assert.fail("Failed to publish message, Exception: " + e.getMessage());
        }
    }
    // 4. Check if message Ids are correct
    log.info("Message IDs = " + messageIds);
    Assert.assertEquals(messageIds.size(), numberOfMessages, "Not all messages published successfully");
    for (int i = 0; i < numberOfMessages; i++) {
        Message message = consumer.receive();
        Assert.assertEquals(new String(message.getData()), messagePredicate + i);
        MessageId messageId = message.getMessageId();
        Assert.assertTrue(messageIds.remove(messageId), "Failed to receive message");
    }
    log.info("Message IDs = " + messageIds);
    Assert.assertEquals(messageIds.size(), 0, "Not all messages received successfully");
    consumer.unsubscribe();
}
Also used : Message(com.yahoo.pulsar.client.api.Message) ArrayList(java.util.ArrayList) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) Producer(com.yahoo.pulsar.client.api.Producer) Consumer(com.yahoo.pulsar.client.api.Consumer) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HashSet(java.util.HashSet) MessageId(com.yahoo.pulsar.client.api.MessageId) Test(org.testng.annotations.Test)

Aggregations

PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)37 Message (com.yahoo.pulsar.client.api.Message)18 Test (org.testng.annotations.Test)14 Consumer (com.yahoo.pulsar.client.api.Consumer)12 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)12 Producer (com.yahoo.pulsar.client.api.Producer)11 CompletableFuture (java.util.concurrent.CompletableFuture)11 PulsarClient (com.yahoo.pulsar.client.api.PulsarClient)7 ByteBuf (io.netty.buffer.ByteBuf)6 IOException (java.io.IOException)5 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)4 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)3 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)3 ClientConfiguration (com.yahoo.pulsar.client.api.ClientConfiguration)3 MessageId (com.yahoo.pulsar.client.api.MessageId)3 ProducerConsumerBase (com.yahoo.pulsar.client.api.ProducerConsumerBase)3 DoubleByteBuf (com.yahoo.pulsar.common.api.DoubleByteBuf)3 MessageMetadata (com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 ParameterException (com.beust.jcommander.ParameterException)2