generic_scheduler.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package core
  14. import (
  15. "context"
  16. "fmt"
  17. "math"
  18. "sort"
  19. "strings"
  20. "sync"
  21. "sync/atomic"
  22. "time"
  23. "k8s.io/klog"
  24. v1 "k8s.io/api/core/v1"
  25. policy "k8s.io/api/policy/v1beta1"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/labels"
  28. "k8s.io/apimachinery/pkg/util/errors"
  29. corelisters "k8s.io/client-go/listers/core/v1"
  30. "k8s.io/client-go/util/workqueue"
  31. "k8s.io/kubernetes/pkg/scheduler/algorithm"
  32. "k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
  33. "k8s.io/kubernetes/pkg/scheduler/algorithm/priorities"
  34. schedulerapi "k8s.io/kubernetes/pkg/scheduler/api"
  35. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  36. internalcache "k8s.io/kubernetes/pkg/scheduler/internal/cache"
  37. internalqueue "k8s.io/kubernetes/pkg/scheduler/internal/queue"
  38. "k8s.io/kubernetes/pkg/scheduler/metrics"
  39. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  40. "k8s.io/kubernetes/pkg/scheduler/util"
  41. "k8s.io/kubernetes/pkg/scheduler/volumebinder"
  42. utiltrace "k8s.io/utils/trace"
  43. )
  44. const (
  45. // minFeasibleNodesToFind is the minimum number of nodes that would be scored
  46. // in each scheduling cycle. This is a semi-arbitrary value to ensure that a
  47. // certain minimum of nodes are checked for feasibility. This in turn helps
  48. // ensure a minimum level of spreading.
  49. minFeasibleNodesToFind = 100
  50. // minFeasibleNodesPercentageToFind is the minimum percentage of nodes that
  51. // would be scored in each scheduling cycle. This is a semi-arbitrary value
  52. // to ensure that a certain minimum of nodes are checked for feasibility.
  53. // This in turn helps ensure a minimum level of spreading.
  54. minFeasibleNodesPercentageToFind = 5
  55. )
  56. var unresolvablePredicateFailureErrors = map[predicates.PredicateFailureReason]struct{}{
  57. predicates.ErrNodeSelectorNotMatch: {},
  58. predicates.ErrPodAffinityRulesNotMatch: {},
  59. predicates.ErrPodNotMatchHostName: {},
  60. predicates.ErrTaintsTolerationsNotMatch: {},
  61. predicates.ErrNodeLabelPresenceViolated: {},
  62. // Node conditions won't change when scheduler simulates removal of preemption victims.
  63. // So, it is pointless to try nodes that have not been able to host the pod due to node
  64. // conditions. These include ErrNodeNotReady, ErrNodeUnderPIDPressure, ErrNodeUnderMemoryPressure, ....
  65. predicates.ErrNodeNotReady: {},
  66. predicates.ErrNodeNetworkUnavailable: {},
  67. predicates.ErrNodeUnderDiskPressure: {},
  68. predicates.ErrNodeUnderPIDPressure: {},
  69. predicates.ErrNodeUnderMemoryPressure: {},
  70. predicates.ErrNodeUnschedulable: {},
  71. predicates.ErrNodeUnknownCondition: {},
  72. predicates.ErrVolumeZoneConflict: {},
  73. predicates.ErrVolumeNodeConflict: {},
  74. predicates.ErrVolumeBindConflict: {},
  75. }
  76. // FailedPredicateMap declares a map[string][]algorithm.PredicateFailureReason type.
  77. type FailedPredicateMap map[string][]predicates.PredicateFailureReason
  78. // FitError describes a fit error of a pod.
  79. type FitError struct {
  80. Pod *v1.Pod
  81. NumAllNodes int
  82. FailedPredicates FailedPredicateMap
  83. }
  84. // ErrNoNodesAvailable is used to describe the error that no nodes available to schedule pods.
  85. var ErrNoNodesAvailable = fmt.Errorf("no nodes available to schedule pods")
  86. const (
  87. // NoNodeAvailableMsg is used to format message when no nodes available.
  88. NoNodeAvailableMsg = "0/%v nodes are available"
  89. )
  90. // Error returns detailed information of why the pod failed to fit on each node
  91. func (f *FitError) Error() string {
  92. reasons := make(map[string]int)
  93. for _, predicates := range f.FailedPredicates {
  94. for _, pred := range predicates {
  95. reasons[pred.GetReason()]++
  96. }
  97. }
  98. sortReasonsHistogram := func() []string {
  99. reasonStrings := []string{}
  100. for k, v := range reasons {
  101. reasonStrings = append(reasonStrings, fmt.Sprintf("%v %v", v, k))
  102. }
  103. sort.Strings(reasonStrings)
  104. return reasonStrings
  105. }
  106. reasonMsg := fmt.Sprintf(NoNodeAvailableMsg+": %v.", f.NumAllNodes, strings.Join(sortReasonsHistogram(), ", "))
  107. return reasonMsg
  108. }
  109. // ScheduleAlgorithm is an interface implemented by things that know how to schedule pods
  110. // onto machines.
  111. // TODO: Rename this type.
  112. type ScheduleAlgorithm interface {
  113. Schedule(*v1.Pod, algorithm.NodeLister) (scheduleResult ScheduleResult, err error)
  114. // Preempt receives scheduling errors for a pod and tries to create room for
  115. // the pod by preempting lower priority pods if possible.
  116. // It returns the node where preemption happened, a list of preempted pods, a
  117. // list of pods whose nominated node name should be removed, and error if any.
  118. Preempt(*v1.Pod, algorithm.NodeLister, error) (selectedNode *v1.Node, preemptedPods []*v1.Pod, cleanupNominatedPods []*v1.Pod, err error)
  119. // Predicates() returns a pointer to a map of predicate functions. This is
  120. // exposed for testing.
  121. Predicates() map[string]predicates.FitPredicate
  122. // Prioritizers returns a slice of priority config. This is exposed for
  123. // testing.
  124. Prioritizers() []priorities.PriorityConfig
  125. }
  126. // ScheduleResult represents the result of one pod scheduled. It will contain
  127. // the final selected Node, along with the selected intermediate information.
  128. type ScheduleResult struct {
  129. // Name of the scheduler suggest host
  130. SuggestedHost string
  131. // Number of nodes scheduler evaluated on one pod scheduled
  132. EvaluatedNodes int
  133. // Number of feasible nodes on one pod scheduled
  134. FeasibleNodes int
  135. }
  136. type genericScheduler struct {
  137. cache internalcache.Cache
  138. schedulingQueue internalqueue.SchedulingQueue
  139. predicates map[string]predicates.FitPredicate
  140. priorityMetaProducer priorities.PriorityMetadataProducer
  141. predicateMetaProducer predicates.PredicateMetadataProducer
  142. prioritizers []priorities.PriorityConfig
  143. framework framework.Framework
  144. extenders []algorithm.SchedulerExtender
  145. lastNodeIndex uint64
  146. alwaysCheckAllPredicates bool
  147. nodeInfoSnapshot *internalcache.NodeInfoSnapshot
  148. volumeBinder *volumebinder.VolumeBinder
  149. pvcLister corelisters.PersistentVolumeClaimLister
  150. pdbLister algorithm.PDBLister
  151. disablePreemption bool
  152. percentageOfNodesToScore int32
  153. enableNonPreempting bool
  154. }
  155. // snapshot snapshots scheduler cache and node infos for all fit and priority
  156. // functions.
  157. func (g *genericScheduler) snapshot() error {
  158. // Used for all fit and priority funcs.
  159. return g.cache.UpdateNodeInfoSnapshot(g.nodeInfoSnapshot)
  160. }
  161. // Schedule tries to schedule the given pod to one of the nodes in the node list.
  162. // If it succeeds, it will return the name of the node.
  163. // If it fails, it will return a FitError error with reasons.
  164. func (g *genericScheduler) Schedule(pod *v1.Pod, nodeLister algorithm.NodeLister) (result ScheduleResult, err error) {
  165. trace := utiltrace.New(fmt.Sprintf("Scheduling %s/%s", pod.Namespace, pod.Name))
  166. defer trace.LogIfLong(100 * time.Millisecond)
  167. if err := podPassesBasicChecks(pod, g.pvcLister); err != nil {
  168. return result, err
  169. }
  170. nodes, err := nodeLister.List()
  171. if err != nil {
  172. return result, err
  173. }
  174. if len(nodes) == 0 {
  175. return result, ErrNoNodesAvailable
  176. }
  177. if err := g.snapshot(); err != nil {
  178. return result, err
  179. }
  180. trace.Step("Computing predicates")
  181. startPredicateEvalTime := time.Now()
  182. filteredNodes, failedPredicateMap, err := g.findNodesThatFit(pod, nodes)
  183. if err != nil {
  184. return result, err
  185. }
  186. if len(filteredNodes) == 0 {
  187. return result, &FitError{
  188. Pod: pod,
  189. NumAllNodes: len(nodes),
  190. FailedPredicates: failedPredicateMap,
  191. }
  192. }
  193. metrics.SchedulingAlgorithmPredicateEvaluationDuration.Observe(metrics.SinceInSeconds(startPredicateEvalTime))
  194. metrics.DeprecatedSchedulingAlgorithmPredicateEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPredicateEvalTime))
  195. metrics.SchedulingLatency.WithLabelValues(metrics.PredicateEvaluation).Observe(metrics.SinceInSeconds(startPredicateEvalTime))
  196. metrics.DeprecatedSchedulingLatency.WithLabelValues(metrics.PredicateEvaluation).Observe(metrics.SinceInSeconds(startPredicateEvalTime))
  197. trace.Step("Prioritizing")
  198. startPriorityEvalTime := time.Now()
  199. // When only one node after predicate, just use it.
  200. if len(filteredNodes) == 1 {
  201. metrics.SchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  202. metrics.DeprecatedSchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPriorityEvalTime))
  203. return ScheduleResult{
  204. SuggestedHost: filteredNodes[0].Name,
  205. EvaluatedNodes: 1 + len(failedPredicateMap),
  206. FeasibleNodes: 1,
  207. }, nil
  208. }
  209. metaPrioritiesInterface := g.priorityMetaProducer(pod, g.nodeInfoSnapshot.NodeInfoMap)
  210. priorityList, err := PrioritizeNodes(pod, g.nodeInfoSnapshot.NodeInfoMap, metaPrioritiesInterface, g.prioritizers, filteredNodes, g.extenders)
  211. //customPriotrityList, err := CustomPrioritizeNodes(pod, g.nodeInfoSnapshot.NodeInfoMap, metaPrioritiesInterface, g.prioritizers, filteredNodes, g.extenders)
  212. if err != nil {
  213. return result, err
  214. }
  215. metrics.SchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  216. metrics.DeprecatedSchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPriorityEvalTime))
  217. metrics.SchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  218. metrics.DeprecatedSchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  219. trace.Step("Selecting host")
  220. host, err := g.selectHost(priorityList)
  221. return ScheduleResult{
  222. SuggestedHost: host,
  223. EvaluatedNodes: len(filteredNodes) + len(failedPredicateMap),
  224. FeasibleNodes: len(filteredNodes),
  225. }, err
  226. }
  227. // Prioritizers returns a slice containing all the scheduler's priority
  228. // functions and their config. It is exposed for testing only.
  229. func (g *genericScheduler) Prioritizers() []priorities.PriorityConfig {
  230. return g.prioritizers
  231. }
  232. // Predicates returns a map containing all the scheduler's predicate
  233. // functions. It is exposed for testing only.
  234. func (g *genericScheduler) Predicates() map[string]predicates.FitPredicate {
  235. return g.predicates
  236. }
  237. // findMaxScores returns the indexes of nodes in the "priorityList" that has the highest "Score".
  238. func findMaxScores(priorityList schedulerapi.HostPriorityList) []int {
  239. maxScoreIndexes := make([]int, 0, len(priorityList)/2)
  240. maxScore := priorityList[0].Score
  241. for i, hp := range priorityList {
  242. if hp.Score > maxScore {
  243. maxScore = hp.Score
  244. maxScoreIndexes = maxScoreIndexes[:0]
  245. maxScoreIndexes = append(maxScoreIndexes, i)
  246. } else if hp.Score == maxScore {
  247. maxScoreIndexes = append(maxScoreIndexes, i)
  248. }
  249. }
  250. return maxScoreIndexes
  251. }
  252. // selectHost takes a prioritized list of nodes and then picks one
  253. // in a round-robin manner from the nodes that had the highest score.
  254. func (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList) (string, error) {
  255. if len(priorityList) == 0 {
  256. return "", fmt.Errorf("empty priorityList")
  257. }
  258. maxScores := findMaxScores(priorityList)
  259. ix := int(g.lastNodeIndex % uint64(len(maxScores)))
  260. g.lastNodeIndex++
  261. return priorityList[maxScores[ix]].Host, nil
  262. }
  263. // preempt finds nodes with pods that can be preempted to make room for "pod" to
  264. // schedule. It chooses one of the nodes and preempts the pods on the node and
  265. // returns 1) the node, 2) the list of preempted pods if such a node is found,
  266. // 3) A list of pods whose nominated node name should be cleared, and 4) any
  267. // possible error.
  268. // Preempt does not update its snapshot. It uses the same snapshot used in the
  269. // scheduling cycle. This is to avoid a scenario where preempt finds feasible
  270. // nodes without preempting any pod. When there are many pending pods in the
  271. // scheduling queue a nominated pod will go back to the queue and behind
  272. // other pods with the same priority. The nominated pod prevents other pods from
  273. // using the nominated resources and the nominated pod could take a long time
  274. // before it is retried after many other pending pods.
  275. func (g *genericScheduler) Preempt(pod *v1.Pod, nodeLister algorithm.NodeLister, scheduleErr error) (*v1.Node, []*v1.Pod, []*v1.Pod, error) {
  276. // Scheduler may return various types of errors. Consider preemption only if
  277. // the error is of type FitError.
  278. fitError, ok := scheduleErr.(*FitError)
  279. if !ok || fitError == nil {
  280. return nil, nil, nil, nil
  281. }
  282. if !podEligibleToPreemptOthers(pod, g.nodeInfoSnapshot.NodeInfoMap, g.enableNonPreempting) {
  283. klog.V(5).Infof("Pod %v/%v is not eligible for more preemption.", pod.Namespace, pod.Name)
  284. return nil, nil, nil, nil
  285. }
  286. allNodes, err := nodeLister.List()
  287. if err != nil {
  288. return nil, nil, nil, err
  289. }
  290. if len(allNodes) == 0 {
  291. return nil, nil, nil, ErrNoNodesAvailable
  292. }
  293. potentialNodes := nodesWherePreemptionMightHelp(allNodes, fitError.FailedPredicates)
  294. if len(potentialNodes) == 0 {
  295. klog.V(3).Infof("Preemption will not help schedule pod %v/%v on any node.", pod.Namespace, pod.Name)
  296. // In this case, we should clean-up any existing nominated node name of the pod.
  297. return nil, nil, []*v1.Pod{pod}, nil
  298. }
  299. pdbs, err := g.pdbLister.List(labels.Everything())
  300. if err != nil {
  301. return nil, nil, nil, err
  302. }
  303. nodeToVictims, err := selectNodesForPreemption(pod, g.nodeInfoSnapshot.NodeInfoMap, potentialNodes, g.predicates,
  304. g.predicateMetaProducer, g.schedulingQueue, pdbs)
  305. if err != nil {
  306. return nil, nil, nil, err
  307. }
  308. // We will only check nodeToVictims with extenders that support preemption.
  309. // Extenders which do not support preemption may later prevent preemptor from being scheduled on the nominated
  310. // node. In that case, scheduler will find a different host for the preemptor in subsequent scheduling cycles.
  311. nodeToVictims, err = g.processPreemptionWithExtenders(pod, nodeToVictims)
  312. if err != nil {
  313. return nil, nil, nil, err
  314. }
  315. candidateNode := pickOneNodeForPreemption(nodeToVictims)
  316. if candidateNode == nil {
  317. return nil, nil, nil, nil
  318. }
  319. // Lower priority pods nominated to run on this node, may no longer fit on
  320. // this node. So, we should remove their nomination. Removing their
  321. // nomination updates these pods and moves them to the active queue. It
  322. // lets scheduler find another place for them.
  323. nominatedPods := g.getLowerPriorityNominatedPods(pod, candidateNode.Name)
  324. if nodeInfo, ok := g.nodeInfoSnapshot.NodeInfoMap[candidateNode.Name]; ok {
  325. return nodeInfo.Node(), nodeToVictims[candidateNode].Pods, nominatedPods, nil
  326. }
  327. return nil, nil, nil, fmt.Errorf(
  328. "preemption failed: the target node %s has been deleted from scheduler cache",
  329. candidateNode.Name)
  330. }
  331. // processPreemptionWithExtenders processes preemption with extenders
  332. func (g *genericScheduler) processPreemptionWithExtenders(
  333. pod *v1.Pod,
  334. nodeToVictims map[*v1.Node]*schedulerapi.Victims,
  335. ) (map[*v1.Node]*schedulerapi.Victims, error) {
  336. if len(nodeToVictims) > 0 {
  337. for _, extender := range g.extenders {
  338. if extender.SupportsPreemption() && extender.IsInterested(pod) {
  339. newNodeToVictims, err := extender.ProcessPreemption(
  340. pod,
  341. nodeToVictims,
  342. g.nodeInfoSnapshot.NodeInfoMap,
  343. )
  344. if err != nil {
  345. if extender.IsIgnorable() {
  346. klog.Warningf("Skipping extender %v as it returned error %v and has ignorable flag set",
  347. extender, err)
  348. continue
  349. }
  350. return nil, err
  351. }
  352. // Replace nodeToVictims with new result after preemption. So the
  353. // rest of extenders can continue use it as parameter.
  354. nodeToVictims = newNodeToVictims
  355. // If node list becomes empty, no preemption can happen regardless of other extenders.
  356. if len(nodeToVictims) == 0 {
  357. break
  358. }
  359. }
  360. }
  361. }
  362. return nodeToVictims, nil
  363. }
  364. // getLowerPriorityNominatedPods returns pods whose priority is smaller than the
  365. // priority of the given "pod" and are nominated to run on the given node.
  366. // Note: We could possibly check if the nominated lower priority pods still fit
  367. // and return those that no longer fit, but that would require lots of
  368. // manipulation of NodeInfo and PredicateMeta per nominated pod. It may not be
  369. // worth the complexity, especially because we generally expect to have a very
  370. // small number of nominated pods per node.
  371. func (g *genericScheduler) getLowerPriorityNominatedPods(pod *v1.Pod, nodeName string) []*v1.Pod {
  372. pods := g.schedulingQueue.NominatedPodsForNode(nodeName)
  373. if len(pods) == 0 {
  374. return nil
  375. }
  376. var lowerPriorityPods []*v1.Pod
  377. podPriority := util.GetPodPriority(pod)
  378. for _, p := range pods {
  379. if util.GetPodPriority(p) < podPriority {
  380. lowerPriorityPods = append(lowerPriorityPods, p)
  381. }
  382. }
  383. return lowerPriorityPods
  384. }
  385. // numFeasibleNodesToFind returns the number of feasible nodes that once found, the scheduler stops
  386. // its search for more feasible nodes.
  387. func (g *genericScheduler) numFeasibleNodesToFind(numAllNodes int32) (numNodes int32) {
  388. if numAllNodes < minFeasibleNodesToFind || g.percentageOfNodesToScore >= 100 {
  389. return numAllNodes
  390. }
  391. adaptivePercentage := g.percentageOfNodesToScore
  392. if adaptivePercentage <= 0 {
  393. adaptivePercentage = schedulerapi.DefaultPercentageOfNodesToScore - numAllNodes/125
  394. if adaptivePercentage < minFeasibleNodesPercentageToFind {
  395. adaptivePercentage = minFeasibleNodesPercentageToFind
  396. }
  397. }
  398. numNodes = numAllNodes * adaptivePercentage / 100
  399. if numNodes < minFeasibleNodesToFind {
  400. return minFeasibleNodesToFind
  401. }
  402. return numNodes
  403. }
  404. // Filters the nodes to find the ones that fit based on the given predicate functions
  405. // Each node is passed through the predicate functions to determine if it is a fit
  406. func (g *genericScheduler) findNodesThatFit(pod *v1.Pod, nodes []*v1.Node) ([]*v1.Node, FailedPredicateMap, error) {
  407. var filtered []*v1.Node
  408. failedPredicateMap := FailedPredicateMap{}
  409. if len(g.predicates) == 0 {
  410. filtered = nodes
  411. } else {
  412. allNodes := int32(g.cache.NodeTree().NumNodes())
  413. numNodesToFind := g.numFeasibleNodesToFind(allNodes)
  414. // Create filtered list with enough space to avoid growing it
  415. // and allow assigning.
  416. filtered = make([]*v1.Node, numNodesToFind)
  417. errs := errors.MessageCountMap{}
  418. var (
  419. predicateResultLock sync.Mutex
  420. filteredLen int32
  421. )
  422. ctx, cancel := context.WithCancel(context.Background())
  423. // We can use the same metadata producer for all nodes.
  424. meta := g.predicateMetaProducer(pod, g.nodeInfoSnapshot.NodeInfoMap)
  425. checkNode := func(i int) {
  426. nodeName := g.cache.NodeTree().Next()
  427. fits, failedPredicates, err := podFitsOnNode(
  428. pod,
  429. meta,
  430. g.nodeInfoSnapshot.NodeInfoMap[nodeName],
  431. g.predicates,
  432. g.schedulingQueue,
  433. g.alwaysCheckAllPredicates,
  434. )
  435. if err != nil {
  436. predicateResultLock.Lock()
  437. errs[err.Error()]++
  438. predicateResultLock.Unlock()
  439. return
  440. }
  441. if fits {
  442. length := atomic.AddInt32(&filteredLen, 1)
  443. if length > numNodesToFind {
  444. cancel()
  445. atomic.AddInt32(&filteredLen, -1)
  446. } else {
  447. filtered[length-1] = g.nodeInfoSnapshot.NodeInfoMap[nodeName].Node()
  448. }
  449. } else {
  450. predicateResultLock.Lock()
  451. failedPredicateMap[nodeName] = failedPredicates
  452. predicateResultLock.Unlock()
  453. }
  454. }
  455. // Stops searching for more nodes once the configured number of feasible nodes
  456. // are found.
  457. workqueue.ParallelizeUntil(ctx, 16, int(allNodes), checkNode)
  458. filtered = filtered[:filteredLen]
  459. if len(errs) > 0 {
  460. return []*v1.Node{}, FailedPredicateMap{}, errors.CreateAggregateFromMessageCountMap(errs)
  461. }
  462. }
  463. if len(filtered) > 0 && len(g.extenders) != 0 {
  464. for _, extender := range g.extenders {
  465. if !extender.IsInterested(pod) {
  466. continue
  467. }
  468. filteredList, failedMap, err := extender.Filter(pod, filtered, g.nodeInfoSnapshot.NodeInfoMap)
  469. if err != nil {
  470. if extender.IsIgnorable() {
  471. klog.Warningf("Skipping extender %v as it returned error %v and has ignorable flag set",
  472. extender, err)
  473. continue
  474. } else {
  475. return []*v1.Node{}, FailedPredicateMap{}, err
  476. }
  477. }
  478. for failedNodeName, failedMsg := range failedMap {
  479. if _, found := failedPredicateMap[failedNodeName]; !found {
  480. failedPredicateMap[failedNodeName] = []predicates.PredicateFailureReason{}
  481. }
  482. failedPredicateMap[failedNodeName] = append(failedPredicateMap[failedNodeName], predicates.NewFailureReason(failedMsg))
  483. }
  484. filtered = filteredList
  485. if len(filtered) == 0 {
  486. break
  487. }
  488. }
  489. }
  490. return filtered, failedPredicateMap, nil
  491. }
  492. // addNominatedPods adds pods with equal or greater priority which are nominated
  493. // to run on the node given in nodeInfo to meta and nodeInfo. It returns 1) whether
  494. // any pod was found, 2) augmented meta data, 3) augmented nodeInfo.
  495. func addNominatedPods(pod *v1.Pod, meta predicates.PredicateMetadata,
  496. nodeInfo *schedulernodeinfo.NodeInfo, queue internalqueue.SchedulingQueue) (bool, predicates.PredicateMetadata,
  497. *schedulernodeinfo.NodeInfo) {
  498. if queue == nil || nodeInfo == nil || nodeInfo.Node() == nil {
  499. // This may happen only in tests.
  500. return false, meta, nodeInfo
  501. }
  502. nominatedPods := queue.NominatedPodsForNode(nodeInfo.Node().Name)
  503. if nominatedPods == nil || len(nominatedPods) == 0 {
  504. return false, meta, nodeInfo
  505. }
  506. var metaOut predicates.PredicateMetadata
  507. if meta != nil {
  508. metaOut = meta.ShallowCopy()
  509. }
  510. nodeInfoOut := nodeInfo.Clone()
  511. for _, p := range nominatedPods {
  512. if util.GetPodPriority(p) >= util.GetPodPriority(pod) && p.UID != pod.UID {
  513. nodeInfoOut.AddPod(p)
  514. if metaOut != nil {
  515. metaOut.AddPod(p, nodeInfoOut)
  516. }
  517. }
  518. }
  519. return true, metaOut, nodeInfoOut
  520. }
  521. // podFitsOnNode checks whether a node given by NodeInfo satisfies the given predicate functions.
  522. // For given pod, podFitsOnNode will check if any equivalent pod exists and try to reuse its cached
  523. // predicate results as possible.
  524. // This function is called from two different places: Schedule and Preempt.
  525. // When it is called from Schedule, we want to test whether the pod is schedulable
  526. // on the node with all the existing pods on the node plus higher and equal priority
  527. // pods nominated to run on the node.
  528. // When it is called from Preempt, we should remove the victims of preemption and
  529. // add the nominated pods. Removal of the victims is done by SelectVictimsOnNode().
  530. // It removes victims from meta and NodeInfo before calling this function.
  531. func podFitsOnNode(
  532. pod *v1.Pod,
  533. meta predicates.PredicateMetadata,
  534. info *schedulernodeinfo.NodeInfo,
  535. predicateFuncs map[string]predicates.FitPredicate,
  536. queue internalqueue.SchedulingQueue,
  537. alwaysCheckAllPredicates bool,
  538. ) (bool, []predicates.PredicateFailureReason, error) {
  539. var failedPredicates []predicates.PredicateFailureReason
  540. podsAdded := false
  541. // We run predicates twice in some cases. If the node has greater or equal priority
  542. // nominated pods, we run them when those pods are added to meta and nodeInfo.
  543. // If all predicates succeed in this pass, we run them again when these
  544. // nominated pods are not added. This second pass is necessary because some
  545. // predicates such as inter-pod affinity may not pass without the nominated pods.
  546. // If there are no nominated pods for the node or if the first run of the
  547. // predicates fail, we don't run the second pass.
  548. // We consider only equal or higher priority pods in the first pass, because
  549. // those are the current "pod" must yield to them and not take a space opened
  550. // for running them. It is ok if the current "pod" take resources freed for
  551. // lower priority pods.
  552. // Requiring that the new pod is schedulable in both circumstances ensures that
  553. // we are making a conservative decision: predicates like resources and inter-pod
  554. // anti-affinity are more likely to fail when the nominated pods are treated
  555. // as running, while predicates like pod affinity are more likely to fail when
  556. // the nominated pods are treated as not running. We can't just assume the
  557. // nominated pods are running because they are not running right now and in fact,
  558. // they may end up getting scheduled to a different node.
  559. for i := 0; i < 2; i++ {
  560. metaToUse := meta
  561. nodeInfoToUse := info
  562. if i == 0 {
  563. podsAdded, metaToUse, nodeInfoToUse = addNominatedPods(pod, meta, info, queue)
  564. } else if !podsAdded || len(failedPredicates) != 0 {
  565. break
  566. }
  567. for _, predicateKey := range predicates.Ordering() {
  568. var (
  569. fit bool
  570. reasons []predicates.PredicateFailureReason
  571. err error
  572. )
  573. //TODO (yastij) : compute average predicate restrictiveness to export it as Prometheus metric
  574. if predicate, exist := predicateFuncs[predicateKey]; exist {
  575. fit, reasons, err = predicate(pod, metaToUse, nodeInfoToUse)
  576. if err != nil {
  577. return false, []predicates.PredicateFailureReason{}, err
  578. }
  579. if !fit {
  580. // eCache is available and valid, and predicates result is unfit, record the fail reasons
  581. failedPredicates = append(failedPredicates, reasons...)
  582. // if alwaysCheckAllPredicates is false, short circuit all predicates when one predicate fails.
  583. if !alwaysCheckAllPredicates {
  584. klog.V(5).Infoln("since alwaysCheckAllPredicates has not been set, the predicate " +
  585. "evaluation is short circuited and there are chances " +
  586. "of other predicates failing as well.")
  587. break
  588. }
  589. }
  590. }
  591. }
  592. }
  593. return len(failedPredicates) == 0, failedPredicates, nil
  594. }
  595. // PrioritizeNodes prioritizes the nodes by running the individual priority functions in parallel.
  596. // Each priority function is expected to set a score of 0-10
  597. // 0 is the lowest priority score (least preferred node) and 10 is the highest
  598. // Each priority function can also have its own weight
  599. // The node scores returned by the priority function are multiplied by the weights to get weighted scores
  600. // All scores are finally combined (added) to get the total weighted scores of all nodes
  601. func PrioritizeNodes(
  602. pod *v1.Pod,
  603. nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
  604. meta interface{},
  605. priorityConfigs []priorities.PriorityConfig,
  606. nodes []*v1.Node,
  607. extenders []algorithm.SchedulerExtender,
  608. ) (schedulerapi.HostPriorityList, error) {
  609. // If no priority configs are provided, then the EqualPriority function is applied
  610. // This is required to generate the priority list in the required format
  611. if len(priorityConfigs) == 0 && len(extenders) == 0 {
  612. result := make(schedulerapi.HostPriorityList, 0, len(nodes))
  613. for i := range nodes {
  614. hostPriority, err := EqualPriorityMap(pod, meta, nodeNameToInfo[nodes[i].Name])
  615. if err != nil {
  616. return nil, err
  617. }
  618. result = append(result, hostPriority)
  619. }
  620. return result, nil
  621. }
  622. var (
  623. mu = sync.Mutex{}
  624. wg = sync.WaitGroup{}
  625. errs []error
  626. )
  627. appendError := func(err error) {
  628. mu.Lock()
  629. defer mu.Unlock()
  630. errs = append(errs, err)
  631. }
  632. results := make([]schedulerapi.HostPriorityList, len(priorityConfigs), len(priorityConfigs))
  633. // DEPRECATED: we can remove this when all priorityConfigs implement the
  634. // Map-Reduce pattern.
  635. for i := range priorityConfigs {
  636. if priorityConfigs[i].Function != nil {
  637. wg.Add(1)
  638. go func(index int) {
  639. defer wg.Done()
  640. var err error
  641. results[index], err = priorityConfigs[index].Function(pod, nodeNameToInfo, nodes)
  642. if err != nil {
  643. appendError(err)
  644. }
  645. }(i)
  646. } else {
  647. results[i] = make(schedulerapi.HostPriorityList, len(nodes))
  648. }
  649. }
  650. workqueue.ParallelizeUntil(context.TODO(), 16, len(nodes), func(index int) {
  651. nodeInfo := nodeNameToInfo[nodes[index].Name]
  652. for i := range priorityConfigs {
  653. if priorityConfigs[i].Function != nil {
  654. continue
  655. }
  656. var err error
  657. results[i][index], err = priorityConfigs[i].Map(pod, meta, nodeInfo)
  658. if err != nil {
  659. appendError(err)
  660. results[i][index].Host = nodes[index].Name
  661. }
  662. }
  663. })
  664. for i := range priorityConfigs {
  665. if priorityConfigs[i].Reduce == nil {
  666. continue
  667. }
  668. wg.Add(1)
  669. go func(index int) {
  670. defer wg.Done()
  671. if err := priorityConfigs[index].Reduce(pod, meta, nodeNameToInfo, results[index]); err != nil {
  672. appendError(err)
  673. }
  674. if klog.V(10) {
  675. for _, hostPriority := range results[index] {
  676. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), hostPriority.Host, priorityConfigs[index].Name, hostPriority.Score)
  677. }
  678. }
  679. }(i)
  680. }
  681. // Wait for all computations to be finished.
  682. wg.Wait()
  683. if len(errs) != 0 {
  684. return schedulerapi.HostPriorityList{}, errors.NewAggregate(errs)
  685. }
  686. // Summarize all scores.
  687. result := make(schedulerapi.HostPriorityList, 0, len(nodes))
  688. for i := range nodes {
  689. result = append(result, schedulerapi.HostPriority{Host: nodes[i].Name, Score: 0})
  690. for j := range priorityConfigs {
  691. result[i].Score += results[j][i].Score * priorityConfigs[j].Weight
  692. }
  693. }
  694. if len(extenders) != 0 && nodes != nil {
  695. combinedScores := make(map[string]int, len(nodeNameToInfo))
  696. for i := range extenders {
  697. if !extenders[i].IsInterested(pod) {
  698. continue
  699. }
  700. wg.Add(1)
  701. go func(extIndex int) {
  702. defer wg.Done()
  703. prioritizedList, weight, err := extenders[extIndex].Prioritize(pod, nodes)
  704. if err != nil {
  705. // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities
  706. return
  707. }
  708. mu.Lock()
  709. for i := range *prioritizedList {
  710. host, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score
  711. if klog.V(10) {
  712. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), host, extenders[extIndex].Name(), score)
  713. }
  714. combinedScores[host] += score * weight
  715. }
  716. mu.Unlock()
  717. }(i)
  718. }
  719. // wait for all go routines to finish
  720. wg.Wait()
  721. for i := range result {
  722. result[i].Score += combinedScores[result[i].Host]
  723. }
  724. }
  725. if klog.V(10) {
  726. for i := range result {
  727. klog.Infof("Host %s => Score %d", result[i].Host, result[i].Score)
  728. }
  729. }
  730. return result, nil
  731. }
  732. //------------------------------------------------------------------
  733. //-------------------START-CUSTOM-BY-IWITA---------------------------------------------------------
  734. //------------------------------------------------------------------
  735. func CustomPrioritizeNodes(
  736. pod *v1.Pod,
  737. nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
  738. meta interface{},
  739. priorityConfigs []priorities.PriorityConfig,
  740. nodes []*v1.Node,
  741. extenders []algorithm.SchedulerExtender,
  742. ) (schedulerapi.CustomHostPriorityList, error) {
  743. // If no priority configs are provided, then the EqualPriority function is applied
  744. // This is required to generate the priority list in the required format
  745. // if len(priorityConfigs) == 0 && len(extenders) == 0 {
  746. // result := make(schedulerapi.CustomHostPriorityList, 0, len(nodes))
  747. // for i := range nodes {
  748. // // initializes nodes with Score = 1
  749. // hostPriority, err := EqualPriorityMap(pod, meta, nodeNameToInfo[nodes[i].Name])
  750. // if err != nil {
  751. // return nil, err
  752. // }
  753. // result = append(result, hostPriority)
  754. // }
  755. // return result, nil
  756. // }
  757. var (
  758. mu = sync.Mutex{}
  759. wg = sync.WaitGroup{}
  760. errs []error
  761. )
  762. appendError := func(err error) {
  763. mu.Lock()
  764. defer mu.Unlock()
  765. errs = append(errs, err)
  766. }
  767. results := make([]schedulerapi.CustomHostPriorityList, len(priorityConfigs), len(priorityConfigs))
  768. // DEPRECATED: we can remove this when all priorityConfigs implement the
  769. // Map-Reduce pattern.
  770. for i := range priorityConfigs {
  771. if priorityConfigs[i].CustomFunction != nil {
  772. wg.Add(1)
  773. go func(index int) {
  774. defer wg.Done()
  775. var err error
  776. results[index], err = priorityConfigs[index].CustomFunction(pod, nodeNameToInfo, nodes)
  777. if err != nil {
  778. appendError(err)
  779. }
  780. }(i)
  781. } else {
  782. results[i] = make(schedulerapi.CustomHostPriorityList, len(nodes))
  783. }
  784. }
  785. workqueue.ParallelizeUntil(context.TODO(), 16, len(nodes), func(index int) {
  786. nodeInfo := nodeNameToInfo[nodes[index].Name]
  787. for i := range priorityConfigs {
  788. if priorityConfigs[i].Function != nil {
  789. continue
  790. }
  791. var err error
  792. results[i][index], err = priorityConfigs[i].CustomMap(pod, meta, nodeInfo)
  793. if err != nil {
  794. appendError(err)
  795. results[i][index].Host = nodes[index].Name
  796. }
  797. }
  798. })
  799. for i := range priorityConfigs {
  800. if priorityConfigs[i].Reduce == nil {
  801. continue
  802. }
  803. wg.Add(1)
  804. go func(index int) {
  805. defer wg.Done()
  806. if err := priorityConfigs[index].CustomReduce(pod, meta, nodeNameToInfo, results[index]); err != nil {
  807. appendError(err)
  808. }
  809. if klog.V(10) {
  810. for _, hostPriority := range results[index] {
  811. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), hostPriority.Host, priorityConfigs[index].Name, hostPriority.Score)
  812. }
  813. }
  814. }(i)
  815. }
  816. // Wait for all computations to be finished.
  817. wg.Wait()
  818. if len(errs) != 0 {
  819. return schedulerapi.CustomHostPriorityList{}, errors.NewAggregate(errs)
  820. }
  821. // Summarize all scores.
  822. result := make(schedulerapi.CustomHostPriorityList, 0, len(nodes))
  823. for i := range nodes {
  824. result = append(result, schedulerapi.CustomHostPriority{Host: nodes[i].Name, Score: 0})
  825. for j := range priorityConfigs {
  826. result[i].Score += results[j][i].Score * float64(priorityConfigs[j].Weight)
  827. }
  828. }
  829. if len(extenders) != 0 && nodes != nil {
  830. combinedScores := make(map[string]float64, len(nodeNameToInfo))
  831. for i := range extenders {
  832. if !extenders[i].IsInterested(pod) {
  833. continue
  834. }
  835. wg.Add(1)
  836. go func(extIndex int) {
  837. defer wg.Done()
  838. prioritizedList, weight, err := extenders[extIndex].CustomPrioritize(pod, nodes)
  839. if err != nil {
  840. // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities
  841. return
  842. }
  843. mu.Lock()
  844. for i := range *prioritizedList {
  845. host, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score
  846. if klog.V(10) {
  847. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), host, extenders[extIndex].Name(), score)
  848. }
  849. combinedScores[host] += score * float64(weight)
  850. }
  851. mu.Unlock()
  852. }(i)
  853. }
  854. // wait for all go routines to finish
  855. wg.Wait()
  856. for i := range result {
  857. result[i].Score += combinedScores[result[i].Host]
  858. }
  859. }
  860. if klog.V(10) {
  861. for i := range result {
  862. klog.Infof("Host %s => Score %d", result[i].Host, result[i].Score)
  863. }
  864. }
  865. return result, nil
  866. }
  867. //------------------------------------------------------------------
  868. // --------------END-CUSTOM-BY-IWITA--------------------------------
  869. //------------------------------------------------------------------
  870. // EqualPriorityMap is a prioritizer function that gives an equal weight of one to all nodes
  871. func EqualPriorityMap(_ *v1.Pod, _ interface{}, nodeInfo *schedulernodeinfo.NodeInfo) (schedulerapi.HostPriority, error) {
  872. node := nodeInfo.Node()
  873. if node == nil {
  874. return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
  875. }
  876. return schedulerapi.HostPriority{
  877. Host: node.Name,
  878. Score: 1,
  879. }, nil
  880. }
  881. // pickOneNodeForPreemption chooses one node among the given nodes. It assumes
  882. // pods in each map entry are ordered by decreasing priority.
  883. // It picks a node based on the following criteria:
  884. // 1. A node with minimum number of PDB violations.
  885. // 2. A node with minimum highest priority victim is picked.
  886. // 3. Ties are broken by sum of priorities of all victims.
  887. // 4. If there are still ties, node with the minimum number of victims is picked.
  888. // 5. If there are still ties, node with the latest start time of all highest priority victims is picked.
  889. // 6. If there are still ties, the first such node is picked (sort of randomly).
  890. // The 'minNodes1' and 'minNodes2' are being reused here to save the memory
  891. // allocation and garbage collection time.
  892. func pickOneNodeForPreemption(nodesToVictims map[*v1.Node]*schedulerapi.Victims) *v1.Node {
  893. if len(nodesToVictims) == 0 {
  894. return nil
  895. }
  896. minNumPDBViolatingPods := math.MaxInt32
  897. var minNodes1 []*v1.Node
  898. lenNodes1 := 0
  899. for node, victims := range nodesToVictims {
  900. if len(victims.Pods) == 0 {
  901. // We found a node that doesn't need any preemption. Return it!
  902. // This should happen rarely when one or more pods are terminated between
  903. // the time that scheduler tries to schedule the pod and the time that
  904. // preemption logic tries to find nodes for preemption.
  905. return node
  906. }
  907. numPDBViolatingPods := victims.NumPDBViolations
  908. if numPDBViolatingPods < minNumPDBViolatingPods {
  909. minNumPDBViolatingPods = numPDBViolatingPods
  910. minNodes1 = nil
  911. lenNodes1 = 0
  912. }
  913. if numPDBViolatingPods == minNumPDBViolatingPods {
  914. minNodes1 = append(minNodes1, node)
  915. lenNodes1++
  916. }
  917. }
  918. if lenNodes1 == 1 {
  919. return minNodes1[0]
  920. }
  921. // There are more than one node with minimum number PDB violating pods. Find
  922. // the one with minimum highest priority victim.
  923. minHighestPriority := int32(math.MaxInt32)
  924. var minNodes2 = make([]*v1.Node, lenNodes1)
  925. lenNodes2 := 0
  926. for i := 0; i < lenNodes1; i++ {
  927. node := minNodes1[i]
  928. victims := nodesToVictims[node]
  929. // highestPodPriority is the highest priority among the victims on this node.
  930. highestPodPriority := util.GetPodPriority(victims.Pods[0])
  931. if highestPodPriority < minHighestPriority {
  932. minHighestPriority = highestPodPriority
  933. lenNodes2 = 0
  934. }
  935. if highestPodPriority == minHighestPriority {
  936. minNodes2[lenNodes2] = node
  937. lenNodes2++
  938. }
  939. }
  940. if lenNodes2 == 1 {
  941. return minNodes2[0]
  942. }
  943. // There are a few nodes with minimum highest priority victim. Find the
  944. // smallest sum of priorities.
  945. minSumPriorities := int64(math.MaxInt64)
  946. lenNodes1 = 0
  947. for i := 0; i < lenNodes2; i++ {
  948. var sumPriorities int64
  949. node := minNodes2[i]
  950. for _, pod := range nodesToVictims[node].Pods {
  951. // We add MaxInt32+1 to all priorities to make all of them >= 0. This is
  952. // needed so that a node with a few pods with negative priority is not
  953. // picked over a node with a smaller number of pods with the same negative
  954. // priority (and similar scenarios).
  955. sumPriorities += int64(util.GetPodPriority(pod)) + int64(math.MaxInt32+1)
  956. }
  957. if sumPriorities < minSumPriorities {
  958. minSumPriorities = sumPriorities
  959. lenNodes1 = 0
  960. }
  961. if sumPriorities == minSumPriorities {
  962. minNodes1[lenNodes1] = node
  963. lenNodes1++
  964. }
  965. }
  966. if lenNodes1 == 1 {
  967. return minNodes1[0]
  968. }
  969. // There are a few nodes with minimum highest priority victim and sum of priorities.
  970. // Find one with the minimum number of pods.
  971. minNumPods := math.MaxInt32
  972. lenNodes2 = 0
  973. for i := 0; i < lenNodes1; i++ {
  974. node := minNodes1[i]
  975. numPods := len(nodesToVictims[node].Pods)
  976. if numPods < minNumPods {
  977. minNumPods = numPods
  978. lenNodes2 = 0
  979. }
  980. if numPods == minNumPods {
  981. minNodes2[lenNodes2] = node
  982. lenNodes2++
  983. }
  984. }
  985. if lenNodes2 == 1 {
  986. return minNodes2[0]
  987. }
  988. // There are a few nodes with same number of pods.
  989. // Find the node that satisfies latest(earliestStartTime(all highest-priority pods on node))
  990. latestStartTime := util.GetEarliestPodStartTime(nodesToVictims[minNodes2[0]])
  991. if latestStartTime == nil {
  992. // If the earliest start time of all pods on the 1st node is nil, just return it,
  993. // which is not expected to happen.
  994. klog.Errorf("earliestStartTime is nil for node %s. Should not reach here.", minNodes2[0])
  995. return minNodes2[0]
  996. }
  997. nodeToReturn := minNodes2[0]
  998. for i := 1; i < lenNodes2; i++ {
  999. node := minNodes2[i]
  1000. // Get earliest start time of all pods on the current node.
  1001. earliestStartTimeOnNode := util.GetEarliestPodStartTime(nodesToVictims[node])
  1002. if earliestStartTimeOnNode == nil {
  1003. klog.Errorf("earliestStartTime is nil for node %s. Should not reach here.", node)
  1004. continue
  1005. }
  1006. if earliestStartTimeOnNode.After(latestStartTime.Time) {
  1007. latestStartTime = earliestStartTimeOnNode
  1008. nodeToReturn = node
  1009. }
  1010. }
  1011. return nodeToReturn
  1012. }
  1013. // selectNodesForPreemption finds all the nodes with possible victims for
  1014. // preemption in parallel.
  1015. func selectNodesForPreemption(pod *v1.Pod,
  1016. nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
  1017. potentialNodes []*v1.Node,
  1018. fitPredicates map[string]predicates.FitPredicate,
  1019. metadataProducer predicates.PredicateMetadataProducer,
  1020. queue internalqueue.SchedulingQueue,
  1021. pdbs []*policy.PodDisruptionBudget,
  1022. ) (map[*v1.Node]*schedulerapi.Victims, error) {
  1023. nodeToVictims := map[*v1.Node]*schedulerapi.Victims{}
  1024. var resultLock sync.Mutex
  1025. // We can use the same metadata producer for all nodes.
  1026. meta := metadataProducer(pod, nodeNameToInfo)
  1027. checkNode := func(i int) {
  1028. nodeName := potentialNodes[i].Name
  1029. var metaCopy predicates.PredicateMetadata
  1030. if meta != nil {
  1031. metaCopy = meta.ShallowCopy()
  1032. }
  1033. pods, numPDBViolations, fits := selectVictimsOnNode(pod, metaCopy, nodeNameToInfo[nodeName], fitPredicates, queue, pdbs)
  1034. if fits {
  1035. resultLock.Lock()
  1036. victims := schedulerapi.Victims{
  1037. Pods: pods,
  1038. NumPDBViolations: numPDBViolations,
  1039. }
  1040. nodeToVictims[potentialNodes[i]] = &victims
  1041. resultLock.Unlock()
  1042. }
  1043. }
  1044. workqueue.ParallelizeUntil(context.TODO(), 16, len(potentialNodes), checkNode)
  1045. return nodeToVictims, nil
  1046. }
  1047. // filterPodsWithPDBViolation groups the given "pods" into two groups of "violatingPods"
  1048. // and "nonViolatingPods" based on whether their PDBs will be violated if they are
  1049. // preempted.
  1050. // This function is stable and does not change the order of received pods. So, if it
  1051. // receives a sorted list, grouping will preserve the order of the input list.
  1052. func filterPodsWithPDBViolation(pods []interface{}, pdbs []*policy.PodDisruptionBudget) (violatingPods, nonViolatingPods []*v1.Pod) {
  1053. for _, obj := range pods {
  1054. pod := obj.(*v1.Pod)
  1055. pdbForPodIsViolated := false
  1056. // A pod with no labels will not match any PDB. So, no need to check.
  1057. if len(pod.Labels) != 0 {
  1058. for _, pdb := range pdbs {
  1059. if pdb.Namespace != pod.Namespace {
  1060. continue
  1061. }
  1062. selector, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)
  1063. if err != nil {
  1064. continue
  1065. }
  1066. // A PDB with a nil or empty selector matches nothing.
  1067. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
  1068. continue
  1069. }
  1070. // We have found a matching PDB.
  1071. if pdb.Status.PodDisruptionsAllowed <= 0 {
  1072. pdbForPodIsViolated = true
  1073. break
  1074. }
  1075. }
  1076. }
  1077. if pdbForPodIsViolated {
  1078. violatingPods = append(violatingPods, pod)
  1079. } else {
  1080. nonViolatingPods = append(nonViolatingPods, pod)
  1081. }
  1082. }
  1083. return violatingPods, nonViolatingPods
  1084. }
  1085. // selectVictimsOnNode finds minimum set of pods on the given node that should
  1086. // be preempted in order to make enough room for "pod" to be scheduled. The
  1087. // minimum set selected is subject to the constraint that a higher-priority pod
  1088. // is never preempted when a lower-priority pod could be (higher/lower relative
  1089. // to one another, not relative to the preemptor "pod").
  1090. // The algorithm first checks if the pod can be scheduled on the node when all the
  1091. // lower priority pods are gone. If so, it sorts all the lower priority pods by
  1092. // their priority and then puts them into two groups of those whose PodDisruptionBudget
  1093. // will be violated if preempted and other non-violating pods. Both groups are
  1094. // sorted by priority. It first tries to reprieve as many PDB violating pods as
  1095. // possible and then does them same for non-PDB-violating pods while checking
  1096. // that the "pod" can still fit on the node.
  1097. // NOTE: This function assumes that it is never called if "pod" cannot be scheduled
  1098. // due to pod affinity, node affinity, or node anti-affinity reasons. None of
  1099. // these predicates can be satisfied by removing more pods from the node.
  1100. func selectVictimsOnNode(
  1101. pod *v1.Pod,
  1102. meta predicates.PredicateMetadata,
  1103. nodeInfo *schedulernodeinfo.NodeInfo,
  1104. fitPredicates map[string]predicates.FitPredicate,
  1105. queue internalqueue.SchedulingQueue,
  1106. pdbs []*policy.PodDisruptionBudget,
  1107. ) ([]*v1.Pod, int, bool) {
  1108. if nodeInfo == nil {
  1109. return nil, 0, false
  1110. }
  1111. potentialVictims := util.SortableList{CompFunc: util.MoreImportantPod}
  1112. nodeInfoCopy := nodeInfo.Clone()
  1113. removePod := func(rp *v1.Pod) {
  1114. nodeInfoCopy.RemovePod(rp)
  1115. if meta != nil {
  1116. meta.RemovePod(rp)
  1117. }
  1118. }
  1119. addPod := func(ap *v1.Pod) {
  1120. nodeInfoCopy.AddPod(ap)
  1121. if meta != nil {
  1122. meta.AddPod(ap, nodeInfoCopy)
  1123. }
  1124. }
  1125. // As the first step, remove all the lower priority pods from the node and
  1126. // check if the given pod can be scheduled.
  1127. podPriority := util.GetPodPriority(pod)
  1128. for _, p := range nodeInfoCopy.Pods() {
  1129. if util.GetPodPriority(p) < podPriority {
  1130. potentialVictims.Items = append(potentialVictims.Items, p)
  1131. removePod(p)
  1132. }
  1133. }
  1134. // If the new pod does not fit after removing all the lower priority pods,
  1135. // we are almost done and this node is not suitable for preemption. The only
  1136. // condition that we could check is if the "pod" is failing to schedule due to
  1137. // inter-pod affinity to one or more victims, but we have decided not to
  1138. // support this case for performance reasons. Having affinity to lower
  1139. // priority pods is not a recommended configuration anyway.
  1140. if fits, _, err := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, queue, false); !fits {
  1141. if err != nil {
  1142. klog.Warningf("Encountered error while selecting victims on node %v: %v", nodeInfo.Node().Name, err)
  1143. }
  1144. return nil, 0, false
  1145. }
  1146. var victims []*v1.Pod
  1147. numViolatingVictim := 0
  1148. potentialVictims.Sort()
  1149. // Try to reprieve as many pods as possible. We first try to reprieve the PDB
  1150. // violating victims and then other non-violating ones. In both cases, we start
  1151. // from the highest priority victims.
  1152. violatingVictims, nonViolatingVictims := filterPodsWithPDBViolation(potentialVictims.Items, pdbs)
  1153. reprievePod := func(p *v1.Pod) bool {
  1154. addPod(p)
  1155. fits, _, _ := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, queue, false)
  1156. if !fits {
  1157. removePod(p)
  1158. victims = append(victims, p)
  1159. klog.V(5).Infof("Pod %v/%v is a potential preemption victim on node %v.", p.Namespace, p.Name, nodeInfo.Node().Name)
  1160. }
  1161. return fits
  1162. }
  1163. for _, p := range violatingVictims {
  1164. if !reprievePod(p) {
  1165. numViolatingVictim++
  1166. }
  1167. }
  1168. // Now we try to reprieve non-violating victims.
  1169. for _, p := range nonViolatingVictims {
  1170. reprievePod(p)
  1171. }
  1172. return victims, numViolatingVictim, true
  1173. }
  1174. // unresolvablePredicateExists checks whether failedPredicates has unresolvable predicate.
  1175. func unresolvablePredicateExists(failedPredicates []predicates.PredicateFailureReason) bool {
  1176. for _, failedPredicate := range failedPredicates {
  1177. if _, ok := unresolvablePredicateFailureErrors[failedPredicate]; ok {
  1178. return true
  1179. }
  1180. }
  1181. return false
  1182. }
  1183. // nodesWherePreemptionMightHelp returns a list of nodes with failed predicates
  1184. // that may be satisfied by removing pods from the node.
  1185. func nodesWherePreemptionMightHelp(nodes []*v1.Node, failedPredicatesMap FailedPredicateMap) []*v1.Node {
  1186. potentialNodes := []*v1.Node{}
  1187. for _, node := range nodes {
  1188. failedPredicates, _ := failedPredicatesMap[node.Name]
  1189. // If we assume that scheduler looks at all nodes and populates the failedPredicateMap
  1190. // (which is the case today), the !found case should never happen, but we'd prefer
  1191. // to rely less on such assumptions in the code when checking does not impose
  1192. // significant overhead.
  1193. // Also, we currently assume all failures returned by extender as resolvable.
  1194. if !unresolvablePredicateExists(failedPredicates) {
  1195. klog.V(3).Infof("Node %v is a potential node for preemption.", node.Name)
  1196. potentialNodes = append(potentialNodes, node)
  1197. }
  1198. }
  1199. return potentialNodes
  1200. }
  1201. // podEligibleToPreemptOthers determines whether this pod should be considered
  1202. // for preempting other pods or not. If this pod has already preempted other
  1203. // pods and those are in their graceful termination period, it shouldn't be
  1204. // considered for preemption.
  1205. // We look at the node that is nominated for this pod and as long as there are
  1206. // terminating pods on the node, we don't consider this for preempting more pods.
  1207. func podEligibleToPreemptOthers(pod *v1.Pod, nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo, enableNonPreempting bool) bool {
  1208. if enableNonPreempting && pod.Spec.PreemptionPolicy != nil && *pod.Spec.PreemptionPolicy == v1.PreemptNever {
  1209. klog.V(5).Infof("Pod %v/%v is not eligible for preemption because it has a preemptionPolicy of %v", pod.Namespace, pod.Name, v1.PreemptNever)
  1210. return false
  1211. }
  1212. nomNodeName := pod.Status.NominatedNodeName
  1213. if len(nomNodeName) > 0 {
  1214. if nodeInfo, found := nodeNameToInfo[nomNodeName]; found {
  1215. podPriority := util.GetPodPriority(pod)
  1216. for _, p := range nodeInfo.Pods() {
  1217. if p.DeletionTimestamp != nil && util.GetPodPriority(p) < podPriority {
  1218. // There is a terminating pod on the nominated node.
  1219. return false
  1220. }
  1221. }
  1222. }
  1223. }
  1224. return true
  1225. }
  1226. // podPassesBasicChecks makes sanity checks on the pod if it can be scheduled.
  1227. func podPassesBasicChecks(pod *v1.Pod, pvcLister corelisters.PersistentVolumeClaimLister) error {
  1228. // Check PVCs used by the pod
  1229. namespace := pod.Namespace
  1230. manifest := &(pod.Spec)
  1231. for i := range manifest.Volumes {
  1232. volume := &manifest.Volumes[i]
  1233. if volume.PersistentVolumeClaim == nil {
  1234. // Volume is not a PVC, ignore
  1235. continue
  1236. }
  1237. pvcName := volume.PersistentVolumeClaim.ClaimName
  1238. pvc, err := pvcLister.PersistentVolumeClaims(namespace).Get(pvcName)
  1239. if err != nil {
  1240. // The error has already enough context ("persistentvolumeclaim "myclaim" not found")
  1241. return err
  1242. }
  1243. if pvc.DeletionTimestamp != nil {
  1244. return fmt.Errorf("persistentvolumeclaim %q is being deleted", pvc.Name)
  1245. }
  1246. }
  1247. return nil
  1248. }
  1249. // NewGenericScheduler creates a genericScheduler object.
  1250. func NewGenericScheduler(
  1251. cache internalcache.Cache,
  1252. podQueue internalqueue.SchedulingQueue,
  1253. predicates map[string]predicates.FitPredicate,
  1254. predicateMetaProducer predicates.PredicateMetadataProducer,
  1255. prioritizers []priorities.PriorityConfig,
  1256. priorityMetaProducer priorities.PriorityMetadataProducer,
  1257. framework framework.Framework,
  1258. extenders []algorithm.SchedulerExtender,
  1259. volumeBinder *volumebinder.VolumeBinder,
  1260. pvcLister corelisters.PersistentVolumeClaimLister,
  1261. pdbLister algorithm.PDBLister,
  1262. alwaysCheckAllPredicates bool,
  1263. disablePreemption bool,
  1264. percentageOfNodesToScore int32,
  1265. enableNonPreempting bool,
  1266. ) ScheduleAlgorithm {
  1267. return &genericScheduler{
  1268. cache: cache,
  1269. schedulingQueue: podQueue,
  1270. predicates: predicates,
  1271. predicateMetaProducer: predicateMetaProducer,
  1272. prioritizers: prioritizers,
  1273. priorityMetaProducer: priorityMetaProducer,
  1274. framework: framework,
  1275. extenders: extenders,
  1276. nodeInfoSnapshot: framework.NodeInfoSnapshot(),
  1277. volumeBinder: volumeBinder,
  1278. pvcLister: pvcLister,
  1279. pdbLister: pdbLister,
  1280. alwaysCheckAllPredicates: alwaysCheckAllPredicates,
  1281. disablePreemption: disablePreemption,
  1282. percentageOfNodesToScore: percentageOfNodesToScore,
  1283. enableNonPreempting: enableNonPreempting,
  1284. }
  1285. }