Search in sources :

Example 1 with ServiceUnitId

use of org.apache.pulsar.common.naming.ServiceUnitId in project incubator-pulsar by apache.

the class ModularLoadManagerImpl method shouldAntiAffinityNamespaceUnload.

public boolean shouldAntiAffinityNamespaceUnload(String namespace, String bundle, String currentBroker) {
    try {
        Optional<Policies> nsPolicies = pulsar.getConfigurationCache().policiesCache().get(path(POLICIES, namespace));
        if (!nsPolicies.isPresent() || StringUtils.isBlank(nsPolicies.get().antiAffinityGroup)) {
            return true;
        }
        synchronized (brokerCandidateCache) {
            brokerCandidateCache.clear();
            ServiceUnitId serviceUnit = pulsar.getNamespaceService().getNamespaceBundleFactory().getBundle(namespace, bundle);
            LoadManagerShared.applyNamespacePolicies(serviceUnit, policies, brokerCandidateCache, getAvailableBrokers(), brokerTopicLoadingPredicate);
            return LoadManagerShared.shouldAntiAffinityNamespaceUnload(namespace, bundle, currentBroker, pulsar, brokerToNamespaceToBundleRange, brokerCandidateCache);
        }
    } catch (Exception e) {
        log.warn("Failed to check anti-affinity namespace ownership for {}/{}/{}, {}", namespace, bundle, currentBroker, e.getMessage());
    }
    return true;
}
Also used : Policies(org.apache.pulsar.common.policies.data.Policies) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) BrokerFilterException(org.apache.pulsar.broker.loadbalance.BrokerFilterException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Example 2 with ServiceUnitId

use of org.apache.pulsar.common.naming.ServiceUnitId in project incubator-pulsar by apache.

the class SimpleLoadManagerImpl method getAvailableBrokers.

private Map<Long, Set<ResourceUnit>> getAvailableBrokers(ServiceUnitId serviceUnitId) throws Exception {
    Map<Long, Set<ResourceUnit>> availableBrokers = sortedRankings.get();
    if (availableBrokers.isEmpty()) {
        // Create a map with all available brokers with no load information
        Set<String> activeBrokers = availableActiveBrokers.get(LOADBALANCE_BROKERS_ROOT);
        List<String> brokersToShuffle = new ArrayList<>(activeBrokers);
        Collections.shuffle(brokersToShuffle);
        activeBrokers = new HashSet<>(brokersToShuffle);
        availableBrokers = Maps.newTreeMap();
        for (String broker : activeBrokers) {
            ResourceUnit resourceUnit = new SimpleResourceUnit(String.format("http://%s", broker), new PulsarResourceDescription());
            availableBrokers.computeIfAbsent(0L, key -> Sets.newTreeSet()).add(resourceUnit);
        }
        log.info("Choosing at random from broker list: [{}]", availableBrokers.values());
    }
    return availableBrokers;
}
Also used : ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) CreateMode(org.apache.zookeeper.CreateMode) Metrics(org.apache.pulsar.common.stats.Metrics) LoadingCache(com.google.common.cache.LoadingCache) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) Ids(org.apache.zookeeper.ZooDefs.Ids) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) Stat(org.apache.zookeeper.data.Stat) SystemResourceUsage(org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage) TreeMultimap(com.google.common.collect.TreeMultimap) 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) BrokerHostUsage(org.apache.pulsar.broker.loadbalance.BrokerHostUsage) Set(java.util.Set) ZooKeeperChildrenCache(org.apache.pulsar.zookeeper.ZooKeeperChildrenCache) ZooKeeperCacheListener(org.apache.pulsar.zookeeper.ZooKeeperCacheListener) LoadReport(org.apache.pulsar.policies.data.loadbalancer.LoadReport) Executors(java.util.concurrent.Executors) ZkUtils(org.apache.bookkeeper.util.ZkUtils) Sets(com.google.common.collect.Sets) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) CacheBuilder(com.google.common.cache.CacheBuilder) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) LOAD_REPORT_UPDATE_MIMIMUM_INTERVAL(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.LOAD_REPORT_UPDATE_MIMIMUM_INTERVAL) Multimap(com.google.common.collect.Multimap) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils.isNotEmpty(org.apache.commons.lang3.StringUtils.isNotEmpty) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Charsets(com.google.common.base.Charsets) 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) BrokerTopicLoadingPredicate(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate) IOException(java.io.IOException) PulsarService(org.apache.pulsar.broker.PulsarService) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) PlacementStrategy(org.apache.pulsar.broker.loadbalance.PlacementStrategy) ResourceType(org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage.ResourceType) TreeMap(java.util.TreeMap) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) Deserializer(org.apache.pulsar.zookeeper.ZooKeeperCache.Deserializer) ResourceUnitRanking(org.apache.pulsar.policies.data.loadbalancer.ResourceUnitRanking) Collections(java.util.Collections) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList)

