Search in sources :

Example 1 with NamespaceService

use of org.apache.pulsar.broker.namespace.NamespaceService in project incubator-pulsar by apache.

the class PersistentDispatcherFailoverConsumerTest method setup.

@BeforeMethod
public void setup() throws Exception {
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    PulsarService pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();
    mlFactoryMock = mock(ManagedLedgerFactory.class);
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();
    ZooKeeper mockZk = createMockZooKeeper();
    doReturn(mockZk).when(pulsar).getZkClient();
    doReturn(createMockBookKeeper(mockZk)).when(pulsar).getBookKeeperClient();
    configCacheService = mock(ConfigurationCacheService.class);
    @SuppressWarnings("unchecked") ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    LocalZooKeeperCacheService zkCache = mock(LocalZooKeeperCacheService.class);
    doReturn(CompletableFuture.completedFuture(Optional.empty())).when(zkDataCache).getAsync(any());
    doReturn(zkDataCache).when(zkCache).policiesCache();
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    doReturn(zkCache).when(pulsar).getLocalZkCacheService();
    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();
    consumerChanges = new LinkedBlockingQueue<>();
    this.channelCtx = mock(ChannelHandlerContext.class);
    doAnswer(invocationOnMock -> {
        ByteBuf buf = invocationOnMock.getArgumentAt(0, ByteBuf.class);
        ByteBuf cmdBuf = buf.retainedSlice(4, buf.writerIndex() - 4);
        try {
            int cmdSize = (int) cmdBuf.readUnsignedInt();
            int writerIndex = cmdBuf.writerIndex();
            cmdBuf.writerIndex(cmdBuf.readerIndex() + cmdSize);
            ByteBufCodedInputStream cmdInputStream = ByteBufCodedInputStream.get(cmdBuf);
            BaseCommand.Builder cmdBuilder = BaseCommand.newBuilder();
            BaseCommand cmd = cmdBuilder.mergeFrom(cmdInputStream, null).build();
            cmdBuilder.recycle();
            cmdBuf.writerIndex(writerIndex);
            cmdInputStream.recycle();
            if (cmd.hasActiveConsumerChange()) {
                consumerChanges.put(cmd.getActiveConsumerChange());
            }
            cmd.recycle();
        } finally {
            cmdBuf.release();
        }
        return null;
    }).when(channelCtx).writeAndFlush(any(), any());
    serverCnx = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnx).isActive();
    doReturn(true).when(serverCnx).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress();
    when(serverCnx.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v12.getNumber());
    when(serverCnx.ctx()).thenReturn(channelCtx);
    serverCnxWithOldVersion = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnxWithOldVersion).isActive();
    doReturn(true).when(serverCnxWithOldVersion).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnxWithOldVersion).clientAddress();
    when(serverCnxWithOldVersion.getRemoteEndpointProtocolVersion()).thenReturn(ProtocolVersion.v11.getNumber());
    when(serverCnxWithOldVersion.ctx()).thenReturn(channelCtx);
    NamespaceService nsSvc = mock(NamespaceService.class);
    doReturn(nsSvc).when(pulsar).getNamespaceService();
    doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class));
    doReturn(true).when(nsSvc).isServiceUnitActive(any(TopicName.class));
    setupMLAsyncCallbackMocks();
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) Policies(org.apache.pulsar.common.policies.data.Policies) BaseCommand(org.apache.pulsar.common.api.proto.PulsarApi.BaseCommand) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) TopicName(org.apache.pulsar.common.naming.TopicName) ZooKeeper(org.apache.zookeeper.ZooKeeper) MockedPulsarServiceBaseTest.createMockZooKeeper(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.createMockZooKeeper) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) PulsarService(org.apache.pulsar.broker.PulsarService) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ConfigurationCacheService(org.apache.pulsar.broker.cache.ConfigurationCacheService) ByteBufCodedInputStream(org.apache.pulsar.common.util.protobuf.ByteBufCodedInputStream) LocalZooKeeperCacheService(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 2 with NamespaceService

use of org.apache.pulsar.broker.namespace.NamespaceService in project incubator-pulsar by apache.

the class PersistentTopicTest method setup.

@BeforeMethod
public void setup() throws Exception {
    ServiceConfiguration svcConfig = spy(new ServiceConfiguration());
    pulsar = spy(new PulsarService(svcConfig));
    doReturn(svcConfig).when(pulsar).getConfiguration();
    mlFactoryMock = mock(ManagedLedgerFactory.class);
    doReturn(mlFactoryMock).when(pulsar).getManagedLedgerFactory();
    ZooKeeper mockZk = createMockZooKeeper();
    doReturn(mockZk).when(pulsar).getZkClient();
    doReturn(createMockBookKeeper(mockZk)).when(pulsar).getBookKeeperClient();
    configCacheService = mock(ConfigurationCacheService.class);
    @SuppressWarnings("unchecked") ZooKeeperDataCache<Policies> zkDataCache = mock(ZooKeeperDataCache.class);
    doReturn(zkDataCache).when(configCacheService).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    doReturn(Optional.empty()).when(zkDataCache).get(anyString());
    LocalZooKeeperCacheService zkCache = mock(LocalZooKeeperCacheService.class);
    doReturn(CompletableFuture.completedFuture(Optional.empty())).when(zkDataCache).getAsync(any());
    doReturn(zkDataCache).when(zkCache).policiesCache();
    doReturn(configCacheService).when(pulsar).getConfigurationCache();
    doReturn(zkCache).when(pulsar).getLocalZkCacheService();
    brokerService = spy(new BrokerService(pulsar));
    doReturn(brokerService).when(pulsar).getBrokerService();
    serverCnx = spy(new ServerCnx(brokerService));
    doReturn(true).when(serverCnx).isActive();
    doReturn(true).when(serverCnx).isWritable();
    doReturn(new InetSocketAddress("localhost", 1234)).when(serverCnx).clientAddress();
    NamespaceService nsSvc = mock(NamespaceService.class);
    doReturn(nsSvc).when(pulsar).getNamespaceService();
    doReturn(true).when(nsSvc).isServiceUnitOwned(any(NamespaceBundle.class));
    doReturn(true).when(nsSvc).isServiceUnitActive(any(TopicName.class));
    setupMLAsyncCallbackMocks();
}
Also used : NamespaceBundle(org.apache.pulsar.common.naming.NamespaceBundle) Policies(org.apache.pulsar.common.policies.data.Policies) InetSocketAddress(java.net.InetSocketAddress) TopicName(org.apache.pulsar.common.naming.TopicName) ZooKeeper(org.apache.zookeeper.ZooKeeper) MockedPulsarServiceBaseTest.createMockZooKeeper(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.createMockZooKeeper) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) PulsarService(org.apache.pulsar.broker.PulsarService) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ConfigurationCacheService(org.apache.pulsar.broker.cache.ConfigurationCacheService) LocalZooKeeperCacheService(org.apache.pulsar.broker.cache.LocalZooKeeperCacheService) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 3 with NamespaceService

