generic_scheduler.go 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. "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. if err != nil {
  212. return result, err
  213. }
  214. metrics.SchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  215. metrics.DeprecatedSchedulingAlgorithmPriorityEvaluationDuration.Observe(metrics.SinceInMicroseconds(startPriorityEvalTime))
  216. metrics.SchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  217. metrics.DeprecatedSchedulingLatency.WithLabelValues(metrics.PriorityEvaluation).Observe(metrics.SinceInSeconds(startPriorityEvalTime))
  218. trace.Step("Selecting host")
  219. host, err := g.selectHost(priorityList)
  220. return ScheduleResult{
  221. SuggestedHost: host,
  222. EvaluatedNodes: len(filteredNodes) + len(failedPredicateMap),
  223. FeasibleNodes: len(filteredNodes),
  224. }, err
  225. }
  226. // Prioritizers returns a slice containing all the scheduler's priority
  227. // functions and their config. It is exposed for testing only.
  228. func (g *genericScheduler) Prioritizers() []priorities.PriorityConfig {
  229. return g.prioritizers
  230. }
  231. // Predicates returns a map containing all the scheduler's predicate
  232. // functions. It is exposed for testing only.
  233. func (g *genericScheduler) Predicates() map[string]predicates.FitPredicate {
  234. return g.predicates
  235. }
  236. // findMaxScores returns the indexes of nodes in the "priorityList" that has the highest "Score".
  237. func findMaxScores(priorityList schedulerapi.HostPriorityList) []int {
  238. maxScoreIndexes := make([]int, 0, len(priorityList)/2)
  239. maxScore := priorityList[0].Score
  240. for i, hp := range priorityList {
  241. if hp.Score > maxScore {
  242. maxScore = hp.Score
  243. maxScoreIndexes = maxScoreIndexes[:0]
  244. maxScoreIndexes = append(maxScoreIndexes, i)
  245. } else if hp.Score == maxScore {
  246. maxScoreIndexes = append(maxScoreIndexes, i)
  247. }
  248. }
  249. return maxScoreIndexes
  250. }
  251. // selectHost takes a prioritized list of nodes and then picks one
  252. // in a round-robin manner from the nodes that had the highest score.
  253. func (g *genericScheduler) selectHost(priorityList schedulerapi.HostPriorityList) (string, error) {
  254. if len(priorityList) == 0 {
  255. return "", fmt.Errorf("empty priorityList")
  256. }
  257. maxScores := findMaxScores(priorityList)
  258. ix := int(g.lastNodeIndex % uint64(len(maxScores)))
  259. g.lastNodeIndex++
  260. return priorityList[maxScores[ix]].Host, nil
  261. }
  262. // preempt finds nodes with pods that can be preempted to make room for "pod" to
  263. // schedule. It chooses one of the nodes and preempts the pods on the node and
  264. // returns 1) the node, 2) the list of preempted pods if such a node is found,
  265. // 3) A list of pods whose nominated node name should be cleared, and 4) any
  266. // possible error.
  267. // Preempt does not update its snapshot. It uses the same snapshot used in the
  268. // scheduling cycle. This is to avoid a scenario where preempt finds feasible
  269. // nodes without preempting any pod. When there are many pending pods in the
  270. // scheduling queue a nominated pod will go back to the queue and behind
  271. // other pods with the same priority. The nominated pod prevents other pods from
  272. // using the nominated resources and the nominated pod could take a long time
  273. // before it is retried after many other pending pods.
  274. func (g *genericScheduler) Preempt(pod *v1.Pod, nodeLister algorithm.NodeLister, scheduleErr error) (*v1.Node, []*v1.Pod, []*v1.Pod, error) {
  275. // Scheduler may return various types of errors. Consider preemption only if
  276. // the error is of type FitError.
  277. fitError, ok := scheduleErr.(*FitError)
  278. if !ok || fitError == nil {
  279. return nil, nil, nil, nil
  280. }
  281. if !podEligibleToPreemptOthers(pod, g.nodeInfoSnapshot.NodeInfoMap, g.enableNonPreempting) {
  282. klog.V(5).Infof("Pod %v/%v is not eligible for more preemption.", pod.Namespace, pod.Name)
  283. return nil, nil, nil, nil
  284. }
  285. allNodes, err := nodeLister.List()
  286. if err != nil {
  287. return nil, nil, nil, err
  288. }
  289. if len(allNodes) == 0 {
  290. return nil, nil, nil, ErrNoNodesAvailable
  291. }
  292. potentialNodes := nodesWherePreemptionMightHelp(allNodes, fitError.FailedPredicates)
  293. if len(potentialNodes) == 0 {
  294. klog.V(3).Infof("Preemption will not help schedule pod %v/%v on any node.", pod.Namespace, pod.Name)
  295. // In this case, we should clean-up any existing nominated node name of the pod.
  296. return nil, nil, []*v1.Pod{pod}, nil
  297. }
  298. pdbs, err := g.pdbLister.List(labels.Everything())
  299. if err != nil {
  300. return nil, nil, nil, err
  301. }
  302. nodeToVictims, err := selectNodesForPreemption(pod, g.nodeInfoSnapshot.NodeInfoMap, potentialNodes, g.predicates,
  303. g.predicateMetaProducer, g.schedulingQueue, pdbs)
  304. if err != nil {
  305. return nil, nil, nil, err
  306. }
  307. // We will only check nodeToVictims with extenders that support preemption.
  308. // Extenders which do not support preemption may later prevent preemptor from being scheduled on the nominated
  309. // node. In that case, scheduler will find a different host for the preemptor in subsequent scheduling cycles.
  310. nodeToVictims, err = g.processPreemptionWithExtenders(pod, nodeToVictims)
  311. if err != nil {
  312. return nil, nil, nil, err
  313. }
  314. candidateNode := pickOneNodeForPreemption(nodeToVictims)
  315. if candidateNode == nil {
  316. return nil, nil, nil, nil
  317. }
  318. // Lower priority pods nominated to run on this node, may no longer fit on
  319. // this node. So, we should remove their nomination. Removing their
  320. // nomination updates these pods and moves them to the active queue. It
  321. // lets scheduler find another place for them.
  322. nominatedPods := g.getLowerPriorityNominatedPods(pod, candidateNode.Name)
  323. if nodeInfo, ok := g.nodeInfoSnapshot.NodeInfoMap[candidateNode.Name]; ok {
  324. return nodeInfo.Node(), nodeToVictims[candidateNode].Pods, nominatedPods, nil
  325. }
  326. return nil, nil, nil, fmt.Errorf(
  327. "preemption failed: the target node %s has been deleted from scheduler cache",
  328. candidateNode.Name)
  329. }
  330. // processPreemptionWithExtenders processes preemption with extenders
  331. func (g *genericScheduler) processPreemptionWithExtenders(
  332. pod *v1.Pod,
  333. nodeToVictims map[*v1.Node]*schedulerapi.Victims,
  334. ) (map[*v1.Node]*schedulerapi.Victims, error) {
  335. if len(nodeToVictims) > 0 {
  336. for _, extender := range g.extenders {
  337. if extender.SupportsPreemption() && extender.IsInterested(pod) {
  338. newNodeToVictims, err := extender.ProcessPreemption(
  339. pod,
  340. nodeToVictims,
  341. g.nodeInfoSnapshot.NodeInfoMap,
  342. )
  343. if err != nil {
  344. if extender.IsIgnorable() {
  345. klog.Warningf("Skipping extender %v as it returned error %v and has ignorable flag set",
  346. extender, err)
  347. continue
  348. }
  349. return nil, err
  350. }
  351. // Replace nodeToVictims with new result after preemption. So the
  352. // rest of extenders can continue use it as parameter.
  353. nodeToVictims = newNodeToVictims
  354. // If node list becomes empty, no preemption can happen regardless of other extenders.
  355. if len(nodeToVictims) == 0 {
  356. break
  357. }
  358. }
  359. }
  360. }
  361. return nodeToVictims, nil
  362. }
  363. // getLowerPriorityNominatedPods returns pods whose priority is smaller than the
  364. // priority of the given "pod" and are nominated to run on the given node.
  365. // Note: We could possibly check if the nominated lower priority pods still fit
  366. // and return those that no longer fit, but that would require lots of
  367. // manipulation of NodeInfo and PredicateMeta per nominated pod. It may not be
  368. // worth the complexity, especially because we generally expect to have a very
  369. // small number of nominated pods per node.
  370. func (g *genericScheduler) getLowerPriorityNominatedPods(pod *v1.Pod, nodeName string) []*v1.Pod {
  371. pods := g.schedulingQueue.NominatedPodsForNode(nodeName)
  372. if len(pods) == 0 {
  373. return nil
  374. }
  375. var lowerPriorityPods []*v1.Pod
  376. podPriority := util.GetPodPriority(pod)
  377. for _, p := range pods {
  378. if util.GetPodPriority(p) < podPriority {
  379. lowerPriorityPods = append(lowerPriorityPods, p)
  380. }
  381. }
  382. return lowerPriorityPods
  383. }
  384. // numFeasibleNodesToFind returns the number of feasible nodes that once found, the scheduler stops
  385. // its search for more feasible nodes.
  386. func (g *genericScheduler) numFeasibleNodesToFind(numAllNodes int32) (numNodes int32) {
  387. if numAllNodes < minFeasibleNodesToFind || g.percentageOfNodesToScore >= 100 {
  388. return numAllNodes
  389. }
  390. adaptivePercentage := g.percentageOfNodesToScore
  391. if adaptivePercentage <= 0 {
  392. adaptivePercentage = schedulerapi.DefaultPercentageOfNodesToScore - numAllNodes/125
  393. if adaptivePercentage < minFeasibleNodesPercentageToFind {
  394. adaptivePercentage = minFeasibleNodesPercentageToFind
  395. }
  396. }
  397. numNodes = numAllNodes * adaptivePercentage / 100
  398. if numNodes < minFeasibleNodesToFind {
  399. return minFeasibleNodesToFind
  400. }
  401. return numNodes
  402. }
  403. // Filters the nodes to find the ones that fit based on the given predicate functions
  404. // Each node is passed through the predicate functions to determine if it is a fit
  405. func (g *genericScheduler) findNodesThatFit(pod *v1.Pod, nodes []*v1.Node) ([]*v1.Node, FailedPredicateMap, error) {
  406. var filtered []*v1.Node
  407. failedPredicateMap := FailedPredicateMap{}
  408. if len(g.predicates) == 0 {
  409. filtered = nodes
  410. } else {
  411. allNodes := int32(g.cache.NodeTree().NumNodes())
  412. numNodesToFind := g.numFeasibleNodesToFind(allNodes)
  413. // Create filtered list with enough space to avoid growing it
  414. // and allow assigning.
  415. filtered = make([]*v1.Node, numNodesToFind)
  416. errs := errors.MessageCountMap{}
  417. var (
  418. predicateResultLock sync.Mutex
  419. filteredLen int32
  420. )
  421. ctx, cancel := context.WithCancel(context.Background())
  422. // We can use the same metadata producer for all nodes.
  423. meta := g.predicateMetaProducer(pod, g.nodeInfoSnapshot.NodeInfoMap)
  424. checkNode := func(i int) {
  425. nodeName := g.cache.NodeTree().Next()
  426. fits, failedPredicates, err := podFitsOnNode(
  427. pod,
  428. meta,
  429. g.nodeInfoSnapshot.NodeInfoMap[nodeName],
  430. g.predicates,
  431. g.schedulingQueue,
  432. g.alwaysCheckAllPredicates,
  433. )
  434. if err != nil {
  435. predicateResultLock.Lock()
  436. errs[err.Error()]++
  437. predicateResultLock.Unlock()
  438. return
  439. }
  440. if fits {
  441. length := atomic.AddInt32(&filteredLen, 1)
  442. if length > numNodesToFind {
  443. cancel()
  444. atomic.AddInt32(&filteredLen, -1)
  445. } else {
  446. filtered[length-1] = g.nodeInfoSnapshot.NodeInfoMap[nodeName].Node()
  447. }
  448. } else {
  449. predicateResultLock.Lock()
  450. failedPredicateMap[nodeName] = failedPredicates
  451. predicateResultLock.Unlock()
  452. }
  453. }
  454. // Stops searching for more nodes once the configured number of feasible nodes
  455. // are found.
  456. workqueue.ParallelizeUntil(ctx, 16, int(allNodes), checkNode)
  457. filtered = filtered[:filteredLen]
  458. if len(errs) > 0 {
  459. return []*v1.Node{}, FailedPredicateMap{}, errors.CreateAggregateFromMessageCountMap(errs)
  460. }
  461. }
  462. if len(filtered) > 0 && len(g.extenders) != 0 {
  463. for _, extender := range g.extenders {
  464. if !extender.IsInterested(pod) {
  465. continue
  466. }
  467. filteredList, failedMap, err := extender.Filter(pod, filtered, g.nodeInfoSnapshot.NodeInfoMap)
  468. if err != nil {
  469. if extender.IsIgnorable() {
  470. klog.Warningf("Skipping extender %v as it returned error %v and has ignorable flag set",
  471. extender, err)
  472. continue
  473. } else {
  474. return []*v1.Node{}, FailedPredicateMap{}, err
  475. }
  476. }
  477. for failedNodeName, failedMsg := range failedMap {
  478. if _, found := failedPredicateMap[failedNodeName]; !found {
  479. failedPredicateMap[failedNodeName] = []predicates.PredicateFailureReason{}
  480. }
  481. failedPredicateMap[failedNodeName] = append(failedPredicateMap[failedNodeName], predicates.NewFailureReason(failedMsg))
  482. }
  483. filtered = filteredList
  484. if len(filtered) == 0 {
  485. break
  486. }
  487. }
  488. }
  489. return filtered, failedPredicateMap, nil
  490. }
  491. // addNominatedPods adds pods with equal or greater priority which are nominated
  492. // to run on the node given in nodeInfo to meta and nodeInfo. It returns 1) whether
  493. // any pod was found, 2) augmented meta data, 3) augmented nodeInfo.
  494. func addNominatedPods(pod *v1.Pod, meta predicates.PredicateMetadata,
  495. nodeInfo *schedulernodeinfo.NodeInfo, queue internalqueue.SchedulingQueue) (bool, predicates.PredicateMetadata,
  496. *schedulernodeinfo.NodeInfo) {
  497. if queue == nil || nodeInfo == nil || nodeInfo.Node() == nil {
  498. // This may happen only in tests.
  499. return false, meta, nodeInfo
  500. }
  501. nominatedPods := queue.NominatedPodsForNode(nodeInfo.Node().Name)
  502. if nominatedPods == nil || len(nominatedPods) == 0 {
  503. return false, meta, nodeInfo
  504. }
  505. var metaOut predicates.PredicateMetadata
  506. if meta != nil {
  507. metaOut = meta.ShallowCopy()
  508. }
  509. nodeInfoOut := nodeInfo.Clone()
  510. for _, p := range nominatedPods {
  511. if util.GetPodPriority(p) >= util.GetPodPriority(pod) && p.UID != pod.UID {
  512. nodeInfoOut.AddPod(p)
  513. if metaOut != nil {
  514. metaOut.AddPod(p, nodeInfoOut)
  515. }
  516. }
  517. }
  518. return true, metaOut, nodeInfoOut
  519. }
  520. // podFitsOnNode checks whether a node given by NodeInfo satisfies the given predicate functions.
  521. // For given pod, podFitsOnNode will check if any equivalent pod exists and try to reuse its cached
  522. // predicate results as possible.
  523. // This function is called from two different places: Schedule and Preempt.
  524. // When it is called from Schedule, we want to test whether the pod is schedulable
  525. // on the node with all the existing pods on the node plus higher and equal priority
  526. // pods nominated to run on the node.
  527. // When it is called from Preempt, we should remove the victims of preemption and
  528. // add the nominated pods. Removal of the victims is done by SelectVictimsOnNode().
  529. // It removes victims from meta and NodeInfo before calling this function.
  530. func podFitsOnNode(
  531. pod *v1.Pod,
  532. meta predicates.PredicateMetadata,
  533. info *schedulernodeinfo.NodeInfo,
  534. predicateFuncs map[string]predicates.FitPredicate,
  535. queue internalqueue.SchedulingQueue,
  536. alwaysCheckAllPredicates bool,
  537. ) (bool, []predicates.PredicateFailureReason, error) {
  538. var failedPredicates []predicates.PredicateFailureReason
  539. podsAdded := false
  540. // We run predicates twice in some cases. If the node has greater or equal priority
  541. // nominated pods, we run them when those pods are added to meta and nodeInfo.
  542. // If all predicates succeed in this pass, we run them again when these
  543. // nominated pods are not added. This second pass is necessary because some
  544. // predicates such as inter-pod affinity may not pass without the nominated pods.
  545. // If there are no nominated pods for the node or if the first run of the
  546. // predicates fail, we don't run the second pass.
  547. // We consider only equal or higher priority pods in the first pass, because
  548. // those are the current "pod" must yield to them and not take a space opened
  549. // for running them. It is ok if the current "pod" take resources freed for
  550. // lower priority pods.
  551. // Requiring that the new pod is schedulable in both circumstances ensures that
  552. // we are making a conservative decision: predicates like resources and inter-pod
  553. // anti-affinity are more likely to fail when the nominated pods are treated
  554. // as running, while predicates like pod affinity are more likely to fail when
  555. // the nominated pods are treated as not running. We can't just assume the
  556. // nominated pods are running because they are not running right now and in fact,
  557. // they may end up getting scheduled to a different node.
  558. for i := 0; i < 2; i++ {
  559. metaToUse := meta
  560. nodeInfoToUse := info
  561. if i == 0 {
  562. podsAdded, metaToUse, nodeInfoToUse = addNominatedPods(pod, meta, info, queue)
  563. } else if !podsAdded || len(failedPredicates) != 0 {
  564. break
  565. }
  566. for _, predicateKey := range predicates.Ordering() {
  567. var (
  568. fit bool
  569. reasons []predicates.PredicateFailureReason
  570. err error
  571. )
  572. //TODO (yastij) : compute average predicate restrictiveness to export it as Prometheus metric
  573. if predicate, exist := predicateFuncs[predicateKey]; exist {
  574. fit, reasons, err = predicate(pod, metaToUse, nodeInfoToUse)
  575. if err != nil {
  576. return false, []predicates.PredicateFailureReason{}, err
  577. }
  578. if !fit {
  579. // eCache is available and valid, and predicates result is unfit, record the fail reasons
  580. failedPredicates = append(failedPredicates, reasons...)
  581. // if alwaysCheckAllPredicates is false, short circuit all predicates when one predicate fails.
  582. if !alwaysCheckAllPredicates {
  583. klog.V(5).Infoln("since alwaysCheckAllPredicates has not been set, the predicate " +
  584. "evaluation is short circuited and there are chances " +
  585. "of other predicates failing as well.")
  586. break
  587. }
  588. }
  589. }
  590. }
  591. }
  592. return len(failedPredicates) == 0, failedPredicates, nil
  593. }
  594. // PrioritizeNodes prioritizes the nodes by running the individual priority functions in parallel.
  595. // Each priority function is expected to set a score of 0-10
  596. // 0 is the lowest priority score (least preferred node) and 10 is the highest
  597. // Each priority function can also have its own weight
  598. // The node scores returned by the priority function are multiplied by the weights to get weighted scores
  599. // All scores are finally combined (added) to get the total weighted scores of all nodes
  600. func PrioritizeNodes(
  601. pod *v1.Pod,
  602. nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
  603. meta interface{},
  604. priorityConfigs []priorities.PriorityConfig,
  605. nodes []*v1.Node,
  606. extenders []algorithm.SchedulerExtender,
  607. ) (schedulerapi.HostPriorityList, error) {
  608. // If no priority configs are provided, then the EqualPriority function is applied
  609. // This is required to generate the priority list in the required format
  610. if len(priorityConfigs) == 0 && len(extenders) == 0 {
  611. result := make(schedulerapi.HostPriorityList, 0, len(nodes))
  612. for i := range nodes {
  613. hostPriority, err := EqualPriorityMap(pod, meta, nodeNameToInfo[nodes[i].Name])
  614. if err != nil {
  615. return nil, err
  616. }
  617. result = append(result, hostPriority)
  618. }
  619. return result, nil
  620. }
  621. var (
  622. mu = sync.Mutex{}
  623. wg = sync.WaitGroup{}
  624. errs []error
  625. )
  626. appendError := func(err error) {
  627. mu.Lock()
  628. defer mu.Unlock()
  629. errs = append(errs, err)
  630. }
  631. results := make([]schedulerapi.HostPriorityList, len(priorityConfigs), len(priorityConfigs))
  632. // DEPRECATED: we can remove this when all priorityConfigs implement the
  633. // Map-Reduce pattern.
  634. for i := range priorityConfigs {
  635. if priorityConfigs[i].Function != nil {
  636. wg.Add(1)
  637. go func(index int) {
  638. defer wg.Done()
  639. var err error
  640. results[index], err = priorityConfigs[index].Function(pod, nodeNameToInfo, nodes)
  641. if err != nil {
  642. appendError(err)
  643. }
  644. }(i)
  645. } else {
  646. results[i] = make(schedulerapi.HostPriorityList, len(nodes))
  647. }
  648. }
  649. workqueue.ParallelizeUntil(context.TODO(), 16, len(nodes), func(index int) {
  650. nodeInfo := nodeNameToInfo[nodes[index].Name]
  651. for i := range priorityConfigs {
  652. if priorityConfigs[i].Function != nil {
  653. continue
  654. }
  655. var err error
  656. results[i][index], err = priorityConfigs[i].Map(pod, meta, nodeInfo)
  657. if err != nil {
  658. appendError(err)
  659. results[i][index].Host = nodes[index].Name
  660. }
  661. }
  662. })
  663. for i := range priorityConfigs {
  664. if priorityConfigs[i].Reduce == nil {
  665. continue
  666. }
  667. wg.Add(1)
  668. go func(index int) {
  669. defer wg.Done()
  670. if err := priorityConfigs[index].Reduce(pod, meta, nodeNameToInfo, results[index]); err != nil {
  671. appendError(err)
  672. }
  673. if klog.V(10) {
  674. for _, hostPriority := range results[index] {
  675. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), hostPriority.Host, priorityConfigs[index].Name, hostPriority.Score)
  676. }
  677. }
  678. }(i)
  679. }
  680. // Wait for all computations to be finished.
  681. wg.Wait()
  682. if len(errs) != 0 {
  683. return schedulerapi.HostPriorityList{}, errors.NewAggregate(errs)
  684. }
  685. // Summarize all scores.
  686. result := make(schedulerapi.HostPriorityList, 0, len(nodes))
  687. for i := range nodes {
  688. result = append(result, schedulerapi.HostPriority{Host: nodes[i].Name, Score: 0})
  689. for j := range priorityConfigs {
  690. result[i].Score += results[j][i].Score * priorityConfigs[j].Weight
  691. }
  692. }
  693. if len(extenders) != 0 && nodes != nil {
  694. combinedScores := make(map[string]int, len(nodeNameToInfo))
  695. for i := range extenders {
  696. if !extenders[i].IsInterested(pod) {
  697. continue
  698. }
  699. wg.Add(1)
  700. go func(extIndex int) {
  701. defer wg.Done()
  702. prioritizedList, weight, err := extenders[extIndex].Prioritize(pod, nodes)
  703. if err != nil {
  704. // Prioritization errors from extender can be ignored, let k8s/other extenders determine the priorities
  705. return
  706. }
  707. mu.Lock()
  708. for i := range *prioritizedList {
  709. host, score := (*prioritizedList)[i].Host, (*prioritizedList)[i].Score
  710. if klog.V(10) {
  711. klog.Infof("%v -> %v: %v, Score: (%d)", util.GetPodFullName(pod), host, extenders[extIndex].Name(), score)
  712. }
  713. combinedScores[host] += score * weight
  714. }
  715. mu.Unlock()
  716. }(i)
  717. }
  718. // wait for all go routines to finish
  719. wg.Wait()
  720. for i := range result {
  721. result[i].Score += combinedScores[result[i].Host]
  722. }
  723. }
  724. if klog.V(10) {
  725. for i := range result {
  726. klog.Infof("Host %s => Score %d", result[i].Host, result[i].Score)
  727. }
  728. }
  729. return result, nil
  730. }
  731. // EqualPriorityMap is a prioritizer function that gives an equal weight of one to all nodes
  732. func EqualPriorityMap(_ *v1.Pod, _ interface{}, nodeInfo *schedulernodeinfo.NodeInfo) (schedulerapi.HostPriority, error) {
  733. node := nodeInfo.Node()
  734. if node == nil {
  735. return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
  736. }
  737. return schedulerapi.HostPriority{
  738. Host: node.Name,
  739. Score: 1,
  740. }, nil
  741. }
  742. // pickOneNodeForPreemption chooses one node among the given nodes. It assumes
  743. // pods in each map entry are ordered by decreasing priority.
  744. // It picks a node based on the following criteria:
  745. // 1. A node with minimum number of PDB violations.
  746. // 2. A node with minimum highest priority victim is picked.
  747. // 3. Ties are broken by sum of priorities of all victims.
  748. // 4. If there are still ties, node with the minimum number of victims is picked.
  749. // 5. If there are still ties, node with the latest start time of all highest priority victims is picked.
  750. // 6. If there are still ties, the first such node is picked (sort of randomly).
  751. // The 'minNodes1' and 'minNodes2' are being reused here to save the memory
  752. // allocation and garbage collection time.
  753. func pickOneNodeForPreemption(nodesToVictims map[*v1.Node]*schedulerapi.Victims) *v1.Node {
  754. if len(nodesToVictims) == 0 {
  755. return nil
  756. }
  757. minNumPDBViolatingPods := math.MaxInt32
  758. var minNodes1 []*v1.Node
  759. lenNodes1 := 0
  760. for node, victims := range nodesToVictims {
  761. if len(victims.Pods) == 0 {
  762. // We found a node that doesn't need any preemption. Return it!
  763. // This should happen rarely when one or more pods are terminated between
  764. // the time that scheduler tries to schedule the pod and the time that
  765. // preemption logic tries to find nodes for preemption.
  766. return node
  767. }
  768. numPDBViolatingPods := victims.NumPDBViolations
  769. if numPDBViolatingPods < minNumPDBViolatingPods {
  770. minNumPDBViolatingPods = numPDBViolatingPods
  771. minNodes1 = nil
  772. lenNodes1 = 0
  773. }
  774. if numPDBViolatingPods == minNumPDBViolatingPods {
  775. minNodes1 = append(minNodes1, node)
  776. lenNodes1++
  777. }
  778. }
  779. if lenNodes1 == 1 {
  780. return minNodes1[0]
  781. }
  782. // There are more than one node with minimum number PDB violating pods. Find
  783. // the one with minimum highest priority victim.
  784. minHighestPriority := int32(math.MaxInt32)
  785. var minNodes2 = make([]*v1.Node, lenNodes1)
  786. lenNodes2 := 0
  787. for i := 0; i < lenNodes1; i++ {
  788. node := minNodes1[i]
  789. victims := nodesToVictims[node]
  790. // highestPodPriority is the highest priority among the victims on this node.
  791. highestPodPriority := util.GetPodPriority(victims.Pods[0])
  792. if highestPodPriority < minHighestPriority {
  793. minHighestPriority = highestPodPriority
  794. lenNodes2 = 0
  795. }
  796. if highestPodPriority == minHighestPriority {
  797. minNodes2[lenNodes2] = node
  798. lenNodes2++
  799. }
  800. }
  801. if lenNodes2 == 1 {
  802. return minNodes2[0]
  803. }
  804. // There are a few nodes with minimum highest priority victim. Find the
  805. // smallest sum of priorities.
  806. minSumPriorities := int64(math.MaxInt64)
  807. lenNodes1 = 0
  808. for i := 0; i < lenNodes2; i++ {
  809. var sumPriorities int64
  810. node := minNodes2[i]
  811. for _, pod := range nodesToVictims[node].Pods {
  812. // We add MaxInt32+1 to all priorities to make all of them >= 0. This is
  813. // needed so that a node with a few pods with negative priority is not
  814. // picked over a node with a smaller number of pods with the same negative
  815. // priority (and similar scenarios).
  816. sumPriorities += int64(util.GetPodPriority(pod)) + int64(math.MaxInt32+1)
  817. }
  818. if sumPriorities < minSumPriorities {
  819. minSumPriorities = sumPriorities
  820. lenNodes1 = 0
  821. }
  822. if sumPriorities == minSumPriorities {
  823. minNodes1[lenNodes1] = node
  824. lenNodes1++
  825. }
  826. }
  827. if lenNodes1 == 1 {
  828. return minNodes1[0]
  829. }
  830. // There are a few nodes with minimum highest priority victim and sum of priorities.
  831. // Find one with the minimum number of pods.
  832. minNumPods := math.MaxInt32
  833. lenNodes2 = 0
  834. for i := 0; i < lenNodes1; i++ {
  835. node := minNodes1[i]
  836. numPods := len(nodesToVictims[node].Pods)
  837. if numPods < minNumPods {
  838. minNumPods = numPods
  839. lenNodes2 = 0
  840. }
  841. if numPods == minNumPods {
  842. minNodes2[lenNodes2] = node
  843. lenNodes2++
  844. }
  845. }
  846. if lenNodes2 == 1 {
  847. return minNodes2[0]
  848. }
  849. // There are a few nodes with same number of pods.
  850. // Find the node that satisfies latest(earliestStartTime(all highest-priority pods on node))
  851. latestStartTime := util.GetEarliestPodStartTime(nodesToVictims[minNodes2[0]])
  852. if latestStartTime == nil {
  853. // If the earliest start time of all pods on the 1st node is nil, just return it,
  854. // which is not expected to happen.
  855. klog.Errorf("earliestStartTime is nil for node %s. Should not reach here.", minNodes2[0])
  856. return minNodes2[0]
  857. }
  858. nodeToReturn := minNodes2[0]
  859. for i := 1; i < lenNodes2; i++ {
  860. node := minNodes2[i]
  861. // Get earliest start time of all pods on the current node.
  862. earliestStartTimeOnNode := util.GetEarliestPodStartTime(nodesToVictims[node])
  863. if earliestStartTimeOnNode == nil {
  864. klog.Errorf("earliestStartTime is nil for node %s. Should not reach here.", node)
  865. continue
  866. }
  867. if earliestStartTimeOnNode.After(latestStartTime.Time) {
  868. latestStartTime = earliestStartTimeOnNode
  869. nodeToReturn = node
  870. }
  871. }
  872. return nodeToReturn
  873. }
  874. // selectNodesForPreemption finds all the nodes with possible victims for
  875. // preemption in parallel.
  876. func selectNodesForPreemption(pod *v1.Pod,
  877. nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo,
  878. potentialNodes []*v1.Node,
  879. fitPredicates map[string]predicates.FitPredicate,
  880. metadataProducer predicates.PredicateMetadataProducer,
  881. queue internalqueue.SchedulingQueue,
  882. pdbs []*policy.PodDisruptionBudget,
  883. ) (map[*v1.Node]*schedulerapi.Victims, error) {
  884. nodeToVictims := map[*v1.Node]*schedulerapi.Victims{}
  885. var resultLock sync.Mutex
  886. // We can use the same metadata producer for all nodes.
  887. meta := metadataProducer(pod, nodeNameToInfo)
  888. checkNode := func(i int) {
  889. nodeName := potentialNodes[i].Name
  890. var metaCopy predicates.PredicateMetadata
  891. if meta != nil {
  892. metaCopy = meta.ShallowCopy()
  893. }
  894. pods, numPDBViolations, fits := selectVictimsOnNode(pod, metaCopy, nodeNameToInfo[nodeName], fitPredicates, queue, pdbs)
  895. if fits {
  896. resultLock.Lock()
  897. victims := schedulerapi.Victims{
  898. Pods: pods,
  899. NumPDBViolations: numPDBViolations,
  900. }
  901. nodeToVictims[potentialNodes[i]] = &victims
  902. resultLock.Unlock()
  903. }
  904. }
  905. workqueue.ParallelizeUntil(context.TODO(), 16, len(potentialNodes), checkNode)
  906. return nodeToVictims, nil
  907. }
  908. // filterPodsWithPDBViolation groups the given "pods" into two groups of "violatingPods"
  909. // and "nonViolatingPods" based on whether their PDBs will be violated if they are
  910. // preempted.
  911. // This function is stable and does not change the order of received pods. So, if it
  912. // receives a sorted list, grouping will preserve the order of the input list.
  913. func filterPodsWithPDBViolation(pods []interface{}, pdbs []*policy.PodDisruptionBudget) (violatingPods, nonViolatingPods []*v1.Pod) {
  914. for _, obj := range pods {
  915. pod := obj.(*v1.Pod)
  916. pdbForPodIsViolated := false
  917. // A pod with no labels will not match any PDB. So, no need to check.
  918. if len(pod.Labels) != 0 {
  919. for _, pdb := range pdbs {
  920. if pdb.Namespace != pod.Namespace {
  921. continue
  922. }
  923. selector, err := metav1.LabelSelectorAsSelector(pdb.Spec.Selector)
  924. if err != nil {
  925. continue
  926. }
  927. // A PDB with a nil or empty selector matches nothing.
  928. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
  929. continue
  930. }
  931. // We have found a matching PDB.
  932. if pdb.Status.PodDisruptionsAllowed <= 0 {
  933. pdbForPodIsViolated = true
  934. break
  935. }
  936. }
  937. }
  938. if pdbForPodIsViolated {
  939. violatingPods = append(violatingPods, pod)
  940. } else {
  941. nonViolatingPods = append(nonViolatingPods, pod)
  942. }
  943. }
  944. return violatingPods, nonViolatingPods
  945. }
  946. // selectVictimsOnNode finds minimum set of pods on the given node that should
  947. // be preempted in order to make enough room for "pod" to be scheduled. The
  948. // minimum set selected is subject to the constraint that a higher-priority pod
  949. // is never preempted when a lower-priority pod could be (higher/lower relative
  950. // to one another, not relative to the preemptor "pod").
  951. // The algorithm first checks if the pod can be scheduled on the node when all the
  952. // lower priority pods are gone. If so, it sorts all the lower priority pods by
  953. // their priority and then puts them into two groups of those whose PodDisruptionBudget
  954. // will be violated if preempted and other non-violating pods. Both groups are
  955. // sorted by priority. It first tries to reprieve as many PDB violating pods as
  956. // possible and then does them same for non-PDB-violating pods while checking
  957. // that the "pod" can still fit on the node.
  958. // NOTE: This function assumes that it is never called if "pod" cannot be scheduled
  959. // due to pod affinity, node affinity, or node anti-affinity reasons. None of
  960. // these predicates can be satisfied by removing more pods from the node.
  961. func selectVictimsOnNode(
  962. pod *v1.Pod,
  963. meta predicates.PredicateMetadata,
  964. nodeInfo *schedulernodeinfo.NodeInfo,
  965. fitPredicates map[string]predicates.FitPredicate,
  966. queue internalqueue.SchedulingQueue,
  967. pdbs []*policy.PodDisruptionBudget,
  968. ) ([]*v1.Pod, int, bool) {
  969. if nodeInfo == nil {
  970. return nil, 0, false
  971. }
  972. potentialVictims := util.SortableList{CompFunc: util.MoreImportantPod}
  973. nodeInfoCopy := nodeInfo.Clone()
  974. removePod := func(rp *v1.Pod) {
  975. nodeInfoCopy.RemovePod(rp)
  976. if meta != nil {
  977. meta.RemovePod(rp)
  978. }
  979. }
  980. addPod := func(ap *v1.Pod) {
  981. nodeInfoCopy.AddPod(ap)
  982. if meta != nil {
  983. meta.AddPod(ap, nodeInfoCopy)
  984. }
  985. }
  986. // As the first step, remove all the lower priority pods from the node and
  987. // check if the given pod can be scheduled.
  988. podPriority := util.GetPodPriority(pod)
  989. for _, p := range nodeInfoCopy.Pods() {
  990. if util.GetPodPriority(p) < podPriority {
  991. potentialVictims.Items = append(potentialVictims.Items, p)
  992. removePod(p)
  993. }
  994. }
  995. // If the new pod does not fit after removing all the lower priority pods,
  996. // we are almost done and this node is not suitable for preemption. The only
  997. // condition that we could check is if the "pod" is failing to schedule due to
  998. // inter-pod affinity to one or more victims, but we have decided not to
  999. // support this case for performance reasons. Having affinity to lower
  1000. // priority pods is not a recommended configuration anyway.
  1001. if fits, _, err := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, queue, false); !fits {
  1002. if err != nil {
  1003. klog.Warningf("Encountered error while selecting victims on node %v: %v", nodeInfo.Node().Name, err)
  1004. }
  1005. return nil, 0, false
  1006. }
  1007. var victims []*v1.Pod
  1008. numViolatingVictim := 0
  1009. potentialVictims.Sort()
  1010. // Try to reprieve as many pods as possible. We first try to reprieve the PDB
  1011. // violating victims and then other non-violating ones. In both cases, we start
  1012. // from the highest priority victims.
  1013. violatingVictims, nonViolatingVictims := filterPodsWithPDBViolation(potentialVictims.Items, pdbs)
  1014. reprievePod := func(p *v1.Pod) bool {
  1015. addPod(p)
  1016. fits, _, _ := podFitsOnNode(pod, meta, nodeInfoCopy, fitPredicates, queue, false)
  1017. if !fits {
  1018. removePod(p)
  1019. victims = append(victims, p)
  1020. klog.V(5).Infof("Pod %v/%v is a potential preemption victim on node %v.", p.Namespace, p.Name, nodeInfo.Node().Name)
  1021. }
  1022. return fits
  1023. }
  1024. for _, p := range violatingVictims {
  1025. if !reprievePod(p) {
  1026. numViolatingVictim++
  1027. }
  1028. }
  1029. // Now we try to reprieve non-violating victims.
  1030. for _, p := range nonViolatingVictims {
  1031. reprievePod(p)
  1032. }
  1033. return victims, numViolatingVictim, true
  1034. }
  1035. // unresolvablePredicateExists checks whether failedPredicates has unresolvable predicate.
  1036. func unresolvablePredicateExists(failedPredicates []predicates.PredicateFailureReason) bool {
  1037. for _, failedPredicate := range failedPredicates {
  1038. if _, ok := unresolvablePredicateFailureErrors[failedPredicate]; ok {
  1039. return true
  1040. }
  1041. }
  1042. return false
  1043. }
  1044. // nodesWherePreemptionMightHelp returns a list of nodes with failed predicates
  1045. // that may be satisfied by removing pods from the node.
  1046. func nodesWherePreemptionMightHelp(nodes []*v1.Node, failedPredicatesMap FailedPredicateMap) []*v1.Node {
  1047. potentialNodes := []*v1.Node{}
  1048. for _, node := range nodes {
  1049. failedPredicates, _ := failedPredicatesMap[node.Name]
  1050. // If we assume that scheduler looks at all nodes and populates the failedPredicateMap
  1051. // (which is the case today), the !found case should never happen, but we'd prefer
  1052. // to rely less on such assumptions in the code when checking does not impose
  1053. // significant overhead.
  1054. // Also, we currently assume all failures returned by extender as resolvable.
  1055. if !unresolvablePredicateExists(failedPredicates) {
  1056. klog.V(3).Infof("Node %v is a potential node for preemption.", node.Name)
  1057. potentialNodes = append(potentialNodes, node)
  1058. }
  1059. }
  1060. return potentialNodes
  1061. }
  1062. // podEligibleToPreemptOthers determines whether this pod should be considered
  1063. // for preempting other pods or not. If this pod has already preempted other
  1064. // pods and those are in their graceful termination period, it shouldn't be
  1065. // considered for preemption.
  1066. // We look at the node that is nominated for this pod and as long as there are
  1067. // terminating pods on the node, we don't consider this for preempting more pods.
  1068. func podEligibleToPreemptOthers(pod *v1.Pod, nodeNameToInfo map[string]*schedulernodeinfo.NodeInfo, enableNonPreempting bool) bool {
  1069. if enableNonPreempting && pod.Spec.PreemptionPolicy != nil && *pod.Spec.PreemptionPolicy == v1.PreemptNever {
  1070. 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)
  1071. return false
  1072. }
  1073. nomNodeName := pod.Status.NominatedNodeName
  1074. if len(nomNodeName) > 0 {
  1075. if nodeInfo, found := nodeNameToInfo[nomNodeName]; found {
  1076. podPriority := util.GetPodPriority(pod)
  1077. for _, p := range nodeInfo.Pods() {
  1078. if p.DeletionTimestamp != nil && util.GetPodPriority(p) < podPriority {
  1079. // There is a terminating pod on the nominated node.
  1080. return false
  1081. }
  1082. }
  1083. }
  1084. }
  1085. return true
  1086. }
  1087. // podPassesBasicChecks makes sanity checks on the pod if it can be scheduled.
  1088. func podPassesBasicChecks(pod *v1.Pod, pvcLister corelisters.PersistentVolumeClaimLister) error {
  1089. // Check PVCs used by the pod
  1090. namespace := pod.Namespace
  1091. manifest := &(pod.Spec)
  1092. for i := range manifest.Volumes {
  1093. volume := &manifest.Volumes[i]
  1094. if volume.PersistentVolumeClaim == nil {
  1095. // Volume is not a PVC, ignore
  1096. continue
  1097. }
  1098. pvcName := volume.PersistentVolumeClaim.ClaimName
  1099. pvc, err := pvcLister.PersistentVolumeClaims(namespace).Get(pvcName)
  1100. if err != nil {
  1101. // The error has already enough context ("persistentvolumeclaim "myclaim" not found")
  1102. return err
  1103. }
  1104. if pvc.DeletionTimestamp != nil {
  1105. return fmt.Errorf("persistentvolumeclaim %q is being deleted", pvc.Name)
  1106. }
  1107. }
  1108. return nil
  1109. }
  1110. // NewGenericScheduler creates a genericScheduler object.
  1111. func NewGenericScheduler(
  1112. cache internalcache.Cache,
  1113. podQueue internalqueue.SchedulingQueue,
  1114. predicates map[string]predicates.FitPredicate,
  1115. predicateMetaProducer predicates.PredicateMetadataProducer,
  1116. prioritizers []priorities.PriorityConfig,
  1117. priorityMetaProducer priorities.PriorityMetadataProducer,
  1118. framework framework.Framework,
  1119. extenders []algorithm.SchedulerExtender,
  1120. volumeBinder *volumebinder.VolumeBinder,
  1121. pvcLister corelisters.PersistentVolumeClaimLister,
  1122. pdbLister algorithm.PDBLister,
  1123. alwaysCheckAllPredicates bool,
  1124. disablePreemption bool,
  1125. percentageOfNodesToScore int32,
  1126. enableNonPreempting bool,
  1127. ) ScheduleAlgorithm {
  1128. return &genericScheduler{
  1129. cache: cache,
  1130. schedulingQueue: podQueue,
  1131. predicates: predicates,
  1132. predicateMetaProducer: predicateMetaProducer,
  1133. prioritizers: prioritizers,
  1134. priorityMetaProducer: priorityMetaProducer,
  1135. framework: framework,
  1136. extenders: extenders,
  1137. nodeInfoSnapshot: framework.NodeInfoSnapshot(),
  1138. volumeBinder: volumeBinder,
  1139. pvcLister: pvcLister,
  1140. pdbLister: pdbLister,
  1141. alwaysCheckAllPredicates: alwaysCheckAllPredicates,
  1142. disablePreemption: disablePreemption,
  1143. percentageOfNodesToScore: percentageOfNodesToScore,
  1144. enableNonPreempting: enableNonPreempting,
  1145. }
  1146. }