Search in sources :

Example 6 with Topic

use of org.apache.pulsar.broker.service.Topic in project incubator-pulsar by apache.

the class PersistentTopicsBase method internalGetSubscriptions.

protected List<String> internalGetSubscriptions(boolean authoritative) {
    if (topicName.isGlobal()) {
        validateGlobalNamespaceOwnership(namespaceName);
    }
    List<String> subscriptions = Lists.newArrayList();
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative);
    if (partitionMetadata.partitions > 0) {
        try {
            // get the subscriptions only from the 1st partition since all the other partitions will have the same
            // subscriptions
            subscriptions.addAll(pulsar().getAdminClient().persistentTopics().getSubscriptions(topicName.getPartition(0).toString()));
        } catch (Exception e) {
            throw new RestException(e);
        }
    } else {
        validateAdminOperationOnTopic(authoritative);
        Topic topic = getTopicReference(topicName);
        try {
            topic.getSubscriptions().forEach((subName, sub) -> subscriptions.add(subName));
        } catch (Exception e) {
            log.error("[{}] Failed to get list of subscriptions for {}", clientAppId(), topicName);
            throw new RestException(e);
        }
    }
    return subscriptions;
}
Also used : RestException(org.apache.pulsar.broker.web.RestException) Topic(org.apache.pulsar.broker.service.Topic) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) PartitionedTopicMetadata(org.apache.pulsar.common.partition.PartitionedTopicMetadata) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) NotFoundException(org.apache.pulsar.client.admin.PulsarAdminException.NotFoundException) PreconditionFailedException(org.apache.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) RestException(org.apache.pulsar.broker.web.RestException) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) KeeperException(org.apache.zookeeper.KeeperException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TopicBusyException(org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Example 7 with Topic

use of org.apache.pulsar.broker.service.Topic in project incubator-pulsar by apache.

the class PersistentTopicsBase method unloadTopic.

protected void unloadTopic(TopicName topicName, boolean authoritative) {
    validateSuperUserAccess();
    validateTopicOwnership(topicName, authoritative);
    try {
        Topic topic = getTopicReference(topicName);
        topic.close().get();
        log.info("[{}] Successfully unloaded topic {}", clientAppId(), topicName);
    } catch (NullPointerException e) {
        log.error("[{}] topic {} not found", clientAppId(), topicName);
        throw new RestException(Status.NOT_FOUND, "Topic does not exist");
    } catch (Exception e) {
        log.error("[{}] Failed to unload topic {}, {}", clientAppId(), topicName, e.getCause().getMessage(), e);
        throw new RestException(e.getCause());
    }
}
Also used : RestException(org.apache.pulsar.broker.web.RestException) Topic(org.apache.pulsar.broker.service.Topic) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) NotAllowedException(org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException) NotFoundException(org.apache.pulsar.client.admin.PulsarAdminException.NotFoundException) PreconditionFailedException(org.apache.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) RestException(org.apache.pulsar.broker.web.RestException) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) SubscriptionBusyException(org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) KeeperException(org.apache.zookeeper.KeeperException) PulsarAdminException(org.apache.pulsar.client.admin.PulsarAdminException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) TopicBusyException(org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Example 8 with Topic

use of org.apache.pulsar.broker.service.Topic in project incubator-pulsar by apache.

the class NonPersistentTopics method getStats.

@GET
@Path("{property}/{namespace}/{topic}/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 NonPersistentTopicStats getStats(@PathParam("property") String property, @PathParam("namespace") String namespace, @PathParam("topic") @Encoded String encodedTopic, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    validateTopicName(property, namespace, encodedTopic);
    validateAdminOperationOnTopic(topicName, authoritative);
    Topic topic = getTopicReference(topicName);
    return ((NonPersistentTopic) topic).getStats();
}
Also used : Topic(org.apache.pulsar.broker.service.Topic) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) NonPersistentTopic(org.apache.pulsar.broker.service.nonpersistent.NonPersistentTopic) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 9 with Topic

use of org.apache.pulsar.broker.service.Topic in project incubator-pulsar by apache.

the class BrokerClientIntegrationTest method testUnsupportedBatchMessageConsumer.

/**
 * It verifies that consumer which doesn't support batch-message:
 * <p>
 * 1. broker disconnects that consumer
 * <p>
 * 2. redeliver all those messages to other supported consumer under the same subscription
 *
 * @param subType
 * @throws Exception
 */
