generic_scheduler.go 55 KB

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