generic_scheduler_test.go 112 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585
  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. "reflect"
  19. "strconv"
  20. "strings"
  21. "sync/atomic"
  22. "testing"
  23. "time"
  24. v1 "k8s.io/api/core/v1"
  25. policy "k8s.io/api/policy/v1beta1"
  26. "k8s.io/apimachinery/pkg/api/resource"
  27. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  28. "k8s.io/apimachinery/pkg/runtime"
  29. "k8s.io/apimachinery/pkg/types"
  30. "k8s.io/apimachinery/pkg/util/sets"
  31. "k8s.io/apimachinery/pkg/util/wait"
  32. "k8s.io/client-go/informers"
  33. clientsetfake "k8s.io/client-go/kubernetes/fake"
  34. schedulerapi "k8s.io/kubernetes/pkg/scheduler/apis/config"
  35. extenderv1 "k8s.io/kubernetes/pkg/scheduler/apis/extender/v1"
  36. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/defaultbinder"
  37. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/defaultpodtopologyspread"
  38. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/interpodaffinity"
  39. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodeaffinity"
  40. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodelabel"
  41. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodename"
  42. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/noderesources"
  43. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/nodeunschedulable"
  44. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/podtopologyspread"
  45. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/queuesort"
  46. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/tainttoleration"
  47. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/volumebinding"
  48. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/volumerestrictions"
  49. "k8s.io/kubernetes/pkg/scheduler/framework/plugins/volumezone"
  50. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  51. internalcache "k8s.io/kubernetes/pkg/scheduler/internal/cache"
  52. internalqueue "k8s.io/kubernetes/pkg/scheduler/internal/queue"
  53. fakelisters "k8s.io/kubernetes/pkg/scheduler/listers/fake"
  54. "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  55. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  56. st "k8s.io/kubernetes/pkg/scheduler/testing"
  57. schedutil "k8s.io/kubernetes/pkg/scheduler/util"
  58. )
  59. var (
  60. errPrioritize = fmt.Errorf("priority map encounters an error")
  61. )
  62. const ErrReasonFake = "Nodes failed the fake predicate"
  63. type trueFilterPlugin struct{}
  64. // Name returns name of the plugin.
  65. func (pl *trueFilterPlugin) Name() string {
  66. return "TrueFilter"
  67. }
  68. // Filter invoked at the filter extension point.
  69. func (pl *trueFilterPlugin) Filter(_ context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  70. return nil
  71. }
  72. // NewTrueFilterPlugin initializes a trueFilterPlugin and returns it.
  73. func NewTrueFilterPlugin(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  74. return &trueFilterPlugin{}, nil
  75. }
  76. type falseFilterPlugin struct{}
  77. // Name returns name of the plugin.
  78. func (pl *falseFilterPlugin) Name() string {
  79. return "FalseFilter"
  80. }
  81. // Filter invoked at the filter extension point.
  82. func (pl *falseFilterPlugin) Filter(_ context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  83. return framework.NewStatus(framework.Unschedulable, ErrReasonFake)
  84. }
  85. // NewFalseFilterPlugin initializes a falseFilterPlugin and returns it.
  86. func NewFalseFilterPlugin(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  87. return &falseFilterPlugin{}, nil
  88. }
  89. type matchFilterPlugin struct{}
  90. // Name returns name of the plugin.
  91. func (pl *matchFilterPlugin) Name() string {
  92. return "MatchFilter"
  93. }
  94. // Filter invoked at the filter extension point.
  95. func (pl *matchFilterPlugin) Filter(_ context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  96. node := nodeInfo.Node()
  97. if node == nil {
  98. return framework.NewStatus(framework.Error, "node not found")
  99. }
  100. if pod.Name == node.Name {
  101. return nil
  102. }
  103. return framework.NewStatus(framework.Unschedulable, ErrReasonFake)
  104. }
  105. // NewMatchFilterPlugin initializes a matchFilterPlugin and returns it.
  106. func NewMatchFilterPlugin(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  107. return &matchFilterPlugin{}, nil
  108. }
  109. type noPodsFilterPlugin struct{}
  110. // Name returns name of the plugin.
  111. func (pl *noPodsFilterPlugin) Name() string {
  112. return "NoPodsFilter"
  113. }
  114. // Filter invoked at the filter extension point.
  115. func (pl *noPodsFilterPlugin) Filter(_ context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  116. if len(nodeInfo.Pods()) == 0 {
  117. return nil
  118. }
  119. return framework.NewStatus(framework.Unschedulable, ErrReasonFake)
  120. }
  121. // NewNoPodsFilterPlugin initializes a noPodsFilterPlugin and returns it.
  122. func NewNoPodsFilterPlugin(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  123. return &noPodsFilterPlugin{}, nil
  124. }
  125. // fakeFilterPlugin is a test filter plugin to record how many times its Filter() function have
  126. // been called, and it returns different 'Code' depending on its internal 'failedNodeReturnCodeMap'.
  127. type fakeFilterPlugin struct {
  128. numFilterCalled int32
  129. failedNodeReturnCodeMap map[string]framework.Code
  130. }
  131. // Name returns name of the plugin.
  132. func (pl *fakeFilterPlugin) Name() string {
  133. return "FakeFilter"
  134. }
  135. // Filter invoked at the filter extension point.
  136. func (pl *fakeFilterPlugin) Filter(_ context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  137. atomic.AddInt32(&pl.numFilterCalled, 1)
  138. if returnCode, ok := pl.failedNodeReturnCodeMap[nodeInfo.Node().Name]; ok {
  139. return framework.NewStatus(returnCode, fmt.Sprintf("injecting failure for pod %v", pod.Name))
  140. }
  141. return nil
  142. }
  143. // NewFakeFilterPlugin initializes a fakeFilterPlugin and returns it.
  144. func NewFakeFilterPlugin(failedNodeReturnCodeMap map[string]framework.Code) framework.PluginFactory {
  145. return func(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  146. return &fakeFilterPlugin{
  147. failedNodeReturnCodeMap: failedNodeReturnCodeMap,
  148. }, nil
  149. }
  150. }
  151. type numericMapPlugin struct{}
  152. func newNumericMapPlugin() framework.PluginFactory {
  153. return func(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  154. return &numericMapPlugin{}, nil
  155. }
  156. }
  157. func (pl *numericMapPlugin) Name() string {
  158. return "NumericMap"
  159. }
  160. func (pl *numericMapPlugin) Score(_ context.Context, _ *framework.CycleState, _ *v1.Pod, nodeName string) (int64, *framework.Status) {
  161. score, err := strconv.Atoi(nodeName)
  162. if err != nil {
  163. return 0, framework.NewStatus(framework.Error, fmt.Sprintf("Error converting nodename to int: %+v", nodeName))
  164. }
  165. return int64(score), nil
  166. }
  167. func (pl *numericMapPlugin) ScoreExtensions() framework.ScoreExtensions {
  168. return nil
  169. }
  170. type reverseNumericMapPlugin struct{}
  171. func newReverseNumericMapPlugin() framework.PluginFactory {
  172. return func(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  173. return &reverseNumericMapPlugin{}, nil
  174. }
  175. }
  176. func (pl *reverseNumericMapPlugin) Name() string {
  177. return "ReverseNumericMap"
  178. }
  179. func (pl *reverseNumericMapPlugin) Score(_ context.Context, _ *framework.CycleState, _ *v1.Pod, nodeName string) (int64, *framework.Status) {
  180. score, err := strconv.Atoi(nodeName)
  181. if err != nil {
  182. return 0, framework.NewStatus(framework.Error, fmt.Sprintf("Error converting nodename to int: %+v", nodeName))
  183. }
  184. return int64(score), nil
  185. }
  186. func (pl *reverseNumericMapPlugin) ScoreExtensions() framework.ScoreExtensions {
  187. return pl
  188. }
  189. func (pl *reverseNumericMapPlugin) NormalizeScore(_ context.Context, _ *framework.CycleState, _ *v1.Pod, nodeScores framework.NodeScoreList) *framework.Status {
  190. var maxScore float64
  191. minScore := math.MaxFloat64
  192. for _, hostPriority := range nodeScores {
  193. maxScore = math.Max(maxScore, float64(hostPriority.Score))
  194. minScore = math.Min(minScore, float64(hostPriority.Score))
  195. }
  196. for i, hostPriority := range nodeScores {
  197. nodeScores[i] = framework.NodeScore{
  198. Name: hostPriority.Name,
  199. Score: int64(maxScore + minScore - float64(hostPriority.Score)),
  200. }
  201. }
  202. return nil
  203. }
  204. type trueMapPlugin struct{}
  205. func newTrueMapPlugin() framework.PluginFactory {
  206. return func(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  207. return &trueMapPlugin{}, nil
  208. }
  209. }
  210. func (pl *trueMapPlugin) Name() string {
  211. return "TrueMap"
  212. }
  213. func (pl *trueMapPlugin) Score(_ context.Context, _ *framework.CycleState, _ *v1.Pod, _ string) (int64, *framework.Status) {
  214. return 1, nil
  215. }
  216. func (pl *trueMapPlugin) ScoreExtensions() framework.ScoreExtensions {
  217. return pl
  218. }
  219. func (pl *trueMapPlugin) NormalizeScore(_ context.Context, _ *framework.CycleState, _ *v1.Pod, nodeScores framework.NodeScoreList) *framework.Status {
  220. for _, host := range nodeScores {
  221. if host.Name == "" {
  222. return framework.NewStatus(framework.Error, "unexpected empty host name")
  223. }
  224. }
  225. return nil
  226. }
  227. type falseMapPlugin struct{}
  228. func newFalseMapPlugin() framework.PluginFactory {
  229. return func(_ *runtime.Unknown, _ framework.FrameworkHandle) (framework.Plugin, error) {
  230. return &falseMapPlugin{}, nil
  231. }
  232. }
  233. func (pl *falseMapPlugin) Name() string {
  234. return "FalseMap"
  235. }
  236. func (pl *falseMapPlugin) Score(_ context.Context, _ *framework.CycleState, _ *v1.Pod, _ string) (int64, *framework.Status) {
  237. return 0, framework.NewStatus(framework.Error, errPrioritize.Error())
  238. }
  239. func (pl *falseMapPlugin) ScoreExtensions() framework.ScoreExtensions {
  240. return nil
  241. }
  242. var emptySnapshot = internalcache.NewEmptySnapshot()
  243. func makeNodeList(nodeNames []string) []*v1.Node {
  244. result := make([]*v1.Node, 0, len(nodeNames))
  245. for _, nodeName := range nodeNames {
  246. result = append(result, &v1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName}})
  247. }
  248. return result
  249. }
  250. func TestSelectHost(t *testing.T) {
  251. scheduler := genericScheduler{}
  252. tests := []struct {
  253. name string
  254. list framework.NodeScoreList
  255. possibleHosts sets.String
  256. expectsErr bool
  257. }{
  258. {
  259. name: "unique properly ordered scores",
  260. list: []framework.NodeScore{
  261. {Name: "machine1.1", Score: 1},
  262. {Name: "machine2.1", Score: 2},
  263. },
  264. possibleHosts: sets.NewString("machine2.1"),
  265. expectsErr: false,
  266. },
  267. {
  268. name: "equal scores",
  269. list: []framework.NodeScore{
  270. {Name: "machine1.1", Score: 1},
  271. {Name: "machine1.2", Score: 2},
  272. {Name: "machine1.3", Score: 2},
  273. {Name: "machine2.1", Score: 2},
  274. },
  275. possibleHosts: sets.NewString("machine1.2", "machine1.3", "machine2.1"),
  276. expectsErr: false,
  277. },
  278. {
  279. name: "out of order scores",
  280. list: []framework.NodeScore{
  281. {Name: "machine1.1", Score: 3},
  282. {Name: "machine1.2", Score: 3},
  283. {Name: "machine2.1", Score: 2},
  284. {Name: "machine3.1", Score: 1},
  285. {Name: "machine1.3", Score: 3},
  286. },
  287. possibleHosts: sets.NewString("machine1.1", "machine1.2", "machine1.3"),
  288. expectsErr: false,
  289. },
  290. {
  291. name: "empty priority list",
  292. list: []framework.NodeScore{},
  293. possibleHosts: sets.NewString(),
  294. expectsErr: true,
  295. },
  296. }
  297. for _, test := range tests {
  298. t.Run(test.name, func(t *testing.T) {
  299. // increase the randomness
  300. for i := 0; i < 10; i++ {
  301. got, err := scheduler.selectHost(test.list)
  302. if test.expectsErr {
  303. if err == nil {
  304. t.Error("Unexpected non-error")
  305. }
  306. } else {
  307. if err != nil {
  308. t.Errorf("Unexpected error: %v", err)
  309. }
  310. if !test.possibleHosts.Has(got) {
  311. t.Errorf("got %s is not in the possible map %v", got, test.possibleHosts)
  312. }
  313. }
  314. }
  315. })
  316. }
  317. }
  318. func TestGenericScheduler(t *testing.T) {
  319. tests := []struct {
  320. name string
  321. registerPlugins []st.RegisterPluginFunc
  322. nodes []string
  323. pvcs []v1.PersistentVolumeClaim
  324. pod *v1.Pod
  325. pods []*v1.Pod
  326. expectedHosts sets.String
  327. wErr error
  328. }{
  329. {
  330. registerPlugins: []st.RegisterPluginFunc{
  331. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  332. st.RegisterFilterPlugin("FalseFilter", NewFalseFilterPlugin),
  333. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  334. },
  335. nodes: []string{"machine1", "machine2"},
  336. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  337. name: "test 1",
  338. wErr: &FitError{
  339. Pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  340. NumAllNodes: 2,
  341. FilteredNodesStatuses: framework.NodeToStatusMap{
  342. "machine1": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  343. "machine2": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  344. },
  345. },
  346. },
  347. {
  348. registerPlugins: []st.RegisterPluginFunc{
  349. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  350. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  351. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  352. },
  353. nodes: []string{"machine1", "machine2"},
  354. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "ignore", UID: types.UID("ignore")}},
  355. expectedHosts: sets.NewString("machine1", "machine2"),
  356. name: "test 2",
  357. wErr: nil,
  358. },
  359. {
  360. // Fits on a machine where the pod ID matches the machine name
  361. registerPlugins: []st.RegisterPluginFunc{
  362. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  363. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  364. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  365. },
  366. nodes: []string{"machine1", "machine2"},
  367. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine2", UID: types.UID("machine2")}},
  368. expectedHosts: sets.NewString("machine2"),
  369. name: "test 3",
  370. wErr: nil,
  371. },
  372. {
  373. registerPlugins: []st.RegisterPluginFunc{
  374. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  375. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  376. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  377. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  378. },
  379. nodes: []string{"3", "2", "1"},
  380. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "ignore", UID: types.UID("ignore")}},
  381. expectedHosts: sets.NewString("3"),
  382. name: "test 4",
  383. wErr: nil,
  384. },
  385. {
  386. registerPlugins: []st.RegisterPluginFunc{
  387. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  388. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  389. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  390. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  391. },
  392. nodes: []string{"3", "2", "1"},
  393. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  394. expectedHosts: sets.NewString("2"),
  395. name: "test 5",
  396. wErr: nil,
  397. },
  398. {
  399. registerPlugins: []st.RegisterPluginFunc{
  400. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  401. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  402. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  403. st.RegisterScorePlugin("ReverseNumericMap", newReverseNumericMapPlugin(), 2),
  404. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  405. },
  406. nodes: []string{"3", "2", "1"},
  407. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  408. expectedHosts: sets.NewString("1"),
  409. name: "test 6",
  410. wErr: nil,
  411. },
  412. {
  413. registerPlugins: []st.RegisterPluginFunc{
  414. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  415. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  416. st.RegisterFilterPlugin("FalseFilter", NewFalseFilterPlugin),
  417. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  418. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  419. },
  420. nodes: []string{"3", "2", "1"},
  421. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  422. name: "test 7",
  423. wErr: &FitError{
  424. Pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  425. NumAllNodes: 3,
  426. FilteredNodesStatuses: framework.NodeToStatusMap{
  427. "3": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  428. "2": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  429. "1": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  430. },
  431. },
  432. },
  433. {
  434. registerPlugins: []st.RegisterPluginFunc{
  435. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  436. st.RegisterFilterPlugin("NoPodsFilter", NewNoPodsFilterPlugin),
  437. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  438. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  439. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  440. },
  441. pods: []*v1.Pod{
  442. {
  443. ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")},
  444. Spec: v1.PodSpec{
  445. NodeName: "2",
  446. },
  447. Status: v1.PodStatus{
  448. Phase: v1.PodRunning,
  449. },
  450. },
  451. },
  452. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  453. nodes: []string{"1", "2"},
  454. name: "test 8",
  455. wErr: &FitError{
  456. Pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2", UID: types.UID("2")}},
  457. NumAllNodes: 2,
  458. FilteredNodesStatuses: framework.NodeToStatusMap{
  459. "1": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  460. "2": framework.NewStatus(framework.Unschedulable, ErrReasonFake),
  461. },
  462. },
  463. },
  464. {
  465. // Pod with existing PVC
  466. registerPlugins: []st.RegisterPluginFunc{
  467. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  468. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  469. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  470. },
  471. nodes: []string{"machine1", "machine2"},
  472. pvcs: []v1.PersistentVolumeClaim{{ObjectMeta: metav1.ObjectMeta{Name: "existingPVC"}}},
  473. pod: &v1.Pod{
  474. ObjectMeta: metav1.ObjectMeta{Name: "ignore", UID: types.UID("ignore")},
  475. Spec: v1.PodSpec{
  476. Volumes: []v1.Volume{
  477. {
  478. VolumeSource: v1.VolumeSource{
  479. PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
  480. ClaimName: "existingPVC",
  481. },
  482. },
  483. },
  484. },
  485. },
  486. },
  487. expectedHosts: sets.NewString("machine1", "machine2"),
  488. name: "existing PVC",
  489. wErr: nil,
  490. },
  491. {
  492. // Pod with non existing PVC
  493. registerPlugins: []st.RegisterPluginFunc{
  494. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  495. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  496. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  497. },
  498. nodes: []string{"machine1", "machine2"},
  499. pod: &v1.Pod{
  500. ObjectMeta: metav1.ObjectMeta{Name: "ignore", UID: types.UID("ignore")},
  501. Spec: v1.PodSpec{
  502. Volumes: []v1.Volume{
  503. {
  504. VolumeSource: v1.VolumeSource{
  505. PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
  506. ClaimName: "unknownPVC",
  507. },
  508. },
  509. },
  510. },
  511. },
  512. },
  513. name: "unknown PVC",
  514. wErr: fmt.Errorf("persistentvolumeclaim \"unknownPVC\" not found"),
  515. },
  516. {
  517. // Pod with deleting PVC
  518. registerPlugins: []st.RegisterPluginFunc{
  519. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  520. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  521. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  522. },
  523. nodes: []string{"machine1", "machine2"},
  524. pvcs: []v1.PersistentVolumeClaim{{ObjectMeta: metav1.ObjectMeta{Name: "existingPVC", DeletionTimestamp: &metav1.Time{}}}},
  525. pod: &v1.Pod{
  526. ObjectMeta: metav1.ObjectMeta{Name: "ignore", UID: types.UID("ignore")},
  527. Spec: v1.PodSpec{
  528. Volumes: []v1.Volume{
  529. {
  530. VolumeSource: v1.VolumeSource{
  531. PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
  532. ClaimName: "existingPVC",
  533. },
  534. },
  535. },
  536. },
  537. },
  538. },
  539. name: "deleted PVC",
  540. wErr: fmt.Errorf("persistentvolumeclaim \"existingPVC\" is being deleted"),
  541. },
  542. {
  543. registerPlugins: []st.RegisterPluginFunc{
  544. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  545. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  546. st.RegisterScorePlugin("FalseMap", newFalseMapPlugin(), 1),
  547. st.RegisterScorePlugin("TrueMap", newTrueMapPlugin(), 2),
  548. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  549. },
  550. nodes: []string{"2", "1"},
  551. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "2"}},
  552. name: "test error with priority map",
  553. wErr: fmt.Errorf("error while running score plugin for pod \"2\": %+v", errPrioritize),
  554. },
  555. {
  556. name: "test podtopologyspread plugin - 2 nodes with maxskew=1",
  557. registerPlugins: []st.RegisterPluginFunc{
  558. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  559. st.RegisterPluginAsExtensions(
  560. podtopologyspread.Name,
  561. 1,
  562. podtopologyspread.New,
  563. "PreFilter",
  564. "Filter",
  565. ),
  566. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  567. },
  568. nodes: []string{"machine1", "machine2"},
  569. pod: &v1.Pod{
  570. ObjectMeta: metav1.ObjectMeta{Name: "p", UID: types.UID("p"), Labels: map[string]string{"foo": ""}},
  571. Spec: v1.PodSpec{
  572. TopologySpreadConstraints: []v1.TopologySpreadConstraint{
  573. {
  574. MaxSkew: 1,
  575. TopologyKey: "hostname",
  576. WhenUnsatisfiable: v1.DoNotSchedule,
  577. LabelSelector: &metav1.LabelSelector{
  578. MatchExpressions: []metav1.LabelSelectorRequirement{
  579. {
  580. Key: "foo",
  581. Operator: metav1.LabelSelectorOpExists,
  582. },
  583. },
  584. },
  585. },
  586. },
  587. },
  588. },
  589. pods: []*v1.Pod{
  590. {
  591. ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1"), Labels: map[string]string{"foo": ""}},
  592. Spec: v1.PodSpec{
  593. NodeName: "machine1",
  594. },
  595. Status: v1.PodStatus{
  596. Phase: v1.PodRunning,
  597. },
  598. },
  599. },
  600. expectedHosts: sets.NewString("machine2"),
  601. wErr: nil,
  602. },
  603. {
  604. name: "test podtopologyspread plugin - 3 nodes with maxskew=2",
  605. registerPlugins: []st.RegisterPluginFunc{
  606. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  607. st.RegisterPluginAsExtensions(
  608. podtopologyspread.Name,
  609. 1,
  610. podtopologyspread.New,
  611. "PreFilter",
  612. "Filter",
  613. ),
  614. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  615. },
  616. nodes: []string{"machine1", "machine2", "machine3"},
  617. pod: &v1.Pod{
  618. ObjectMeta: metav1.ObjectMeta{Name: "p", UID: types.UID("p"), Labels: map[string]string{"foo": ""}},
  619. Spec: v1.PodSpec{
  620. TopologySpreadConstraints: []v1.TopologySpreadConstraint{
  621. {
  622. MaxSkew: 2,
  623. TopologyKey: "hostname",
  624. WhenUnsatisfiable: v1.DoNotSchedule,
  625. LabelSelector: &metav1.LabelSelector{
  626. MatchExpressions: []metav1.LabelSelectorRequirement{
  627. {
  628. Key: "foo",
  629. Operator: metav1.LabelSelectorOpExists,
  630. },
  631. },
  632. },
  633. },
  634. },
  635. },
  636. },
  637. pods: []*v1.Pod{
  638. {
  639. ObjectMeta: metav1.ObjectMeta{Name: "pod1a", UID: types.UID("pod1a"), Labels: map[string]string{"foo": ""}},
  640. Spec: v1.PodSpec{
  641. NodeName: "machine1",
  642. },
  643. Status: v1.PodStatus{
  644. Phase: v1.PodRunning,
  645. },
  646. },
  647. {
  648. ObjectMeta: metav1.ObjectMeta{Name: "pod1b", UID: types.UID("pod1b"), Labels: map[string]string{"foo": ""}},
  649. Spec: v1.PodSpec{
  650. NodeName: "machine1",
  651. },
  652. Status: v1.PodStatus{
  653. Phase: v1.PodRunning,
  654. },
  655. },
  656. {
  657. ObjectMeta: metav1.ObjectMeta{Name: "pod2", UID: types.UID("pod2"), Labels: map[string]string{"foo": ""}},
  658. Spec: v1.PodSpec{
  659. NodeName: "machine2",
  660. },
  661. Status: v1.PodStatus{
  662. Phase: v1.PodRunning,
  663. },
  664. },
  665. },
  666. expectedHosts: sets.NewString("machine2", "machine3"),
  667. wErr: nil,
  668. },
  669. {
  670. name: "test with filter plugin returning Unschedulable status",
  671. registerPlugins: []st.RegisterPluginFunc{
  672. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  673. st.RegisterFilterPlugin(
  674. "FakeFilter",
  675. NewFakeFilterPlugin(map[string]framework.Code{"3": framework.Unschedulable}),
  676. ),
  677. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  678. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  679. },
  680. nodes: []string{"3"},
  681. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-filter", UID: types.UID("test-filter")}},
  682. expectedHosts: nil,
  683. wErr: &FitError{
  684. Pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-filter", UID: types.UID("test-filter")}},
  685. NumAllNodes: 1,
  686. FilteredNodesStatuses: framework.NodeToStatusMap{
  687. "3": framework.NewStatus(framework.Unschedulable, "injecting failure for pod test-filter"),
  688. },
  689. },
  690. },
  691. {
  692. name: "test with filter plugin returning UnschedulableAndUnresolvable status",
  693. registerPlugins: []st.RegisterPluginFunc{
  694. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  695. st.RegisterFilterPlugin(
  696. "FakeFilter",
  697. NewFakeFilterPlugin(map[string]framework.Code{"3": framework.UnschedulableAndUnresolvable}),
  698. ),
  699. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  700. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  701. },
  702. nodes: []string{"3"},
  703. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-filter", UID: types.UID("test-filter")}},
  704. expectedHosts: nil,
  705. wErr: &FitError{
  706. Pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-filter", UID: types.UID("test-filter")}},
  707. NumAllNodes: 1,
  708. FilteredNodesStatuses: framework.NodeToStatusMap{
  709. "3": framework.NewStatus(framework.UnschedulableAndUnresolvable, "injecting failure for pod test-filter"),
  710. },
  711. },
  712. },
  713. {
  714. name: "test with partial failed filter plugin",
  715. registerPlugins: []st.RegisterPluginFunc{
  716. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  717. st.RegisterFilterPlugin(
  718. "FakeFilter",
  719. NewFakeFilterPlugin(map[string]framework.Code{"1": framework.Unschedulable}),
  720. ),
  721. st.RegisterScorePlugin("NumericMap", newNumericMapPlugin(), 1),
  722. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  723. },
  724. nodes: []string{"1", "2"},
  725. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-filter", UID: types.UID("test-filter")}},
  726. expectedHosts: nil,
  727. wErr: nil,
  728. },
  729. }
  730. for _, test := range tests {
  731. t.Run(test.name, func(t *testing.T) {
  732. client := clientsetfake.NewSimpleClientset()
  733. informerFactory := informers.NewSharedInformerFactory(client, 0)
  734. cache := internalcache.New(time.Duration(0), wait.NeverStop)
  735. for _, pod := range test.pods {
  736. cache.AddPod(pod)
  737. }
  738. var nodes []*v1.Node
  739. for _, name := range test.nodes {
  740. node := &v1.Node{ObjectMeta: metav1.ObjectMeta{Name: name, Labels: map[string]string{"hostname": name}}}
  741. nodes = append(nodes, node)
  742. cache.AddNode(node)
  743. }
  744. snapshot := internalcache.NewSnapshot(test.pods, nodes)
  745. fwk, err := st.NewFramework(test.registerPlugins, framework.WithSnapshotSharedLister(snapshot))
  746. if err != nil {
  747. t.Fatal(err)
  748. }
  749. var pvcs []v1.PersistentVolumeClaim
  750. pvcs = append(pvcs, test.pvcs...)
  751. pvcLister := fakelisters.PersistentVolumeClaimLister(pvcs)
  752. scheduler := NewGenericScheduler(
  753. cache,
  754. internalqueue.NewSchedulingQueue(nil),
  755. snapshot,
  756. fwk,
  757. []SchedulerExtender{},
  758. nil,
  759. pvcLister,
  760. informerFactory.Policy().V1beta1().PodDisruptionBudgets().Lister(),
  761. false,
  762. schedulerapi.DefaultPercentageOfNodesToScore,
  763. false)
  764. result, err := scheduler.Schedule(context.Background(), framework.NewCycleState(), test.pod)
  765. if !reflect.DeepEqual(err, test.wErr) {
  766. t.Errorf("Unexpected error: %v, expected: %v", err.Error(), test.wErr)
  767. }
  768. if test.expectedHosts != nil && !test.expectedHosts.Has(result.SuggestedHost) {
  769. t.Errorf("Expected: %s, got: %s", test.expectedHosts, result.SuggestedHost)
  770. }
  771. if test.wErr == nil && len(test.nodes) != result.EvaluatedNodes {
  772. t.Errorf("Expected EvaluatedNodes: %d, got: %d", len(test.nodes), result.EvaluatedNodes)
  773. }
  774. })
  775. }
  776. }
  777. // makeScheduler makes a simple genericScheduler for testing.
  778. func makeScheduler(nodes []*v1.Node, fns ...st.RegisterPluginFunc) *genericScheduler {
  779. cache := internalcache.New(time.Duration(0), wait.NeverStop)
  780. for _, n := range nodes {
  781. cache.AddNode(n)
  782. }
  783. fwk, _ := st.NewFramework(fns)
  784. s := NewGenericScheduler(
  785. cache,
  786. internalqueue.NewSchedulingQueue(nil),
  787. emptySnapshot,
  788. fwk,
  789. nil, nil, nil, nil, false,
  790. schedulerapi.DefaultPercentageOfNodesToScore, false)
  791. cache.UpdateSnapshot(s.(*genericScheduler).nodeInfoSnapshot)
  792. return s.(*genericScheduler)
  793. }
  794. func TestFindFitAllError(t *testing.T) {
  795. nodes := makeNodeList([]string{"3", "2", "1"})
  796. scheduler := makeScheduler(
  797. nodes,
  798. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  799. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  800. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  801. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  802. )
  803. _, nodeToStatusMap, err := scheduler.findNodesThatFitPod(context.Background(), framework.NewCycleState(), &v1.Pod{})
  804. if err != nil {
  805. t.Errorf("unexpected error: %v", err)
  806. }
  807. if len(nodeToStatusMap) != len(nodes) {
  808. t.Errorf("unexpected failed status map: %v", nodeToStatusMap)
  809. }
  810. for _, node := range nodes {
  811. t.Run(node.Name, func(t *testing.T) {
  812. status, found := nodeToStatusMap[node.Name]
  813. if !found {
  814. t.Errorf("failed to find node %v in %v", node.Name, nodeToStatusMap)
  815. }
  816. reasons := status.Reasons()
  817. if len(reasons) != 1 || reasons[0] != ErrReasonFake {
  818. t.Errorf("unexpected failure reasons: %v", reasons)
  819. }
  820. })
  821. }
  822. }
  823. func TestFindFitSomeError(t *testing.T) {
  824. nodes := makeNodeList([]string{"3", "2", "1"})
  825. scheduler := makeScheduler(
  826. nodes,
  827. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  828. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  829. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  830. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  831. )
  832. pod := &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "1", UID: types.UID("1")}}
  833. _, nodeToStatusMap, err := scheduler.findNodesThatFitPod(context.Background(), framework.NewCycleState(), pod)
  834. if err != nil {
  835. t.Errorf("unexpected error: %v", err)
  836. }
  837. if len(nodeToStatusMap) != len(nodes)-1 {
  838. t.Errorf("unexpected failed status map: %v", nodeToStatusMap)
  839. }
  840. for _, node := range nodes {
  841. if node.Name == pod.Name {
  842. continue
  843. }
  844. t.Run(node.Name, func(t *testing.T) {
  845. status, found := nodeToStatusMap[node.Name]
  846. if !found {
  847. t.Errorf("failed to find node %v in %v", node.Name, nodeToStatusMap)
  848. }
  849. reasons := status.Reasons()
  850. if len(reasons) != 1 || reasons[0] != ErrReasonFake {
  851. t.Errorf("unexpected failures: %v", reasons)
  852. }
  853. })
  854. }
  855. }
  856. func TestFindFitPredicateCallCounts(t *testing.T) {
  857. tests := []struct {
  858. name string
  859. pod *v1.Pod
  860. expectedCount int32
  861. }{
  862. {
  863. name: "nominated pods have lower priority, predicate is called once",
  864. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "1", UID: types.UID("1")}, Spec: v1.PodSpec{Priority: &highPriority}},
  865. expectedCount: 1,
  866. },
  867. {
  868. name: "nominated pods have higher priority, predicate is called twice",
  869. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "1", UID: types.UID("1")}, Spec: v1.PodSpec{Priority: &lowPriority}},
  870. expectedCount: 2,
  871. },
  872. }
  873. for _, test := range tests {
  874. nodes := makeNodeList([]string{"1"})
  875. cache := internalcache.New(time.Duration(0), wait.NeverStop)
  876. for _, n := range nodes {
  877. cache.AddNode(n)
  878. }
  879. plugin := fakeFilterPlugin{}
  880. registerFakeFilterFunc := st.RegisterFilterPlugin(
  881. "FakeFilter",
  882. func(_ *runtime.Unknown, fh framework.FrameworkHandle) (framework.Plugin, error) {
  883. return &plugin, nil
  884. },
  885. )
  886. registerPlugins := []st.RegisterPluginFunc{
  887. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  888. registerFakeFilterFunc,
  889. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  890. }
  891. fwk, err := st.NewFramework(registerPlugins)
  892. if err != nil {
  893. t.Fatal(err)
  894. }
  895. queue := internalqueue.NewSchedulingQueue(nil)
  896. scheduler := NewGenericScheduler(
  897. cache,
  898. queue,
  899. emptySnapshot,
  900. fwk,
  901. nil, nil, nil, nil, false,
  902. schedulerapi.DefaultPercentageOfNodesToScore, false).(*genericScheduler)
  903. cache.UpdateSnapshot(scheduler.nodeInfoSnapshot)
  904. queue.UpdateNominatedPodForNode(&v1.Pod{ObjectMeta: metav1.ObjectMeta{UID: types.UID("nominated")}, Spec: v1.PodSpec{Priority: &midPriority}}, "1")
  905. _, _, err = scheduler.findNodesThatFitPod(context.Background(), framework.NewCycleState(), test.pod)
  906. if err != nil {
  907. t.Errorf("unexpected error: %v", err)
  908. }
  909. if test.expectedCount != plugin.numFilterCalled {
  910. t.Errorf("predicate was called %d times, expected is %d", plugin.numFilterCalled, test.expectedCount)
  911. }
  912. }
  913. }
  914. func makeNode(node string, milliCPU, memory int64) *v1.Node {
  915. return &v1.Node{
  916. ObjectMeta: metav1.ObjectMeta{Name: node},
  917. Status: v1.NodeStatus{
  918. Capacity: v1.ResourceList{
  919. v1.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI),
  920. v1.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI),
  921. "pods": *resource.NewQuantity(100, resource.DecimalSI),
  922. },
  923. Allocatable: v1.ResourceList{
  924. v1.ResourceCPU: *resource.NewMilliQuantity(milliCPU, resource.DecimalSI),
  925. v1.ResourceMemory: *resource.NewQuantity(memory, resource.BinarySI),
  926. "pods": *resource.NewQuantity(100, resource.DecimalSI),
  927. },
  928. },
  929. }
  930. }
  931. // The point of this test is to show that you:
  932. // - get the same priority for a zero-request pod as for a pod with the defaults requests,
  933. // both when the zero-request pod is already on the machine and when the zero-request pod
  934. // is the one being scheduled.
  935. // - don't get the same score no matter what we schedule.
  936. func TestZeroRequest(t *testing.T) {
  937. // A pod with no resources. We expect spreading to count it as having the default resources.
  938. noResources := v1.PodSpec{
  939. Containers: []v1.Container{
  940. {},
  941. },
  942. }
  943. noResources1 := noResources
  944. noResources1.NodeName = "machine1"
  945. // A pod with the same resources as a 0-request pod gets by default as its resources (for spreading).
  946. small := v1.PodSpec{
  947. Containers: []v1.Container{
  948. {
  949. Resources: v1.ResourceRequirements{
  950. Requests: v1.ResourceList{
  951. v1.ResourceCPU: resource.MustParse(
  952. strconv.FormatInt(schedutil.DefaultMilliCPURequest, 10) + "m"),
  953. v1.ResourceMemory: resource.MustParse(
  954. strconv.FormatInt(schedutil.DefaultMemoryRequest, 10)),
  955. },
  956. },
  957. },
  958. },
  959. }
  960. small2 := small
  961. small2.NodeName = "machine2"
  962. // A larger pod.
  963. large := v1.PodSpec{
  964. Containers: []v1.Container{
  965. {
  966. Resources: v1.ResourceRequirements{
  967. Requests: v1.ResourceList{
  968. v1.ResourceCPU: resource.MustParse(
  969. strconv.FormatInt(schedutil.DefaultMilliCPURequest*3, 10) + "m"),
  970. v1.ResourceMemory: resource.MustParse(
  971. strconv.FormatInt(schedutil.DefaultMemoryRequest*3, 10)),
  972. },
  973. },
  974. },
  975. },
  976. }
  977. large1 := large
  978. large1.NodeName = "machine1"
  979. large2 := large
  980. large2.NodeName = "machine2"
  981. tests := []struct {
  982. pod *v1.Pod
  983. pods []*v1.Pod
  984. nodes []*v1.Node
  985. name string
  986. expectedScore int64
  987. }{
  988. // The point of these next two tests is to show you get the same priority for a zero-request pod
  989. // as for a pod with the defaults requests, both when the zero-request pod is already on the machine
  990. // and when the zero-request pod is the one being scheduled.
  991. {
  992. pod: &v1.Pod{Spec: noResources},
  993. nodes: []*v1.Node{makeNode("machine1", 1000, schedutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, schedutil.DefaultMemoryRequest*10)},
  994. name: "test priority of zero-request pod with machine with zero-request pod",
  995. pods: []*v1.Pod{
  996. {Spec: large1}, {Spec: noResources1},
  997. {Spec: large2}, {Spec: small2},
  998. },
  999. expectedScore: 250,
  1000. },
  1001. {
  1002. pod: &v1.Pod{Spec: small},
  1003. nodes: []*v1.Node{makeNode("machine1", 1000, schedutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, schedutil.DefaultMemoryRequest*10)},
  1004. name: "test priority of nonzero-request pod with machine with zero-request pod",
  1005. pods: []*v1.Pod{
  1006. {Spec: large1}, {Spec: noResources1},
  1007. {Spec: large2}, {Spec: small2},
  1008. },
  1009. expectedScore: 250,
  1010. },
  1011. // The point of this test is to verify that we're not just getting the same score no matter what we schedule.
  1012. {
  1013. pod: &v1.Pod{Spec: large},
  1014. nodes: []*v1.Node{makeNode("machine1", 1000, schedutil.DefaultMemoryRequest*10), makeNode("machine2", 1000, schedutil.DefaultMemoryRequest*10)},
  1015. name: "test priority of larger pod with machine with zero-request pod",
  1016. pods: []*v1.Pod{
  1017. {Spec: large1}, {Spec: noResources1},
  1018. {Spec: large2}, {Spec: small2},
  1019. },
  1020. expectedScore: 230,
  1021. },
  1022. }
  1023. for _, test := range tests {
  1024. t.Run(test.name, func(t *testing.T) {
  1025. client := clientsetfake.NewSimpleClientset()
  1026. informerFactory := informers.NewSharedInformerFactory(client, 0)
  1027. snapshot := internalcache.NewSnapshot(test.pods, test.nodes)
  1028. pluginRegistrations := []st.RegisterPluginFunc{
  1029. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1030. st.RegisterScorePlugin(noderesources.LeastAllocatedName, noderesources.NewLeastAllocated, 1),
  1031. st.RegisterScorePlugin(noderesources.BalancedAllocationName, noderesources.NewBalancedAllocation, 1),
  1032. st.RegisterScorePlugin(defaultpodtopologyspread.Name, defaultpodtopologyspread.New, 1),
  1033. st.RegisterPostFilterPlugin(defaultpodtopologyspread.Name, defaultpodtopologyspread.New),
  1034. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1035. }
  1036. fwk, err := st.NewFramework(
  1037. pluginRegistrations,
  1038. framework.WithInformerFactory(informerFactory),
  1039. framework.WithSnapshotSharedLister(snapshot),
  1040. framework.WithClientSet(client),
  1041. )
  1042. if err != nil {
  1043. t.Fatalf("error creating framework: %+v", err)
  1044. }
  1045. scheduler := NewGenericScheduler(
  1046. nil,
  1047. nil,
  1048. emptySnapshot,
  1049. fwk,
  1050. []SchedulerExtender{},
  1051. nil,
  1052. nil,
  1053. nil,
  1054. false,
  1055. schedulerapi.DefaultPercentageOfNodesToScore,
  1056. false).(*genericScheduler)
  1057. scheduler.nodeInfoSnapshot = snapshot
  1058. ctx := context.Background()
  1059. state := framework.NewCycleState()
  1060. _, filteredNodesStatuses, err := scheduler.findNodesThatFitPod(ctx, state, test.pod)
  1061. if err != nil {
  1062. t.Fatalf("error filtering nodes: %+v", err)
  1063. }
  1064. scheduler.framework.RunPostFilterPlugins(ctx, state, test.pod, test.nodes, filteredNodesStatuses)
  1065. list, err := scheduler.prioritizeNodes(
  1066. ctx,
  1067. state,
  1068. test.pod,
  1069. test.nodes,
  1070. )
  1071. if err != nil {
  1072. t.Errorf("unexpected error: %v", err)
  1073. }
  1074. for _, hp := range list {
  1075. if hp.Score != test.expectedScore {
  1076. t.Errorf("expected %d for all priorities, got list %#v", test.expectedScore, list)
  1077. }
  1078. }
  1079. })
  1080. }
  1081. }
  1082. func printNodeToVictims(nodeToVictims map[*v1.Node]*extenderv1.Victims) string {
  1083. var output string
  1084. for node, victims := range nodeToVictims {
  1085. output += node.Name + ": ["
  1086. for _, pod := range victims.Pods {
  1087. output += pod.Name + ", "
  1088. }
  1089. output += "]"
  1090. }
  1091. return output
  1092. }
  1093. type victims struct {
  1094. pods sets.String
  1095. numPDBViolations int64
  1096. }
  1097. func checkPreemptionVictims(expected map[string]victims, nodeToPods map[*v1.Node]*extenderv1.Victims) error {
  1098. if len(expected) == len(nodeToPods) {
  1099. for k, victims := range nodeToPods {
  1100. if expVictims, ok := expected[k.Name]; ok {
  1101. if len(victims.Pods) != len(expVictims.pods) {
  1102. return fmt.Errorf("unexpected number of pods. expected: %v, got: %v", expected, printNodeToVictims(nodeToPods))
  1103. }
  1104. prevPriority := int32(math.MaxInt32)
  1105. for _, p := range victims.Pods {
  1106. // Check that pods are sorted by their priority.
  1107. if *p.Spec.Priority > prevPriority {
  1108. return fmt.Errorf("pod %v of node %v was not sorted by priority", p.Name, k)
  1109. }
  1110. prevPriority = *p.Spec.Priority
  1111. if !expVictims.pods.Has(p.Name) {
  1112. return fmt.Errorf("pod %v was not expected. Expected: %v", p.Name, expVictims.pods)
  1113. }
  1114. }
  1115. if expVictims.numPDBViolations != victims.NumPDBViolations {
  1116. return fmt.Errorf("unexpected numPDBViolations. expected: %d, got: %d", expVictims.numPDBViolations, victims.NumPDBViolations)
  1117. }
  1118. } else {
  1119. return fmt.Errorf("unexpected machines. expected: %v, got: %v", expected, printNodeToVictims(nodeToPods))
  1120. }
  1121. }
  1122. } else {
  1123. return fmt.Errorf("unexpected number of machines. expected: %v, got: %v", expected, printNodeToVictims(nodeToPods))
  1124. }
  1125. return nil
  1126. }
  1127. var smallContainers = []v1.Container{
  1128. {
  1129. Resources: v1.ResourceRequirements{
  1130. Requests: v1.ResourceList{
  1131. "cpu": resource.MustParse(
  1132. strconv.FormatInt(schedutil.DefaultMilliCPURequest, 10) + "m"),
  1133. "memory": resource.MustParse(
  1134. strconv.FormatInt(schedutil.DefaultMemoryRequest, 10)),
  1135. },
  1136. },
  1137. },
  1138. }
  1139. var mediumContainers = []v1.Container{
  1140. {
  1141. Resources: v1.ResourceRequirements{
  1142. Requests: v1.ResourceList{
  1143. "cpu": resource.MustParse(
  1144. strconv.FormatInt(schedutil.DefaultMilliCPURequest*2, 10) + "m"),
  1145. "memory": resource.MustParse(
  1146. strconv.FormatInt(schedutil.DefaultMemoryRequest*2, 10)),
  1147. },
  1148. },
  1149. },
  1150. }
  1151. var largeContainers = []v1.Container{
  1152. {
  1153. Resources: v1.ResourceRequirements{
  1154. Requests: v1.ResourceList{
  1155. "cpu": resource.MustParse(
  1156. strconv.FormatInt(schedutil.DefaultMilliCPURequest*3, 10) + "m"),
  1157. "memory": resource.MustParse(
  1158. strconv.FormatInt(schedutil.DefaultMemoryRequest*3, 10)),
  1159. },
  1160. },
  1161. },
  1162. }
  1163. var veryLargeContainers = []v1.Container{
  1164. {
  1165. Resources: v1.ResourceRequirements{
  1166. Requests: v1.ResourceList{
  1167. "cpu": resource.MustParse(
  1168. strconv.FormatInt(schedutil.DefaultMilliCPURequest*5, 10) + "m"),
  1169. "memory": resource.MustParse(
  1170. strconv.FormatInt(schedutil.DefaultMemoryRequest*5, 10)),
  1171. },
  1172. },
  1173. },
  1174. }
  1175. var negPriority, lowPriority, midPriority, highPriority, veryHighPriority = int32(-100), int32(0), int32(100), int32(1000), int32(10000)
  1176. var startTime = metav1.Date(2019, 1, 1, 1, 1, 1, 0, time.UTC)
  1177. var startTime20190102 = metav1.Date(2019, 1, 2, 1, 1, 1, 0, time.UTC)
  1178. var startTime20190103 = metav1.Date(2019, 1, 3, 1, 1, 1, 0, time.UTC)
  1179. var startTime20190104 = metav1.Date(2019, 1, 4, 1, 1, 1, 0, time.UTC)
  1180. var startTime20190105 = metav1.Date(2019, 1, 5, 1, 1, 1, 0, time.UTC)
  1181. var startTime20190106 = metav1.Date(2019, 1, 6, 1, 1, 1, 0, time.UTC)
  1182. var startTime20190107 = metav1.Date(2019, 1, 7, 1, 1, 1, 0, time.UTC)
  1183. // TestSelectNodesForPreemption tests selectNodesForPreemption. This test assumes
  1184. // that podsFitsOnNode works correctly and is tested separately.
  1185. func TestSelectNodesForPreemption(t *testing.T) {
  1186. tests := []struct {
  1187. name string
  1188. registerPlugins []st.RegisterPluginFunc
  1189. nodes []string
  1190. pod *v1.Pod
  1191. pods []*v1.Pod
  1192. pdbs []*policy.PodDisruptionBudget
  1193. filterReturnCode framework.Code
  1194. expected map[string]victims
  1195. expectedNumFilterCalled int32
  1196. }{
  1197. {
  1198. name: "a pod that does not fit on any machine",
  1199. registerPlugins: []st.RegisterPluginFunc{
  1200. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1201. st.RegisterFilterPlugin("FalseFilter", NewFalseFilterPlugin),
  1202. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1203. },
  1204. nodes: []string{"machine1", "machine2"},
  1205. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "new", UID: types.UID("new")}, Spec: v1.PodSpec{Priority: &highPriority}},
  1206. pods: []*v1.Pod{
  1207. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine1"}},
  1208. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine2"}}},
  1209. expected: map[string]victims{},
  1210. expectedNumFilterCalled: 2,
  1211. },
  1212. {
  1213. name: "a pod that fits with no preemption",
  1214. registerPlugins: []st.RegisterPluginFunc{
  1215. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1216. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  1217. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1218. },
  1219. nodes: []string{"machine1", "machine2"},
  1220. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "new", UID: types.UID("new")}, Spec: v1.PodSpec{Priority: &highPriority}},
  1221. pods: []*v1.Pod{
  1222. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine1"}},
  1223. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine2"}}},
  1224. expected: map[string]victims{"machine1": {}, "machine2": {}},
  1225. expectedNumFilterCalled: 4,
  1226. },
  1227. {
  1228. name: "a pod that fits on one machine with no preemption",
  1229. registerPlugins: []st.RegisterPluginFunc{
  1230. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1231. st.RegisterFilterPlugin("MatchFilter", NewMatchFilterPlugin),
  1232. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1233. },
  1234. nodes: []string{"machine1", "machine2"},
  1235. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Priority: &highPriority}},
  1236. pods: []*v1.Pod{
  1237. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine1"}},
  1238. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Priority: &midPriority, NodeName: "machine2"}}},
  1239. expected: map[string]victims{"machine1": {}},
  1240. expectedNumFilterCalled: 3,
  1241. },
  1242. {
  1243. name: "a pod that fits on both machines when lower priority pods are preempted",
  1244. registerPlugins: []st.RegisterPluginFunc{
  1245. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1246. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1247. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1248. },
  1249. nodes: []string{"machine1", "machine2"},
  1250. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1251. pods: []*v1.Pod{
  1252. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}},
  1253. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}}},
  1254. expected: map[string]victims{"machine1": {pods: sets.NewString("a")}, "machine2": {pods: sets.NewString("b")}},
  1255. expectedNumFilterCalled: 4,
  1256. },
  1257. {
  1258. name: "a pod that would fit on the machines, but other pods running are higher priority",
  1259. registerPlugins: []st.RegisterPluginFunc{
  1260. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1261. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1262. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1263. },
  1264. nodes: []string{"machine1", "machine2"},
  1265. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &lowPriority}},
  1266. pods: []*v1.Pod{
  1267. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}},
  1268. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}}},
  1269. expected: map[string]victims{},
  1270. expectedNumFilterCalled: 2,
  1271. },
  1272. {
  1273. name: "medium priority pod is preempted, but lower priority one stays as it is small",
  1274. registerPlugins: []st.RegisterPluginFunc{
  1275. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1276. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1277. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1278. },
  1279. nodes: []string{"machine1", "machine2"},
  1280. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1281. pods: []*v1.Pod{
  1282. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}},
  1283. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}},
  1284. {ObjectMeta: metav1.ObjectMeta{Name: "c", UID: types.UID("c")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}}},
  1285. expected: map[string]victims{"machine1": {pods: sets.NewString("b")}, "machine2": {pods: sets.NewString("c")}},
  1286. expectedNumFilterCalled: 5,
  1287. },
  1288. {
  1289. name: "mixed priority pods are preempted",
  1290. registerPlugins: []st.RegisterPluginFunc{
  1291. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1292. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1293. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1294. },
  1295. nodes: []string{"machine1", "machine2"},
  1296. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1297. pods: []*v1.Pod{
  1298. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}},
  1299. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}},
  1300. {ObjectMeta: metav1.ObjectMeta{Name: "c", UID: types.UID("c")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}},
  1301. {ObjectMeta: metav1.ObjectMeta{Name: "d", UID: types.UID("d")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &highPriority, NodeName: "machine1"}},
  1302. {ObjectMeta: metav1.ObjectMeta{Name: "e", UID: types.UID("e")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}}},
  1303. expected: map[string]victims{"machine1": {pods: sets.NewString("b", "c")}},
  1304. expectedNumFilterCalled: 5,
  1305. },
  1306. {
  1307. name: "mixed priority pods are preempted, pick later StartTime one when priorities are equal",
  1308. registerPlugins: []st.RegisterPluginFunc{
  1309. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1310. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1311. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1312. },
  1313. nodes: []string{"machine1", "machine2"},
  1314. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1315. pods: []*v1.Pod{
  1316. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190107}},
  1317. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190106}},
  1318. {ObjectMeta: metav1.ObjectMeta{Name: "c", UID: types.UID("c")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190105}},
  1319. {ObjectMeta: metav1.ObjectMeta{Name: "d", UID: types.UID("d")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &highPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190104}},
  1320. {ObjectMeta: metav1.ObjectMeta{Name: "e", UID: types.UID("e")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190103}}},
  1321. expected: map[string]victims{"machine1": {pods: sets.NewString("a", "c")}},
  1322. expectedNumFilterCalled: 5,
  1323. },
  1324. {
  1325. name: "pod with anti-affinity is preempted",
  1326. registerPlugins: []st.RegisterPluginFunc{
  1327. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1328. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1329. st.RegisterFilterPlugin(interpodaffinity.Name, interpodaffinity.New),
  1330. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1331. },
  1332. nodes: []string{"machine1", "machine2"},
  1333. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{
  1334. Name: "machine1",
  1335. Labels: map[string]string{"pod": "preemptor"}}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &highPriority}},
  1336. pods: []*v1.Pod{
  1337. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a"), Labels: map[string]string{"service": "securityscan"}}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1", Affinity: &v1.Affinity{
  1338. PodAntiAffinity: &v1.PodAntiAffinity{
  1339. RequiredDuringSchedulingIgnoredDuringExecution: []v1.PodAffinityTerm{
  1340. {
  1341. LabelSelector: &metav1.LabelSelector{
  1342. MatchExpressions: []metav1.LabelSelectorRequirement{
  1343. {
  1344. Key: "pod",
  1345. Operator: metav1.LabelSelectorOpIn,
  1346. Values: []string{"preemptor", "value2"},
  1347. },
  1348. },
  1349. },
  1350. TopologyKey: "hostname",
  1351. },
  1352. },
  1353. }}}},
  1354. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}},
  1355. {ObjectMeta: metav1.ObjectMeta{Name: "d", UID: types.UID("d")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &highPriority, NodeName: "machine1"}},
  1356. {ObjectMeta: metav1.ObjectMeta{Name: "e", UID: types.UID("e")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}}},
  1357. expected: map[string]victims{"machine1": {pods: sets.NewString("a")}, "machine2": {}},
  1358. expectedNumFilterCalled: 4,
  1359. },
  1360. {
  1361. name: "preemption to resolve even pods spread FitError",
  1362. registerPlugins: []st.RegisterPluginFunc{
  1363. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1364. st.RegisterPluginAsExtensions(
  1365. podtopologyspread.Name,
  1366. 1,
  1367. podtopologyspread.New,
  1368. "PreFilter",
  1369. "Filter",
  1370. ),
  1371. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1372. },
  1373. nodes: []string{"node-a/zone1", "node-b/zone1", "node-x/zone2"},
  1374. pod: &v1.Pod{
  1375. ObjectMeta: metav1.ObjectMeta{
  1376. Name: "p",
  1377. Labels: map[string]string{"foo": ""},
  1378. },
  1379. Spec: v1.PodSpec{
  1380. Priority: &highPriority,
  1381. TopologySpreadConstraints: []v1.TopologySpreadConstraint{
  1382. {
  1383. MaxSkew: 1,
  1384. TopologyKey: "zone",
  1385. WhenUnsatisfiable: v1.DoNotSchedule,
  1386. LabelSelector: &metav1.LabelSelector{
  1387. MatchExpressions: []metav1.LabelSelectorRequirement{
  1388. {
  1389. Key: "foo",
  1390. Operator: metav1.LabelSelectorOpExists,
  1391. },
  1392. },
  1393. },
  1394. },
  1395. {
  1396. MaxSkew: 1,
  1397. TopologyKey: "hostname",
  1398. WhenUnsatisfiable: v1.DoNotSchedule,
  1399. LabelSelector: &metav1.LabelSelector{
  1400. MatchExpressions: []metav1.LabelSelectorRequirement{
  1401. {
  1402. Key: "foo",
  1403. Operator: metav1.LabelSelectorOpExists,
  1404. },
  1405. },
  1406. },
  1407. },
  1408. },
  1409. },
  1410. },
  1411. pods: []*v1.Pod{
  1412. {
  1413. ObjectMeta: metav1.ObjectMeta{Name: "pod-a1", UID: types.UID("pod-a1"), Labels: map[string]string{"foo": ""}},
  1414. Spec: v1.PodSpec{NodeName: "node-a", Priority: &midPriority},
  1415. Status: v1.PodStatus{Phase: v1.PodRunning},
  1416. },
  1417. {
  1418. ObjectMeta: metav1.ObjectMeta{Name: "pod-a2", UID: types.UID("pod-a2"), Labels: map[string]string{"foo": ""}},
  1419. Spec: v1.PodSpec{NodeName: "node-a", Priority: &lowPriority},
  1420. Status: v1.PodStatus{Phase: v1.PodRunning},
  1421. },
  1422. {
  1423. ObjectMeta: metav1.ObjectMeta{Name: "pod-b1", UID: types.UID("pod-b1"), Labels: map[string]string{"foo": ""}},
  1424. Spec: v1.PodSpec{NodeName: "node-b", Priority: &lowPriority},
  1425. Status: v1.PodStatus{Phase: v1.PodRunning},
  1426. },
  1427. {
  1428. ObjectMeta: metav1.ObjectMeta{Name: "pod-x1", UID: types.UID("pod-x1"), Labels: map[string]string{"foo": ""}},
  1429. Spec: v1.PodSpec{NodeName: "node-x", Priority: &highPriority},
  1430. Status: v1.PodStatus{Phase: v1.PodRunning},
  1431. },
  1432. {
  1433. ObjectMeta: metav1.ObjectMeta{Name: "pod-x2", UID: types.UID("pod-x2"), Labels: map[string]string{"foo": ""}},
  1434. Spec: v1.PodSpec{NodeName: "node-x", Priority: &highPriority},
  1435. Status: v1.PodStatus{Phase: v1.PodRunning},
  1436. },
  1437. },
  1438. expected: map[string]victims{
  1439. "node-a": {pods: sets.NewString("pod-a2")},
  1440. "node-b": {pods: sets.NewString("pod-b1")},
  1441. },
  1442. expectedNumFilterCalled: 6,
  1443. },
  1444. {
  1445. name: "get Unschedulable in the preemption phase when the filter plugins filtering the nodes",
  1446. registerPlugins: []st.RegisterPluginFunc{
  1447. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1448. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1449. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1450. },
  1451. nodes: []string{"machine1", "machine2"},
  1452. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1453. pods: []*v1.Pod{
  1454. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}},
  1455. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}}},
  1456. filterReturnCode: framework.Unschedulable,
  1457. expected: map[string]victims{},
  1458. expectedNumFilterCalled: 2,
  1459. },
  1460. {
  1461. name: "preemption with violation of same pdb",
  1462. registerPlugins: []st.RegisterPluginFunc{
  1463. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1464. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1465. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1466. },
  1467. nodes: []string{"machine1"},
  1468. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1469. pods: []*v1.Pod{
  1470. {ObjectMeta: metav1.ObjectMeta{Name: "a", UID: types.UID("a"), Labels: map[string]string{"app": "foo"}}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}},
  1471. {ObjectMeta: metav1.ObjectMeta{Name: "b", UID: types.UID("b"), Labels: map[string]string{"app": "foo"}}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}}},
  1472. pdbs: []*policy.PodDisruptionBudget{
  1473. {Spec: policy.PodDisruptionBudgetSpec{Selector: &metav1.LabelSelector{MatchLabels: map[string]string{"app": "foo"}}}, Status: policy.PodDisruptionBudgetStatus{DisruptionsAllowed: 1}}},
  1474. expected: map[string]victims{"machine1": {pods: sets.NewString("a", "b"), numPDBViolations: 1}},
  1475. expectedNumFilterCalled: 3,
  1476. },
  1477. }
  1478. labelKeys := []string{"hostname", "zone", "region"}
  1479. for _, test := range tests {
  1480. t.Run(test.name, func(t *testing.T) {
  1481. client := clientsetfake.NewSimpleClientset()
  1482. informerFactory := informers.NewSharedInformerFactory(client, 0)
  1483. filterFailedNodeReturnCodeMap := map[string]framework.Code{}
  1484. cache := internalcache.New(time.Duration(0), wait.NeverStop)
  1485. for _, pod := range test.pods {
  1486. cache.AddPod(pod)
  1487. }
  1488. for _, name := range test.nodes {
  1489. filterFailedNodeReturnCodeMap[name] = test.filterReturnCode
  1490. cache.AddNode(&v1.Node{ObjectMeta: metav1.ObjectMeta{Name: name, Labels: map[string]string{"hostname": name}}})
  1491. }
  1492. var nodes []*v1.Node
  1493. for _, n := range test.nodes {
  1494. node := makeNode(n, 1000*5, schedutil.DefaultMemoryRequest*5)
  1495. // if possible, split node name by '/' to form labels in a format of
  1496. // {"hostname": node.Name[0], "zone": node.Name[1], "region": node.Name[2]}
  1497. node.ObjectMeta.Labels = make(map[string]string)
  1498. for i, label := range strings.Split(node.Name, "/") {
  1499. node.ObjectMeta.Labels[labelKeys[i]] = label
  1500. }
  1501. node.Name = node.ObjectMeta.Labels["hostname"]
  1502. nodes = append(nodes, node)
  1503. }
  1504. // For each test, prepend a FakeFilterPlugin.
  1505. fakePlugin := fakeFilterPlugin{}
  1506. fakePlugin.failedNodeReturnCodeMap = filterFailedNodeReturnCodeMap
  1507. registerFakeFilterFunc := st.RegisterFilterPlugin(
  1508. "FakeFilter",
  1509. func(_ *runtime.Unknown, fh framework.FrameworkHandle) (framework.Plugin, error) {
  1510. return &fakePlugin, nil
  1511. },
  1512. )
  1513. registerPlugins := append([]st.RegisterPluginFunc{registerFakeFilterFunc}, test.registerPlugins...)
  1514. // Use a real snapshot since it's needed in some Filter Plugin (e.g., PodAffinity)
  1515. snapshot := internalcache.NewSnapshot(test.pods, nodes)
  1516. fwk, err := st.NewFramework(registerPlugins, framework.WithSnapshotSharedLister(snapshot))
  1517. if err != nil {
  1518. t.Fatal(err)
  1519. }
  1520. scheduler := NewGenericScheduler(
  1521. nil,
  1522. internalqueue.NewSchedulingQueue(nil),
  1523. snapshot,
  1524. fwk,
  1525. []SchedulerExtender{},
  1526. nil,
  1527. nil,
  1528. informerFactory.Policy().V1beta1().PodDisruptionBudgets().Lister(),
  1529. false,
  1530. schedulerapi.DefaultPercentageOfNodesToScore,
  1531. false)
  1532. g := scheduler.(*genericScheduler)
  1533. assignDefaultStartTime(test.pods)
  1534. state := framework.NewCycleState()
  1535. // Some tests rely on PreFilter plugin to compute its CycleState.
  1536. preFilterStatus := fwk.RunPreFilterPlugins(context.Background(), state, test.pod)
  1537. if !preFilterStatus.IsSuccess() {
  1538. t.Errorf("Unexpected preFilterStatus: %v", preFilterStatus)
  1539. }
  1540. nodeInfos, err := nodesToNodeInfos(nodes, snapshot)
  1541. if err != nil {
  1542. t.Fatal(err)
  1543. }
  1544. nodeToPods, err := g.selectNodesForPreemption(context.Background(), state, test.pod, nodeInfos, test.pdbs)
  1545. if err != nil {
  1546. t.Error(err)
  1547. }
  1548. if test.expectedNumFilterCalled != fakePlugin.numFilterCalled {
  1549. t.Errorf("expected fakePlugin.numFilterCalled is %d, but got %d", test.expectedNumFilterCalled, fakePlugin.numFilterCalled)
  1550. }
  1551. if err := checkPreemptionVictims(test.expected, nodeToPods); err != nil {
  1552. t.Error(err)
  1553. }
  1554. })
  1555. }
  1556. }
  1557. // TestPickOneNodeForPreemption tests pickOneNodeForPreemption.
  1558. func TestPickOneNodeForPreemption(t *testing.T) {
  1559. tests := []struct {
  1560. name string
  1561. registerPlugins []st.RegisterPluginFunc
  1562. nodes []string
  1563. pod *v1.Pod
  1564. pods []*v1.Pod
  1565. expected []string // any of the items is valid
  1566. }{
  1567. {
  1568. name: "No node needs preemption",
  1569. registerPlugins: []st.RegisterPluginFunc{
  1570. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1571. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1572. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1573. },
  1574. nodes: []string{"machine1"},
  1575. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1576. pods: []*v1.Pod{
  1577. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}}},
  1578. expected: []string{"machine1"},
  1579. },
  1580. {
  1581. name: "a pod that fits on both machines when lower priority pods are preempted",
  1582. registerPlugins: []st.RegisterPluginFunc{
  1583. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1584. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1585. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1586. },
  1587. nodes: []string{"machine1", "machine2"},
  1588. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1589. pods: []*v1.Pod{
  1590. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1591. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}}},
  1592. expected: []string{"machine1", "machine2"},
  1593. },
  1594. {
  1595. name: "a pod that fits on a machine with no preemption",
  1596. registerPlugins: []st.RegisterPluginFunc{
  1597. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1598. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1599. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1600. },
  1601. nodes: []string{"machine1", "machine2", "machine3"},
  1602. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority}},
  1603. pods: []*v1.Pod{
  1604. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1605. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}}},
  1606. expected: []string{"machine3"},
  1607. },
  1608. {
  1609. name: "machine with min highest priority pod is picked",
  1610. registerPlugins: []st.RegisterPluginFunc{
  1611. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1612. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1613. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1614. },
  1615. nodes: []string{"machine1", "machine2", "machine3"},
  1616. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1617. pods: []*v1.Pod{
  1618. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1619. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1620. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1621. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1622. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1623. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1624. },
  1625. expected: []string{"machine3"},
  1626. },
  1627. {
  1628. name: "when highest priorities are the same, minimum sum of priorities is picked",
  1629. registerPlugins: []st.RegisterPluginFunc{
  1630. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1631. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1632. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1633. },
  1634. nodes: []string{"machine1", "machine2", "machine3"},
  1635. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1636. pods: []*v1.Pod{
  1637. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1638. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1639. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1640. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1641. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1642. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1643. },
  1644. expected: []string{"machine2"},
  1645. },
  1646. {
  1647. name: "when highest priority and sum are the same, minimum number of pods is picked",
  1648. registerPlugins: []st.RegisterPluginFunc{
  1649. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1650. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1651. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1652. },
  1653. nodes: []string{"machine1", "machine2", "machine3"},
  1654. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1655. pods: []*v1.Pod{
  1656. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1657. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1658. {ObjectMeta: metav1.ObjectMeta{Name: "m1.3", UID: types.UID("m1.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1659. {ObjectMeta: metav1.ObjectMeta{Name: "m1.4", UID: types.UID("m1.4")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1660. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1661. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &negPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1662. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1663. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1664. {ObjectMeta: metav1.ObjectMeta{Name: "m3.3", UID: types.UID("m3.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1665. },
  1666. expected: []string{"machine2"},
  1667. },
  1668. {
  1669. // pickOneNodeForPreemption adjusts pod priorities when finding the sum of the victims. This
  1670. // test ensures that the logic works correctly.
  1671. name: "sum of adjusted priorities is considered",
  1672. registerPlugins: []st.RegisterPluginFunc{
  1673. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1674. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1675. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1676. },
  1677. nodes: []string{"machine1", "machine2", "machine3"},
  1678. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1679. pods: []*v1.Pod{
  1680. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1681. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1682. {ObjectMeta: metav1.ObjectMeta{Name: "m1.3", UID: types.UID("m1.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1683. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1684. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &negPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1685. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1686. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1687. {ObjectMeta: metav1.ObjectMeta{Name: "m3.3", UID: types.UID("m3.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1688. },
  1689. expected: []string{"machine2"},
  1690. },
  1691. {
  1692. name: "non-overlapping lowest high priority, sum priorities, and number of pods",
  1693. registerPlugins: []st.RegisterPluginFunc{
  1694. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1695. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1696. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1697. },
  1698. nodes: []string{"machine1", "machine2", "machine3", "machine4"},
  1699. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &veryHighPriority}},
  1700. pods: []*v1.Pod{
  1701. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1702. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1703. {ObjectMeta: metav1.ObjectMeta{Name: "m1.3", UID: types.UID("m1.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime}},
  1704. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime}},
  1705. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1706. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1707. {ObjectMeta: metav1.ObjectMeta{Name: "m3.3", UID: types.UID("m3.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1708. {ObjectMeta: metav1.ObjectMeta{Name: "m3.4", UID: types.UID("m3.4")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime}},
  1709. {ObjectMeta: metav1.ObjectMeta{Name: "m4.1", UID: types.UID("m4.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine4"}, Status: v1.PodStatus{StartTime: &startTime}},
  1710. {ObjectMeta: metav1.ObjectMeta{Name: "m4.2", UID: types.UID("m4.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine4"}, Status: v1.PodStatus{StartTime: &startTime}},
  1711. {ObjectMeta: metav1.ObjectMeta{Name: "m4.3", UID: types.UID("m4.3")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine4"}, Status: v1.PodStatus{StartTime: &startTime}},
  1712. {ObjectMeta: metav1.ObjectMeta{Name: "m4.4", UID: types.UID("m4.4")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &negPriority, NodeName: "machine4"}, Status: v1.PodStatus{StartTime: &startTime}},
  1713. },
  1714. expected: []string{"machine1"},
  1715. },
  1716. {
  1717. name: "same priority, same number of victims, different start time for each machine's pod",
  1718. registerPlugins: []st.RegisterPluginFunc{
  1719. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1720. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1721. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1722. },
  1723. nodes: []string{"machine1", "machine2", "machine3"},
  1724. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1725. pods: []*v1.Pod{
  1726. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190103}},
  1727. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190103}},
  1728. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190104}},
  1729. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190104}},
  1730. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190102}},
  1731. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190102}},
  1732. },
  1733. expected: []string{"machine2"},
  1734. },
  1735. {
  1736. name: "same priority, same number of victims, different start time for all pods",
  1737. registerPlugins: []st.RegisterPluginFunc{
  1738. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1739. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1740. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1741. },
  1742. nodes: []string{"machine1", "machine2", "machine3"},
  1743. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1744. pods: []*v1.Pod{
  1745. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190105}},
  1746. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190103}},
  1747. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190106}},
  1748. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190102}},
  1749. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190104}},
  1750. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190107}},
  1751. },
  1752. expected: []string{"machine3"},
  1753. },
  1754. {
  1755. name: "different priority, same number of victims, different start time for all pods",
  1756. registerPlugins: []st.RegisterPluginFunc{
  1757. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1758. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1759. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1760. },
  1761. nodes: []string{"machine1", "machine2", "machine3"},
  1762. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "machine1", UID: types.UID("machine1")}, Spec: v1.PodSpec{Containers: veryLargeContainers, Priority: &highPriority}},
  1763. pods: []*v1.Pod{
  1764. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190105}},
  1765. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{StartTime: &startTime20190103}},
  1766. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190107}},
  1767. {ObjectMeta: metav1.ObjectMeta{Name: "m2.2", UID: types.UID("m2.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine2"}, Status: v1.PodStatus{StartTime: &startTime20190102}},
  1768. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &lowPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190104}},
  1769. {ObjectMeta: metav1.ObjectMeta{Name: "m3.2", UID: types.UID("m3.2")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{StartTime: &startTime20190106}},
  1770. },
  1771. expected: []string{"machine2"},
  1772. },
  1773. }
  1774. for _, test := range tests {
  1775. t.Run(test.name, func(t *testing.T) {
  1776. var nodes []*v1.Node
  1777. for _, n := range test.nodes {
  1778. nodes = append(nodes, makeNode(n, schedutil.DefaultMilliCPURequest*5, schedutil.DefaultMemoryRequest*5))
  1779. }
  1780. snapshot := internalcache.NewSnapshot(test.pods, nodes)
  1781. fwk, err := st.NewFramework(test.registerPlugins, framework.WithSnapshotSharedLister(snapshot))
  1782. if err != nil {
  1783. t.Fatal(err)
  1784. }
  1785. g := &genericScheduler{
  1786. framework: fwk,
  1787. nodeInfoSnapshot: snapshot,
  1788. }
  1789. assignDefaultStartTime(test.pods)
  1790. nodeInfos, err := nodesToNodeInfos(nodes, snapshot)
  1791. if err != nil {
  1792. t.Fatal(err)
  1793. }
  1794. state := framework.NewCycleState()
  1795. candidateNodes, _ := g.selectNodesForPreemption(context.Background(), state, test.pod, nodeInfos, nil)
  1796. node := pickOneNodeForPreemption(candidateNodes)
  1797. found := false
  1798. for _, nodeName := range test.expected {
  1799. if node.Name == nodeName {
  1800. found = true
  1801. break
  1802. }
  1803. }
  1804. if !found {
  1805. t.Errorf("unexpected node: %v", node)
  1806. }
  1807. })
  1808. }
  1809. }
  1810. func TestNodesWherePreemptionMightHelp(t *testing.T) {
  1811. // Prepare 4 node names.
  1812. nodeNames := make([]string, 0, 4)
  1813. for i := 1; i < 5; i++ {
  1814. nodeNames = append(nodeNames, fmt.Sprintf("machine%d", i))
  1815. }
  1816. tests := []struct {
  1817. name string
  1818. nodesStatuses framework.NodeToStatusMap
  1819. expected map[string]bool // set of expected node names. Value is ignored.
  1820. }{
  1821. {
  1822. name: "No node should be attempted",
  1823. nodesStatuses: framework.NodeToStatusMap{
  1824. "machine1": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodeaffinity.ErrReason),
  1825. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodename.ErrReason),
  1826. "machine3": framework.NewStatus(framework.UnschedulableAndUnresolvable, tainttoleration.ErrReasonNotMatch),
  1827. "machine4": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodelabel.ErrReasonPresenceViolated),
  1828. },
  1829. expected: map[string]bool{},
  1830. },
  1831. {
  1832. name: "ErrReasonAffinityNotMatch should be tried as it indicates that the pod is unschedulable due to inter-pod affinity or anti-affinity",
  1833. nodesStatuses: framework.NodeToStatusMap{
  1834. "machine1": framework.NewStatus(framework.Unschedulable, interpodaffinity.ErrReasonAffinityNotMatch),
  1835. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodename.ErrReason),
  1836. "machine3": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodeunschedulable.ErrReasonUnschedulable),
  1837. },
  1838. expected: map[string]bool{"machine1": true, "machine4": true},
  1839. },
  1840. {
  1841. name: "pod with both pod affinity and anti-affinity should be tried",
  1842. nodesStatuses: framework.NodeToStatusMap{
  1843. "machine1": framework.NewStatus(framework.Unschedulable, interpodaffinity.ErrReasonAffinityNotMatch),
  1844. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodename.ErrReason),
  1845. },
  1846. expected: map[string]bool{"machine1": true, "machine3": true, "machine4": true},
  1847. },
  1848. {
  1849. name: "ErrReasonAffinityRulesNotMatch should not be tried as it indicates that the pod is unschedulable due to inter-pod affinity, but ErrReasonAffinityNotMatch should be tried as it indicates that the pod is unschedulable due to inter-pod affinity or anti-affinity",
  1850. nodesStatuses: framework.NodeToStatusMap{
  1851. "machine1": framework.NewStatus(framework.UnschedulableAndUnresolvable, interpodaffinity.ErrReasonAffinityRulesNotMatch),
  1852. "machine2": framework.NewStatus(framework.Unschedulable, interpodaffinity.ErrReasonAffinityNotMatch),
  1853. },
  1854. expected: map[string]bool{"machine2": true, "machine3": true, "machine4": true},
  1855. },
  1856. {
  1857. name: "Mix of failed predicates works fine",
  1858. nodesStatuses: framework.NodeToStatusMap{
  1859. "machine1": framework.NewStatus(framework.UnschedulableAndUnresolvable, volumerestrictions.ErrReasonDiskConflict),
  1860. "machine2": framework.NewStatus(framework.Unschedulable, fmt.Sprintf("Insufficient %v", v1.ResourceMemory)),
  1861. },
  1862. expected: map[string]bool{"machine2": true, "machine3": true, "machine4": true},
  1863. },
  1864. {
  1865. name: "Node condition errors should be considered unresolvable",
  1866. nodesStatuses: framework.NodeToStatusMap{
  1867. "machine1": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodeunschedulable.ErrReasonUnknownCondition),
  1868. },
  1869. expected: map[string]bool{"machine2": true, "machine3": true, "machine4": true},
  1870. },
  1871. {
  1872. name: "ErrVolume... errors should not be tried as it indicates that the pod is unschedulable due to no matching volumes for pod on node",
  1873. nodesStatuses: framework.NodeToStatusMap{
  1874. "machine1": framework.NewStatus(framework.UnschedulableAndUnresolvable, volumezone.ErrReasonConflict),
  1875. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, volumebinding.ErrReasonNodeConflict),
  1876. "machine3": framework.NewStatus(framework.UnschedulableAndUnresolvable, volumebinding.ErrReasonBindConflict),
  1877. },
  1878. expected: map[string]bool{"machine4": true},
  1879. },
  1880. {
  1881. name: "ErrTopologySpreadConstraintsNotMatch should be tried as it indicates that the pod is unschedulable due to topology spread constraints",
  1882. nodesStatuses: framework.NodeToStatusMap{
  1883. "machine1": framework.NewStatus(framework.Unschedulable, podtopologyspread.ErrReasonConstraintsNotMatch),
  1884. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, nodename.ErrReason),
  1885. "machine3": framework.NewStatus(framework.Unschedulable, podtopologyspread.ErrReasonConstraintsNotMatch),
  1886. },
  1887. expected: map[string]bool{"machine1": true, "machine3": true, "machine4": true},
  1888. },
  1889. {
  1890. name: "UnschedulableAndUnresolvable status should be skipped but Unschedulable should be tried",
  1891. nodesStatuses: framework.NodeToStatusMap{
  1892. "machine2": framework.NewStatus(framework.UnschedulableAndUnresolvable, ""),
  1893. "machine3": framework.NewStatus(framework.Unschedulable, ""),
  1894. "machine4": framework.NewStatus(framework.UnschedulableAndUnresolvable, ""),
  1895. },
  1896. expected: map[string]bool{"machine1": true, "machine3": true},
  1897. },
  1898. }
  1899. for _, test := range tests {
  1900. t.Run(test.name, func(t *testing.T) {
  1901. fitErr := FitError{
  1902. FilteredNodesStatuses: test.nodesStatuses,
  1903. }
  1904. var nodeInfos []*schedulernodeinfo.NodeInfo
  1905. for _, n := range makeNodeList(nodeNames) {
  1906. ni := schedulernodeinfo.NewNodeInfo()
  1907. ni.SetNode(n)
  1908. nodeInfos = append(nodeInfos, ni)
  1909. }
  1910. nodes := nodesWherePreemptionMightHelp(nodeInfos, &fitErr)
  1911. if len(test.expected) != len(nodes) {
  1912. t.Errorf("number of nodes is not the same as expected. exptectd: %d, got: %d. Nodes: %v", len(test.expected), len(nodes), nodes)
  1913. }
  1914. for _, node := range nodes {
  1915. name := node.Node().Name
  1916. if _, found := test.expected[name]; !found {
  1917. t.Errorf("node %v is not expected.", name)
  1918. }
  1919. }
  1920. })
  1921. }
  1922. }
  1923. func TestPreempt(t *testing.T) {
  1924. defaultFailedNodeToStatusMap := framework.NodeToStatusMap{
  1925. "machine1": framework.NewStatus(framework.Unschedulable, fmt.Sprintf("Insufficient %v", v1.ResourceMemory)),
  1926. "machine2": framework.NewStatus(framework.Unschedulable, volumerestrictions.ErrReasonDiskConflict),
  1927. "machine3": framework.NewStatus(framework.Unschedulable, fmt.Sprintf("Insufficient %v", v1.ResourceMemory)),
  1928. }
  1929. // Prepare 3 node names.
  1930. var defaultNodeNames []string
  1931. for i := 1; i < 4; i++ {
  1932. defaultNodeNames = append(defaultNodeNames, fmt.Sprintf("machine%d", i))
  1933. }
  1934. var (
  1935. preemptLowerPriority = v1.PreemptLowerPriority
  1936. preemptNever = v1.PreemptNever
  1937. )
  1938. tests := []struct {
  1939. name string
  1940. pod *v1.Pod
  1941. pods []*v1.Pod
  1942. extenders []*FakeExtender
  1943. failedNodeToStatusMap framework.NodeToStatusMap
  1944. nodeNames []string
  1945. registerPlugins []st.RegisterPluginFunc
  1946. expectedNode string
  1947. expectedPods []string // list of preempted pods
  1948. }{
  1949. {
  1950. name: "basic preemption logic",
  1951. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  1952. Containers: veryLargeContainers,
  1953. Priority: &highPriority,
  1954. PreemptionPolicy: &preemptLowerPriority},
  1955. },
  1956. pods: []*v1.Pod{
  1957. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1958. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1959. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1960. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1961. },
  1962. registerPlugins: []st.RegisterPluginFunc{
  1963. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1964. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1965. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1966. },
  1967. expectedNode: "machine1",
  1968. expectedPods: []string{"m1.1", "m1.2"},
  1969. },
  1970. {
  1971. name: "One node doesn't need any preemption",
  1972. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  1973. Containers: veryLargeContainers,
  1974. Priority: &highPriority,
  1975. PreemptionPolicy: &preemptLowerPriority},
  1976. },
  1977. pods: []*v1.Pod{
  1978. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1979. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1980. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  1981. },
  1982. registerPlugins: []st.RegisterPluginFunc{
  1983. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  1984. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  1985. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  1986. },
  1987. expectedNode: "machine3",
  1988. expectedPods: []string{},
  1989. },
  1990. {
  1991. name: "preemption for topology spread constraints",
  1992. pod: &v1.Pod{
  1993. ObjectMeta: metav1.ObjectMeta{
  1994. Name: "p",
  1995. Labels: map[string]string{"foo": ""},
  1996. },
  1997. Spec: v1.PodSpec{
  1998. Priority: &highPriority,
  1999. TopologySpreadConstraints: []v1.TopologySpreadConstraint{
  2000. {
  2001. MaxSkew: 1,
  2002. TopologyKey: "zone",
  2003. WhenUnsatisfiable: v1.DoNotSchedule,
  2004. LabelSelector: &metav1.LabelSelector{
  2005. MatchExpressions: []metav1.LabelSelectorRequirement{
  2006. {
  2007. Key: "foo",
  2008. Operator: metav1.LabelSelectorOpExists,
  2009. },
  2010. },
  2011. },
  2012. },
  2013. {
  2014. MaxSkew: 1,
  2015. TopologyKey: "hostname",
  2016. WhenUnsatisfiable: v1.DoNotSchedule,
  2017. LabelSelector: &metav1.LabelSelector{
  2018. MatchExpressions: []metav1.LabelSelectorRequirement{
  2019. {
  2020. Key: "foo",
  2021. Operator: metav1.LabelSelectorOpExists,
  2022. },
  2023. },
  2024. },
  2025. },
  2026. },
  2027. },
  2028. },
  2029. pods: []*v1.Pod{
  2030. {
  2031. ObjectMeta: metav1.ObjectMeta{Name: "pod-a1", UID: types.UID("pod-a1"), Labels: map[string]string{"foo": ""}},
  2032. Spec: v1.PodSpec{NodeName: "node-a", Priority: &highPriority},
  2033. Status: v1.PodStatus{Phase: v1.PodRunning},
  2034. },
  2035. {
  2036. ObjectMeta: metav1.ObjectMeta{Name: "pod-a2", UID: types.UID("pod-a2"), Labels: map[string]string{"foo": ""}},
  2037. Spec: v1.PodSpec{NodeName: "node-a", Priority: &highPriority},
  2038. Status: v1.PodStatus{Phase: v1.PodRunning},
  2039. },
  2040. {
  2041. ObjectMeta: metav1.ObjectMeta{Name: "pod-b1", UID: types.UID("pod-b1"), Labels: map[string]string{"foo": ""}},
  2042. Spec: v1.PodSpec{NodeName: "node-b", Priority: &lowPriority},
  2043. Status: v1.PodStatus{Phase: v1.PodRunning},
  2044. },
  2045. {
  2046. ObjectMeta: metav1.ObjectMeta{Name: "pod-x1", UID: types.UID("pod-x1"), Labels: map[string]string{"foo": ""}},
  2047. Spec: v1.PodSpec{NodeName: "node-x", Priority: &highPriority},
  2048. Status: v1.PodStatus{Phase: v1.PodRunning},
  2049. },
  2050. {
  2051. ObjectMeta: metav1.ObjectMeta{Name: "pod-x2", UID: types.UID("pod-x2"), Labels: map[string]string{"foo": ""}},
  2052. Spec: v1.PodSpec{NodeName: "node-x", Priority: &highPriority},
  2053. Status: v1.PodStatus{Phase: v1.PodRunning},
  2054. },
  2055. },
  2056. failedNodeToStatusMap: framework.NodeToStatusMap{
  2057. "node-a": framework.NewStatus(framework.Unschedulable, podtopologyspread.ErrReasonConstraintsNotMatch),
  2058. "node-b": framework.NewStatus(framework.Unschedulable, podtopologyspread.ErrReasonConstraintsNotMatch),
  2059. "node-x": framework.NewStatus(framework.Unschedulable, podtopologyspread.ErrReasonConstraintsNotMatch),
  2060. },
  2061. nodeNames: []string{"node-a/zone1", "node-b/zone1", "node-x/zone2"},
  2062. registerPlugins: []st.RegisterPluginFunc{
  2063. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2064. st.RegisterPluginAsExtensions(
  2065. podtopologyspread.Name,
  2066. 1,
  2067. podtopologyspread.New,
  2068. "PreFilter",
  2069. "Filter",
  2070. ),
  2071. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2072. },
  2073. expectedNode: "node-b",
  2074. expectedPods: []string{"pod-b1"},
  2075. },
  2076. {
  2077. name: "Scheduler extenders allow only machine1, otherwise machine3 would have been chosen",
  2078. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2079. Containers: veryLargeContainers,
  2080. Priority: &highPriority,
  2081. PreemptionPolicy: &preemptLowerPriority},
  2082. },
  2083. pods: []*v1.Pod{
  2084. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2085. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2086. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2087. },
  2088. extenders: []*FakeExtender{
  2089. {
  2090. predicates: []fitPredicate{truePredicateExtender},
  2091. },
  2092. {
  2093. predicates: []fitPredicate{machine1PredicateExtender},
  2094. },
  2095. },
  2096. registerPlugins: []st.RegisterPluginFunc{
  2097. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2098. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2099. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2100. },
  2101. expectedNode: "machine1",
  2102. expectedPods: []string{"m1.1", "m1.2"},
  2103. },
  2104. {
  2105. name: "Scheduler extenders do not allow any preemption",
  2106. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2107. Containers: veryLargeContainers,
  2108. Priority: &highPriority,
  2109. PreemptionPolicy: &preemptLowerPriority},
  2110. },
  2111. pods: []*v1.Pod{
  2112. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2113. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2114. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2115. },
  2116. extenders: []*FakeExtender{
  2117. {
  2118. predicates: []fitPredicate{falsePredicateExtender},
  2119. },
  2120. },
  2121. registerPlugins: []st.RegisterPluginFunc{
  2122. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2123. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2124. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2125. },
  2126. expectedNode: "",
  2127. expectedPods: []string{},
  2128. },
  2129. {
  2130. name: "One scheduler extender allows only machine1, the other returns error but ignorable. Only machine1 would be chosen",
  2131. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2132. Containers: veryLargeContainers,
  2133. Priority: &highPriority,
  2134. PreemptionPolicy: &preemptLowerPriority},
  2135. },
  2136. pods: []*v1.Pod{
  2137. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2138. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2139. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2140. },
  2141. extenders: []*FakeExtender{
  2142. {
  2143. predicates: []fitPredicate{errorPredicateExtender},
  2144. ignorable: true,
  2145. },
  2146. {
  2147. predicates: []fitPredicate{machine1PredicateExtender},
  2148. },
  2149. },
  2150. registerPlugins: []st.RegisterPluginFunc{
  2151. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2152. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2153. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2154. },
  2155. expectedNode: "machine1",
  2156. expectedPods: []string{"m1.1", "m1.2"},
  2157. },
  2158. {
  2159. name: "One scheduler extender allows only machine1, but it is not interested in given pod, otherwise machine1 would have been chosen",
  2160. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2161. Containers: veryLargeContainers,
  2162. Priority: &highPriority,
  2163. PreemptionPolicy: &preemptLowerPriority},
  2164. },
  2165. pods: []*v1.Pod{
  2166. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &midPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2167. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2168. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &midPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2169. },
  2170. extenders: []*FakeExtender{
  2171. {
  2172. predicates: []fitPredicate{machine1PredicateExtender},
  2173. unInterested: true,
  2174. },
  2175. {
  2176. predicates: []fitPredicate{truePredicateExtender},
  2177. },
  2178. },
  2179. registerPlugins: []st.RegisterPluginFunc{
  2180. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2181. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2182. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2183. },
  2184. expectedNode: "machine3",
  2185. expectedPods: []string{},
  2186. },
  2187. {
  2188. name: "no preempting in pod",
  2189. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2190. Containers: veryLargeContainers,
  2191. Priority: &highPriority,
  2192. PreemptionPolicy: &preemptNever},
  2193. },
  2194. pods: []*v1.Pod{
  2195. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2196. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2197. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2198. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2199. },
  2200. registerPlugins: []st.RegisterPluginFunc{
  2201. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2202. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2203. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2204. },
  2205. expectedNode: "",
  2206. expectedPods: nil,
  2207. },
  2208. {
  2209. name: "PreemptionPolicy is nil",
  2210. pod: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "pod1", UID: types.UID("pod1")}, Spec: v1.PodSpec{
  2211. Containers: veryLargeContainers,
  2212. Priority: &highPriority,
  2213. PreemptionPolicy: nil},
  2214. },
  2215. pods: []*v1.Pod{
  2216. {ObjectMeta: metav1.ObjectMeta{Name: "m1.1", UID: types.UID("m1.1")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2217. {ObjectMeta: metav1.ObjectMeta{Name: "m1.2", UID: types.UID("m1.2")}, Spec: v1.PodSpec{Containers: smallContainers, Priority: &lowPriority, NodeName: "machine1"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2218. {ObjectMeta: metav1.ObjectMeta{Name: "m2.1", UID: types.UID("m2.1")}, Spec: v1.PodSpec{Containers: largeContainers, Priority: &highPriority, NodeName: "machine2"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2219. {ObjectMeta: metav1.ObjectMeta{Name: "m3.1", UID: types.UID("m3.1")}, Spec: v1.PodSpec{Containers: mediumContainers, Priority: &midPriority, NodeName: "machine3"}, Status: v1.PodStatus{Phase: v1.PodRunning}},
  2220. },
  2221. registerPlugins: []st.RegisterPluginFunc{
  2222. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2223. st.RegisterFilterPlugin(noderesources.FitName, noderesources.NewFit),
  2224. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2225. },
  2226. expectedNode: "machine1",
  2227. expectedPods: []string{"m1.1", "m1.2"},
  2228. },
  2229. }
  2230. labelKeys := []string{"hostname", "zone", "region"}
  2231. for _, test := range tests {
  2232. t.Run(test.name, func(t *testing.T) {
  2233. client := clientsetfake.NewSimpleClientset()
  2234. informerFactory := informers.NewSharedInformerFactory(client, 0)
  2235. stop := make(chan struct{})
  2236. cache := internalcache.New(time.Duration(0), stop)
  2237. for _, pod := range test.pods {
  2238. cache.AddPod(pod)
  2239. }
  2240. cachedNodeInfoMap := map[string]*schedulernodeinfo.NodeInfo{}
  2241. nodeNames := defaultNodeNames
  2242. if len(test.nodeNames) != 0 {
  2243. nodeNames = test.nodeNames
  2244. }
  2245. var nodes []*v1.Node
  2246. for i, name := range nodeNames {
  2247. node := makeNode(name, 1000*5, schedutil.DefaultMemoryRequest*5)
  2248. // if possible, split node name by '/' to form labels in a format of
  2249. // {"hostname": node.Name[0], "zone": node.Name[1], "region": node.Name[2]}
  2250. node.ObjectMeta.Labels = make(map[string]string)
  2251. for i, label := range strings.Split(node.Name, "/") {
  2252. node.ObjectMeta.Labels[labelKeys[i]] = label
  2253. }
  2254. node.Name = node.ObjectMeta.Labels["hostname"]
  2255. cache.AddNode(node)
  2256. nodes = append(nodes, node)
  2257. nodeNames[i] = node.Name
  2258. // Set nodeInfo to extenders to mock extenders' cache for preemption.
  2259. cachedNodeInfo := schedulernodeinfo.NewNodeInfo()
  2260. cachedNodeInfo.SetNode(node)
  2261. cachedNodeInfoMap[node.Name] = cachedNodeInfo
  2262. }
  2263. var extenders []SchedulerExtender
  2264. for _, extender := range test.extenders {
  2265. // Set nodeInfoMap as extenders cached node information.
  2266. extender.cachedNodeNameToInfo = cachedNodeInfoMap
  2267. extenders = append(extenders, extender)
  2268. }
  2269. snapshot := internalcache.NewSnapshot(test.pods, nodes)
  2270. fwk, err := st.NewFramework(test.registerPlugins, framework.WithSnapshotSharedLister(snapshot))
  2271. if err != nil {
  2272. t.Fatal(err)
  2273. }
  2274. scheduler := NewGenericScheduler(
  2275. cache,
  2276. internalqueue.NewSchedulingQueue(nil),
  2277. snapshot,
  2278. fwk,
  2279. extenders,
  2280. nil,
  2281. informerFactory.Core().V1().PersistentVolumeClaims().Lister(),
  2282. informerFactory.Policy().V1beta1().PodDisruptionBudgets().Lister(),
  2283. false,
  2284. schedulerapi.DefaultPercentageOfNodesToScore,
  2285. true)
  2286. state := framework.NewCycleState()
  2287. // Some tests rely on PreFilter plugin to compute its CycleState.
  2288. preFilterStatus := fwk.RunPreFilterPlugins(context.Background(), state, test.pod)
  2289. if !preFilterStatus.IsSuccess() {
  2290. t.Errorf("Unexpected preFilterStatus: %v", preFilterStatus)
  2291. }
  2292. // Call Preempt and check the expected results.
  2293. failedNodeToStatusMap := defaultFailedNodeToStatusMap
  2294. if test.failedNodeToStatusMap != nil {
  2295. failedNodeToStatusMap = test.failedNodeToStatusMap
  2296. }
  2297. node, victims, _, err := scheduler.Preempt(context.Background(), state, test.pod, error(&FitError{Pod: test.pod, FilteredNodesStatuses: failedNodeToStatusMap}))
  2298. if err != nil {
  2299. t.Errorf("unexpected error in preemption: %v", err)
  2300. }
  2301. if node != nil && node.Name != test.expectedNode {
  2302. t.Errorf("expected node: %v, got: %v", test.expectedNode, node.GetName())
  2303. }
  2304. if node == nil && len(test.expectedNode) != 0 {
  2305. t.Errorf("expected node: %v, got: nothing", test.expectedNode)
  2306. }
  2307. if len(victims) != len(test.expectedPods) {
  2308. t.Errorf("expected %v pods, got %v.", len(test.expectedPods), len(victims))
  2309. }
  2310. for _, victim := range victims {
  2311. found := false
  2312. for _, expPod := range test.expectedPods {
  2313. if expPod == victim.Name {
  2314. found = true
  2315. break
  2316. }
  2317. }
  2318. if !found {
  2319. t.Errorf("pod %v is not expected to be a victim.", victim.Name)
  2320. }
  2321. // Mark the victims for deletion and record the preemptor's nominated node name.
  2322. now := metav1.Now()
  2323. victim.DeletionTimestamp = &now
  2324. test.pod.Status.NominatedNodeName = node.Name
  2325. }
  2326. // Call preempt again and make sure it doesn't preempt any more pods.
  2327. node, victims, _, err = scheduler.Preempt(context.Background(), state, test.pod, error(&FitError{Pod: test.pod, FilteredNodesStatuses: failedNodeToStatusMap}))
  2328. if err != nil {
  2329. t.Errorf("unexpected error in preemption: %v", err)
  2330. }
  2331. if node != nil && len(victims) > 0 {
  2332. t.Errorf("didn't expect any more preemption. Node %v is selected for preemption.", node)
  2333. }
  2334. close(stop)
  2335. })
  2336. }
  2337. }
  2338. func TestNumFeasibleNodesToFind(t *testing.T) {
  2339. tests := []struct {
  2340. name string
  2341. percentageOfNodesToScore int32
  2342. numAllNodes int32
  2343. wantNumNodes int32
  2344. }{
  2345. {
  2346. name: "not set percentageOfNodesToScore and nodes number not more than 50",
  2347. numAllNodes: 10,
  2348. wantNumNodes: 10,
  2349. },
  2350. {
  2351. name: "set percentageOfNodesToScore and nodes number not more than 50",
  2352. percentageOfNodesToScore: 40,
  2353. numAllNodes: 10,
  2354. wantNumNodes: 10,
  2355. },
  2356. {
  2357. name: "not set percentageOfNodesToScore and nodes number more than 50",
  2358. numAllNodes: 1000,
  2359. wantNumNodes: 420,
  2360. },
  2361. {
  2362. name: "set percentageOfNodesToScore and nodes number more than 50",
  2363. percentageOfNodesToScore: 40,
  2364. numAllNodes: 1000,
  2365. wantNumNodes: 400,
  2366. },
  2367. {
  2368. name: "not set percentageOfNodesToScore and nodes number more than 50*125",
  2369. numAllNodes: 6000,
  2370. wantNumNodes: 300,
  2371. },
  2372. {
  2373. name: "set percentageOfNodesToScore and nodes number more than 50*125",
  2374. percentageOfNodesToScore: 40,
  2375. numAllNodes: 6000,
  2376. wantNumNodes: 2400,
  2377. },
  2378. }
  2379. for _, tt := range tests {
  2380. t.Run(tt.name, func(t *testing.T) {
  2381. g := &genericScheduler{
  2382. percentageOfNodesToScore: tt.percentageOfNodesToScore,
  2383. }
  2384. if gotNumNodes := g.numFeasibleNodesToFind(tt.numAllNodes); gotNumNodes != tt.wantNumNodes {
  2385. t.Errorf("genericScheduler.numFeasibleNodesToFind() = %v, want %v", gotNumNodes, tt.wantNumNodes)
  2386. }
  2387. })
  2388. }
  2389. }
  2390. func assignDefaultStartTime(pods []*v1.Pod) {
  2391. now := metav1.Now()
  2392. for i := range pods {
  2393. pod := pods[i]
  2394. if pod.Status.StartTime == nil {
  2395. pod.Status.StartTime = &now
  2396. }
  2397. }
  2398. }
  2399. func TestFairEvaluationForNodes(t *testing.T) {
  2400. numAllNodes := 500
  2401. nodeNames := make([]string, 0, numAllNodes)
  2402. for i := 0; i < numAllNodes; i++ {
  2403. nodeNames = append(nodeNames, strconv.Itoa(i))
  2404. }
  2405. nodes := makeNodeList(nodeNames)
  2406. g := makeScheduler(
  2407. nodes,
  2408. st.RegisterQueueSortPlugin(queuesort.Name, queuesort.New),
  2409. st.RegisterFilterPlugin("TrueFilter", NewTrueFilterPlugin),
  2410. st.RegisterBindPlugin(defaultbinder.Name, defaultbinder.New),
  2411. )
  2412. // To make numAllNodes % nodesToFind != 0
  2413. g.percentageOfNodesToScore = 30
  2414. nodesToFind := int(g.numFeasibleNodesToFind(int32(numAllNodes)))
  2415. // Iterating over all nodes more than twice
  2416. for i := 0; i < 2*(numAllNodes/nodesToFind+1); i++ {
  2417. nodesThatFit, _, err := g.findNodesThatFitPod(context.Background(), framework.NewCycleState(), &v1.Pod{})
  2418. if err != nil {
  2419. t.Errorf("unexpected error: %v", err)
  2420. }
  2421. if len(nodesThatFit) != nodesToFind {
  2422. t.Errorf("got %d nodes filtered, want %d", len(nodesThatFit), nodesToFind)
  2423. }
  2424. if g.nextStartNodeIndex != (i+1)*nodesToFind%numAllNodes {
  2425. t.Errorf("got %d lastProcessedNodeIndex, want %d", g.nextStartNodeIndex, (i+1)*nodesToFind%numAllNodes)
  2426. }
  2427. }
  2428. }
  2429. func nodesToNodeInfos(nodes []*v1.Node, snapshot *internalcache.Snapshot) ([]*schedulernodeinfo.NodeInfo, error) {
  2430. var nodeInfos []*schedulernodeinfo.NodeInfo
  2431. for _, n := range nodes {
  2432. nodeInfo, err := snapshot.NodeInfos().Get(n.Name)
  2433. if err != nil {
  2434. return nil, err
  2435. }
  2436. nodeInfos = append(nodeInfos, nodeInfo)
  2437. }
  2438. return nodeInfos, nil
  2439. }