Example 3 with ServiceUnitId

use of org.apache.pulsar.common.naming.ServiceUnitId in project incubator-pulsar by apache.

the class SimpleLoadManagerImpl method findBrokerForPlacement.

/**
 * Assign owner for specified ServiceUnit from the given candidates, following the the principles: 1) Optimum
 * distribution: fill up one broker till its load reaches optimum level (defined by underload threshold) before pull
 * another idle broker in; 2) Even distribution: once all brokers' load are above optimum level, maintain all
 * brokers to have even load; 3) Set the underload threshold to small value (like 1) for pure even distribution, and
 * high value (like 80) for pure optimum distribution;
 *
 * Strategy to select broker: 1) The first choice is the least loaded broker which is underload but not idle; 2) The
 * second choice is idle broker (if there is any); 3) Othewise simply select the least loaded broker if it is NOT
 * overloaded; 4) If all brokers are overloaded, select the broker with maximum available capacity (considering
 * brokers could have different hardware configuration, this usually means to select the broker with more hardware
 * resource);
 *
 * Broker's load level: 1) Load ranking (triggered by LoadReport update) estimate the load level according to the
 * resourse usage and namespace bundles already loaded by each broker; 2) When leader broker decide the owner for a
 * new namespace bundle, it may take time for the real owner to actually load the bundle and refresh LoadReport,
 * leader broker will store the bundle in a list called preAllocatedBundles, and the quota of all
 * preAllocatedBundles in preAllocatedQuotas, and re-estimate the broker's load level by putting the
 * preAllocatedQuota into calculation; 3) Everything (preAllocatedBundles and preAllocatedQuotas) will get reset in
 * load ranking.
 */
