generic_scheduler.go 54 KB

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