Search in sources :

Example 16 with DestinationName

use of com.yahoo.pulsar.common.naming.DestinationName in project pulsar by yahoo.

the class NamespacesTest method testDeleteNamespaces.

@Test
public void testDeleteNamespaces() throws Exception {
    try {
        namespaces.deleteNamespace(this.testProperty, this.testLocalCluster, "non-existing-namespace-1", false);
        fail("should have failed");
    } catch (RestException e) {
        assertEquals(e.getResponse().getStatus(), Status.NOT_FOUND.getStatusCode());
    }
    NamespaceName testNs = this.testLocalNamespaces.get(1);
    DestinationName topicName = DestinationName.get(testNs.getPersistentTopicName("my-topic"));
    ZkUtils.createFullPathOptimistic(mockZookKeeper, "/managed-ledgers/" + topicName.getPersistenceNamingEncoding(), new byte[0], null, null);
    // setup ownership to localhost
    URL localWebServiceUrl = new URL(pulsar.getWebServiceAddress());
    doReturn(localWebServiceUrl).when(nsSvc).getWebServiceUrl(testNs, false, false, false);
    doReturn(true).when(nsSvc).isServiceUnitOwned(testNs);
    try {
        namespaces.deleteNamespace(testNs.getProperty(), testNs.getCluster(), testNs.getLocalName(), false);
        fail("should have failed");
    } catch (RestException e) {
        // Ok, namespace not empty
        assertEquals(e.getResponse().getStatus(), Status.CONFLICT.getStatusCode());
    }
    testNs = this.testGlobalNamespaces.get(0);
    // setup ownership to localhost
    doReturn(localWebServiceUrl).when(nsSvc).getWebServiceUrl(testNs, false, false, false);
    doReturn(true).when(nsSvc).isServiceUnitOwned(testNs);
    namespaces.deleteNamespace(testNs.getProperty(), testNs.getCluster(), testNs.getLocalName(), false);
    testNs = this.testLocalNamespaces.get(0);
    // setup ownership to localhost
    doReturn(localWebServiceUrl).when(nsSvc).getWebServiceUrl(testNs, false, false, false);
    doReturn(true).when(nsSvc).isServiceUnitOwned(testNs);
    namespaces.deleteNamespace(testNs.getProperty(), testNs.getCluster(), testNs.getLocalName(), false);
    List<String> nsList = Lists.newArrayList(this.testLocalNamespaces.get(1).toString(), this.testLocalNamespaces.get(2).toString());
    nsList.sort(null);
    assertEquals(namespaces.getPropertyNamespaces(this.testProperty), nsList);
    testNs = this.testLocalNamespaces.get(1);
    try {
        namespaces.deleteNamespace(testNs.getProperty(), testNs.getCluster(), testNs.getLocalName(), false);
        fail("should have failed");
    } catch (RestException e) {
    // Ok
    }
    // delete the topic from ZK
    mockZookKeeper.delete("/managed-ledgers/" + topicName.getPersistenceNamingEncoding(), -1);
    // ensure refreshed destination list in the cache
    pulsar.getLocalZkCacheService().managedLedgerListCache().clearTree();
    // setup ownership to localhost
    doReturn(localWebServiceUrl).when(nsSvc).getWebServiceUrl(testNs, false, false, false);
    doReturn(true).when(nsSvc).isServiceUnitOwned(testNs);
    namespaces.deleteNamespace(testNs.getProperty(), testNs.getCluster(), testNs.getLocalName(), false);
}
Also used : NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) RestException(com.yahoo.pulsar.broker.web.RestException) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) URL(java.net.URL) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(com.yahoo.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 17 with DestinationName

use of com.yahoo.pulsar.common.naming.DestinationName in project pulsar by yahoo.

the class BookieClientStatsGenerator method generate.

private Map<String, Map<String, PendingBookieOpsStats>> generate() throws Exception {
    if (pulsar.getBrokerService() != null && pulsar.getBrokerService().getTopics() != null) {
        pulsar.getBrokerService().getTopics().forEach((name, topicFuture) -> {
            PersistentTopic persistentTopic = (PersistentTopic) topicFuture.getNow(null);
            if (persistentTopic != null) {
                DestinationName destinationName = DestinationName.get(persistentTopic.getName());
                put(destinationName, persistentTopic.getManagedLedger().getStats().getPendingBookieOpsStats());
            }
        });
    }
    return nsBookieClientStatsMap;
}
Also used : PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) DestinationName(com.yahoo.pulsar.common.naming.DestinationName)

