Search in sources :

Example 11 with PersistentTopic

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

the class PersistentTopicsBase method internalExpireMessagesForAllSubscriptions.

protected void internalExpireMessagesForAllSubscriptions(int expireTimeInSeconds, boolean authoritative) {
    if (topicName.isGlobal()) {
        validateGlobalNamespaceOwnership(namespaceName);
    }
    PartitionedTopicMetadata partitionMetadata = getPartitionedTopicMetadata(topicName, authoritative);
    if (partitionMetadata.partitions > 0) {
        try {
            // expire messages for each partition topic
            for (int i = 0; i < partitionMetadata.partitions; i++) {
                pulsar().getAdminClient().persistentTopics().expireMessagesForAllSubscriptions(topicName.getPartition(i).toString(), expireTimeInSeconds);
            }
        } catch (Exception e) {
            log.error("[{}] Failed to expire messages up to {} on {} {}", clientAppId(), expireTimeInSeconds, topicName, e);
            throw new RestException(e);
        }
    } else {
        // validate ownership and redirect if current broker is not owner
        validateAdminOperationOnTopic(authoritative);
        PersistentTopic topic = (PersistentTopic) getTopicReference(topicName);
        topic.getReplicators().forEach((subName, replicator) -> {
            internalExpireMessages(subName, expireTimeInSeconds, authoritative);
        });
        topic.getSubscriptions().forEach((subName, subscriber) -> {
            internalExpireMessages(subName, expireTimeInSeconds, authoritative);
        });
    }
}
Also used : PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) RestException(org.apache.pulsar.broker.web.RestException) 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 12 with PersistentTopic

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

the class PersistentTopicTest method testConcurrentTopicAndSubscriptionDelete.

