Search in sources :

Example 81 with PersistentTopic

use of com.yahoo.pulsar.broker.service.persistent.PersistentTopic in project pulsar by yahoo.

the class ResendRequestTest method testExclusiveCumulativeAckedNormalTopic.

@Test(timeOut = testTimeout)
public void testExclusiveCumulativeAckedNormalTopic() throws Exception {
    String key = "testExclusiveCumulativeAckedNormalTopic";
    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;
    // 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 = 0; i < 7; i++) {
        printIncomingMessageQueue(consumer);
        message = consumer.receive();
        log.info("Message received " + new String(message.getData()));
    }
    consumer.redeliverUnacknowledgedMessages();
    Thread.sleep(1000);
    consumer.acknowledgeCumulative(message);
    do {
        message = consumer.receive(1000, TimeUnit.MILLISECONDS);
    } while (message != null);
    log.info("Consumer Requests Messages");
    consumer.redeliverUnacknowledgedMessages();
    int numOfReceives = 0;
    message = consumer.receive();
    do {
        numOfReceives += 1;
        log.info("Message received " + new String(message.getData()));
        message = consumer.receive(1000, TimeUnit.MILLISECONDS);
    } while (message != null);
    assertEquals(numOfReceives, 2);
}
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) Test(org.testng.annotations.Test)

Example 82 with PersistentTopic

use of com.yahoo.pulsar.broker.service.persistent.PersistentTopic in project pulsar by yahoo.

the class ServerCnx method handleConsumerStats.

@Override
protected void handleConsumerStats(CommandConsumerStats commandConsumerStats) {
    if (log.isDebugEnabled()) {
        log.debug("Received CommandConsumerStats call from {}", remoteAddress);
    }
    final long requestId = commandConsumerStats.getRequestId();
    final String topicName = commandConsumerStats.getTopicName();
    final String subscriptionName = commandConsumerStats.getSubscriptionName();
    final long consumerId = commandConsumerStats.getConsumerId();
    if (log.isDebugEnabled()) {
        log.debug("CommandConsumerStats[requestId = {}, topicName = {}, subscriptionName = {}, consumerId = {}]", requestId, topicName, subscriptionName, consumerId);
    }
    ByteBuf msg = null;
    try {
        PersistentTopic topic = (PersistentTopic) getBrokerService().getTopicReference(topicName);
        if (topic != null) {
            if (topic.getSubscriptions().containsKey(subscriptionName)) {
                PersistentSubscription subscription = topic.getSubscriptions().get(subscriptionName);
                boolean consumerFound = false;
                for (Consumer consumer : subscription.getConsumers()) {
                    if (consumer.consumerId() == consumerId) {
                        consumerFound = true;
                        msg = Commands.newConsumerStatsResponse(createConsumerStatsResponse(consumer, subscription, requestId));
                        break;
                    }
                }
                if (!consumerFound) {
                    log.error("Failed to get consumer-stats response - Consumer not found for CommandConsumerStats[remoteAddress = {}, requestId = {}, topicName = {}, subscriptionName = {}, consumerId = {}]", remoteAddress, requestId, topicName, subscriptionName, consumerId);
                    msg = Commands.newConsumerStatsResponse(ServerError.ConsumerNotFound, "Consumer " + consumerId + " not found", requestId);
                }
            } else {
                log.error("Failed to get consumer-stats response - Subscription  not found for CommandConsumerStats[remoteAddress = {}, requestId = {}, topicName = {}, subscriptionName = {}, consumerId = {}]", remoteAddress, requestId, topicName, subscriptionName, consumerId);
                msg = Commands.newConsumerStatsResponse(ServerError.SubscriptionNotFound, "Subscription " + subscriptionName + " not found", requestId);
            }
        } else {
            log.error("Failed to get consumer-stats response - Topic not found for CommandConsumerStats[remoteAddress = {}, requestId = {}, topicName = {}, subscriptionName = {}, consumerId = {}]", remoteAddress, requestId, topicName, subscriptionName, consumerId);
            msg = Commands.newConsumerStatsResponse(ServerError.TopicNotFound, "Topic " + topicName + " not found", requestId);
        }
    } catch (Exception e) {
        log.error("Failed to get consumer-stats response - Exception: {} for CommandConsumerStats[remoteAddress = {}, requestId = {}, topicName = {}, subscriptionName = {}, consumerId = {}]", e, remoteAddress, requestId, topicName, subscriptionName, consumerId);
        msg = Commands.newConsumerStatsResponse(ServerError.UnknownError, "Exception: " + e, requestId);
    } finally {
        if (msg != null) {
            ctx.writeAndFlush(msg);
        }
    }
}
Also used : CommandCloseConsumer(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandCloseConsumer) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) ByteBuf(io.netty.buffer.ByteBuf) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) AuthenticationException(javax.naming.AuthenticationException) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException)