@Test(timeOut = 7000, dataProvider = "subType")
public void testUnsupportedBatchMessageConsumer(SubscriptionType subType) throws Exception {
    log.info("-- Starting {} test --", methodName);
    final int batchMessageDelayMs = 1000;
    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    final String subscriptionName = "my-subscriber-name" + subType;
    ConsumerImpl<byte[]> consumer1 = (ConsumerImpl<byte[]>) pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName).subscriptionType(subType).subscribe();
    Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create();
    Producer<byte[]> batchProducer = pulsarClient.newProducer().topic(topicName).enableBatching(true).batchingMaxPublishDelay(batchMessageDelayMs, TimeUnit.MILLISECONDS).batchingMaxMessages(20).create();
    // update consumer's version to incompatible batch-message version = Version.V3
    Topic topic = pulsar.getBrokerService().getTopic(topicName).get();
    org.apache.pulsar.broker.service.Consumer brokerConsumer = topic.getSubscriptions().get(subscriptionName).getConsumers().get(0);
    Field cnxField = org.apache.pulsar.broker.service.Consumer.class.getDeclaredField("cnx");
    cnxField.setAccessible(true);
    PulsarHandler cnx = (PulsarHandler) cnxField.get(brokerConsumer);
    Field versionField = PulsarHandler.class.getDeclaredField("remoteEndpointProtocolVersion");
    versionField.setAccessible(true);
    versionField.set(cnx, 3);
    // (1) send non-batch message: consumer should be able to consume
    for (int i = 0; i < 10; i++) {
        String message = "my-message-" + i;
        producer.send(message.getBytes());
    }
    Set<String> messageSet = Sets.newHashSet();
    Message<byte[]> msg = null;
    for (int i = 0; i < 10; i++) {
        msg = consumer1.receive(1, TimeUnit.SECONDS);
        String receivedMessage = new String(msg.getData());
        String expectedMessage = "my-message-" + i;
        testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage);
        consumer1.acknowledge(msg);
    }
    // Also set clientCnx of the consumer to null so, it avoid reconnection so, other consumer can consume for
    // verification
    consumer1.setClientCnx(null);
    // (2) send batch-message which should not be able to consume: as broker will disconnect the consumer
    for (int i = 0; i < 10; i++) {
        String message = "my-message-" + i;
        batchProducer.sendAsync(message.getBytes());
    }
    Thread.sleep(batchMessageDelayMs);
    // consumer should have not received any message as it should have been disconnected
    msg = consumer1.receive(2, TimeUnit.SECONDS);
    assertNull(msg);
    // subscrie consumer2 with supporting batch version
    Consumer<byte[]> consumer2 = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriptionName).subscribe();
    messageSet.clear();
    for (int i = 0; i < 10; i++) {
        msg = consumer2.receive(1, TimeUnit.SECONDS);
        String receivedMessage = new String(msg.getData());
        log.debug("Received message: [{}]", receivedMessage);
        String expectedMessage = "my-message-" + i;
        testMessageOrderAndDuplicates(messageSet, receivedMessage, expectedMessage);
        consumer2.acknowledge(msg);
    }
    consumer2.close();
    producer.close();
    batchProducer.close();
    log.info("-- Exiting {} test --", methodName);
}
Also used : Field(java.lang.reflect.Field) Topic(org.apache.pulsar.broker.service.Topic) PulsarHandler(org.apache.pulsar.common.api.PulsarHandler) Test(org.testng.annotations.Test)

Example 10 with Topic

use of org.apache.pulsar.broker.service.Topic in project incubator-pulsar by apache.

the class NamespaceServiceTest method testUnloadNamespaceBundleFailure.

@Test
public void testUnloadNamespaceBundleFailure() throws Exception {
    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    pulsarClient.newConsumer().topic(topicName).subscriptionName("my-subscriber-name").subscribe();
    ConcurrentOpenHashMap<String, CompletableFuture<Topic>> topics = pulsar.getBrokerService().getTopics();
    Topic spyTopic = spy(topics.get(topicName).get());
    topics.clear();
    CompletableFuture<Topic> topicFuture = CompletableFuture.completedFuture(spyTopic);
    // add mock topic
    topics.put(topicName, topicFuture);
    doAnswer(new Answer<CompletableFuture<Void>>() {

        @Override
        public CompletableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
            CompletableFuture<Void> result = new CompletableFuture<>();
            result.completeExceptionally(new RuntimeException("first time failed"));
            return result;
        }
    }).when(spyTopic).close();
    NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(TopicName.get(topicName));
    try {
        pulsar.getNamespaceService().unloadNamespaceBundle(bundle);
    } catch (Exception e) {
        // fail
        fail(e.getMessage());
    }
    try {
        pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(bundle), null, null);
        fail("it should fail as node is not present");
    } catch (org.apache.zookeeper.KeeperException.NoNodeException e) {
    // ok
    }
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) CompletableFuture(java.util.concurrent.CompletableFuture) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Topic(org.apache.pulsar.broker.service.Topic) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) Test(org.testng.annotations.Test)

Aggregations

Topic (org.apache.pulsar.broker.service.Topic)28 PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)15 KeeperException (org.apache.zookeeper.KeeperException)15 SubscriptionBusyException (org.apache.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException)13 NotAllowedException (org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException)11 TopicBusyException (org.apache.pulsar.broker.service.BrokerServiceException.TopicBusyException)11 CompletableFuture (java.util.concurrent.CompletableFuture)10 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)10 RestException (org.apache.pulsar.broker.web.RestException)10 ExecutionException (java.util.concurrent.ExecutionException)9 PulsarServerException (org.apache.pulsar.broker.PulsarServerException)9 WebApplicationException (javax.ws.rs.WebApplicationException)8 PulsarAdminException (org.apache.pulsar.client.admin.PulsarAdminException)8 IOException (java.io.IOException)6 Subscription (org.apache.pulsar.broker.service.Subscription)6 ObjectObjectHashMap (com.carrotsearch.hppc.ObjectObjectHashMap)5 MoreObjects (com.google.common.base.MoreObjects)5 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)5 Lists (com.google.common.collect.Lists)5 Maps (com.google.common.collect.Maps)5