Example 18 with DestinationName

use of com.yahoo.pulsar.common.naming.DestinationName in project pulsar by yahoo.

the class NamespaceServiceTest method testIsServiceUnitDisabled.

@Test
public void testIsServiceUnitDisabled() throws Exception {
    OwnershipCache MockOwnershipCache = spy(pulsar.getNamespaceService().getOwnershipCache());
    ManagedLedger ledger = mock(ManagedLedger.class);
    when(ledger.getCursors()).thenReturn(Lists.newArrayList());
    doNothing().when(MockOwnershipCache).disableOwnership(any(NamespaceBundle.class));
    Field ownership = NamespaceService.class.getDeclaredField("ownershipCache");
    ownership.setAccessible(true);
    ownership.set(pulsar.getNamespaceService(), MockOwnershipCache);
    NamespaceService namespaceService = pulsar.getNamespaceService();
    NamespaceName nsname = new NamespaceName("pulsar/global/ns1");
    DestinationName dn = DestinationName.get("persistent://pulsar/global/ns1/topic-1");
    NamespaceBundles bundles = namespaceService.getNamespaceBundleFactory().getBundles(nsname);
    NamespaceBundle originalBundle = bundles.findBundle(dn);
    assertFalse(namespaceService.isNamespaceBundleDisabled(originalBundle));
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Field(java.lang.reflect.Field) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) NamespaceBundles(com.yahoo.pulsar.common.naming.NamespaceBundles) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) Test(org.testng.annotations.Test)

Example 19 with DestinationName

use of com.yahoo.pulsar.common.naming.DestinationName in project pulsar by yahoo.

the class LoadBalancerTest method testDestinationAssignmentWithExistingBundles.

/*
     * Pre-publish load report to ZK, each broker has: - Difference memory capacity, for the first 3 brokers memory is
     * bottleneck, for the 4/5th brokers CPU become bottleneck since memory is big enough - already has some bundles
     * assigned Check the distribution of new destinations is roughly consistent (with <10% variation) with the ranking
     */
