generic_scheduler.go 55 KB

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