volume_binding_test.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. /*
  2. Copyright 2017 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 scheduler
  14. // This file tests the VolumeScheduling feature.
  15. import (
  16. "fmt"
  17. "os"
  18. "strconv"
  19. "strings"
  20. "testing"
  21. "time"
  22. "k8s.io/klog"
  23. "k8s.io/api/core/v1"
  24. storagev1 "k8s.io/api/storage/v1"
  25. "k8s.io/apimachinery/pkg/api/resource"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/util/rand"
  28. "k8s.io/apimachinery/pkg/util/sets"
  29. "k8s.io/apimachinery/pkg/util/wait"
  30. utilfeature "k8s.io/apiserver/pkg/util/feature"
  31. "k8s.io/client-go/informers"
  32. clientset "k8s.io/client-go/kubernetes"
  33. featuregatetesting "k8s.io/component-base/featuregate/testing"
  34. "k8s.io/kubernetes/pkg/controller/volume/persistentvolume"
  35. persistentvolumeoptions "k8s.io/kubernetes/pkg/controller/volume/persistentvolume/options"
  36. "k8s.io/kubernetes/pkg/features"
  37. "k8s.io/kubernetes/pkg/scheduler/algorithm/predicates"
  38. schedulerconfig "k8s.io/kubernetes/pkg/scheduler/apis/config"
  39. "k8s.io/kubernetes/pkg/volume"
  40. volumetest "k8s.io/kubernetes/pkg/volume/testing"
  41. imageutils "k8s.io/kubernetes/test/utils/image"
  42. )
  43. type testConfig struct {
  44. client clientset.Interface
  45. ns string
  46. stop <-chan struct{}
  47. teardown func()
  48. }
  49. var (
  50. // Delete API objects immediately
  51. deletePeriod = int64(0)
  52. deleteOption = &metav1.DeleteOptions{GracePeriodSeconds: &deletePeriod}
  53. modeWait = storagev1.VolumeBindingWaitForFirstConsumer
  54. modeImmediate = storagev1.VolumeBindingImmediate
  55. classWait = "wait"
  56. classImmediate = "immediate"
  57. classDynamic = "dynamic"
  58. classTopoMismatch = "topomismatch"
  59. sharedClasses = map[string]*storagev1.StorageClass{
  60. classImmediate: makeStorageClass(classImmediate, &modeImmediate),
  61. classWait: makeStorageClass(classWait, &modeWait),
  62. }
  63. )
  64. const (
  65. node1 = "node-1"
  66. node2 = "node-2"
  67. podLimit = 100
  68. volsPerPod = 5
  69. nodeAffinityLabelKey = "kubernetes.io/hostname"
  70. provisionerPluginName = "kubernetes.io/mock-provisioner"
  71. )
  72. type testPV struct {
  73. name string
  74. scName string
  75. preboundPVC string
  76. node string
  77. }
  78. type testPVC struct {
  79. name string
  80. scName string
  81. preboundPV string
  82. }
  83. func TestVolumeBinding(t *testing.T) {
  84. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  85. config := setupCluster(t, "volume-scheduling-", 2, 0, 0)
  86. defer config.teardown()
  87. cases := map[string]struct {
  88. pod *v1.Pod
  89. pvs []*testPV
  90. pvcs []*testPVC
  91. // Create these, but they should not be bound in the end
  92. unboundPvcs []*testPVC
  93. unboundPvs []*testPV
  94. shouldFail bool
  95. }{
  96. "immediate can bind": {
  97. pod: makePod("pod-i-canbind", config.ns, []string{"pvc-i-canbind"}),
  98. pvs: []*testPV{{"pv-i-canbind", classImmediate, "", node1}},
  99. pvcs: []*testPVC{{"pvc-i-canbind", classImmediate, ""}},
  100. },
  101. "immediate cannot bind": {
  102. pod: makePod("pod-i-cannotbind", config.ns, []string{"pvc-i-cannotbind"}),
  103. unboundPvcs: []*testPVC{{"pvc-i-cannotbind", classImmediate, ""}},
  104. shouldFail: true,
  105. },
  106. "immediate pvc prebound": {
  107. pod: makePod("pod-i-pvc-prebound", config.ns, []string{"pvc-i-prebound"}),
  108. pvs: []*testPV{{"pv-i-pvc-prebound", classImmediate, "", node1}},
  109. pvcs: []*testPVC{{"pvc-i-prebound", classImmediate, "pv-i-pvc-prebound"}},
  110. },
  111. "immediate pv prebound": {
  112. pod: makePod("pod-i-pv-prebound", config.ns, []string{"pvc-i-pv-prebound"}),
  113. pvs: []*testPV{{"pv-i-prebound", classImmediate, "pvc-i-pv-prebound", node1}},
  114. pvcs: []*testPVC{{"pvc-i-pv-prebound", classImmediate, ""}},
  115. },
  116. "wait can bind": {
  117. pod: makePod("pod-w-canbind", config.ns, []string{"pvc-w-canbind"}),
  118. pvs: []*testPV{{"pv-w-canbind", classWait, "", node1}},
  119. pvcs: []*testPVC{{"pvc-w-canbind", classWait, ""}},
  120. },
  121. "wait cannot bind": {
  122. pod: makePod("pod-w-cannotbind", config.ns, []string{"pvc-w-cannotbind"}),
  123. unboundPvcs: []*testPVC{{"pvc-w-cannotbind", classWait, ""}},
  124. shouldFail: true,
  125. },
  126. "wait pvc prebound": {
  127. pod: makePod("pod-w-pvc-prebound", config.ns, []string{"pvc-w-prebound"}),
  128. pvs: []*testPV{{"pv-w-pvc-prebound", classWait, "", node1}},
  129. pvcs: []*testPVC{{"pvc-w-prebound", classWait, "pv-w-pvc-prebound"}},
  130. },
  131. "wait pv prebound": {
  132. pod: makePod("pod-w-pv-prebound", config.ns, []string{"pvc-w-pv-prebound"}),
  133. pvs: []*testPV{{"pv-w-prebound", classWait, "pvc-w-pv-prebound", node1}},
  134. pvcs: []*testPVC{{"pvc-w-pv-prebound", classWait, ""}},
  135. },
  136. "wait can bind two": {
  137. pod: makePod("pod-w-canbind-2", config.ns, []string{"pvc-w-canbind-2", "pvc-w-canbind-3"}),
  138. pvs: []*testPV{
  139. {"pv-w-canbind-2", classWait, "", node2},
  140. {"pv-w-canbind-3", classWait, "", node2},
  141. },
  142. pvcs: []*testPVC{
  143. {"pvc-w-canbind-2", classWait, ""},
  144. {"pvc-w-canbind-3", classWait, ""},
  145. },
  146. unboundPvs: []*testPV{
  147. {"pv-w-canbind-5", classWait, "", node1},
  148. },
  149. },
  150. "wait cannot bind two": {
  151. pod: makePod("pod-w-cannotbind-2", config.ns, []string{"pvc-w-cannotbind-1", "pvc-w-cannotbind-2"}),
  152. unboundPvcs: []*testPVC{
  153. {"pvc-w-cannotbind-1", classWait, ""},
  154. {"pvc-w-cannotbind-2", classWait, ""},
  155. },
  156. unboundPvs: []*testPV{
  157. {"pv-w-cannotbind-1", classWait, "", node2},
  158. {"pv-w-cannotbind-2", classWait, "", node1},
  159. },
  160. shouldFail: true,
  161. },
  162. "mix immediate and wait": {
  163. pod: makePod("pod-mix-bound", config.ns, []string{"pvc-w-canbind-4", "pvc-i-canbind-2"}),
  164. pvs: []*testPV{
  165. {"pv-w-canbind-4", classWait, "", node1},
  166. {"pv-i-canbind-2", classImmediate, "", node1},
  167. },
  168. pvcs: []*testPVC{
  169. {"pvc-w-canbind-4", classWait, ""},
  170. {"pvc-i-canbind-2", classImmediate, ""},
  171. },
  172. },
  173. }
  174. for name, test := range cases {
  175. klog.Infof("Running test %v", name)
  176. // Create two StorageClasses
  177. suffix := rand.String(4)
  178. classes := map[string]*storagev1.StorageClass{}
  179. classes[classImmediate] = makeStorageClass(fmt.Sprintf("immediate-%v", suffix), &modeImmediate)
  180. classes[classWait] = makeStorageClass(fmt.Sprintf("wait-%v", suffix), &modeWait)
  181. for _, sc := range classes {
  182. if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
  183. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  184. }
  185. }
  186. // Create PVs
  187. for _, pvConfig := range test.pvs {
  188. pv := makePV(pvConfig.name, classes[pvConfig.scName].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
  189. if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  190. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  191. }
  192. }
  193. for _, pvConfig := range test.unboundPvs {
  194. pv := makePV(pvConfig.name, classes[pvConfig.scName].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
  195. if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  196. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  197. }
  198. }
  199. // Create PVCs
  200. for _, pvcConfig := range test.pvcs {
  201. pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scName].Name, pvcConfig.preboundPV)
  202. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  203. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  204. }
  205. }
  206. for _, pvcConfig := range test.unboundPvcs {
  207. pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scName].Name, pvcConfig.preboundPV)
  208. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  209. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  210. }
  211. }
  212. // Create Pod
  213. if _, err := config.client.CoreV1().Pods(config.ns).Create(test.pod); err != nil {
  214. t.Fatalf("Failed to create Pod %q: %v", test.pod.Name, err)
  215. }
  216. if test.shouldFail {
  217. if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
  218. t.Errorf("Pod %q was not unschedulable: %v", test.pod.Name, err)
  219. }
  220. } else {
  221. if err := waitForPodToSchedule(config.client, test.pod); err != nil {
  222. t.Errorf("Failed to schedule Pod %q: %v", test.pod.Name, err)
  223. }
  224. }
  225. // Validate PVC/PV binding
  226. for _, pvc := range test.pvcs {
  227. validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimBound, false)
  228. }
  229. for _, pvc := range test.unboundPvcs {
  230. validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimPending, false)
  231. }
  232. for _, pv := range test.pvs {
  233. validatePVPhase(t, config.client, pv.name, v1.VolumeBound)
  234. }
  235. for _, pv := range test.unboundPvs {
  236. validatePVPhase(t, config.client, pv.name, v1.VolumeAvailable)
  237. }
  238. // Force delete objects, but they still may not be immediately removed
  239. deleteTestObjects(config.client, config.ns, deleteOption)
  240. }
  241. }
  242. // TestVolumeBindingRescheduling tests scheduler will retry scheduling when needed.
  243. func TestVolumeBindingRescheduling(t *testing.T) {
  244. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  245. config := setupCluster(t, "volume-scheduling-", 2, 0, 0)
  246. defer config.teardown()
  247. storageClassName := "local-storage"
  248. cases := map[string]struct {
  249. pod *v1.Pod
  250. pvcs []*testPVC
  251. pvs []*testPV
  252. trigger func(config *testConfig)
  253. shouldFail bool
  254. }{
  255. "reschedule on WaitForFirstConsumer dynamic storage class add": {
  256. pod: makePod("pod-reschedule-onclassadd-dynamic", config.ns, []string{"pvc-reschedule-onclassadd-dynamic"}),
  257. pvcs: []*testPVC{
  258. {"pvc-reschedule-onclassadd-dynamic", "", ""},
  259. },
  260. trigger: func(config *testConfig) {
  261. sc := makeDynamicProvisionerStorageClass(storageClassName, &modeWait, nil)
  262. if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
  263. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  264. }
  265. },
  266. shouldFail: false,
  267. },
  268. "reschedule on WaitForFirstConsumer static storage class add": {
  269. pod: makePod("pod-reschedule-onclassadd-static", config.ns, []string{"pvc-reschedule-onclassadd-static"}),
  270. pvcs: []*testPVC{
  271. {"pvc-reschedule-onclassadd-static", "", ""},
  272. },
  273. trigger: func(config *testConfig) {
  274. sc := makeStorageClass(storageClassName, &modeWait)
  275. if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
  276. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  277. }
  278. // Create pv for this class to mock static provisioner behavior.
  279. pv := makePV("pv-reschedule-onclassadd-static", storageClassName, "", "", node1)
  280. if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  281. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  282. }
  283. },
  284. shouldFail: false,
  285. },
  286. "reschedule on delay binding PVC add": {
  287. pod: makePod("pod-reschedule-onpvcadd", config.ns, []string{"pvc-reschedule-onpvcadd"}),
  288. pvs: []*testPV{
  289. {
  290. name: "pv-reschedule-onpvcadd",
  291. scName: classWait,
  292. node: node1,
  293. },
  294. },
  295. trigger: func(config *testConfig) {
  296. pvc := makePVC("pvc-reschedule-onpvcadd", config.ns, &classWait, "")
  297. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  298. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  299. }
  300. },
  301. shouldFail: false,
  302. },
  303. }
  304. for name, test := range cases {
  305. klog.Infof("Running test %v", name)
  306. if test.pod == nil {
  307. t.Fatal("pod is required for this test")
  308. }
  309. // Create unbound pvc
  310. for _, pvcConfig := range test.pvcs {
  311. pvc := makePVC(pvcConfig.name, config.ns, &storageClassName, "")
  312. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  313. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  314. }
  315. }
  316. // Create PVs
  317. for _, pvConfig := range test.pvs {
  318. pv := makePV(pvConfig.name, sharedClasses[pvConfig.scName].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
  319. if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  320. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  321. }
  322. }
  323. // Create pod
  324. if _, err := config.client.CoreV1().Pods(config.ns).Create(test.pod); err != nil {
  325. t.Fatalf("Failed to create Pod %q: %v", test.pod.Name, err)
  326. }
  327. // Wait for pod is unschedulable.
  328. klog.Infof("Waiting for pod is unschedulable")
  329. if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
  330. t.Errorf("Failed as Pod %s was not unschedulable: %v", test.pod.Name, err)
  331. }
  332. // Trigger
  333. test.trigger(config)
  334. // Wait for pod is scheduled or unscheduable.
  335. if !test.shouldFail {
  336. klog.Infof("Waiting for pod is scheduled")
  337. if err := waitForPodToSchedule(config.client, test.pod); err != nil {
  338. t.Errorf("Failed to schedule Pod %q: %v", test.pod.Name, err)
  339. }
  340. } else {
  341. klog.Infof("Waiting for pod is unschedulable")
  342. if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
  343. t.Errorf("Failed as Pod %s was not unschedulable: %v", test.pod.Name, err)
  344. }
  345. }
  346. // Force delete objects, but they still may not be immediately removed
  347. deleteTestObjects(config.client, config.ns, deleteOption)
  348. }
  349. }
  350. // TestVolumeBindingStress creates <podLimit> pods, each with <volsPerPod> unbound or prebound PVCs.
  351. // PVs are precreated.
  352. func TestVolumeBindingStress(t *testing.T) {
  353. testVolumeBindingStress(t, 0, false, 0)
  354. }
  355. // Like TestVolumeBindingStress but with scheduler resync. In real cluster,
  356. // scheduler will schedule failed pod frequently due to various events, e.g.
  357. // service/node update events.
  358. // This is useful to detect possible race conditions.
  359. func TestVolumeBindingStressWithSchedulerResync(t *testing.T) {
  360. testVolumeBindingStress(t, time.Second, false, 0)
  361. }
  362. // Like TestVolumeBindingStress but with fast dynamic provisioning
  363. func TestVolumeBindingDynamicStressFast(t *testing.T) {
  364. testVolumeBindingStress(t, 0, true, 0)
  365. }
  366. // Like TestVolumeBindingStress but with slow dynamic provisioning
  367. func TestVolumeBindingDynamicStressSlow(t *testing.T) {
  368. testVolumeBindingStress(t, 0, true, 30)
  369. }
  370. func testVolumeBindingStress(t *testing.T, schedulerResyncPeriod time.Duration, dynamic bool, provisionDelaySeconds int) {
  371. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  372. config := setupCluster(t, "volume-binding-stress-", 1, schedulerResyncPeriod, provisionDelaySeconds)
  373. defer config.teardown()
  374. // Set max volume limit to the number of PVCs the test will create
  375. // TODO: remove when max volume limit allows setting through storageclass
  376. if err := os.Setenv(predicates.KubeMaxPDVols, fmt.Sprintf("%v", podLimit*volsPerPod)); err != nil {
  377. t.Fatalf("failed to set max pd limit: %v", err)
  378. }
  379. defer os.Unsetenv(predicates.KubeMaxPDVols)
  380. scName := &classWait
  381. if dynamic {
  382. scName = &classDynamic
  383. sc := makeDynamicProvisionerStorageClass(*scName, &modeWait, nil)
  384. if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
  385. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  386. }
  387. }
  388. // Create enough PVs and PVCs for all the pods
  389. pvs := []*v1.PersistentVolume{}
  390. pvcs := []*v1.PersistentVolumeClaim{}
  391. for i := 0; i < podLimit*volsPerPod; i++ {
  392. var (
  393. pv *v1.PersistentVolume
  394. pvc *v1.PersistentVolumeClaim
  395. pvName = fmt.Sprintf("pv-stress-%v", i)
  396. pvcName = fmt.Sprintf("pvc-stress-%v", i)
  397. )
  398. // Don't create pvs for dynamic provisioning test
  399. if !dynamic {
  400. if rand.Int()%2 == 0 {
  401. // static unbound pvs
  402. pv = makePV(pvName, *scName, "", "", node1)
  403. } else {
  404. // static prebound pvs
  405. pv = makePV(pvName, classImmediate, pvcName, config.ns, node1)
  406. }
  407. if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  408. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  409. }
  410. pvs = append(pvs, pv)
  411. }
  412. if pv != nil && pv.Spec.ClaimRef != nil && pv.Spec.ClaimRef.Name == pvcName {
  413. pvc = makePVC(pvcName, config.ns, &classImmediate, pv.Name)
  414. } else {
  415. pvc = makePVC(pvcName, config.ns, scName, "")
  416. }
  417. if pvc, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  418. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  419. }
  420. pvcs = append(pvcs, pvc)
  421. }
  422. pods := []*v1.Pod{}
  423. for i := 0; i < podLimit; i++ {
  424. // Generate string of all the PVCs for the pod
  425. podPvcs := []string{}
  426. for j := i * volsPerPod; j < (i+1)*volsPerPod; j++ {
  427. podPvcs = append(podPvcs, pvcs[j].Name)
  428. }
  429. pod := makePod(fmt.Sprintf("pod%03d", i), config.ns, podPvcs)
  430. if pod, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
  431. t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
  432. }
  433. pods = append(pods, pod)
  434. }
  435. // Validate Pods scheduled
  436. for _, pod := range pods {
  437. // Use increased timeout for stress test because there is a higher chance of
  438. // PV sync error
  439. if err := waitForPodToScheduleWithTimeout(config.client, pod, 2*time.Minute); err != nil {
  440. t.Errorf("Failed to schedule Pod %q: %v", pod.Name, err)
  441. }
  442. }
  443. // Validate PVC/PV binding
  444. for _, pvc := range pvcs {
  445. validatePVCPhase(t, config.client, pvc.Name, config.ns, v1.ClaimBound, dynamic)
  446. }
  447. for _, pv := range pvs {
  448. validatePVPhase(t, config.client, pv.Name, v1.VolumeBound)
  449. }
  450. }
  451. func testVolumeBindingWithAffinity(t *testing.T, anti bool, numNodes, numPods, numPVsFirstNode int) {
  452. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  453. config := setupCluster(t, "volume-pod-affinity-", numNodes, 0, 0)
  454. defer config.teardown()
  455. pods := []*v1.Pod{}
  456. pvcs := []*v1.PersistentVolumeClaim{}
  457. pvs := []*v1.PersistentVolume{}
  458. // Create PVs for the first node
  459. for i := 0; i < numPVsFirstNode; i++ {
  460. pv := makePV(fmt.Sprintf("pv-node1-%v", i), classWait, "", "", node1)
  461. if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  462. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  463. }
  464. pvs = append(pvs, pv)
  465. }
  466. // Create 1 PV per Node for the remaining nodes
  467. for i := 2; i <= numNodes; i++ {
  468. pv := makePV(fmt.Sprintf("pv-node%v-0", i), classWait, "", "", fmt.Sprintf("node-%v", i))
  469. if pv, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  470. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  471. }
  472. pvs = append(pvs, pv)
  473. }
  474. // Create pods
  475. for i := 0; i < numPods; i++ {
  476. // Create one pvc per pod
  477. pvc := makePVC(fmt.Sprintf("pvc-%v", i), config.ns, &classWait, "")
  478. if pvc, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  479. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  480. }
  481. pvcs = append(pvcs, pvc)
  482. // Create pod with pod affinity
  483. pod := makePod(fmt.Sprintf("pod%03d", i), config.ns, []string{pvc.Name})
  484. pod.Spec.Affinity = &v1.Affinity{}
  485. affinityTerms := []v1.PodAffinityTerm{
  486. {
  487. LabelSelector: &metav1.LabelSelector{
  488. MatchExpressions: []metav1.LabelSelectorRequirement{
  489. {
  490. Key: "app",
  491. Operator: metav1.LabelSelectorOpIn,
  492. Values: []string{"volume-binding-test"},
  493. },
  494. },
  495. },
  496. TopologyKey: nodeAffinityLabelKey,
  497. },
  498. }
  499. if anti {
  500. pod.Spec.Affinity.PodAntiAffinity = &v1.PodAntiAffinity{
  501. RequiredDuringSchedulingIgnoredDuringExecution: affinityTerms,
  502. }
  503. } else {
  504. pod.Spec.Affinity.PodAffinity = &v1.PodAffinity{
  505. RequiredDuringSchedulingIgnoredDuringExecution: affinityTerms,
  506. }
  507. }
  508. if pod, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
  509. t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
  510. }
  511. pods = append(pods, pod)
  512. }
  513. // Validate Pods scheduled
  514. scheduledNodes := sets.NewString()
  515. for _, pod := range pods {
  516. if err := waitForPodToSchedule(config.client, pod); err != nil {
  517. t.Errorf("Failed to schedule Pod %q: %v", pod.Name, err)
  518. } else {
  519. // Keep track of all the nodes that the Pods were scheduled on
  520. pod, err = config.client.CoreV1().Pods(config.ns).Get(pod.Name, metav1.GetOptions{})
  521. if err != nil {
  522. t.Fatalf("Failed to get Pod %q: %v", pod.Name, err)
  523. }
  524. if pod.Spec.NodeName == "" {
  525. t.Fatalf("Pod %q node name unset after scheduling", pod.Name)
  526. }
  527. scheduledNodes.Insert(pod.Spec.NodeName)
  528. }
  529. }
  530. // Validate the affinity policy
  531. if anti {
  532. // The pods should have been spread across different nodes
  533. if scheduledNodes.Len() != numPods {
  534. t.Errorf("Pods were scheduled across %v nodes instead of %v", scheduledNodes.Len(), numPods)
  535. }
  536. } else {
  537. // The pods should have been scheduled on 1 node
  538. if scheduledNodes.Len() != 1 {
  539. t.Errorf("Pods were scheduled across %v nodes instead of %v", scheduledNodes.Len(), 1)
  540. }
  541. }
  542. // Validate PVC binding
  543. for _, pvc := range pvcs {
  544. validatePVCPhase(t, config.client, pvc.Name, config.ns, v1.ClaimBound, false)
  545. }
  546. }
  547. func TestVolumeBindingWithAntiAffinity(t *testing.T) {
  548. numNodes := 10
  549. // Create as many pods as number of nodes
  550. numPods := numNodes
  551. // Create many more PVs on node1 to increase chance of selecting node1
  552. numPVsFirstNode := 10 * numNodes
  553. testVolumeBindingWithAffinity(t, true, numNodes, numPods, numPVsFirstNode)
  554. }
  555. func TestVolumeBindingWithAffinity(t *testing.T) {
  556. numPods := 10
  557. // Create many more nodes to increase chance of selecting a PV on a different node than node1
  558. numNodes := 10 * numPods
  559. // Create numPods PVs on the first node
  560. numPVsFirstNode := numPods
  561. testVolumeBindingWithAffinity(t, true, numNodes, numPods, numPVsFirstNode)
  562. }
  563. func TestPVAffinityConflict(t *testing.T) {
  564. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  565. config := setupCluster(t, "volume-scheduling-", 3, 0, 0)
  566. defer config.teardown()
  567. pv := makePV("local-pv", classImmediate, "", "", node1)
  568. pvc := makePVC("local-pvc", config.ns, &classImmediate, "")
  569. // Create PV
  570. if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  571. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  572. }
  573. // Create PVC
  574. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  575. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  576. }
  577. // Wait for PVC bound
  578. if err := waitForPVCBound(config.client, pvc); err != nil {
  579. t.Fatalf("PVC %q failed to bind: %v", pvc.Name, err)
  580. }
  581. nodeMarkers := []interface{}{
  582. markNodeAffinity,
  583. markNodeSelector,
  584. }
  585. for i := 0; i < len(nodeMarkers); i++ {
  586. podName := "local-pod-" + strconv.Itoa(i+1)
  587. pod := makePod(podName, config.ns, []string{"local-pvc"})
  588. nodeMarkers[i].(func(*v1.Pod, string))(pod, "node-2")
  589. // Create Pod
  590. if _, err := config.client.CoreV1().Pods(config.ns).Create(pod); err != nil {
  591. t.Fatalf("Failed to create Pod %q: %v", pod.Name, err)
  592. }
  593. // Give time to shceduler to attempt to schedule pod
  594. if err := waitForPodUnschedulable(config.client, pod); err != nil {
  595. t.Errorf("Failed as Pod %s was not unschedulable: %v", pod.Name, err)
  596. }
  597. // Check pod conditions
  598. p, err := config.client.CoreV1().Pods(config.ns).Get(podName, metav1.GetOptions{})
  599. if err != nil {
  600. t.Fatalf("Failed to access Pod %s status: %v", podName, err)
  601. }
  602. if strings.Compare(string(p.Status.Phase), "Pending") != 0 {
  603. t.Fatalf("Failed as Pod %s was in: %s state and not in expected: Pending state", podName, p.Status.Phase)
  604. }
  605. if strings.Compare(p.Status.Conditions[0].Reason, "Unschedulable") != 0 {
  606. t.Fatalf("Failed as Pod %s reason was: %s but expected: Unschedulable", podName, p.Status.Conditions[0].Reason)
  607. }
  608. if !strings.Contains(p.Status.Conditions[0].Message, "node(s) didn't match node selector") || !strings.Contains(p.Status.Conditions[0].Message, "node(s) had volume node affinity conflict") {
  609. t.Fatalf("Failed as Pod's %s failure message does not contain expected message: node(s) didn't match node selector, node(s) had volume node affinity conflict. Got message %q", podName, p.Status.Conditions[0].Message)
  610. }
  611. // Deleting test pod
  612. if err := config.client.CoreV1().Pods(config.ns).Delete(podName, &metav1.DeleteOptions{}); err != nil {
  613. t.Fatalf("Failed to delete Pod %s: %v", podName, err)
  614. }
  615. }
  616. }
  617. func TestVolumeProvision(t *testing.T) {
  618. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.PersistentLocalVolumes, true)()
  619. config := setupCluster(t, "volume-scheduling", 1, 0, 0)
  620. defer config.teardown()
  621. cases := map[string]struct {
  622. pod *v1.Pod
  623. pvs []*testPV
  624. boundPvcs []*testPVC
  625. provisionedPvcs []*testPVC
  626. // Create these, but they should not be bound in the end
  627. unboundPvcs []*testPVC
  628. shouldFail bool
  629. }{
  630. "wait provisioned": {
  631. pod: makePod("pod-pvc-canprovision", config.ns, []string{"pvc-canprovision"}),
  632. provisionedPvcs: []*testPVC{{"pvc-canprovision", classWait, ""}},
  633. },
  634. "topolgy unsatisfied": {
  635. pod: makePod("pod-pvc-topomismatch", config.ns, []string{"pvc-topomismatch"}),
  636. unboundPvcs: []*testPVC{{"pvc-topomismatch", classTopoMismatch, ""}},
  637. shouldFail: true,
  638. },
  639. "wait one bound, one provisioned": {
  640. pod: makePod("pod-pvc-canbind-or-provision", config.ns, []string{"pvc-w-canbind", "pvc-canprovision"}),
  641. pvs: []*testPV{{"pv-w-canbind", classWait, "", node1}},
  642. boundPvcs: []*testPVC{{"pvc-w-canbind", classWait, ""}},
  643. provisionedPvcs: []*testPVC{{"pvc-canprovision", classWait, ""}},
  644. },
  645. "one immediate pv prebound, one wait provisioned": {
  646. pod: makePod("pod-i-pv-prebound-w-provisioned", config.ns, []string{"pvc-i-pv-prebound", "pvc-canprovision"}),
  647. pvs: []*testPV{{"pv-i-prebound", classImmediate, "pvc-i-pv-prebound", node1}},
  648. boundPvcs: []*testPVC{{"pvc-i-pv-prebound", classImmediate, ""}},
  649. provisionedPvcs: []*testPVC{{"pvc-canprovision", classWait, ""}},
  650. },
  651. "wait one pv prebound, one provisioned": {
  652. pod: makePod("pod-w-pv-prebound-w-provisioned", config.ns, []string{"pvc-w-pv-prebound", "pvc-canprovision"}),
  653. pvs: []*testPV{{"pv-w-prebound", classWait, "pvc-w-pv-prebound", node1}},
  654. boundPvcs: []*testPVC{{"pvc-w-pv-prebound", classWait, ""}},
  655. provisionedPvcs: []*testPVC{{"pvc-canprovision", classWait, ""}},
  656. },
  657. "immediate provisioned by controller": {
  658. pod: makePod("pod-i-unbound", config.ns, []string{"pvc-controller-provisioned"}),
  659. // A pvc of immediate binding mode is expected to be provisioned by controller,
  660. // we treat it as "bound" here because it is supposed to be in same state
  661. // with bound claims, i.e. in bound status and has no selectedNode annotation.
  662. boundPvcs: []*testPVC{{"pvc-controller-provisioned", classImmediate, ""}},
  663. },
  664. }
  665. for name, test := range cases {
  666. klog.Infof("Running test %v", name)
  667. // Create StorageClasses
  668. suffix := rand.String(4)
  669. classes := map[string]*storagev1.StorageClass{}
  670. classes[classImmediate] = makeDynamicProvisionerStorageClass(fmt.Sprintf("immediate-%v", suffix), &modeImmediate, nil)
  671. classes[classWait] = makeDynamicProvisionerStorageClass(fmt.Sprintf("wait-%v", suffix), &modeWait, nil)
  672. topo := []v1.TopologySelectorTerm{
  673. {
  674. MatchLabelExpressions: []v1.TopologySelectorLabelRequirement{
  675. {
  676. Key: nodeAffinityLabelKey,
  677. Values: []string{node2},
  678. },
  679. },
  680. },
  681. }
  682. classes[classTopoMismatch] = makeDynamicProvisionerStorageClass(fmt.Sprintf("topomismatch-%v", suffix), &modeWait, topo)
  683. for _, sc := range classes {
  684. if _, err := config.client.StorageV1().StorageClasses().Create(sc); err != nil {
  685. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  686. }
  687. }
  688. // Create PVs
  689. for _, pvConfig := range test.pvs {
  690. pv := makePV(pvConfig.name, classes[pvConfig.scName].Name, pvConfig.preboundPVC, config.ns, pvConfig.node)
  691. if _, err := config.client.CoreV1().PersistentVolumes().Create(pv); err != nil {
  692. t.Fatalf("Failed to create PersistentVolume %q: %v", pv.Name, err)
  693. }
  694. }
  695. // Create PVCs
  696. for _, pvcConfig := range test.boundPvcs {
  697. pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scName].Name, pvcConfig.preboundPV)
  698. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  699. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  700. }
  701. }
  702. for _, pvcConfig := range test.unboundPvcs {
  703. pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scName].Name, pvcConfig.preboundPV)
  704. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  705. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  706. }
  707. }
  708. for _, pvcConfig := range test.provisionedPvcs {
  709. pvc := makePVC(pvcConfig.name, config.ns, &classes[pvcConfig.scName].Name, pvcConfig.preboundPV)
  710. if _, err := config.client.CoreV1().PersistentVolumeClaims(config.ns).Create(pvc); err != nil {
  711. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  712. }
  713. }
  714. // Create Pod
  715. if _, err := config.client.CoreV1().Pods(config.ns).Create(test.pod); err != nil {
  716. t.Fatalf("Failed to create Pod %q: %v", test.pod.Name, err)
  717. }
  718. if test.shouldFail {
  719. if err := waitForPodUnschedulable(config.client, test.pod); err != nil {
  720. t.Errorf("Pod %q was not unschedulable: %v", test.pod.Name, err)
  721. }
  722. } else {
  723. if err := waitForPodToSchedule(config.client, test.pod); err != nil {
  724. t.Errorf("Failed to schedule Pod %q: %v", test.pod.Name, err)
  725. }
  726. }
  727. // Validate PVC/PV binding
  728. for _, pvc := range test.boundPvcs {
  729. validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimBound, false)
  730. }
  731. for _, pvc := range test.unboundPvcs {
  732. validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimPending, false)
  733. }
  734. for _, pvc := range test.provisionedPvcs {
  735. validatePVCPhase(t, config.client, pvc.name, config.ns, v1.ClaimBound, true)
  736. }
  737. for _, pv := range test.pvs {
  738. validatePVPhase(t, config.client, pv.name, v1.VolumeBound)
  739. }
  740. // Force delete objects, but they still may not be immediately removed
  741. deleteTestObjects(config.client, config.ns, deleteOption)
  742. }
  743. }
  744. // TestRescheduleProvisioning validate that PV controller will remove
  745. // selectedNode annotation from a claim to reschedule volume provision
  746. // on provision failure.
  747. func TestRescheduleProvisioning(t *testing.T) {
  748. // Set feature gates
  749. controllerCh := make(chan struct{})
  750. context := initTestMaster(t, "reschedule-volume-provision", nil)
  751. clientset := context.clientSet
  752. ns := context.ns.Name
  753. defer func() {
  754. close(controllerCh)
  755. deleteTestObjects(clientset, ns, nil)
  756. context.clientSet.CoreV1().Nodes().DeleteCollection(nil, metav1.ListOptions{})
  757. context.closeFn()
  758. }()
  759. ctrl, informerFactory, err := initPVController(context, 0)
  760. if err != nil {
  761. t.Fatalf("Failed to create PV controller: %v", err)
  762. }
  763. // Prepare node and storage class.
  764. testNode := makeNode(0)
  765. if _, err := clientset.CoreV1().Nodes().Create(testNode); err != nil {
  766. t.Fatalf("Failed to create Node %q: %v", testNode.Name, err)
  767. }
  768. scName := "fail-provision"
  769. sc := makeDynamicProvisionerStorageClass(scName, &modeWait, nil)
  770. // Expect the storage class fail to provision.
  771. sc.Parameters[volumetest.ExpectProvisionFailureKey] = ""
  772. if _, err := clientset.StorageV1().StorageClasses().Create(sc); err != nil {
  773. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  774. }
  775. // Create a pvc with selected node annotation.
  776. pvcName := "pvc-fail-to-provision"
  777. pvc := makePVC(pvcName, ns, &scName, "")
  778. pvc.Annotations = map[string]string{"volume.kubernetes.io/selected-node": node1}
  779. pvc, err = clientset.CoreV1().PersistentVolumeClaims(ns).Create(pvc)
  780. if err != nil {
  781. t.Fatalf("Failed to create PersistentVolumeClaim %q: %v", pvc.Name, err)
  782. }
  783. // Validate selectedNode annotation exists on created claim.
  784. selectedNodeAnn, exist := pvc.Annotations["volume.kubernetes.io/selected-node"]
  785. if !exist || selectedNodeAnn != node1 {
  786. t.Fatalf("Created pvc is not annotated as expected")
  787. }
  788. // Start controller.
  789. go ctrl.Run(controllerCh)
  790. informerFactory.Start(controllerCh)
  791. informerFactory.WaitForCacheSync(controllerCh)
  792. // Validate that the annotation is removed by controller for provision reschedule.
  793. if err := waitForProvisionAnn(clientset, pvc, false); err != nil {
  794. t.Errorf("Expect to reschedule provision for PVC %v/%v, but still found selected-node annotation on it", ns, pvcName)
  795. }
  796. }
  797. func setupCluster(t *testing.T, nsName string, numberOfNodes int, resyncPeriod time.Duration, provisionDelaySeconds int) *testConfig {
  798. context := initTestSchedulerWithOptions(t, initTestMaster(t, nsName, nil), false, nil, nil,
  799. nil, []schedulerconfig.PluginConfig{}, false, resyncPeriod)
  800. clientset := context.clientSet
  801. ns := context.ns.Name
  802. ctrl, informerFactory, err := initPVController(context, provisionDelaySeconds)
  803. if err != nil {
  804. t.Fatalf("Failed to create PV controller: %v", err)
  805. }
  806. go ctrl.Run(context.stopCh)
  807. // Start informer factory after all controllers are configured and running.
  808. informerFactory.Start(context.stopCh)
  809. informerFactory.WaitForCacheSync(context.stopCh)
  810. // Create shared objects
  811. // Create nodes
  812. for i := 0; i < numberOfNodes; i++ {
  813. testNode := makeNode(i)
  814. if _, err := clientset.CoreV1().Nodes().Create(testNode); err != nil {
  815. t.Fatalf("Failed to create Node %q: %v", testNode.Name, err)
  816. }
  817. }
  818. // Create SCs
  819. for _, sc := range sharedClasses {
  820. if _, err := clientset.StorageV1().StorageClasses().Create(sc); err != nil {
  821. t.Fatalf("Failed to create StorageClass %q: %v", sc.Name, err)
  822. }
  823. }
  824. return &testConfig{
  825. client: clientset,
  826. ns: ns,
  827. stop: context.stopCh,
  828. teardown: func() {
  829. deleteTestObjects(clientset, ns, nil)
  830. cleanupTest(t, context)
  831. },
  832. }
  833. }
  834. func initPVController(context *testContext, provisionDelaySeconds int) (*persistentvolume.PersistentVolumeController, informers.SharedInformerFactory, error) {
  835. clientset := context.clientSet
  836. // Informers factory for controllers, we disable resync period for testing.
  837. informerFactory := informers.NewSharedInformerFactory(clientset, 0)
  838. // Start PV controller for volume binding.
  839. host := volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)
  840. plugin := &volumetest.FakeVolumePlugin{
  841. PluginName: provisionerPluginName,
  842. Host: host,
  843. Config: volume.VolumeConfig{},
  844. LastProvisionerOptions: volume.VolumeOptions{},
  845. ProvisionDelaySeconds: provisionDelaySeconds,
  846. NewAttacherCallCount: 0,
  847. NewDetacherCallCount: 0,
  848. Mounters: nil,
  849. Unmounters: nil,
  850. Attachers: nil,
  851. Detachers: nil,
  852. }
  853. plugins := []volume.VolumePlugin{plugin}
  854. controllerOptions := persistentvolumeoptions.NewPersistentVolumeControllerOptions()
  855. params := persistentvolume.ControllerParameters{
  856. KubeClient: clientset,
  857. SyncPeriod: controllerOptions.PVClaimBinderSyncPeriod,
  858. VolumePlugins: plugins,
  859. Cloud: nil,
  860. ClusterName: "volume-test-cluster",
  861. VolumeInformer: informerFactory.Core().V1().PersistentVolumes(),
  862. ClaimInformer: informerFactory.Core().V1().PersistentVolumeClaims(),
  863. ClassInformer: informerFactory.Storage().V1().StorageClasses(),
  864. PodInformer: informerFactory.Core().V1().Pods(),
  865. NodeInformer: informerFactory.Core().V1().Nodes(),
  866. EnableDynamicProvisioning: true,
  867. }
  868. ctrl, err := persistentvolume.NewController(params)
  869. if err != nil {
  870. return nil, nil, err
  871. }
  872. return ctrl, informerFactory, nil
  873. }
  874. func deleteTestObjects(client clientset.Interface, ns string, option *metav1.DeleteOptions) {
  875. client.CoreV1().Pods(ns).DeleteCollection(option, metav1.ListOptions{})
  876. client.CoreV1().PersistentVolumeClaims(ns).DeleteCollection(option, metav1.ListOptions{})
  877. client.CoreV1().PersistentVolumes().DeleteCollection(option, metav1.ListOptions{})
  878. client.StorageV1().StorageClasses().DeleteCollection(option, metav1.ListOptions{})
  879. }
  880. func makeStorageClass(name string, mode *storagev1.VolumeBindingMode) *storagev1.StorageClass {
  881. return &storagev1.StorageClass{
  882. ObjectMeta: metav1.ObjectMeta{
  883. Name: name,
  884. },
  885. Provisioner: "kubernetes.io/no-provisioner",
  886. VolumeBindingMode: mode,
  887. }
  888. }
  889. func makeDynamicProvisionerStorageClass(name string, mode *storagev1.VolumeBindingMode, allowedTopologies []v1.TopologySelectorTerm) *storagev1.StorageClass {
  890. return &storagev1.StorageClass{
  891. ObjectMeta: metav1.ObjectMeta{
  892. Name: name,
  893. },
  894. Provisioner: provisionerPluginName,
  895. VolumeBindingMode: mode,
  896. AllowedTopologies: allowedTopologies,
  897. Parameters: map[string]string{},
  898. }
  899. }
  900. func makePV(name, scName, pvcName, ns, node string) *v1.PersistentVolume {
  901. pv := &v1.PersistentVolume{
  902. ObjectMeta: metav1.ObjectMeta{
  903. Name: name,
  904. Annotations: map[string]string{},
  905. },
  906. Spec: v1.PersistentVolumeSpec{
  907. Capacity: v1.ResourceList{
  908. v1.ResourceName(v1.ResourceStorage): resource.MustParse("5Gi"),
  909. },
  910. AccessModes: []v1.PersistentVolumeAccessMode{
  911. v1.ReadWriteOnce,
  912. },
  913. StorageClassName: scName,
  914. PersistentVolumeSource: v1.PersistentVolumeSource{
  915. Local: &v1.LocalVolumeSource{
  916. Path: "/test-path",
  917. },
  918. },
  919. NodeAffinity: &v1.VolumeNodeAffinity{
  920. Required: &v1.NodeSelector{
  921. NodeSelectorTerms: []v1.NodeSelectorTerm{
  922. {
  923. MatchExpressions: []v1.NodeSelectorRequirement{
  924. {
  925. Key: nodeAffinityLabelKey,
  926. Operator: v1.NodeSelectorOpIn,
  927. Values: []string{node},
  928. },
  929. },
  930. },
  931. },
  932. },
  933. },
  934. },
  935. }
  936. if pvcName != "" {
  937. pv.Spec.ClaimRef = &v1.ObjectReference{Name: pvcName, Namespace: ns}
  938. }
  939. return pv
  940. }
  941. func makePVC(name, ns string, scName *string, volumeName string) *v1.PersistentVolumeClaim {
  942. return &v1.PersistentVolumeClaim{
  943. ObjectMeta: metav1.ObjectMeta{
  944. Name: name,
  945. Namespace: ns,
  946. },
  947. Spec: v1.PersistentVolumeClaimSpec{
  948. AccessModes: []v1.PersistentVolumeAccessMode{
  949. v1.ReadWriteOnce,
  950. },
  951. Resources: v1.ResourceRequirements{
  952. Requests: v1.ResourceList{
  953. v1.ResourceName(v1.ResourceStorage): resource.MustParse("5Gi"),
  954. },
  955. },
  956. StorageClassName: scName,
  957. VolumeName: volumeName,
  958. },
  959. }
  960. }
  961. func makePod(name, ns string, pvcs []string) *v1.Pod {
  962. volumes := []v1.Volume{}
  963. for i, pvc := range pvcs {
  964. volumes = append(volumes, v1.Volume{
  965. Name: fmt.Sprintf("vol%v", i),
  966. VolumeSource: v1.VolumeSource{
  967. PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
  968. ClaimName: pvc,
  969. },
  970. },
  971. })
  972. }
  973. return &v1.Pod{
  974. ObjectMeta: metav1.ObjectMeta{
  975. Name: name,
  976. Namespace: ns,
  977. Labels: map[string]string{
  978. "app": "volume-binding-test",
  979. },
  980. },
  981. Spec: v1.PodSpec{
  982. Containers: []v1.Container{
  983. {
  984. Name: "write-pod",
  985. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  986. Command: []string{"/bin/sh"},
  987. Args: []string{"-c", "while true; do sleep 1; done"},
  988. },
  989. },
  990. Volumes: volumes,
  991. },
  992. }
  993. }
  994. func makeNode(index int) *v1.Node {
  995. return &v1.Node{
  996. ObjectMeta: metav1.ObjectMeta{
  997. Name: fmt.Sprintf("node-%d", index+1),
  998. Labels: map[string]string{nodeAffinityLabelKey: fmt.Sprintf("node-%d", index+1)},
  999. },
  1000. Spec: v1.NodeSpec{Unschedulable: false},
  1001. Status: v1.NodeStatus{
  1002. Capacity: v1.ResourceList{
  1003. v1.ResourcePods: *resource.NewQuantity(podLimit, resource.DecimalSI),
  1004. },
  1005. Conditions: []v1.NodeCondition{
  1006. {
  1007. Type: v1.NodeReady,
  1008. Status: v1.ConditionTrue,
  1009. Reason: fmt.Sprintf("schedulable condition"),
  1010. LastHeartbeatTime: metav1.Time{Time: time.Now()},
  1011. },
  1012. },
  1013. },
  1014. }
  1015. }
  1016. func validatePVCPhase(t *testing.T, client clientset.Interface, pvcName string, ns string, phase v1.PersistentVolumeClaimPhase, isProvisioned bool) {
  1017. claim, err := client.CoreV1().PersistentVolumeClaims(ns).Get(pvcName, metav1.GetOptions{})
  1018. if err != nil {
  1019. t.Errorf("Failed to get PVC %v/%v: %v", ns, pvcName, err)
  1020. }
  1021. if claim.Status.Phase != phase {
  1022. t.Errorf("PVC %v/%v phase not %v, got %v", ns, pvcName, phase, claim.Status.Phase)
  1023. }
  1024. // Check whether the bound claim is provisioned/bound as expect.
  1025. if phase == v1.ClaimBound {
  1026. if err := validateProvisionAnn(claim, isProvisioned); err != nil {
  1027. t.Errorf("Provisoning annotaion on PVC %v/%v not bahaviors as expected: %v", ns, pvcName, err)
  1028. }
  1029. }
  1030. }
  1031. func validateProvisionAnn(claim *v1.PersistentVolumeClaim, volIsProvisioned bool) error {
  1032. selectedNode, provisionAnnoExist := claim.Annotations["volume.kubernetes.io/selected-node"]
  1033. if volIsProvisioned {
  1034. if !provisionAnnoExist {
  1035. return fmt.Errorf("PVC %v/%v expected to be provisioned, but no selected-node annotation found", claim.Namespace, claim.Name)
  1036. }
  1037. if selectedNode != node1 {
  1038. return fmt.Errorf("PVC %v/%v expected to be annotated as %v, but got %v", claim.Namespace, claim.Name, node1, selectedNode)
  1039. }
  1040. }
  1041. if !volIsProvisioned && provisionAnnoExist {
  1042. return fmt.Errorf("PVC %v/%v not expected to be provisioned, but found selected-node annotation", claim.Namespace, claim.Name)
  1043. }
  1044. return nil
  1045. }
  1046. func waitForProvisionAnn(client clientset.Interface, pvc *v1.PersistentVolumeClaim, annShouldExist bool) error {
  1047. return wait.Poll(time.Second, 30*time.Second, func() (bool, error) {
  1048. claim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{})
  1049. if err != nil {
  1050. return false, err
  1051. }
  1052. if err := validateProvisionAnn(claim, annShouldExist); err == nil {
  1053. return true, nil
  1054. }
  1055. return false, nil
  1056. })
  1057. }
  1058. func validatePVPhase(t *testing.T, client clientset.Interface, pvName string, phase v1.PersistentVolumePhase) {
  1059. pv, err := client.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{})
  1060. if err != nil {
  1061. t.Errorf("Failed to get PV %v: %v", pvName, err)
  1062. }
  1063. if pv.Status.Phase != phase {
  1064. t.Errorf("PV %v phase not %v, got %v", pvName, phase, pv.Status.Phase)
  1065. }
  1066. }
  1067. func waitForPVCBound(client clientset.Interface, pvc *v1.PersistentVolumeClaim) error {
  1068. return wait.Poll(time.Second, 30*time.Second, func() (bool, error) {
  1069. claim, err := client.CoreV1().PersistentVolumeClaims(pvc.Namespace).Get(pvc.Name, metav1.GetOptions{})
  1070. if err != nil {
  1071. return false, err
  1072. }
  1073. if claim.Status.Phase == v1.ClaimBound {
  1074. return true, nil
  1075. }
  1076. return false, nil
  1077. })
  1078. }
  1079. func markNodeAffinity(pod *v1.Pod, node string) {
  1080. affinity := &v1.Affinity{
  1081. NodeAffinity: &v1.NodeAffinity{
  1082. RequiredDuringSchedulingIgnoredDuringExecution: &v1.NodeSelector{
  1083. NodeSelectorTerms: []v1.NodeSelectorTerm{
  1084. {
  1085. MatchExpressions: []v1.NodeSelectorRequirement{
  1086. {
  1087. Key: nodeAffinityLabelKey,
  1088. Operator: v1.NodeSelectorOpIn,
  1089. Values: []string{node},
  1090. },
  1091. },
  1092. },
  1093. },
  1094. },
  1095. },
  1096. }
  1097. pod.Spec.Affinity = affinity
  1098. }
  1099. func markNodeSelector(pod *v1.Pod, node string) {
  1100. ns := map[string]string{
  1101. nodeAffinityLabelKey: node,
  1102. }
  1103. pod.Spec.NodeSelector = ns
  1104. }