Example 83 with PersistentTopic

use of com.yahoo.pulsar.broker.service.persistent.PersistentTopic in project pulsar by yahoo.

the class PersistentTopics method getTopicReference.

/**
     * Get the Topic object reference from the Pulsar broker
     */
private PersistentTopic getTopicReference(DestinationName dn) {
    try {
        PersistentTopic topic = (PersistentTopic) pulsar().getBrokerService().getTopicReference(dn.toString());
        checkNotNull(topic);
        return topic;
    } catch (Exception e) {
        throw new RestException(Status.NOT_FOUND, "Topic not found");
    }
}
Also used : PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) RestException(com.yahoo.pulsar.broker.web.RestException) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException)

Example 84 with PersistentTopic

use of com.yahoo.pulsar.broker.service.persistent.PersistentTopic in project pulsar by yahoo.

the class PersistentTopics method getStats.

@GET
@Path("{property}/{cluster}/{namespace}/{destination}/stats")
@ApiOperation(value = "Get the stats for the topic.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Topic does not exist") })
public PersistentTopicStats getStats(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    validateAdminOperationOnDestination(dn, authoritative);
    PersistentTopic topic = getTopicReference(dn);
    return topic.getStats();
}
Also used : PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 85 with PersistentTopic

use of com.yahoo.pulsar.broker.service.persistent.PersistentTopic in project pulsar by yahoo.

the class PersistentTopics method deleteSubscription.

@DELETE
@Path("/{property}/{cluster}/{namespace}/{destination}/subscription/{subName}")
@ApiOperation(value = "Delete a subscription.", notes = "There should not be any active consumers on the subscription.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Topic does not exist"), @ApiResponse(code = 412, message = "Subscription has active consumers") })
public void deleteSubscription(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, @PathParam("subName") String subName, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(property, cluster, namespace, destination, authoritative);
    if (partitionMetadata.partitions > 0) {
        try {
            for (int i = 0; i < partitionMetadata.partitions; i++) {
                pulsar().getAdminClient().persistentTopics().deleteSubscription(dn.getPartition(i).toString(), subName);
            }
        } catch (Exception e) {
            throw new RestException(e);
        }
    } else {
        validateAdminOperationOnDestination(dn, authoritative);
        PersistentTopic topic = getTopicReference(dn);
        try {
            PersistentSubscription sub = topic.getPersistentSubscription(subName);
            checkNotNull(sub);
            sub.delete().get();
            log.info("[{}][{}] Deleted subscription {}", clientAppId(), dn, subName);
        } catch (Exception e) {
            Throwable t = e.getCause();
            log.error("[{}] Failed to delete subscription {} {}", clientAppId(), dn, subName, e);
            if (e instanceof NullPointerException) {
                throw new RestException(Status.NOT_FOUND, "Subscription not found");
            } else if (t instanceof SubscriptionBusyException) {
                throw new RestException(Status.PRECONDITION_FAILED, "Subscription has active connected consumers");
            } else {
                throw new RestException(t);
            }
        }
    }
}
Also used : PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) RestException(com.yahoo.pulsar.broker.web.RestException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) PartitionedTopicMetadata(com.yahoo.pulsar.common.partition.PartitionedTopicMetadata) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)92 Test (org.testng.annotations.Test)67 Producer (com.yahoo.pulsar.client.api.Producer)35 Consumer (com.yahoo.pulsar.client.api.Consumer)33 Message (com.yahoo.pulsar.client.api.Message)31 PersistentSubscription (com.yahoo.pulsar.broker.service.persistent.PersistentSubscription)29 DestinationName (com.yahoo.pulsar.common.naming.DestinationName)24 ConsumerConfiguration (com.yahoo.pulsar.client.api.ConsumerConfiguration)23 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)21 CompletableFuture (java.util.concurrent.CompletableFuture)17 KeeperException (org.apache.zookeeper.KeeperException)15 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)14 PersistentReplicator (com.yahoo.pulsar.broker.service.persistent.PersistentReplicator)13 IOException (java.io.IOException)13 SubscriptionBusyException (com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException)12 PersistentDispatcherSingleActiveConsumer (com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer)12 RestException (com.yahoo.pulsar.broker.web.RestException)12 PreconditionFailedException (com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException)12 ProducerConfiguration (com.yahoo.pulsar.client.api.ProducerConfiguration)12 CountDownLatch (java.util.concurrent.CountDownLatch)12