Search in sources :

Example 1 with BrokerTopicLoadingPredicate

use of org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate in project incubator-pulsar by apache.

the class ModularLoadManagerImpl method selectBrokerForAssignment.

/**
 * As the leader broker, find a suitable broker for the assignment of the given bundle.
 *
 * @param serviceUnit
 *            ServiceUnitId for the bundle.
 * @return The name of the selected broker, as it appears on ZooKeeper.
 */
@Override
public Optional<String> selectBrokerForAssignment(final ServiceUnitId serviceUnit) {
    // Use brokerCandidateCache as a lock to reduce synchronization.
    synchronized (brokerCandidateCache) {
        final String bundle = serviceUnit.toString();
        if (preallocatedBundleToBroker.containsKey(bundle)) {
            // If the given bundle is already in preallocated, return the selected broker.
            return Optional.of(preallocatedBundleToBroker.get(bundle));
        }
        final BundleData data = loadData.getBundleData().computeIfAbsent(bundle, key -> getBundleDataOrDefault(bundle));
        brokerCandidateCache.clear();
        LoadManagerShared.applyNamespacePolicies(serviceUnit, policies, brokerCandidateCache, getAvailableBrokers(), brokerTopicLoadingPredicate);
        // filter brokers which owns topic higher than threshold
        LoadManagerShared.filterBrokersWithLargeTopicCount(brokerCandidateCache, loadData, conf.getLoadBalancerBrokerMaxTopics());
        // distribute namespaces to domain and brokers according to anti-affinity-group
        LoadManagerShared.filterAntiAffinityGroupOwnedBrokers(pulsar, serviceUnit.toString(), brokerCandidateCache, brokerToNamespaceToBundleRange, brokerToFailureDomainMap);
        // distribute bundles evenly to candidate-brokers
        LoadManagerShared.removeMostServicingBrokersForNamespace(serviceUnit.toString(), brokerCandidateCache, brokerToNamespaceToBundleRange);
        log.info("{} brokers being considered for assignment of {}", brokerCandidateCache.size(), bundle);
        // Use the filter pipeline to finalize broker candidates.
        try {
            for (BrokerFilter filter : filterPipeline) {
                filter.filter(brokerCandidateCache, data, loadData, conf);
            }
        } catch (BrokerFilterException x) {
            // restore the list of brokers to the full set
            LoadManagerShared.applyNamespacePolicies(serviceUnit, policies, brokerCandidateCache, getAvailableBrokers(), brokerTopicLoadingPredicate);
        }
        if (brokerCandidateCache.isEmpty()) {
            // restore the list of brokers to the full set
            LoadManagerShared.applyNamespacePolicies(serviceUnit, policies, brokerCandidateCache, getAvailableBrokers(), brokerTopicLoadingPredicate);
        }
        // Choose a broker among the potentially smaller filtered list, when possible
        Optional<String> broker = placementStrategy.selectBroker(brokerCandidateCache, data, loadData, conf);
        if (log.isDebugEnabled()) {
            log.debug("Selected broker {} from candidate brokers {}", broker, brokerCandidateCache);
        }
        if (!broker.isPresent()) {
            // No brokers available
            return broker;
        }
        final double overloadThreshold = conf.getLoadBalancerBrokerOverloadedThresholdPercentage() / 100.0;
        final double maxUsage = loadData.getBrokerData().get(broker.get()).getLocalData().getMaxResourceUsage();
        if (maxUsage > overloadThreshold) {
            // All brokers that were in the filtered list were overloaded, so check if there is a better broker
            LoadManagerShared.applyNamespacePolicies(serviceUnit, policies, brokerCandidateCache, getAvailableBrokers(), brokerTopicLoadingPredicate);
            broker = placementStrategy.selectBroker(brokerCandidateCache, data, loadData, conf);
        }
        // Add new bundle to preallocated.
        loadData.getBrokerData().get(broker.get()).getPreallocatedBundleData().put(bundle, data);
        preallocatedBundleToBroker.put(bundle, broker.get());
        final String namespaceName = LoadManagerShared.getNamespaceNameFromBundleName(bundle);
        final String bundleRange = LoadManagerShared.getBundleRangeFromBundleName(bundle);
        brokerToNamespaceToBundleRange.get(broker.get()).computeIfAbsent(namespaceName, k -> new HashSet<>()).add(bundleRange);
        return broker;
    }
}
Also used : BrokerFilter(org.apache.pulsar.broker.loadbalance.BrokerFilter) CreateMode(org.apache.zookeeper.CreateMode) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) LoadSheddingStrategy(org.apache.pulsar.broker.loadbalance.LoadSheddingStrategy) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) ModularLoadManagerStrategy(org.apache.pulsar.broker.loadbalance.ModularLoadManagerStrategy) Stat(org.apache.zookeeper.data.Stat) StringUtils(org.apache.commons.lang3.StringUtils) BundleSplitStrategy(org.apache.pulsar.broker.loadbalance.BundleSplitStrategy) SystemResourceUsage(org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage) Map(java.util.Map) ZooKeeperDataCache(org.apache.pulsar.zookeeper.ZooKeeperDataCache) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) AdminResource.jsonMapper(org.apache.pulsar.broker.admin.AdminResource.jsonMapper) ZooKeeper(org.apache.zookeeper.ZooKeeper) BrokerHostUsage(org.apache.pulsar.broker.loadbalance.BrokerHostUsage) LoadData(org.apache.pulsar.broker.loadbalance.LoadData) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ZooKeeperChildrenCache(org.apache.pulsar.zookeeper.ZooKeeperChildrenCache) ZooKeeperCacheListener(org.apache.pulsar.zookeeper.ZooKeeperCacheListener) ModularLoadManager(org.apache.pulsar.broker.loadbalance.ModularLoadManager) Executors(java.util.concurrent.Executors) ZkUtils(org.apache.bookkeeper.util.ZkUtils) BrokerData(org.apache.pulsar.broker.BrokerData) NamespaceBundleFactory(org.apache.pulsar.common.naming.NamespaceBundleFactory) List(java.util.List) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) TimeAverageBrokerData(org.apache.pulsar.broker.TimeAverageBrokerData) PulsarWebResource.path(org.apache.pulsar.broker.web.PulsarWebResource.path) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) BundleData(org.apache.pulsar.broker.BundleData) BrokerFilter(org.apache.pulsar.broker.loadbalance.BrokerFilter) HashSet(java.util.HashSet) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BrokerFilterException(org.apache.pulsar.broker.loadbalance.BrokerFilterException) ResourceQuota(org.apache.pulsar.common.policies.data.ResourceQuota) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) KeeperException(org.apache.zookeeper.KeeperException) SystemUtils(org.apache.commons.lang3.SystemUtils) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) LocalBrokerData(org.apache.pulsar.policies.data.loadbalancer.LocalBrokerData) BrokerTopicLoadingPredicate(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate) FailureDomain(org.apache.pulsar.common.policies.data.FailureDomain) IOException(java.io.IOException) PulsarService(org.apache.pulsar.broker.PulsarService) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) Policies(org.apache.pulsar.common.policies.data.Policies) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) TimeAverageMessageData(org.apache.pulsar.broker.TimeAverageMessageData) ZooDefs(org.apache.zookeeper.ZooDefs) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) Deserializer(org.apache.pulsar.zookeeper.ZooKeeperCache.Deserializer) BundleData(org.apache.pulsar.broker.BundleData) BrokerFilterException(org.apache.pulsar.broker.loadbalance.BrokerFilterException) HashSet(java.util.HashSet)