// @Test
public void testConcurrentTopicAndSubscriptionDelete() throws Exception {
    // create topic
    final PersistentTopic topic = (PersistentTopic) brokerService.getTopic(successTopicName).get();
    CommandSubscribe cmd = CommandSubscribe.newBuilder().setConsumerId(1).setTopic(successTopicName).setSubscription(successSubName).setRequestId(1).setSubType(SubType.Exclusive).build();
    Future<Consumer> f1 = topic.subscribe(serverCnx, cmd.getSubscription(), cmd.getConsumerId(), cmd.getSubType(), 0, cmd.getConsumerName(), cmd.getDurable(), null, Collections.emptyMap(), cmd.getReadCompacted(), InitialPosition.Latest);
    f1.get();
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final CountDownLatch counter = new CountDownLatch(2);
    final AtomicBoolean gotException = new AtomicBoolean(false);
    Thread deleter = new Thread() {

        @Override
        public void run() {
            try {
                barrier.await();
                // assertTrue(topic.unsubscribe(successSubName).isDone());
                Thread.sleep(5, 0);
                log.info("deleter outcome is {}", topic.delete().get());
            } catch (Exception e) {
                e.printStackTrace();
                gotException.set(true);
            } finally {
                counter.countDown();
            }
        }
    };
    Thread unsubscriber = new Thread() {

        @Override
        public void run() {
            try {
                barrier.await();
                // do subscription delete
                ConcurrentOpenHashMap<String, PersistentSubscription> subscriptions = topic.getSubscriptions();
                PersistentSubscription ps = subscriptions.get(successSubName);
                // Thread.sleep(5,0);
                log.info("unsubscriber outcome is {}", ps.doUnsubscribe(ps.getConsumers().get(0)).get());
            // assertFalse(ps.delete().isCompletedExceptionally());
            } catch (Exception e) {
                e.printStackTrace();
                gotException.set(true);
            } finally {
                counter.countDown();
            }
        }
    };
    deleter.start();
    unsubscriber.start();
    counter.await();
    assertEquals(gotException.get(), false);
}
Also used : CommandSubscribe(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) PersistentDispatcherSingleActiveConsumer(org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) Matchers.anyString(org.mockito.Matchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ExecutionException(java.util.concurrent.ExecutionException) CyclicBarrier(java.util.concurrent.CyclicBarrier)

Example 13 with PersistentTopic

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

the class PersistentTopicTest method testMaxConsumersShared.

public void testMaxConsumersShared() throws Exception {
    PersistentTopic topic = new PersistentTopic(successTopicName, ledgerMock, brokerService);
    PersistentSubscription sub = new PersistentSubscription(topic, "sub-1", cursorMock);
    PersistentSubscription sub2 = new PersistentSubscription(topic, "sub-2", cursorMock);
    // for count consumers on topic
    ConcurrentOpenHashMap<String, PersistentSubscription> subscriptions = new ConcurrentOpenHashMap<>(16, 1);
    subscriptions.put("sub-1", sub);
    subscriptions.put("sub-2", sub2);
    Field field = topic.getClass().getDeclaredField("subscriptions");
    field.setAccessible(true);
    field.set(topic, subscriptions);
    // 1. add consumer1
    Consumer consumer = new Consumer(sub, SubType.Shared, topic.getName(), 1, /* consumer id */
    0, "Cons1", /* consumer name */
    50000, serverCnx, "myrole-1", Collections.emptyMap(), false, /* read compacted */
    InitialPosition.Latest);
    sub.addConsumer(consumer);
    assertEquals(sub.getConsumers().size(), 1);
    // 2. add consumer2
    Consumer consumer2 = new Consumer(sub, SubType.Shared, topic.getName(), 2, /* consumer id */
    0, "Cons2", /* consumer name */
    50000, serverCnx, "myrole-1", Collections.emptyMap(), false, /* read compacted */
    InitialPosition.Latest);
    sub.addConsumer(consumer2);
    assertEquals(sub.getConsumers().size(), 2);
    // 3. add consumer3 but reach maxConsumersPerSubscription
    try {
        Consumer consumer3 = new Consumer(sub, SubType.Shared, topic.getName(), 3, /* consumer id */
        0, "Cons3", /* consumer name */
        50000, serverCnx, "myrole-1", Collections.emptyMap(), false, /* read compacted */
        InitialPosition.Latest);
        sub.addConsumer(consumer3);
        fail("should have failed");
    } catch (BrokerServiceException e) {
        assertTrue(e instanceof BrokerServiceException.ConsumerBusyException);
    }
    // check number of consumers on topic
    assertEquals(topic.getNumberOfConsumers(), 2);
    // 4. add consumer4 to sub2
    Consumer consumer4 = new Consumer(sub2, SubType.Shared, topic.getName(), 4, /* consumer id */
    0, "Cons4", /* consumer name */
    50000, serverCnx, "myrole-1", Collections.emptyMap(), false, /* read compacted */
    InitialPosition.Latest);
    sub2.addConsumer(consumer4);
    assertEquals(sub2.getConsumers().size(), 1);
    // check number of consumers on topic
    assertEquals(topic.getNumberOfConsumers(), 3);
    // 5. add consumer5 to sub2 but reach maxConsumersPerTopic
    try {
        Consumer consumer5 = new Consumer(sub2, SubType.Shared, topic.getName(), 5, /* consumer id */
        0, "Cons5", /* consumer name */
        50000, serverCnx, "myrole-1", Collections.emptyMap(), false, /* read compacted */
        InitialPosition.Latest);
        sub2.addConsumer(consumer5);
        fail("should have failed");
    } catch (BrokerServiceException e) {
        assertTrue(e instanceof BrokerServiceException.ConsumerBusyException);
    }
}
Also used : Field(java.lang.reflect.Field) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) PersistentDispatcherSingleActiveConsumer(org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) Matchers.anyString(org.mockito.Matchers.anyString) PersistentSubscription(org.apache.pulsar.broker.service.persistent.PersistentSubscription)

Example 14 with PersistentTopic

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

the class PersistentTopicTest method testDeleteTopicRaceConditions.

