generic_scheduler.go 55 KB

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