Example 2 with BrokerTopicLoadingPredicate

use of org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate in project incubator-pulsar by apache.

the class ModularLoadManagerImplTest method testNamespaceIsolationPoliciesForPrimaryAndSecondaryBrokers.

/**
 * It verifies namespace-isolation policies with primary and secondary brokers.
 *
 * usecase:
 *
 * <pre>
 *  1. Namespace: primary=broker1, secondary=broker2, shared=broker3, min_limit = 1
 *     a. available-brokers: broker1, broker2, broker3 => result: broker1
 *     b. available-brokers: broker2, broker3          => result: broker2
 *     c. available-brokers: broker3                   => result: NULL
 *  2. Namespace: primary=broker1, secondary=broker2, shared=broker3, min_limit = 2
 *     a. available-brokers: broker1, broker2, broker3 => result: broker1, broker2
 *     b. available-brokers: broker2, broker3          => result: broker2
 *     c. available-brokers: broker3                   => result: NULL
 * </pre>
 *
 * @throws Exception
 */
@Test
public void testNamespaceIsolationPoliciesForPrimaryAndSecondaryBrokers() throws Exception {
    final String property = "my-property";
    final String cluster = "use";
    final String namespace = "my-ns";
    final String broker1Address = pulsar1.getAdvertisedAddress() + "0";
    final String broker2Address = pulsar2.getAdvertisedAddress() + "1";
    final String sharedBroker = "broker3";
    admin1.clusters().createCluster(cluster, new ClusterData("http://" + pulsar1.getAdvertisedAddress()));
    admin1.properties().createProperty(property, new PropertyAdmin(Lists.newArrayList("appid1", "appid2"), Sets.newHashSet(cluster)));
    admin1.namespaces().createNamespace(property + "/" + cluster + "/" + namespace);
    // set a new policy
    String newPolicyJsonTemplate = "{\"namespaces\":[\"%s/%s/%s.*\"],\"primary\":[\"%s\"]," + "\"secondary\":[\"%s\"],\"auto_failover_policy\":{\"policy_type\":\"min_available\",\"parameters\":{\"min_limit\":%s,\"usage_threshold\":80}}}";
    String newPolicyJson = String.format(newPolicyJsonTemplate, property, cluster, namespace, broker1Address, broker2Address, 1);
    String newPolicyName = "my-ns-isolation-policies";
    ObjectMapper jsonMapper = ObjectMapperFactory.create();
    NamespaceIsolationData nsPolicyData = jsonMapper.readValue(newPolicyJson.getBytes(), NamespaceIsolationData.class);
    admin1.clusters().createNamespaceIsolationPolicy("use", newPolicyName, nsPolicyData);
    SimpleResourceAllocationPolicies simpleResourceAllocationPolicies = new SimpleResourceAllocationPolicies(pulsar1);
    ServiceUnitId serviceUnit = LoadBalancerTestingUtils.makeBundles(nsFactory, property, cluster, namespace, 1)[0];
    BrokerTopicLoadingPredicate brokerTopicLoadingPredicate = new BrokerTopicLoadingPredicate() {

        @Override
        public boolean isEnablePersistentTopics(String brokerUrl) {
            return true;
        }

        @Override
        public boolean isEnableNonPersistentTopics(String brokerUrl) {
            return true;
        }
    };
    // (1) now we have isolation policy : primary=broker1, secondary=broker2, minLimit=1
    // test1: shared=1, primary=1, secondary=1 => It should return 1 primary broker only
    Set<String> brokerCandidateCache = Sets.newHashSet();
    Set<String> availableBrokers = Sets.newHashSet(sharedBroker, broker1Address, broker2Address);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 1);
    assertTrue(brokerCandidateCache.contains(broker1Address));
    // test2: shared=1, primary=0, secondary=1 => It should return 1 secondary broker only
    brokerCandidateCache = Sets.newHashSet();
    availableBrokers = Sets.newHashSet(sharedBroker, broker2Address);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 1);
    assertTrue(brokerCandidateCache.contains(broker2Address));
    // test3: shared=1, primary=0, secondary=0 => It should return 0 broker
    brokerCandidateCache = Sets.newHashSet();
    availableBrokers = Sets.newHashSet(sharedBroker);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 0);
    // (2) now we will have isolation policy : primary=broker1, secondary=broker2, minLimit=2
    newPolicyJson = String.format(newPolicyJsonTemplate, property, cluster, namespace, broker1Address, broker2Address, 2);
    nsPolicyData = jsonMapper.readValue(newPolicyJson.getBytes(), NamespaceIsolationData.class);
    admin1.clusters().createNamespaceIsolationPolicy("use", newPolicyName, nsPolicyData);
    // test1: shared=1, primary=1, secondary=1 => It should return primary + secondary
    brokerCandidateCache = Sets.newHashSet();
    availableBrokers = Sets.newHashSet(sharedBroker, broker1Address, broker2Address);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 2);
    assertTrue(brokerCandidateCache.contains(broker1Address));
    assertTrue(brokerCandidateCache.contains(broker2Address));
    // test2: shared=1, secondary=1 => It should return secondary
    brokerCandidateCache = Sets.newHashSet();
    availableBrokers = Sets.newHashSet(sharedBroker, broker2Address);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 1);
    assertTrue(brokerCandidateCache.contains(broker2Address));
    // test3: shared=1, => It should return 0 broker
    brokerCandidateCache = Sets.newHashSet();
    availableBrokers = Sets.newHashSet(sharedBroker);
    LoadManagerShared.applyNamespacePolicies(serviceUnit, simpleResourceAllocationPolicies, brokerCandidateCache, availableBrokers, brokerTopicLoadingPredicate);
    assertEquals(brokerCandidateCache.size(), 0);
}
Also used : BrokerTopicLoadingPredicate(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate) ClusterData(org.apache.pulsar.common.policies.data.ClusterData) PropertyAdmin(org.apache.pulsar.common.policies.data.PropertyAdmin) SimpleResourceAllocationPolicies(org.apache.pulsar.broker.loadbalance.impl.SimpleResourceAllocationPolicies) NamespaceIsolationData(org.apache.pulsar.common.policies.data.NamespaceIsolationData) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.testng.annotations.Test)

Aggregations

BrokerTopicLoadingPredicate (org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate)2 ServiceUnitId (org.apache.pulsar.common.naming.ServiceUnitId)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Maps (com.google.common.collect.Maps)1 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Executors (java.util.concurrent.Executors)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 TimeUnit (java.util.concurrent.TimeUnit)1 ZkUtils (org.apache.bookkeeper.util.ZkUtils)1 StringUtils (org.apache.commons.lang3.StringUtils)1