@Test
public void testDeleteTopicRaceConditions() throws Exception {
    PersistentTopic topic = (PersistentTopic) brokerService.getTopic(successTopicName).get();
    // override ledger deletion callback to slow down deletion
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            Thread.sleep(1000);
            ((DeleteLedgerCallback) invocationOnMock.getArguments()[0]).deleteLedgerComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDelete(any(DeleteLedgerCallback.class), anyObject());
    ExecutorService executor = Executors.newCachedThreadPool();
    executor.submit(() -> {
        topic.delete();
        return null;
    }).get();
    try {
        String role = "appid1";
        Thread.sleep(10);
        /* delay to ensure that the delete gets executed first */
        Producer producer = new Producer(topic, serverCnx, 1, /* producer id */
        "prod-name", role, false, null, SchemaVersion.Latest);
        topic.addProducer(producer);
        fail("Should have failed");
    } catch (BrokerServiceException e) {
        assertTrue(e instanceof BrokerServiceException.TopicFencedException);
    }
    CommandSubscribe cmd = CommandSubscribe.newBuilder().setConsumerId(1).setTopic(successTopicName).setSubscription(successSubName).setRequestId(1).setSubType(SubType.Exclusive).build();
    Future<Consumer> f = topic.subscribe(serverCnx, cmd.getSubscription(), cmd.getConsumerId(), cmd.getSubType(), 0, cmd.getConsumerName(), cmd.getDurable(), null, Collections.emptyMap(), cmd.getReadCompacted(), InitialPosition.Latest);
    try {
        f.get();
        fail("should have failed");
    } catch (ExecutionException ee) {
        assertTrue(ee.getCause() instanceof BrokerServiceException.TopicFencedException);
    // Expected
    }
}
Also used : Matchers.anyString(org.mockito.Matchers.anyString) CommandSubscribe(org.apache.pulsar.common.api.proto.PulsarApi.CommandSubscribe) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) PersistentDispatcherSingleActiveConsumer(org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) ExecutorService(java.util.concurrent.ExecutorService) Matchers.anyObject(org.mockito.Matchers.anyObject) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 15 with PersistentTopic

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

the class PersistentTopicTest method testDispatcherSingleConsumerReadFailed.

@Test
public void testDispatcherSingleConsumerReadFailed() throws Exception {
    PersistentTopic topic = spy(new PersistentTopic(successTopicName, ledgerMock, brokerService));
    ManagedCursor cursor = mock(ManagedCursor.class);
    when(cursor.getName()).thenReturn("cursor");
    PersistentDispatcherSingleActiveConsumer dispatcher = new PersistentDispatcherSingleActiveConsumer(cursor, SubType.Exclusive, 1, topic);
    Consumer consumer = mock(Consumer.class);
    dispatcher.readEntriesFailed(new ManagedLedgerException.InvalidCursorPositionException("failed"), consumer);
    verify(topic, atLeast(1)).getBrokerService();
}
Also used : ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PersistentDispatcherSingleActiveConsumer(org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) PersistentDispatcherSingleActiveConsumer(org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Test(org.testng.annotations.Test)

Aggregations

PersistentTopic (org.apache.pulsar.broker.service.persistent.PersistentTopic)126 Test (org.testng.annotations.Test)100 PersistentSubscription (org.apache.pulsar.broker.service.persistent.PersistentSubscription)34 Field (java.lang.reflect.Field)23 CompletableFuture (java.util.concurrent.CompletableFuture)22 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)22 CountDownLatch (java.util.concurrent.CountDownLatch)20 PersistentDispatcherSingleActiveConsumer (org.apache.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer)20 PulsarClientException (org.apache.pulsar.client.api.PulsarClientException)19 ManagedLedgerImpl (org.apache.bookkeeper.mledger.impl.ManagedLedgerImpl)17 ExecutionException (java.util.concurrent.ExecutionException)16 NotAllowedException (org.apache.pulsar.broker.service.BrokerServiceException.NotAllowedException)13 KeeperException (org.apache.zookeeper.KeeperException)13 IOException (java.io.IOException)12 PulsarAdminException (org.apache.pulsar.client.admin.PulsarAdminException)12 PersistentReplicator (org.apache.pulsar.broker.service.persistent.PersistentReplicator)11 TopicName (org.apache.pulsar.common.naming.TopicName)11 DispatchRate (org.apache.pulsar.common.policies.data.DispatchRate)11 ByteBuf (io.netty.buffer.ByteBuf)10 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)10