generic_scheduler.go 55 KB

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