generic_scheduler.go 55 KB

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