private synchronized ResourceUnit findBrokerForPlacement(Multimap<Long, ResourceUnit> candidates, ServiceUnitId serviceUnit) {
    long underloadThreshold = this.getLoadBalancerBrokerUnderloadedThresholdPercentage();
    long overloadThreshold = this.getLoadBalancerBrokerOverloadedThresholdPercentage();
    ResourceQuota defaultQuota = pulsar.getLocalZkCacheService().getResourceQuotaCache().getDefaultQuota();
    double minLoadPercentage = 101.0;
    long maxAvailability = -1;
    ResourceUnit idleRU = null;
    ResourceUnit maxAvailableRU = null;
    ResourceUnit randomRU = null;
    ResourceUnit selectedRU = null;
    ResourceUnitRanking selectedRanking = null;
    String serviceUnitId = serviceUnit.toString();
    // If the ranking is expected to be in the range [0,100] (which is the case for LOADBALANCER_STRATEGY_LLS),
    // the ranks are bounded. Otherwise (as is the case in LOADBALANCER_STRATEGY_LEAST_MSG, the ranks are simply
    // the total message rate which is in the range [0,Infinity) so they are unbounded. The
    // "boundedness" affects how two ranks are compared to see which one is better
    boolean unboundedRanks = getLoadBalancerPlacementStrategy().equals(LOADBALANCER_STRATEGY_LEAST_MSG);
    long randomBrokerIndex = (candidates.size() > 0) ? (this.brokerRotationCursor % candidates.size()) : 0;
    // find the least loaded & not-idle broker
    for (Map.Entry<Long, ResourceUnit> candidateOwner : candidates.entries()) {
        ResourceUnit candidate = candidateOwner.getValue();
        randomBrokerIndex--;
        // skip broker which is not ranked. this should never happen except in unit test
        if (!resourceUnitRankings.containsKey(candidate)) {
            continue;
        }
        String resourceUnitId = candidate.getResourceId();
        ResourceUnitRanking ranking = resourceUnitRankings.get(candidate);
        // check if this ServiceUnit is already loaded
        if (ranking.isServiceUnitLoaded(serviceUnitId)) {
            ranking.removeLoadedServiceUnit(serviceUnitId, this.getResourceQuota(serviceUnitId));
        }
        // record a random broker
        if (randomBrokerIndex < 0 && randomRU == null) {
            randomRU = candidate;
        }
        // check the available capacity
        double loadPercentage = ranking.getEstimatedLoadPercentage();
        double availablePercentage = Math.max(0, (100 - loadPercentage) / 100);
        long availability = (long) (ranking.estimateMaxCapacity(defaultQuota) * availablePercentage);
        if (availability > maxAvailability) {
            maxAvailability = availability;
            maxAvailableRU = candidate;
        }
        // check the load percentage
        if (ranking.isIdle()) {
            if (idleRU == null) {
                idleRU = candidate;
            }
        } else {
            if (selectedRU == null) {
                selectedRU = candidate;
                selectedRanking = ranking;
                minLoadPercentage = loadPercentage;
            } else {
                if ((unboundedRanks ? ranking.compareMessageRateTo(selectedRanking) : ranking.compareTo(selectedRanking)) < 0) {
                    minLoadPercentage = loadPercentage;
                    selectedRU = candidate;
                    selectedRanking = ranking;
                }
            }
        }
    }
    if ((minLoadPercentage > underloadThreshold && idleRU != null) || selectedRU == null) {
        // assigned to idle broker is the least loaded broker already have optimum load (which means NOT
        // underloaded), or all brokers are idle
        selectedRU = idleRU;
    } else if (minLoadPercentage >= 100.0 && randomRU != null && !unboundedRanks) {
        // all brokers are full, assign to a random one
        selectedRU = randomRU;
    } else if (minLoadPercentage > overloadThreshold && !unboundedRanks) {
        // assign to the broker with maximum available capacity if all brokers are overloaded
        selectedRU = maxAvailableRU;
    }
    // re-calculate load level for selected broker
    if (selectedRU != null) {
        this.brokerRotationCursor = (this.brokerRotationCursor + 1) % 1000000;
        ResourceUnitRanking ranking = resourceUnitRankings.get(selectedRU);
        String loadPercentageDesc = ranking.getEstimatedLoadPercentageString();
        log.info("Assign {} to {} with ({}).", serviceUnitId, selectedRU.getResourceId(), loadPercentageDesc);
        if (!ranking.isServiceUnitPreAllocated(serviceUnitId)) {
            final String namespaceName = LoadManagerShared.getNamespaceNameFromBundleName(serviceUnitId);
            final String bundleRange = LoadManagerShared.getBundleRangeFromBundleName(serviceUnitId);
            ResourceQuota quota = this.getResourceQuota(serviceUnitId);
            // Add preallocated bundle range so incoming bundles from the same namespace are not assigned to the
            // same broker.
            brokerToNamespaceToBundleRange.computeIfAbsent(selectedRU.getResourceId().replace("http://", ""), k -> new HashMap<>()).computeIfAbsent(namespaceName, k -> new HashSet<>()).add(bundleRange);
            ranking.addPreAllocatedServiceUnit(serviceUnitId, quota);
            resourceUnitRankings.put(selectedRU, ranking);
        }
    }
    return selectedRU;
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) Metrics(org.apache.pulsar.common.stats.Metrics) LoadingCache(com.google.common.cache.LoadingCache) DefaultThreadFactory(io.netty.util.concurrent.DefaultThreadFactory) Ids(org.apache.zookeeper.ZooDefs.Ids) ObjectMapperFactory(org.apache.pulsar.common.util.ObjectMapperFactory) LoggerFactory(org.slf4j.LoggerFactory) LoadManager(org.apache.pulsar.broker.loadbalance.LoadManager) Stat(org.apache.zookeeper.data.Stat) SystemResourceUsage(org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage) TreeMultimap(com.google.common.collect.TreeMultimap) 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) BrokerHostUsage(org.apache.pulsar.broker.loadbalance.BrokerHostUsage) Set(java.util.Set) ZooKeeperChildrenCache(org.apache.pulsar.zookeeper.ZooKeeperChildrenCache) ZooKeeperCacheListener(org.apache.pulsar.zookeeper.ZooKeeperCacheListener) LoadReport(org.apache.pulsar.policies.data.loadbalancer.LoadReport) Executors(java.util.concurrent.Executors) ZkUtils(org.apache.bookkeeper.util.ZkUtils) Sets(com.google.common.collect.Sets) CacheLoader(com.google.common.cache.CacheLoader) List(java.util.List) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) Optional(java.util.Optional) NamespaceBundleStats(org.apache.pulsar.policies.data.loadbalancer.NamespaceBundleStats) CacheBuilder(com.google.common.cache.CacheBuilder) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) LOAD_REPORT_UPDATE_MIMIMUM_INTERVAL(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.LOAD_REPORT_UPDATE_MIMIMUM_INTERVAL) Multimap(com.google.common.collect.Multimap) AtomicReference(java.util.concurrent.atomic.AtomicReference) StringUtils.isNotEmpty(org.apache.commons.lang3.StringUtils.isNotEmpty) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Charsets(com.google.common.base.Charsets) 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) BrokerTopicLoadingPredicate(org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate) IOException(java.io.IOException) PulsarService(org.apache.pulsar.broker.PulsarService) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) PlacementStrategy(org.apache.pulsar.broker.loadbalance.PlacementStrategy) ResourceType(org.apache.pulsar.policies.data.loadbalancer.SystemResourceUsage.ResourceType) TreeMap(java.util.TreeMap) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) Deserializer(org.apache.pulsar.zookeeper.ZooKeeperCache.Deserializer) ResourceUnitRanking(org.apache.pulsar.policies.data.loadbalancer.ResourceUnitRanking) Collections(java.util.Collections) ResourceUnit(org.apache.pulsar.broker.loadbalance.ResourceUnit) ResourceQuota(org.apache.pulsar.common.policies.data.ResourceQuota) ResourceUnitRanking(org.apache.pulsar.policies.data.loadbalancer.ResourceUnitRanking) Map(java.util.Map) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) HashSet(java.util.HashSet)