use of org.apache.pulsar.broker.namespace.NamespaceService in project incubator-pulsar by apache.

the class DispatcherBlockConsumerTest method testBrokerSubscriptionRecovery.

/**
 * <pre>
 * It verifies that cursor-recovery
 * 1. recovers individualDeletedMessages
 * 2. sets readPosition with last acked-message
 * 3. replay all unack messages
 * </pre>
 *
 * @throws Exception
 */
@Test(dataProvider = "gracefulUnload")
public void testBrokerSubscriptionRecovery(boolean unloadBundleGracefully) throws Exception {
    log.info("-- Starting {} test --", methodName);
    final String topicName = "persistent://my-property/use/my-ns/unacked-topic";
    final String subscriberName = "subscriber-1";
    final int totalProducedMsgs = 500;
    Consumer<byte[]> consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriberName).subscriptionType(SubscriptionType.Shared).subscribe();
    Producer<byte[]> producer = pulsarClient.newProducer().topic("persistent://my-property/use/my-ns/unacked-topic").create();
    CountDownLatch latch = new CountDownLatch(totalProducedMsgs);
    // (1) Produced Messages
    for (int i = 0; i < totalProducedMsgs; i++) {
        String message = "my-message-" + i;
        producer.sendAsync(message.getBytes()).thenAccept(msg -> latch.countDown());
    }
    latch.await();
    // (2) consume all messages except: unackMessages-set
    Set<Integer> unackMessages = Sets.newHashSet(5, 10, 20, 21, 22, 23, 25, 26, 30, 32, 40, 80, 160, 320);
    int receivedMsgCount = 0;
    for (int i = 0; i < totalProducedMsgs; i++) {
        Message<?> msg = consumer.receive(500, TimeUnit.MILLISECONDS);
        if (!unackMessages.contains(i)) {
            consumer.acknowledge(msg);
        }
        receivedMsgCount++;
    }
    assertEquals(totalProducedMsgs, receivedMsgCount);
    consumer.close();
    // if broker unload bundle gracefully then cursor metadata recovered from zk else from ledger
    if (unloadBundleGracefully) {
        // set clean namespace which will not let broker unload bundle gracefully: stop broker
        Supplier<NamespaceService> namespaceServiceSupplier = () -> spy(new NamespaceService(pulsar));
        doReturn(namespaceServiceSupplier).when(pulsar).getNamespaceServiceProvider();
    }
    stopBroker();
    // start broker which will recover topic-cursor from the ledger
    startBroker();
    consumer = pulsarClient.newConsumer().topic(topicName).subscriptionName(subscriberName).subscriptionType(SubscriptionType.Shared).subscribe();
    // consumer should only receive unakced messages
    Set<String> unackMsgs = unackMessages.stream().map(i -> "my-message-" + i).collect(Collectors.toSet());
    Set<String> receivedMsgs = Sets.newHashSet();
    for (int i = 0; i < totalProducedMsgs; i++) {
        Message<?> msg = consumer.receive(500, TimeUnit.MILLISECONDS);
        if (msg == null) {
            break;
        }
        receivedMsgs.add(new String(msg.getData()));
    }
    receivedMsgs.removeAll(unackMsgs);
    assertTrue(receivedMsgs.isEmpty());
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) SubscriptionStats(org.apache.pulsar.common.policies.data.SubscriptionStats) Lists(org.testng.collections.Lists) PersistentTopicStats(org.apache.pulsar.common.policies.data.PersistentTopicStats) DataProvider(org.testng.annotations.DataProvider) LoggerFactory(org.slf4j.LoggerFactory) Assert.assertEquals(org.testng.Assert.assertEquals) Test(org.testng.annotations.Test) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) Mockito.spy(org.mockito.Mockito.spy) AfterMethod(org.testng.annotations.AfterMethod) Multimap(com.google.common.collect.Multimap) Supplier(java.util.function.Supplier) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Mockito.doReturn(org.mockito.Mockito.doReturn) PersistentDispatcherMultipleConsumers(org.apache.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) Assert.assertNotEquals(org.testng.Assert.assertNotEquals) ConsumerImpl(org.apache.pulsar.client.impl.ConsumerImpl) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Assert.fail(org.testng.Assert.fail) BeforeMethod(org.testng.annotations.BeforeMethod) Set(java.util.Set) Assert.assertNotNull(org.testng.Assert.assertNotNull) BrokerService(org.apache.pulsar.broker.service.BrokerService) Field(java.lang.reflect.Field) Collectors(java.util.stream.Collectors) Maps(com.google.common.collect.Maps) Executors(java.util.concurrent.Executors) Sets(com.google.common.collect.Sets) TimeUnit(java.util.concurrent.TimeUnit) MessageIdImpl(org.apache.pulsar.client.impl.MessageIdImpl) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) PersistentTopic(org.apache.pulsar.broker.service.persistent.PersistentTopic) ConcurrentOpenHashSet(org.apache.pulsar.common.util.collections.ConcurrentOpenHashSet) Queues(com.google.common.collect.Queues) Assert.assertTrue(org.testng.Assert.assertTrue) Queue(java.util.Queue) NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.testng.annotations.Test)

