From d21cba6c59c79f78126c71fe3512bea5533aef31 Mon Sep 17 00:00:00 2001 From: Sunil Date: Fri, 19 Aug 2016 21:01:11 +0530 Subject: [PATCH] YARN-2009 --- .../AbstractPreemptableResourceCalculator.java | 208 ++++++++++++++ .../CapacitySchedulerPreemptionContext.java | 7 + .../monitor/capacity/FifoCandidatesSelector.java | 41 --- .../IntraQueuePreemptableResourceCalculator.java | 304 +++++++++++++++++++++ .../capacity/PreemptableResourceCalculator.java | 179 +++--------- .../capacity/PreemptionCandidatesSelector.java | 51 ++++ .../capacity/PriorityCandidatesSelector.java | 200 ++++++++++++++ .../ProportionalCapacityPreemptionPolicy.java | 32 ++- .../monitor/capacity/TempAppPerQueue.java | 157 +++++++++++ .../monitor/capacity/TempQueuePerPartition.java | 4 + .../capacity/CapacitySchedulerConfiguration.java | 20 ++ .../scheduler/capacity/LeafQueue.java | 24 ++ .../scheduler/common/fica/FiCaSchedulerApp.java | 18 ++ 13 files changed, 1064 insertions(+), 181 deletions(-) create mode 100644 hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/AbstractPreemptableResourceCalculator.java create mode 100644 hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/IntraQueuePreemptableResourceCalculator.java create mode 100644 hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PriorityCandidatesSelector.java create mode 100644 hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempAppPerQueue.java diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/AbstractPreemptableResourceCalculator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/AbstractPreemptableResourceCalculator.java new file mode 100644 index 0000000..dd007bc --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/AbstractPreemptableResourceCalculator.java @@ -0,0 +1,208 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.yarn.api.records.ApplicationId; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity.PreemptableResourceCalculator.TQComparator; +import org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity.PriorityCandidatesSelector.AppPriorityComparator; +import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; +import org.apache.hadoop.yarn.util.resource.ResourceCalculator; +import org.apache.hadoop.yarn.util.resource.Resources; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Set; + +/** + * Calculate how much resources need to be preempted for each queue, + * will be used by {@link PreemptionCandidatesSelector} + */ +public class AbstractPreemptableResourceCalculator { + private static final Log LOG = + LogFactory.getLog(AbstractPreemptableResourceCalculator.class); + + protected final CapacitySchedulerPreemptionContext context; + protected final ResourceCalculator rc; + protected boolean isReservedPreemptionCandidatesSelector; + + /** + * PreemptableResourceCalculator constructor + * + * @param preemptionContext + * @param isReservedPreemptionCandidatesSelector this will be set by + * different implementation of candidate selectors, please refer to + * TempQueuePerPartition#offer for details. + */ + public AbstractPreemptableResourceCalculator( + CapacitySchedulerPreemptionContext preemptionContext, + boolean isReservedPreemptionCandidatesSelector) { + context = preemptionContext; + rc = preemptionContext.getResourceCalculator(); + this.isReservedPreemptionCandidatesSelector = + isReservedPreemptionCandidatesSelector; + } + + /** + * Given a set of queues compute the fix-point distribution of unassigned + * resources among them. As pending request of a queue are exhausted, the + * queue is removed from the set and remaining capacity redistributed among + * remaining queues. The distribution is weighted based on guaranteed + * capacity, unless asked to ignoreGuarantee, in which case resources are + * distributed uniformly. + */ + protected void computeFixpointAllocation(ResourceCalculator rc, + Resource tot_guarant, Collection qAlloc, + Resource unassigned, boolean ignoreGuarantee, + Collection underServedQueues) { + // Prior to assigning the unused resources, process each queue as follows: + // If current > guaranteed, idealAssigned = guaranteed + untouchable extra + // Else idealAssigned = current; + // Subtract idealAssigned resources from unassigned. + // If the queue has all of its needs met (that is, if + // idealAssigned >= current + pending), remove it from consideration. + // Sort queues from most under-guaranteed to most over-guaranteed. + TQComparator tqComparator = new TQComparator(rc, tot_guarant); + PriorityQueue orderedByNeed = new PriorityQueue<>(10, + tqComparator); + for (Iterator i = qAlloc.iterator(); i.hasNext();) { + TempQueuePerPartition q = i.next(); + Resource used = q.getUsed(); + + if (Resources.greaterThan(rc, tot_guarant, used, + q.getGuaranteed())) { + q.idealAssigned = Resources.add( + q.getGuaranteed(), q.untouchableExtra); + } else { + q.idealAssigned = Resources.clone(used); + } + Resources.subtractFrom(unassigned, q.idealAssigned); + // If idealAssigned < (allocated + used + pending), q needs more resources, so + // add it to the list of underserved queues, ordered by need. + Resource curPlusPend = Resources.add(q.getUsed(), q.pending); + if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) { + orderedByNeed.add(q); + } + } + + // As per the first round of under-served calculation, get all queues which + // are under-served. Both zero-guaranteed and guaranteed queues at one tree + // level hiearchy will be added to this list. + underServedQueues.addAll(getMostUnderservedQueues(orderedByNeed, tqComparator)); + + //assign all cluster resources until no more demand, or no resources are left + while (!orderedByNeed.isEmpty() + && Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) { + Resource wQassigned = Resource.newInstance(0, 0); + // we compute normalizedGuarantees capacity based on currently active + // queues + resetCapacity(rc, unassigned, orderedByNeed, ignoreGuarantee); + + // For each underserved queue (or set of queues if multiple are equally + // underserved), offer its share of the unassigned resources based on its + // normalized guarantee. After the offer, if the queue is not satisfied, + // place it back in the ordered list of queues, recalculating its place + // in the order of most under-guaranteed to most over-guaranteed. In this + // way, the most underserved queue(s) are always given resources first. + Collection underserved = + getMostUnderservedQueues(orderedByNeed, tqComparator); + for (Iterator i = underserved.iterator(); i + .hasNext();) { + TempQueuePerPartition sub = i.next(); + Resource wQavail = Resources.multiplyAndNormalizeUp(rc, + unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1)); + Resource wQidle = sub.offer(wQavail, rc, tot_guarant, + isReservedPreemptionCandidatesSelector); + Resource wQdone = Resources.subtract(wQavail, wQidle); + + if (Resources.greaterThan(rc, tot_guarant, + wQdone, Resources.none())) { + // The queue is still asking for more. Put it back in the priority + // queue, recalculating its order based on need. + orderedByNeed.add(sub); + } + Resources.addTo(wQassigned, wQdone); + } + Resources.subtractFrom(unassigned, wQassigned); + } + } + + /** + * Computes a normalizedGuaranteed capacity based on active queues + * @param rc resource calculator + * @param clusterResource the total amount of resources in the cluster + * @param queues the list of queues to consider + */ + protected void resetCapacity(ResourceCalculator rc, Resource clusterResource, + Collection queues, boolean ignoreGuar) { + Resource activeCap = Resource.newInstance(0, 0); + + if (ignoreGuar) { + for (TempQueuePerPartition q : queues) { + q.normalizedGuarantee = 1.0f / queues.size(); + } + } else { + for (TempQueuePerPartition q : queues) { + Resources.addTo(activeCap, q.getGuaranteed()); + } + for (TempQueuePerPartition q : queues) { + q.normalizedGuarantee = Resources.divide(rc, clusterResource, + q.getGuaranteed(), activeCap); + } + } + } + + // Take the most underserved TempQueue (the one on the head). Collect and + // return the list of all queues that have the same idealAssigned + // percentage of guaranteed. + protected Collection getMostUnderservedQueues( + PriorityQueue orderedByNeed, + TQComparator tqComparator) { + ArrayList underserved = new ArrayList<>(); + while (!orderedByNeed.isEmpty()) { + TempQueuePerPartition q1 = orderedByNeed.remove(); + underserved.add(q1); + TempQueuePerPartition q2 = orderedByNeed.peek(); + // q1's pct of guaranteed won't be larger than q2's. If it's less, then + // return what has already been collected. Otherwise, q1's pct of + // guaranteed == that of q2, so add q2 to underserved list during the + // next pass. + if (q2 == null || tqComparator.compare(q1,q2) < 0) { + return underserved; + } + } + return underserved; + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/CapacitySchedulerPreemptionContext.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/CapacitySchedulerPreemptionContext.java index c52127d..f700df1 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/CapacitySchedulerPreemptionContext.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/CapacitySchedulerPreemptionContext.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; import org.apache.hadoop.yarn.api.records.ContainerId; +import org.apache.hadoop.yarn.api.records.Resource; import org.apache.hadoop.yarn.server.resourcemanager.RMContext; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; @@ -49,4 +50,10 @@ TempQueuePerPartition getQueueByPartition(String queueName, Set getLeafQueueNames(); Set getAllPartitions(); + + int getClusterMaxApplicationPriority(); + + float getMaxLimitForPreemptableAppsIntraQueue(); + + Resource getPartitionResource(String partition); } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/FifoCandidatesSelector.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/FifoCandidatesSelector.java index 9df395d..59024dd 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/FifoCandidatesSelector.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/FifoCandidatesSelector.java @@ -194,16 +194,6 @@ private void preemptAMContainers(Resource clusterResource, skippedAMContainerlist.clear(); } - private boolean preemptMapContains( - Map> preemptMap, - ApplicationAttemptId attemptId, RMContainer rmContainer) { - Set rmContainers; - if (null == (rmContainers = preemptMap.get(attemptId))) { - return false; - } - return rmContainers.contains(rmContainer); - } - /** * Return should we preempt rmContainer. If we should, deduct from * resourceToObtainByPartition @@ -331,35 +321,4 @@ private void preemptFrom(FiCaSchedulerApp app, clusterResource, selectedContainers, totalPreemptionAllowed); } } - - /** - * Compare by reversed priority order first, and then reversed containerId - * order - * @param containers - */ - @VisibleForTesting - static void sortContainers(List containers){ - Collections.sort(containers, new Comparator() { - @Override - public int compare(RMContainer a, RMContainer b) { - int schedKeyComp = b.getAllocatedSchedulerKey() - .compareTo(a.getAllocatedSchedulerKey()); - if (schedKeyComp != 0) { - return schedKeyComp; - } - return b.getContainerId().compareTo(a.getContainerId()); - } - }); - } - - private void addToPreemptMap( - Map> preemptMap, - ApplicationAttemptId appAttemptId, RMContainer containerToPreempt) { - Set set; - if (null == (set = preemptMap.get(appAttemptId))) { - set = new HashSet<>(); - preemptMap.put(appAttemptId, set); - } - set.add(containerToPreempt); - } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/IntraQueuePreemptableResourceCalculator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/IntraQueuePreemptableResourceCalculator.java new file mode 100644 index 0000000..b3bc8dc --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/IntraQueuePreemptableResourceCalculator.java @@ -0,0 +1,304 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; +import org.apache.hadoop.yarn.util.resource.ResourceCalculator; +import org.apache.hadoop.yarn.util.resource.Resources; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Set; +import java.util.Map.Entry; + +/** + * Calculate how much resources need to be preempted for each queue, + * will be used by {@link PreemptionCandidatesSelector} + */ +public class IntraQueuePreemptableResourceCalculator + extends + AbstractPreemptableResourceCalculator { + private static final Log LOG = LogFactory + .getLog(IntraQueuePreemptableResourceCalculator.class); + + static class TAComparator implements Comparator { + TAComparator(ResourceCalculator rc) { + } + + @Override + public int compare(TempAppPerQueue tq1, TempAppPerQueue tq2) { + if (tq1.getPriority() < tq2.getPriority()) { + return 1; + } + if (tq1.getPriority() > tq2.getPriority()) { + return -1; + } + return 0; + } + } + + /** + * PreemptableResourceCalculator constructor + * + * @param preemptionContext + * @param isReservedPreemptionCandidatesSelector + * this will be set by different implementation of candidate + * selectors, please refer to TempQueuePerPartition#offer for + * details. + */ + public IntraQueuePreemptableResourceCalculator( + CapacitySchedulerPreemptionContext preemptionContext, + boolean isReservedPreemptionCandidatesSelector) { + super(preemptionContext, isReservedPreemptionCandidatesSelector); + } + + public Map> computeIntraQueuePreemptionDemand( + Resource clusterResource, Resource totalPreemptedResourceAllowed, + Map resToObtainByPartition) { + Map> queuesPerPartition = new HashMap>(); + + // 1. Use same inter-queue design to find under-served queues per partition + for (String partition : context.getAllPartitions()) { + TempQueuePerPartition tRoot = context + .getQueueByPartition(CapacitySchedulerConfiguration.ROOT, partition); + + // 2. compute the ideal distribution of resources among queues + // and updates cloned queues state accordingly. Also get the queues + // per partition in most-under served order. + tRoot.idealAssigned = tRoot.getGuaranteed(); + ArrayList tot_queues = new ArrayList(); + recursivelyComputeIdealAssignment(tRoot, totalPreemptedResourceAllowed, + tot_queues); + queuesPerPartition.put(partition, tot_queues); + } + + // Iterate over the partitions again to calculate pending resource of apps + // per partition + for (Entry> entry : queuesPerPartition + .entrySet()) { + String partition = entry.getKey(); + + // This map will store per-partition level resource demand (per queue) + if (!resToObtainByPartition.containsKey(partition)) { + Resource actualPreemptNeeded = Resources.createResource(0, 0); + resToObtainByPartition.put(partition, actualPreemptNeeded); + } + + // per-partition level queues in most under-served order + ArrayList queues = entry.getValue(); + for (LeafQueue leafQueue : queues) { + TempQueuePerPartition tq = context + .getQueueByPartition(leafQueue.getQueueName(), partition); + + // After visiting a queue to get high priority apps, we also ensure that + // all partition based pending resource also has calculated per app + // level inside getResourceDemandFromAppsPerQueue. + // Hence we need not have to consider this queue from other partitions. + if (tq.intraQueuePreemptionCalculationDone == true) { + continue; + } + + // 3. Get all running and pending apps of the queue + Collection apps = leafQueue.getApplications(); + apps.addAll(leafQueue.getPendingApplications()); + + // 4. Get apps from a queue with priority comparator + PriorityQueue appsOrderedByPriority = getStarvingAppsRatioPerQueue( + leafQueue, apps); + + // 5. Calculate demand from high priority apps per partition level. + getResourceDemandFromAppsPerQueue(leafQueue, appsOrderedByPriority, + resToObtainByPartition, + context.getMaxLimitForPreemptableAppsIntraQueue()); + + // Consider this queue as already visited. + tq.intraQueuePreemptionCalculationDone = true; + } + } + + return queuesPerPartition; + } + + private void recursivelyComputeIdealAssignment(TempQueuePerPartition root, + Resource totalPreemptedResourceAllowed, List tot_queues) { + if (root.getChildren() != null && root.getChildren().size() > 0) { + // Find underserved queues at each level. This will be same as children of + // queue + // arranged in most under-served order. + List underServedQueues = new ArrayList(); + + // compute ideal distribution at this level + computeIdealResourceDistribution(rc, root, root.getChildren(), + totalPreemptedResourceAllowed, root.idealAssigned, underServedQueues, + tot_queues); + + // compute recursively for lower levels and build list of leafs. + // Ensured underServedQueues is nothing but root.getChildren() ordered + // with under-served property. + for (TempQueuePerPartition t : underServedQueues) { + recursivelyComputeIdealAssignment(t, totalPreemptedResourceAllowed, + tot_queues); + } + } + } + + private void computeIdealResourceDistribution(ResourceCalculator rc, + TempQueuePerPartition root, ArrayList children, + Resource totalPreemptedResourceAllowed, Resource tot_guarant, + List underServedQueues, + List fullQueues) { + + // qAlloc tracks currently active queues (will decrease progressively as + // demand is met) + List qAlloc = new ArrayList<>(children); + // unassigned tracks how much resources are still to assign, initialized + // with the total capacity for this set of queues + Resource unassigned = Resources.clone(tot_guarant); + + // group queues based on whether they have non-zero guaranteed capacity + Set nonZeroGuarQueues = new HashSet<>(); + Set zeroGuarQueues = new HashSet<>(); + + for (TempQueuePerPartition q : qAlloc) { + if (Resources.greaterThan(rc, tot_guarant, q.getGuaranteed(), + Resources.none())) { + nonZeroGuarQueues.add(q); + } else { + zeroGuarQueues.add(q); + } + } + + // first compute the allocation as a fixpoint based on guaranteed capacity + computeFixpointAllocation(rc, tot_guarant, nonZeroGuarQueues, unassigned, + false, underServedQueues); + + // if any capacity is left unassigned, distributed among zero-guarantee + // queues uniformly (i.e., not based on guaranteed capacity, as this is + // zero) + if (!zeroGuarQueues.isEmpty() && Resources.greaterThan(rc, tot_guarant, + unassigned, Resources.none())) { + computeFixpointAllocation(rc, tot_guarant, zeroGuarQueues, unassigned, + true, underServedQueues); + } else { + // We need to add zeroGuarQueues to underServedQueues list as we need to + // iterate over whole children of a queue. + if (!zeroGuarQueues.isEmpty()) { + // Since zeroGuarQueues is added to the end of list, this queue will be + // maintaining its under-served nature (first queue in this list will + // most under-served) + underServedQueues.addAll(zeroGuarQueues); + } + } + + // We are hitting a leafqueue now which is under-served. This will be + // hitting in the order of most under-served first. Add to list. + if (root.leafQueue != null) { + fullQueues.add(root.leafQueue); + } + } + + public PriorityQueue getStarvingAppsRatioPerQueue(LeafQueue q, + Collection apps) { + TAComparator taComparator = new TAComparator(rc); + PriorityQueue orderedByPriority = new PriorityQueue<>(10, + taComparator); + + // have an internal temp app structure to store intermediate data (priority) + for (FiCaSchedulerApp app : apps) { + + // Create TempAppPerQueue for further calculatuion. + TempAppPerQueue tmpApp = new TempAppPerQueue(app.getQueueName(), + app.getApplicationId(), app.getCurrentConsumption(), + Resources.createResource(0, 0), null, app.getCurrentReservation(), + app.getTotalPendingRequests(), + (HashMap) app.getTotalPendingRequestsPerPartition(), + app.getPriority().getPriority(), app); + + // Skip an app which doesn't have any outstanding resource requests + if (Resources.lessThanOrEqual(rc, Resources.none(), + app.getTotalPendingRequests(), Resources.none())) { + continue; + } + orderedByPriority.add(tmpApp); + } + + return orderedByPriority; + } + + private LinkedList getResourceDemandFromAppsPerQueue( + LeafQueue leafQueue, PriorityQueue perQueueApps, + Map resToObtainByPartition, + float maxPreemptableApssLimit) { + Resource actualPreemptNeeded = null; + + LinkedList highPriorityApps = new LinkedList(); + int maxPreemptableApps = (int) (maxPreemptableApssLimit + * perQueueApps.size()); + int preemptableAppsCounter = 0; + + while (!perQueueApps.isEmpty()) { + TempAppPerQueue a1 = perQueueApps.remove(); + highPriorityApps.add(a1); + + // Identify how much pending resource is there. Add to actualPreemptNeeded + if (preemptableAppsCounter < maxPreemptableApps) { + // For each app, add pending resource request per partition level to + // resToObtainByPartition. + for (Entry entry : a1.getPendingPerPartition() + .entrySet()) { + String partition = entry.getKey(); + + // Can skip apps which are already crossing user-limit. + // For this, Get the userlimit from scheduler and ensure that app is + // not crossing userlimit here. Such apps can be skipped. + Resource userHeadroom = leafQueue.getUserLimitHeadRoomPerApp( + a1.getFiCaSchedulerApp(), context.getPartitionResource(partition), + partition); + if (Resources.lessThanOrEqual(rc, + context.getPartitionResource(partition), userHeadroom, + Resources.none())) { + continue; + } + + // Updating pending resource per-partition level. + if ((actualPreemptNeeded = resToObtainByPartition + .get(partition)) != null) { + Resources.addTo(actualPreemptNeeded, + a1.getPendingPerPartition().get(partition)); + } + } + } + preemptableAppsCounter++; + } + + return highPriorityApps; + } +} \ No newline at end of file diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptableResourceCalculator.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptableResourceCalculator.java index d1d2485..26169af 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptableResourceCalculator.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptableResourceCalculator.java @@ -20,18 +20,28 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity.PriorityCandidatesSelector.AppPriorityComparator; import org.apache.hadoop.yarn.server.resourcemanager.nodelabels.RMNodeLabelsManager; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySchedulerConfiguration; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; import org.apache.hadoop.yarn.util.resource.Resources; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.Comparator; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.PriorityQueue; import java.util.Set; @@ -39,12 +49,12 @@ * Calculate how much resources need to be preempted for each queue, * will be used by {@link PreemptionCandidatesSelector} */ -public class PreemptableResourceCalculator { +public class PreemptableResourceCalculator + extends + AbstractPreemptableResourceCalculator { private static final Log LOG = LogFactory.getLog(PreemptableResourceCalculator.class); - private final CapacitySchedulerPreemptionContext context; - private final ResourceCalculator rc; private boolean isReservedPreemptionCandidatesSelector; static class TQComparator implements Comparator { @@ -82,6 +92,25 @@ private double getIdealPctOfGuaranteed(TempQueuePerPartition q) { } } + static class TAComparator implements Comparator { + private ResourceCalculator rc; + + TAComparator(ResourceCalculator rc) { + this.rc = rc; + } + + @Override + public int compare(TempAppPerQueue tq1, TempAppPerQueue tq2) { + if (tq1.getPriority() < tq2.getPriority()) { + return 1; + } + if (tq1.getPriority() > tq2.getPriority()) { + return -1; + } + return 0; + } + } + /** * PreemptableResourceCalculator constructor * @@ -93,136 +122,7 @@ private double getIdealPctOfGuaranteed(TempQueuePerPartition q) { public PreemptableResourceCalculator( CapacitySchedulerPreemptionContext preemptionContext, boolean isReservedPreemptionCandidatesSelector) { - context = preemptionContext; - rc = preemptionContext.getResourceCalculator(); - this.isReservedPreemptionCandidatesSelector = - isReservedPreemptionCandidatesSelector; - } - - /** - * Computes a normalizedGuaranteed capacity based on active queues - * @param rc resource calculator - * @param clusterResource the total amount of resources in the cluster - * @param queues the list of queues to consider - */ - private void resetCapacity(ResourceCalculator rc, Resource clusterResource, - Collection queues, boolean ignoreGuar) { - Resource activeCap = Resource.newInstance(0, 0); - - if (ignoreGuar) { - for (TempQueuePerPartition q : queues) { - q.normalizedGuarantee = 1.0f / queues.size(); - } - } else { - for (TempQueuePerPartition q : queues) { - Resources.addTo(activeCap, q.getGuaranteed()); - } - for (TempQueuePerPartition q : queues) { - q.normalizedGuarantee = Resources.divide(rc, clusterResource, - q.getGuaranteed(), activeCap); - } - } - } - - // Take the most underserved TempQueue (the one on the head). Collect and - // return the list of all queues that have the same idealAssigned - // percentage of guaranteed. - protected Collection getMostUnderservedQueues( - PriorityQueue orderedByNeed, - TQComparator tqComparator) { - ArrayList underserved = new ArrayList<>(); - while (!orderedByNeed.isEmpty()) { - TempQueuePerPartition q1 = orderedByNeed.remove(); - underserved.add(q1); - TempQueuePerPartition q2 = orderedByNeed.peek(); - // q1's pct of guaranteed won't be larger than q2's. If it's less, then - // return what has already been collected. Otherwise, q1's pct of - // guaranteed == that of q2, so add q2 to underserved list during the - // next pass. - if (q2 == null || tqComparator.compare(q1,q2) < 0) { - return underserved; - } - } - return underserved; - } - - - /** - * Given a set of queues compute the fix-point distribution of unassigned - * resources among them. As pending request of a queue are exhausted, the - * queue is removed from the set and remaining capacity redistributed among - * remaining queues. The distribution is weighted based on guaranteed - * capacity, unless asked to ignoreGuarantee, in which case resources are - * distributed uniformly. - */ - private void computeFixpointAllocation(ResourceCalculator rc, - Resource tot_guarant, Collection qAlloc, - Resource unassigned, boolean ignoreGuarantee) { - // Prior to assigning the unused resources, process each queue as follows: - // If current > guaranteed, idealAssigned = guaranteed + untouchable extra - // Else idealAssigned = current; - // Subtract idealAssigned resources from unassigned. - // If the queue has all of its needs met (that is, if - // idealAssigned >= current + pending), remove it from consideration. - // Sort queues from most under-guaranteed to most over-guaranteed. - TQComparator tqComparator = new TQComparator(rc, tot_guarant); - PriorityQueue orderedByNeed = new PriorityQueue<>(10, - tqComparator); - for (Iterator i = qAlloc.iterator(); i.hasNext();) { - TempQueuePerPartition q = i.next(); - Resource used = q.getUsed(); - - if (Resources.greaterThan(rc, tot_guarant, used, - q.getGuaranteed())) { - q.idealAssigned = Resources.add( - q.getGuaranteed(), q.untouchableExtra); - } else { - q.idealAssigned = Resources.clone(used); - } - Resources.subtractFrom(unassigned, q.idealAssigned); - // If idealAssigned < (allocated + used + pending), q needs more resources, so - // add it to the list of underserved queues, ordered by need. - Resource curPlusPend = Resources.add(q.getUsed(), q.pending); - if (Resources.lessThan(rc, tot_guarant, q.idealAssigned, curPlusPend)) { - orderedByNeed.add(q); - } - } - - //assign all cluster resources until no more demand, or no resources are left - while (!orderedByNeed.isEmpty() - && Resources.greaterThan(rc,tot_guarant, unassigned,Resources.none())) { - Resource wQassigned = Resource.newInstance(0, 0); - // we compute normalizedGuarantees capacity based on currently active - // queues - resetCapacity(rc, unassigned, orderedByNeed, ignoreGuarantee); - - // For each underserved queue (or set of queues if multiple are equally - // underserved), offer its share of the unassigned resources based on its - // normalized guarantee. After the offer, if the queue is not satisfied, - // place it back in the ordered list of queues, recalculating its place - // in the order of most under-guaranteed to most over-guaranteed. In this - // way, the most underserved queue(s) are always given resources first. - Collection underserved = - getMostUnderservedQueues(orderedByNeed, tqComparator); - for (Iterator i = underserved.iterator(); i - .hasNext();) { - TempQueuePerPartition sub = i.next(); - Resource wQavail = Resources.multiplyAndNormalizeUp(rc, - unassigned, sub.normalizedGuarantee, Resource.newInstance(1, 1)); - Resource wQidle = sub.offer(wQavail, rc, tot_guarant, - isReservedPreemptionCandidatesSelector); - Resource wQdone = Resources.subtract(wQavail, wQidle); - - if (Resources.greaterThan(rc, tot_guarant, - wQdone, Resources.none())) { - // The queue is still asking for more. Put it back in the priority - // queue, recalculating its order based on need. - orderedByNeed.add(sub); - } - Resources.addTo(wQassigned, wQdone); - } - Resources.subtractFrom(unassigned, wQassigned); - } + super(preemptionContext, isReservedPreemptionCandidatesSelector); } /** @@ -240,7 +140,7 @@ private void computeFixpointAllocation(ResourceCalculator rc, */ private void computeIdealResourceDistribution(ResourceCalculator rc, List queues, Resource totalPreemptionAllowed, - Resource tot_guarant) { + Resource tot_guarant, List underServedQueues) { // qAlloc tracks currently active queues (will decrease progressively as // demand is met) @@ -264,14 +164,14 @@ private void computeIdealResourceDistribution(ResourceCalculator rc, // first compute the allocation as a fixpoint based on guaranteed capacity computeFixpointAllocation(rc, tot_guarant, nonZeroGuarQueues, unassigned, - false); + false, underServedQueues); // if any capacity is left unassigned, distributed among zero-guarantee // queues uniformly (i.e., not based on guaranteed capacity, as this is zero) if (!zeroGuarQueues.isEmpty() && Resources.greaterThan(rc, tot_guarant, unassigned, Resources.none())) { computeFixpointAllocation(rc, tot_guarant, zeroGuarQueues, unassigned, - true); + true, underServedQueues); } // based on ideal assignment computed above and current assignment we derive @@ -317,17 +217,18 @@ private void recursivelyComputeIdealAssignment( TempQueuePerPartition root, Resource totalPreemptionAllowed) { if (root.getChildren() != null && root.getChildren().size() > 0) { + List underServedQueues = + new ArrayList(); // compute ideal distribution at this level computeIdealResourceDistribution(rc, root.getChildren(), - totalPreemptionAllowed, root.idealAssigned); + totalPreemptionAllowed, root.idealAssigned, underServedQueues); // compute recursively for lower levels and build list of leafs - for(TempQueuePerPartition t : root.getChildren()) { + for (TempQueuePerPartition t : root.getChildren()) { recursivelyComputeIdealAssignment(t, totalPreemptionAllowed); } } } - private void calculateResToObtainByPartitionForLeafQueues( Set leafQueueNames, Resource clusterResource) { // Loop all leaf queues diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptionCandidatesSelector.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptionCandidatesSelector.java index dd33d8f..36b4961 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptionCandidatesSelector.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PreemptionCandidatesSelector.java @@ -23,6 +23,12 @@ import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; import org.apache.hadoop.yarn.util.resource.ResourceCalculator; +import com.google.common.annotations.VisibleForTesting; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; @@ -49,4 +55,49 @@ public abstract Map> selectCandidates( Map> selectedCandidates, Resource clusterResource, Resource totalPreemptedResourceAllowed); + + /** + * Compare by reversed priority order first, and then reversed containerId + * order + * + * @param containers + */ + // ToDo: reuse form FiFoCandidatesSelector + @VisibleForTesting + static void sortContainers(List containers) { + Collections.sort(containers, new Comparator() { + @Override + public int compare(RMContainer a, RMContainer b) { + int schedKeyComp = b.getAllocatedSchedulerKey() + .compareTo(a.getAllocatedSchedulerKey()); + if (schedKeyComp != 0) { + return schedKeyComp; + } + return b.getContainerId().compareTo(a.getContainerId()); + } + }); + } + + // ToDo: reuse form FiFoCandidatesSelector + protected void addToPreemptMap( + Map> preemptMap, + ApplicationAttemptId appAttemptId, RMContainer containerToPreempt) { + Set set; + if (null == (set = preemptMap.get(appAttemptId))) { + set = new HashSet<>(); + preemptMap.put(appAttemptId, set); + } + set.add(containerToPreempt); + } + + // ToDo: reuse form FiFoCandidatesSelector + protected boolean preemptMapContains( + Map> preemptMap, + ApplicationAttemptId attemptId, RMContainer rmContainer) { + Set rmContainers; + if (null == (rmContainers = preemptMap.get(attemptId))) { + return false; + } + return rmContainers.contains(rmContainer); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PriorityCandidatesSelector.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PriorityCandidatesSelector.java new file mode 100644 index 0000000..1f670c5 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/PriorityCandidatesSelector.java @@ -0,0 +1,200 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.hadoop.yarn.api.records.ApplicationAttemptId; +import org.apache.hadoop.yarn.api.records.NodeId; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.server.resourcemanager.rmcontainer.RMContainer; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; +import org.apache.hadoop.yarn.util.resource.Resources; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; + +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + + +public class PriorityCandidatesSelector extends PreemptionCandidatesSelector { + private static final Log LOG = LogFactory + .getLog(PriorityCandidatesSelector.class); + + private IntraQueuePreemptableResourceCalculator intraQPreemptableAmountCalculator; + + PriorityCandidatesSelector( + CapacitySchedulerPreemptionContext preemptionContext) { + super(preemptionContext); + intraQPreemptableAmountCalculator = new IntraQueuePreemptableResourceCalculator( + preemptionContext, true); + } + + static class AppPriorityComparator implements Comparator { + + @Override + public int compare(LeafQueue tq1, LeafQueue tq2) { + if (tq1.getIntraQueuePreemptionCost() < tq2 + .getIntraQueuePreemptionCost()) { + return 1; + } + if (tq1.getIntraQueuePreemptionCost() > tq2 + .getIntraQueuePreemptionCost()) { + return -1; + } + return 0; + } + } + + @Override + public Map> selectCandidates( + Map> selectedCandidates, + Resource clusterResource, Resource totalPreemptedResourceAllowed) { + + Map resToObtainByPartition = new HashMap(); + + // Calculate the abnormality within each queue one by one. + // Get back Partition -> underserved queues mappings + Map> partitionToUnderServedQueues = intraQPreemptableAmountCalculator + .computeIntraQueuePreemptionDemand(clusterResource, + totalPreemptedResourceAllowed, resToObtainByPartition); + + // Loop all partitions + for (String partition : preemptionContext.getAllPartitions()) { + ArrayList queues = partitionToUnderServedQueues.get(partition); + + // Iterate from most under-served in order. + for (LeafQueue leafQueue : queues) { + // if more resources are to be freed, go through all live containers in + // reverse priority and reverse allocation order and mark them for + // preemption + Iterator desc = + leafQueue.getOrderingPolicy().getPreemptionIterator(); + while (desc.hasNext()) { + FiCaSchedulerApp app = desc.next(); + + preemptFromLeastStarvedApp(selectedCandidates, clusterResource, + totalPreemptedResourceAllowed, resToObtainByPartition, leafQueue, + app); + } + } + } + + return selectedCandidates; + } + + private void preemptFromLeastStarvedApp( + Map> selectedCandidates, + Resource clusterResource, Resource totalPreemptedResourceAllowed, + Map resToObtainByPartition, LeafQueue leafQueue, FiCaSchedulerApp app) { + + // ToDo: + // 1. Reuse reservation selector here. + + List liveContainers = new ArrayList<>( + app.getLiveContainers()); + sortContainers(liveContainers); + + for (RMContainer c : liveContainers) { + String nodePartition = getPartitionByNodeId(c.getAllocatedNode()); + Resource toObtainByPartition = resToObtainByPartition.get(nodePartition); + + // When we have no more resource need to obtain, remove from map. + if (Resources.lessThanOrEqual(rc, clusterResource, toObtainByPartition, + Resources.none())) { + resToObtainByPartition.remove(nodePartition); + } + if (CapacitySchedulerPreemptionUtils.isContainerAlreadySelected(c, + selectedCandidates)) { + Resources.subtractFrom(toObtainByPartition, c.getAllocatedResource()); + Resources.subtractFrom(toObtainByPartition, c.getAllocatedResource()); + continue; + } + + // Skip already marked to killable containers + if (null != preemptionContext.getKillableContainers() && preemptionContext + .getKillableContainers().contains(c.getContainerId())) { + continue; + } + + // Skip AM Container from preemption for now. + // ToDo: Need to decide whether intra preemption need to take AM containers + // or not. + if (c.isAMContainer()) { + continue; + } + + // Try to preempt this container + tryPreemptContainerAndDeductResToObtain(toObtainByPartition, c, + clusterResource, selectedCandidates, totalPreemptedResourceAllowed); + } + } + + private String getPartitionByNodeId(NodeId nodeId) { + return preemptionContext.getScheduler().getSchedulerNode(nodeId) + .getPartition(); + } + + + /** + * Return should we preempt rmContainer. If we should, deduct from + * resourceToObtainByPartition + */ + private boolean tryPreemptContainerAndDeductResToObtain( + Resource actualPreemptNeeded, RMContainer rmContainer, + Resource clusterResource, + Map> preemptMap, + Resource totalPreemptionAllowed) { + ApplicationAttemptId attemptId = rmContainer.getApplicationAttemptId(); + + // We will not account resource of a container twice or more + if (preemptMapContains(preemptMap, attemptId, rmContainer)) { + return false; + } + + Resource toObtainByPartition = actualPreemptNeeded; + + if (null != toObtainByPartition + && Resources.greaterThan(rc, clusterResource, toObtainByPartition, + Resources.none()) + && Resources.fitsIn(rc, clusterResource, + rmContainer.getAllocatedResource(), totalPreemptionAllowed)) { + Resources.subtractFrom(toObtainByPartition, + rmContainer.getAllocatedResource()); + Resources.subtractFrom(totalPreemptionAllowed, + rmContainer.getAllocatedResource()); + + if (LOG.isDebugEnabled()) { + LOG.debug(this.getClass().getName() + " Marked container=" + + rmContainer.getContainerId() + " queue=" + + rmContainer.getQueueName() + " to be preemption candidates"); + } + // Add to preemptMap + addToPreemptMap(preemptMap, attemptId, rmContainer); + return true; + } + + return false; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java index 36383502..5448ae9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/ProportionalCapacityPreemptionPolicy.java @@ -91,6 +91,8 @@ private boolean observeOnly; private boolean lazyPreempionEnabled; + private float maxLimitForPreemptableAppsIntraQueue; + // Pointer to other RM components private RMContext rmContext; private ResourceCalculator rc; @@ -171,6 +173,10 @@ public void init(Configuration config, RMContext context, CapacitySchedulerConfiguration.LAZY_PREEMPTION_ENALBED, CapacitySchedulerConfiguration.DEFAULT_LAZY_PREEMPTION_ENABLED); + maxLimitForPreemptableAppsIntraQueue = csConfig.getFloat( + CapacitySchedulerConfiguration.INTRAQUEUE_MAXIMUM_PREEMPTABLE_APPS_LIMIT, + CapacitySchedulerConfiguration.DEFAULT_INTRAQUEUE_MAXIMUM_PREEMPTABLE_APPS_LIMIT); + rc = scheduler.getResourceCalculator(); nlm = scheduler.getRMContext().getNodeLabelManager(); @@ -186,8 +192,16 @@ public void init(Configuration config, RMContext context, // initialize candidates preemption selection policies candidatesSelectionPolicies.add( new FifoCandidatesSelector(this)); + + // Do we need to specially consider reserved containers? + boolean selectIntraQueuePreemptCandidatesByPriority = csConfig.getBoolean( + CapacitySchedulerConfiguration.PREEMPTION_SELECT_INTRAQUEUE_CANDIDATES_BY_APP_PRIORITY, + CapacitySchedulerConfiguration.DEFAULT_PREEMPTION_SELECT_INTRAQUEUE_CANDIDATES_BY_APP_PRIORITY); + if (selectIntraQueuePreemptCandidatesByPriority) { + candidatesSelectionPolicies.add(new PriorityCandidatesSelector(this)); + } } - + @Override public ResourceCalculator getResourceCalculator() { return rc; @@ -542,4 +556,20 @@ public double getNaturalTerminationFactor() { Map> getQueuePartitions() { return queueToPartitions; } + + @Override + public int getClusterMaxApplicationPriority() { + return scheduler.getMaxClusterLevelAppPriority().getPriority(); + } + + @Override + public float getMaxLimitForPreemptableAppsIntraQueue() { + return maxLimitForPreemptableAppsIntraQueue; + } + + @Override + public Resource getPartitionResource(String partition) { + return Resources.clone(nlm.getResourceByLabel(partition, + Resources.clone(scheduler.getClusterResource()))); + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempAppPerQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempAppPerQueue.java new file mode 100644 index 0000000..45080f9 --- /dev/null +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempAppPerQueue.java @@ -0,0 +1,157 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.yarn.server.resourcemanager.monitor.capacity; + +import org.apache.hadoop.yarn.api.records.ApplicationId; +import org.apache.hadoop.yarn.api.records.Resource; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CSQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue; +import org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica.FiCaSchedulerApp; +import org.apache.hadoop.yarn.util.resource.ResourceCalculator; +import org.apache.hadoop.yarn.util.resource.Resources; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Temporary data-structure tracking resource availability, pending resource + * need, current utilization for an application. + */ +public class TempAppPerQueue { + // Following fields are copied from scheduler + final String queueName; + final Resource pending; + final HashMap pendingPerPartition; + + private final Resource current; + private final Resource killable; + private final Resource reserved; + + // Following fields are settled and used by candidate selection policies + Resource idealAssigned; + Resource toBePreempted; + Resource untouchableExtra; + Resource preemptableExtra; + private Resource actuallyToBePreempted; + + private final int priority; + private final ApplicationId applicationId; + LeafQueue leafQueue; + FiCaSchedulerApp app; + + TempAppPerQueue(String queueName, ApplicationId applicationId, + Resource current, Resource killable, Resource totalPartitionResource, + Resource reserved, Resource pending, + HashMap pendingPerPartition, int priority, FiCaSchedulerApp app) { + this.queueName = queueName; + this.current = current; + this.pending = pending; + this.pendingPerPartition = pendingPerPartition; + + this.idealAssigned = Resource.newInstance(0, 0); + this.actuallyToBePreempted = Resource.newInstance(0, 0); + this.toBePreempted = Resource.newInstance(0, 0); + this.untouchableExtra = Resource.newInstance(0, 0); + this.preemptableExtra = Resource.newInstance(0, 0); + + this.killable = killable; + this.reserved = reserved; + this.priority = priority; + this.applicationId = applicationId; + this.app = app; + } + + public void setLeafQueue(LeafQueue l) { + this.leafQueue = l; + } + + public Resource getUsed() { + return current; + } + + public Resource getUsedDeductReservd() { + return Resources.subtract(current, reserved); + } + + public HashMap getPendingPerPartition() { + return pendingPerPartition; + } + + public FiCaSchedulerApp getFiCaSchedulerApp() { + return app; + } + + public Resource getGuaranteed() { + return Resources.none(); + } + public void updatePreemptableExtras(ResourceCalculator rc) { + // Reset untouchableExtra and preemptableExtra + untouchableExtra = Resources.none(); + preemptableExtra = Resources.none(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(" NAME: " + queueName).append(" CUR: ").append(current) + .append(" PEN: ").append(pending).append(" RESERVED: ").append(reserved) + .append(" IDEAL_ASSIGNED: ").append(idealAssigned) + .append(" IDEAL_PREEMPT: ").append(toBePreempted) + .append(" ACTUAL_PREEMPT: ").append(actuallyToBePreempted) + .append(" UNTOUCHABLE: ").append(untouchableExtra) + .append(" PREEMPTABLE: ").append(preemptableExtra).append("\n"); + + return sb.toString(); + } + + + public Resource getActuallyToBePreempted() { + return actuallyToBePreempted; + } + + public void setActuallyToBePreempted(Resource res) { + this.actuallyToBePreempted = res; + } + + void appendLogString(StringBuilder sb) { + sb.append(queueName).append(", ").append(current.getMemorySize()) + .append(", ").append(current.getVirtualCores()).append(", ") + .append(pending.getMemorySize()).append(", ") + .append(pending.getVirtualCores()).append(", ") + .append(getGuaranteed().getMemorySize()).append(", ") + .append(getGuaranteed().getVirtualCores()).append(", ") + .append(idealAssigned.getMemorySize()).append(", ") + .append(idealAssigned.getVirtualCores()).append(", ") + .append(toBePreempted.getMemorySize()).append(", ") + .append(toBePreempted.getVirtualCores()).append(", ") + .append(actuallyToBePreempted.getMemorySize()).append(", ") + .append(actuallyToBePreempted.getVirtualCores()); + } + + public int getPriority() { + return priority; + } + + public ApplicationId getApplicationId() { + return applicationId; + } +} diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempQueuePerPartition.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempQueuePerPartition.java index 04ed135..6ab4ce9 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempQueuePerPartition.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/monitor/capacity/TempQueuePerPartition.java @@ -51,8 +51,10 @@ private Resource actuallyToBePreempted; double normalizedGuarantee; + boolean intraQueuePreemptionCalculationDone; final ArrayList children; + private ArrayList apps; LeafQueue leafQueue; boolean preemptionDisabled; @@ -77,6 +79,7 @@ this.toBePreempted = Resource.newInstance(0, 0); this.normalizedGuarantee = Float.NaN; this.children = new ArrayList<>(); + this.apps = new ArrayList<>(); this.untouchableExtra = Resource.newInstance(0, 0); this.preemptableExtra = Resource.newInstance(0, 0); this.preemptionDisabled = preemptionDisabled; @@ -86,6 +89,7 @@ this.absMaxCapacity = absMaxCapacity; this.totalPartitionResource = totalPartitionResource; this.reserved = reserved; + this.intraQueuePreemptionCalculationDone = false; } public void setLeafQueue(LeafQueue l) { diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java index d5d1374..3f5397f 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/CapacitySchedulerConfiguration.java @@ -1077,4 +1077,24 @@ public boolean getLazyPreemptionEnabled() { PREEMPTION_CONFIG_PREFIX + "select_based_on_reserved_containers"; public static final boolean DEFAULT_PREEMPTION_SELECT_CANDIDATES_FOR_RESERVED_CONTAINERS = false; + + /** + * For intra-queue preemption, priority based selector can help to preempt + * containers of lowest priority apps to find resources for high priority + * apps. + */ + public static final String PREEMPTION_SELECT_INTRAQUEUE_CANDIDATES_BY_APP_PRIORITY = + PREEMPTION_CONFIG_PREFIX + + "select_based_on_priority_of_applications"; + public static final boolean DEFAULT_PREEMPTION_SELECT_INTRAQUEUE_CANDIDATES_BY_APP_PRIORITY = + true; // Change to false later. + + /** + * For intra-queue preemption, we should not try to consider all the demand from + * high priority apps in one shot. Certain percentage of active apps can only + * be considered per round. + */ + public static final String INTRAQUEUE_MAXIMUM_PREEMPTABLE_APPS_LIMIT = + PREEMPTION_CONFIG_PREFIX + "intraqueue_max_preemptable_app_limit"; + public static final float DEFAULT_INTRAQUEUE_MAXIMUM_PREEMPTABLE_APPS_LIMIT = 0.3f; } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java index 9aae909..35fefda 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/LeafQueue.java @@ -123,6 +123,7 @@ private OrderingPolicy orderingPolicy = null; + private volatile float intraQueuePreemptionCost = 0f; // record all ignore partition exclusivityRMContainer, this will be used to do // preemption, key is the partition of the RMContainer allocated on private Map> ignorePartitionExclusivityRMContainers = @@ -1664,6 +1665,21 @@ public synchronized Resource getTotalPendingResourcesConsideringUserLimit( return pendingConsideringUserLimit; } + public synchronized Resource getUserLimitHeadRoomPerApp(FiCaSchedulerApp app, + Resource resources, String partition) { + + String userName = app.getUser(); + User user = getUser(userName); + Resource headroom = Resources.subtract( + computeUserLimit(app, resources, user, partition, + SchedulingMode.RESPECT_PARTITION_EXCLUSIVITY), + user.getUsed(partition)); + // Make sure headroom is not negative. + headroom = Resources.componentwiseMax(headroom, Resources.none()); + + return headroom; + } + @Override public synchronized void collectSchedulerApplications( Collection apps) { @@ -1861,4 +1877,12 @@ public Resource getClusterResource() { return clusterResource; } } + + public void updateIntraQueuePreemptionCost(float cost) { + this.intraQueuePreemptionCost = cost; + } + + public float getIntraQueuePreemptionCost() { + return intraQueuePreemptionCost; + } } diff --git a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/fica/FiCaSchedulerApp.java b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/fica/FiCaSchedulerApp.java index 67d93a4..3b16ff7 100644 --- a/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/fica/FiCaSchedulerApp.java +++ b/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/common/fica/FiCaSchedulerApp.java @@ -19,6 +19,7 @@ package org.apache.hadoop.yarn.server.resourcemanager.scheduler.common.fica; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -314,6 +315,23 @@ public synchronized Resource getTotalPendingRequests() { return ret; } + public synchronized Map getTotalPendingRequestsPerPartition() { + + Map ret = new HashMap(); + Resource res = null; + for (SchedulerRequestKey key : appSchedulingInfo.getSchedulerKeys()) { + ResourceRequest rr = appSchedulingInfo.getResourceRequest(key, "*"); + if ((res = ret.get(rr.getNodeLabelExpression())) == null) { + res = Resources.createResource(0, 0); + ret.put(rr.getNodeLabelExpression(), res); + } + + Resources.addTo(res, + Resources.multiply(rr.getCapability(), rr.getNumContainers())); + } + return ret; + } + public synchronized void markContainerForPreemption(ContainerId cont) { // ignore already completed containers if (liveContainers.containsKey(cont)) { -- 2.7.4 (Apple Git-66)