@Test
public void testDestinationAssignmentWithExistingBundles() throws Exception {
    for (int i = 0; i < BROKER_COUNT; i++) {
        ResourceQuota defaultQuota = new ResourceQuota();
        defaultQuota.setMsgRateIn(20);
        defaultQuota.setMsgRateOut(60);
        defaultQuota.setBandwidthIn(20000);
        defaultQuota.setBandwidthOut(60000);
        defaultQuota.setMemory(87);
        pulsarServices[i].getLocalZkCacheService().getResourceQuotaCache().setDefaultQuota(defaultQuota);
        LoadReport lr = new LoadReport();
        lr.setName(lookupAddresses[i]);
        SystemResourceUsage sru = new SystemResourceUsage();
        sru.setBandwidthIn(new ResourceUsage(0, 1024000));
        sru.setBandwidthOut(new ResourceUsage(0, 1024000));
        sru.setMemory(new ResourceUsage(0, 2048 * (i + 1)));
        sru.setCpu(new ResourceUsage(60, 400));
        lr.setSystemResourceUsage(sru);
        Map<String, NamespaceBundleStats> bundleStats = new HashMap<String, NamespaceBundleStats>();
        for (int j = 0; j < (i + 1) * 5; j++) {
            String bundleName = String.format("pulsar/use/primary-ns-%d-%d/0x00000000_0xffffffff", i, j);
            NamespaceBundleStats stats = new NamespaceBundleStats();
            bundleStats.put(bundleName, stats);
        }
        lr.setBundleStats(bundleStats);
        String znodePath = String.format("%s/%s", SimpleLoadManagerImpl.LOADBALANCE_BROKERS_ROOT, lookupAddresses[i]);
        String loadReportJson = objectMapper.writeValueAsString(lr);
        bkEnsemble.getZkClient().setData(znodePath, loadReportJson.getBytes(Charsets.UTF_8), -1);
    }
    // sleep to wait load ranking be triggered
    Thread.sleep(5000);
    // print ranking
    for (int i = 0; i < BROKER_COUNT; i++) {
        AtomicReference<Map<Long, Set<ResourceUnit>>> sortedRanking = getSortedRanking(pulsarServices[i]);
        printSortedRanking(sortedRanking);
    }
    // check owner of new destiations and verify that the distribution is roughly
    // consistent (variation < 10%) with the broker capacity:
    int totalNamespaces = 250;
    int[] expectedAssignments = new int[] { 17, 34, 51, 68, 85 };
    Map<String, Integer> namespaceOwner = new HashMap<>();
    for (int i = 0; i < totalNamespaces; i++) {
        DestinationName fqdn = DestinationName.get("persistent://pulsar/use/primary-ns-" + i + "/test-topic");
        ResourceUnit found = pulsarServices[0].getLoadManager().getLeastLoaded(pulsarServices[0].getNamespaceService().getBundle(fqdn));
        if (namespaceOwner.containsKey(found.getResourceId())) {
            namespaceOwner.put(found.getResourceId(), namespaceOwner.get(found.getResourceId()) + 1);
        } else {
            namespaceOwner.put(found.getResourceId(), 1);
        }
    }
    double expectedMaxVariation = 10.0;
    for (int i = 0; i < BROKER_COUNT; i++) {
        long actualValue = 0;
        String resourceId = "http://" + lookupAddresses[i];
        if (namespaceOwner.containsKey(resourceId)) {
            actualValue = namespaceOwner.get(resourceId);
        }
        long expectedValue = expectedAssignments[i];
        double variation = Math.abs(actualValue - expectedValue) * 100.0 / expectedValue;
        log.info("Destination assignment - {}, actual: {}, expected baseline: {}, variation: {}/%", lookupAddresses[i], actualValue, expectedValue, String.format("%.2f", variation));
        assertTrue(variation < expectedMaxVariation);
    }
}
Also used : HashMap(java.util.HashMap) SystemResourceUsage(com.yahoo.pulsar.common.policies.data.loadbalancer.SystemResourceUsage) ResourceUsage(com.yahoo.pulsar.common.policies.data.loadbalancer.ResourceUsage) SystemResourceUsage(com.yahoo.pulsar.common.policies.data.loadbalancer.SystemResourceUsage) SimpleResourceUnit(com.yahoo.pulsar.broker.loadbalance.impl.SimpleResourceUnit) ResourceQuota(com.yahoo.pulsar.common.policies.data.ResourceQuota) NamespaceBundleStats(com.yahoo.pulsar.common.policies.data.loadbalancer.NamespaceBundleStats) LoadReport(com.yahoo.pulsar.common.policies.data.loadbalancer.LoadReport) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) Test(org.testng.annotations.Test)

Example 20 with DestinationName

use of com.yahoo.pulsar.common.naming.DestinationName in project pulsar by yahoo.

the class BrokerService method addTopicToStatsMaps.