Example 4 with NamespaceService

use of org.apache.pulsar.broker.namespace.NamespaceService in project incubator-pulsar by apache.

the class MockedPulsarServiceBaseTest method setupBrokerMocks.

protected void setupBrokerMocks(PulsarService pulsar) throws Exception {
    // Override default providers with mocked ones
    doReturn(mockZooKeeperClientFactory).when(pulsar).getZooKeeperClientFactory();
    doReturn(mockBookKeeperClientFactory).when(pulsar).getBookKeeperClientFactory();
    Supplier<NamespaceService> namespaceServiceSupplier = () -> spy(new NamespaceService(pulsar));
    doReturn(namespaceServiceSupplier).when(pulsar).getNamespaceServiceProvider();
    doReturn(sameThreadOrderedSafeExecutor).when(pulsar).getOrderedExecutor();
}
Also used : NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService)

Example 5 with NamespaceService

use of org.apache.pulsar.broker.namespace.NamespaceService in project incubator-pulsar by apache.

the class PulsarWebResource method isBundleOwnedByAnyBroker.

/**
 * Checks whether a given bundle is currently loaded by any broker
 */
protected boolean isBundleOwnedByAnyBroker(NamespaceName fqnn, BundlesData bundles, String bundleRange) {
    NamespaceBundle nsBundle = validateNamespaceBundleRange(fqnn, bundles, bundleRange);
    NamespaceService nsService = pulsar().getNamespaceService();
    try {
        return nsService.getWebServiceUrl(nsBundle, /*authoritative */
        false, isRequestHttps(), /* read-only */
        true).isPresent();
    } catch (Exception e) {
        log.error("[{}] Failed to check whether namespace bundle is owned {}/{}", clientAppId(), fqnn.toString(), bundleRange, e);
        throw new RestException(e);
    }
}
Also used : NamespaceService(org.apache.pulsar.broker.namespace.NamespaceService) KeeperException(org.apache.zookeeper.KeeperException) MalformedURLException(java.net.MalformedURLException) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