Example 4 with ServiceUnitId

use of org.apache.pulsar.common.naming.ServiceUnitId 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 5 with ServiceUnitId

use of org.apache.pulsar.common.naming.ServiceUnitId in project incubator-pulsar by apache.

the class AntiAffinityNamespaceGroupTest method testBrokerSelectionForAntiAffinityGroup.

/**
 * It verifies anti-affinity with failure domain enabled with 2 brokers.
 *
 * <pre>
 * 1. Register brokers to domain: domain-1: broker1 & domain-2: broker2
 * 2. Load-Manager receives a watch and updates brokerToDomain cache with new domain data
 * 3. Create two namespace with anti-affinity
 * 4. Load-manager selects broker for each namespace such that from different domains
 *
 * </pre>
 *
 * @throws Exception
 */
@Test
public void testBrokerSelectionForAntiAffinityGroup() throws Exception {
    final String broker1 = primaryHost;
    final String broker2 = secondaryHost;
    final String cluster = pulsar1.getConfiguration().getClusterName();
    final String property = "prop";
    final String namespace1 = property + "/" + cluster + "/ns1";
    final String namespace2 = property + "/" + cluster + "/ns2";
    final String namespaceAntiAffinityGroup = "group";
    FailureDomain domain = new FailureDomain();
    domain.brokers = Sets.newHashSet(broker1);
    admin1.clusters().createFailureDomain(cluster, "domain1", domain);
    domain.brokers = Sets.newHashSet(broker2);
    admin1.clusters().createFailureDomain(cluster, "domain1", domain);
    admin1.properties().createProperty(property, new PropertyAdmin(null, Sets.newHashSet(cluster)));
    admin1.namespaces().createNamespace(namespace1);
    admin1.namespaces().createNamespace(namespace2);
    admin1.namespaces().setNamespaceAntiAffinityGroup(namespace1, namespaceAntiAffinityGroup);
    admin1.namespaces().setNamespaceAntiAffinityGroup(namespace2, namespaceAntiAffinityGroup);
    // validate strategically if brokerToDomainCache updated
    for (int i = 0; i < 5; i++) {
        if (!isLoadManagerUpdatedDomainCache(primaryLoadManager) || !isLoadManagerUpdatedDomainCache(secondaryLoadManager) || i != 4) {
            Thread.sleep(200);
        }
    }
    assertTrue(isLoadManagerUpdatedDomainCache(primaryLoadManager));
    assertTrue(isLoadManagerUpdatedDomainCache(secondaryLoadManager));
    ServiceUnitId serviceUnit = makeBundle(property, cluster, "ns1");
    String selectedBroker1 = primaryLoadManager.selectBrokerForAssignment(serviceUnit).get();
    serviceUnit = makeBundle(property, cluster, "ns2");
    String selectedBroker2 = primaryLoadManager.selectBrokerForAssignment(serviceUnit).get();
    assertNotEquals(selectedBroker1, selectedBroker2);
}
Also used : PropertyAdmin(org.apache.pulsar.common.policies.data.PropertyAdmin) FailureDomain(org.apache.pulsar.common.policies.data.FailureDomain) ServiceUnitId(org.apache.pulsar.common.naming.ServiceUnitId) Test(org.testng.annotations.Test)

Aggregations

ServiceUnitId (org.apache.pulsar.common.naming.ServiceUnitId)7 IOException (java.io.IOException)4 PulsarServerException (org.apache.pulsar.broker.PulsarServerException)4 BrokerTopicLoadingPredicate (org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.BrokerTopicLoadingPredicate)4 Maps (com.google.common.collect.Maps)3 DefaultThreadFactory (io.netty.util.concurrent.DefaultThreadFactory)3 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Iterator (java.util.Iterator)3 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Set (java.util.Set)3 Executors (java.util.concurrent.Executors)3 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)3 TimeUnit (java.util.concurrent.TimeUnit)3 ZkUtils (org.apache.bookkeeper.util.ZkUtils)3 SystemUtils (org.apache.commons.lang3.SystemUtils)3 PulsarService (org.apache.pulsar.broker.PulsarService)3