generic_scheduler.go 54 KB

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