private void addTopicToStatsMaps(DestinationName topicName, PersistentTopic topic) {
    try {
        NamespaceBundle namespaceBundle = pulsar.getNamespaceService().getBundle(topicName);
        if (namespaceBundle != null) {
            synchronized (multiLayerTopicsMap) {
                String serviceUnit = namespaceBundle.toString();
                //
                multiLayerTopicsMap.computeIfAbsent(topicName.getNamespace(), //
                k -> new ConcurrentOpenHashMap<>()).computeIfAbsent(serviceUnit, //
                k -> new ConcurrentOpenHashMap<>()).put(topicName.toString(), topic);
            }
        }
        invalidateOfflineTopicStatCache(topicName);
    } catch (Exception e) {
        log.warn("Got exception when retrieving bundle name during create persistent topic", e);
    }
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) LoggerFactory(org.slf4j.LoggerFactory) NamespaceBundleStats(com.yahoo.pulsar.common.policies.data.loadbalancer.NamespaceBundleStats) Stat(org.apache.zookeeper.data.Stat) Policies(com.yahoo.pulsar.common.policies.data.Policies) EpollMode(io.netty.channel.epoll.EpollMode) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PersistentOfflineTopicStats(com.yahoo.pulsar.common.policies.data.PersistentOfflineTopicStats) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Map(java.util.Map) ZooKeeperCacheListener(com.yahoo.pulsar.zookeeper.ZooKeeperCacheListener) PulsarService(com.yahoo.pulsar.broker.PulsarService) FieldParser(com.yahoo.pulsar.common.util.FieldParser) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) FutureUtil(com.yahoo.pulsar.client.util.FutureUtil) URI(java.net.URI) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) SystemUtils(org.apache.commons.lang.SystemUtils) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) DigestType(org.apache.bookkeeper.client.BookKeeper.DigestType) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) Set(java.util.Set) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ObjectMapperFactory(com.yahoo.pulsar.common.util.ObjectMapperFactory) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) Metrics(com.yahoo.pulsar.broker.stats.Metrics) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) ClientConfiguration(com.yahoo.pulsar.client.api.ClientConfiguration) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Optional(java.util.Optional) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) ChannelOption(io.netty.channel.ChannelOption) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) SafeRun.safeRun(org.apache.bookkeeper.mledger.util.SafeRun.safeRun) PersistentTopicStats(com.yahoo.pulsar.common.policies.data.PersistentTopicStats) EpollChannelOption(io.netty.channel.epoll.EpollChannelOption) Lists(com.google.common.collect.Lists) FieldContext(com.yahoo.pulsar.common.configuration.FieldContext) ByteBuf(io.netty.buffer.ByteBuf) EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) ConcurrentOpenHashSet(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashSet) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) AdaptiveRecvByteBufAllocator(io.netty.channel.AdaptiveRecvByteBufAllocator) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) NamespaceBundleFactory(com.yahoo.pulsar.common.naming.NamespaceBundleFactory) PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) ClusterReplicationMetrics(com.yahoo.pulsar.broker.stats.ClusterReplicationMetrics) Logger(org.slf4j.Logger) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) EventLoopGroup(io.netty.channel.EventLoopGroup) KeeperException(org.apache.zookeeper.KeeperException) Semaphore(java.util.concurrent.Semaphore) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) IOException(java.io.IOException) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Field(java.lang.reflect.Field) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) PulsarWebResource(com.yahoo.pulsar.broker.web.PulsarWebResource) Closeable(java.io.Closeable) CollectionUtils.isEmpty(org.apache.commons.collections.CollectionUtils.isEmpty) AuthorizationManager(com.yahoo.pulsar.broker.authorization.AuthorizationManager) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) AuthenticationService(com.yahoo.pulsar.broker.authentication.AuthenticationService) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) PersistenceException(com.yahoo.pulsar.broker.service.BrokerServiceException.PersistenceException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) KeeperException(org.apache.zookeeper.KeeperException) ServerMetadataException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServerMetadataException) IOException(java.io.IOException) ServiceUnitNotReadyException(com.yahoo.pulsar.broker.service.BrokerServiceException.ServiceUnitNotReadyException)

Aggregations

DestinationName (com.yahoo.pulsar.common.naming.DestinationName)91 Test (org.testng.annotations.Test)36 PulsarClientException (com.yahoo.pulsar.client.api.PulsarClientException)33 PersistentTopic (com.yahoo.pulsar.broker.service.persistent.PersistentTopic)26 CompletableFuture (java.util.concurrent.CompletableFuture)24 KeeperException (org.apache.zookeeper.KeeperException)23 PreconditionFailedException (com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException)22 WebApplicationException (javax.ws.rs.WebApplicationException)21 IOException (java.io.IOException)20 ManagedLedgerException (org.apache.bookkeeper.mledger.ManagedLedgerException)19 RestException (com.yahoo.pulsar.broker.web.RestException)18 NotFoundException (com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException)18 PartitionedTopicMetadata (com.yahoo.pulsar.common.partition.PartitionedTopicMetadata)17 SubscriptionBusyException (com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException)16 TopicBusyException (com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException)16 Path (javax.ws.rs.Path)16 NotAllowedException (com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException)14 ApiOperation (io.swagger.annotations.ApiOperation)14 ApiResponses (io.swagger.annotations.ApiResponses)14 Field (java.lang.reflect.Field)14