NamespaceService (org.apache.pulsar.broker.namespace.NamespaceService)10 BeforeMethod (org.testng.annotations.BeforeMethod)5 ManagedLedgerFactory (org.apache.bookkeeper.mledger.ManagedLedgerFactory)4 PulsarService (org.apache.pulsar.broker.PulsarService)4 ServiceConfiguration (org.apache.pulsar.broker.ServiceConfiguration)4 MockedPulsarServiceBaseTest.createMockZooKeeper (org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.createMockZooKeeper)4 NamespaceBundle (org.apache.pulsar.common.naming.NamespaceBundle)4 TopicName (org.apache.pulsar.common.naming.TopicName)4 ZooKeeper (org.apache.zookeeper.ZooKeeper)4 WebApplicationException (javax.ws.rs.WebApplicationException)3 ConfigurationCacheService (org.apache.pulsar.broker.cache.ConfigurationCacheService)3 LocalZooKeeperCacheService (org.apache.pulsar.broker.cache.LocalZooKeeperCacheService)3 Policies (org.apache.pulsar.common.policies.data.Policies)3 InetSocketAddress (java.net.InetSocketAddress)2 MalformedURLException (java.net.MalformedURLException)2 URI (java.net.URI)2 URL (java.net.URL)2 BrokerService (org.apache.pulsar.broker.service.BrokerService)2 ArrayListMultimap (com.google.common.collect.ArrayListMultimap)1 Maps (com.google.common.collect.Maps)1