persistent_volumes_test.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  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 volume
  14. import (
  15. "fmt"
  16. "math/rand"
  17. "net/http/httptest"
  18. "os"
  19. "strconv"
  20. "testing"
  21. "time"
  22. "k8s.io/api/core/v1"
  23. storage "k8s.io/api/storage/v1"
  24. "k8s.io/apimachinery/pkg/api/resource"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/watch"
  27. "k8s.io/client-go/informers"
  28. clientset "k8s.io/client-go/kubernetes"
  29. restclient "k8s.io/client-go/rest"
  30. ref "k8s.io/client-go/tools/reference"
  31. fakecloud "k8s.io/cloud-provider/fake"
  32. "k8s.io/kubernetes/pkg/api/legacyscheme"
  33. persistentvolumecontroller "k8s.io/kubernetes/pkg/controller/volume/persistentvolume"
  34. "k8s.io/kubernetes/pkg/volume"
  35. volumetest "k8s.io/kubernetes/pkg/volume/testing"
  36. "k8s.io/kubernetes/test/integration/framework"
  37. "k8s.io/apimachinery/pkg/runtime/schema"
  38. "k8s.io/klog"
  39. )
  40. // Several tests in this file are configurable by environment variables:
  41. // KUBE_INTEGRATION_PV_OBJECTS - nr. of PVs/PVCs to be created
  42. // (100 by default)
  43. // KUBE_INTEGRATION_PV_SYNC_PERIOD - volume controller sync period
  44. // (1s by default)
  45. // KUBE_INTEGRATION_PV_END_SLEEP - for how long should
  46. // TestPersistentVolumeMultiPVsPVCs sleep when it's finished (0s by
  47. // default). This is useful to test how long does it take for periodic sync
  48. // to process bound PVs/PVCs.
  49. //
  50. const defaultObjectCount = 100
  51. const defaultSyncPeriod = 1 * time.Second
  52. const provisionerPluginName = "kubernetes.io/mock-provisioner"
  53. func getObjectCount() int {
  54. objectCount := defaultObjectCount
  55. if s := os.Getenv("KUBE_INTEGRATION_PV_OBJECTS"); s != "" {
  56. var err error
  57. objectCount, err = strconv.Atoi(s)
  58. if err != nil {
  59. klog.Fatalf("cannot parse value of KUBE_INTEGRATION_PV_OBJECTS: %v", err)
  60. }
  61. }
  62. klog.V(2).Infof("using KUBE_INTEGRATION_PV_OBJECTS=%d", objectCount)
  63. return objectCount
  64. }
  65. func getSyncPeriod(syncPeriod time.Duration) time.Duration {
  66. period := syncPeriod
  67. if s := os.Getenv("KUBE_INTEGRATION_PV_SYNC_PERIOD"); s != "" {
  68. var err error
  69. period, err = time.ParseDuration(s)
  70. if err != nil {
  71. klog.Fatalf("cannot parse value of KUBE_INTEGRATION_PV_SYNC_PERIOD: %v", err)
  72. }
  73. }
  74. klog.V(2).Infof("using KUBE_INTEGRATION_PV_SYNC_PERIOD=%v", period)
  75. return period
  76. }
  77. func testSleep() {
  78. var period time.Duration
  79. if s := os.Getenv("KUBE_INTEGRATION_PV_END_SLEEP"); s != "" {
  80. var err error
  81. period, err = time.ParseDuration(s)
  82. if err != nil {
  83. klog.Fatalf("cannot parse value of KUBE_INTEGRATION_PV_END_SLEEP: %v", err)
  84. }
  85. }
  86. klog.V(2).Infof("using KUBE_INTEGRATION_PV_END_SLEEP=%v", period)
  87. if period != 0 {
  88. time.Sleep(period)
  89. klog.V(2).Infof("sleep finished")
  90. }
  91. }
  92. func TestPersistentVolumeRecycler(t *testing.T) {
  93. klog.V(2).Infof("TestPersistentVolumeRecycler started")
  94. _, s, closeFn := framework.RunAMaster(nil)
  95. defer closeFn()
  96. ns := framework.CreateTestingNamespace("pv-recycler", s, t)
  97. defer framework.DeleteTestingNamespace(ns, s, t)
  98. testClient, ctrl, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  99. defer watchPV.Stop()
  100. defer watchPVC.Stop()
  101. // NOTE: This test cannot run in parallel, because it is creating and deleting
  102. // non-namespaced objects (PersistenceVolumes).
  103. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  104. stopCh := make(chan struct{})
  105. informers.Start(stopCh)
  106. go ctrl.Run(stopCh)
  107. defer close(stopCh)
  108. // This PV will be claimed, released, and recycled.
  109. pv := createPV("fake-pv-recycler", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRecycle)
  110. pvc := createPVC("fake-pvc-recycler", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  111. _, err := testClient.CoreV1().PersistentVolumes().Create(pv)
  112. if err != nil {
  113. t.Errorf("Failed to create PersistentVolume: %v", err)
  114. }
  115. klog.V(2).Infof("TestPersistentVolumeRecycler pvc created")
  116. _, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  117. if err != nil {
  118. t.Errorf("Failed to create PersistentVolumeClaim: %v", err)
  119. }
  120. klog.V(2).Infof("TestPersistentVolumeRecycler pvc created")
  121. // wait until the controller pairs the volume and claim
  122. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound)
  123. klog.V(2).Infof("TestPersistentVolumeRecycler pv bound")
  124. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  125. klog.V(2).Infof("TestPersistentVolumeRecycler pvc bound")
  126. // deleting a claim releases the volume, after which it can be recycled
  127. if err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Delete(pvc.Name, nil); err != nil {
  128. t.Errorf("error deleting claim %s", pvc.Name)
  129. }
  130. klog.V(2).Infof("TestPersistentVolumeRecycler pvc deleted")
  131. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeReleased)
  132. klog.V(2).Infof("TestPersistentVolumeRecycler pv released")
  133. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeAvailable)
  134. klog.V(2).Infof("TestPersistentVolumeRecycler pv available")
  135. }
  136. func TestPersistentVolumeDeleter(t *testing.T) {
  137. klog.V(2).Infof("TestPersistentVolumeDeleter started")
  138. _, s, closeFn := framework.RunAMaster(nil)
  139. defer closeFn()
  140. ns := framework.CreateTestingNamespace("pv-deleter", s, t)
  141. defer framework.DeleteTestingNamespace(ns, s, t)
  142. testClient, ctrl, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  143. defer watchPV.Stop()
  144. defer watchPVC.Stop()
  145. // NOTE: This test cannot run in parallel, because it is creating and deleting
  146. // non-namespaced objects (PersistenceVolumes).
  147. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  148. stopCh := make(chan struct{})
  149. informers.Start(stopCh)
  150. go ctrl.Run(stopCh)
  151. defer close(stopCh)
  152. // This PV will be claimed, released, and deleted.
  153. pv := createPV("fake-pv-deleter", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimDelete)
  154. pvc := createPVC("fake-pvc-deleter", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  155. _, err := testClient.CoreV1().PersistentVolumes().Create(pv)
  156. if err != nil {
  157. t.Errorf("Failed to create PersistentVolume: %v", err)
  158. }
  159. klog.V(2).Infof("TestPersistentVolumeDeleter pv created")
  160. _, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  161. if err != nil {
  162. t.Errorf("Failed to create PersistentVolumeClaim: %v", err)
  163. }
  164. klog.V(2).Infof("TestPersistentVolumeDeleter pvc created")
  165. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound)
  166. klog.V(2).Infof("TestPersistentVolumeDeleter pv bound")
  167. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  168. klog.V(2).Infof("TestPersistentVolumeDeleter pvc bound")
  169. // deleting a claim releases the volume, after which it can be recycled
  170. if err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Delete(pvc.Name, nil); err != nil {
  171. t.Errorf("error deleting claim %s", pvc.Name)
  172. }
  173. klog.V(2).Infof("TestPersistentVolumeDeleter pvc deleted")
  174. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeReleased)
  175. klog.V(2).Infof("TestPersistentVolumeDeleter pv released")
  176. for {
  177. event := <-watchPV.ResultChan()
  178. if event.Type == watch.Deleted {
  179. break
  180. }
  181. }
  182. klog.V(2).Infof("TestPersistentVolumeDeleter pv deleted")
  183. }
  184. func TestPersistentVolumeBindRace(t *testing.T) {
  185. // Test a race binding many claims to a PV that is pre-bound to a specific
  186. // PVC. Only this specific PVC should get bound.
  187. klog.V(2).Infof("TestPersistentVolumeBindRace started")
  188. _, s, closeFn := framework.RunAMaster(nil)
  189. defer closeFn()
  190. ns := framework.CreateTestingNamespace("pv-bind-race", s, t)
  191. defer framework.DeleteTestingNamespace(ns, s, t)
  192. testClient, ctrl, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  193. defer watchPV.Stop()
  194. defer watchPVC.Stop()
  195. // NOTE: This test cannot run in parallel, because it is creating and deleting
  196. // non-namespaced objects (PersistenceVolumes).
  197. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  198. stopCh := make(chan struct{})
  199. informers.Start(stopCh)
  200. go ctrl.Run(stopCh)
  201. defer close(stopCh)
  202. pv := createPV("fake-pv-race", "/tmp/foo", "10G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain)
  203. pvc := createPVC("fake-pvc-race", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  204. counter := 0
  205. maxClaims := 100
  206. claims := []*v1.PersistentVolumeClaim{}
  207. for counter <= maxClaims {
  208. counter++
  209. newPvc := pvc.DeepCopy()
  210. newPvc.ObjectMeta = metav1.ObjectMeta{Name: fmt.Sprintf("fake-pvc-race-%d", counter)}
  211. claim, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(newPvc)
  212. if err != nil {
  213. t.Fatalf("Error creating newPvc: %v", err)
  214. }
  215. claims = append(claims, claim)
  216. }
  217. klog.V(2).Infof("TestPersistentVolumeBindRace claims created")
  218. // putting a bind manually on a pv should only match the claim it is bound to
  219. claim := claims[rand.Intn(maxClaims-1)]
  220. claimRef, err := ref.GetReference(legacyscheme.Scheme, claim)
  221. if err != nil {
  222. t.Fatalf("Unexpected error getting claimRef: %v", err)
  223. }
  224. pv.Spec.ClaimRef = claimRef
  225. pv.Spec.ClaimRef.UID = ""
  226. pv, err = testClient.CoreV1().PersistentVolumes().Create(pv)
  227. if err != nil {
  228. t.Fatalf("Unexpected error creating pv: %v", err)
  229. }
  230. klog.V(2).Infof("TestPersistentVolumeBindRace pv created, pre-bound to %s", claim.Name)
  231. waitForPersistentVolumePhase(testClient, pv.Name, watchPV, v1.VolumeBound)
  232. klog.V(2).Infof("TestPersistentVolumeBindRace pv bound")
  233. waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound)
  234. klog.V(2).Infof("TestPersistentVolumeBindRace pvc bound")
  235. pv, err = testClient.CoreV1().PersistentVolumes().Get(pv.Name, metav1.GetOptions{})
  236. if err != nil {
  237. t.Fatalf("Unexpected error getting pv: %v", err)
  238. }
  239. if pv.Spec.ClaimRef == nil {
  240. t.Fatalf("Unexpected nil claimRef")
  241. }
  242. if pv.Spec.ClaimRef.Namespace != claimRef.Namespace || pv.Spec.ClaimRef.Name != claimRef.Name {
  243. t.Fatalf("Bind mismatch! Expected %s/%s but got %s/%s", claimRef.Namespace, claimRef.Name, pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name)
  244. }
  245. }
  246. // TestPersistentVolumeClaimLabelSelector test binding using label selectors
  247. func TestPersistentVolumeClaimLabelSelector(t *testing.T) {
  248. _, s, closeFn := framework.RunAMaster(nil)
  249. defer closeFn()
  250. ns := framework.CreateTestingNamespace("pvc-label-selector", s, t)
  251. defer framework.DeleteTestingNamespace(ns, s, t)
  252. testClient, controller, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  253. defer watchPV.Stop()
  254. defer watchPVC.Stop()
  255. // NOTE: This test cannot run in parallel, because it is creating and deleting
  256. // non-namespaced objects (PersistenceVolumes).
  257. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  258. stopCh := make(chan struct{})
  259. informers.Start(stopCh)
  260. go controller.Run(stopCh)
  261. defer close(stopCh)
  262. var (
  263. err error
  264. modes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}
  265. reclaim = v1.PersistentVolumeReclaimRetain
  266. pvTrue = createPV("pv-true", "/tmp/foo-label", "1G", modes, reclaim)
  267. pvFalse = createPV("pv-false", "/tmp/foo-label", "1G", modes, reclaim)
  268. pvc = createPVC("pvc-ls-1", ns.Name, "1G", modes, "")
  269. )
  270. pvTrue.ObjectMeta.SetLabels(map[string]string{"foo": "true"})
  271. pvFalse.ObjectMeta.SetLabels(map[string]string{"foo": "false"})
  272. _, err = testClient.CoreV1().PersistentVolumes().Create(pvTrue)
  273. if err != nil {
  274. t.Fatalf("Failed to create PersistentVolume: %v", err)
  275. }
  276. _, err = testClient.CoreV1().PersistentVolumes().Create(pvFalse)
  277. if err != nil {
  278. t.Fatalf("Failed to create PersistentVolume: %v", err)
  279. }
  280. t.Log("volumes created")
  281. pvc.Spec.Selector = &metav1.LabelSelector{
  282. MatchLabels: map[string]string{
  283. "foo": "true",
  284. },
  285. }
  286. _, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  287. if err != nil {
  288. t.Fatalf("Failed to create PersistentVolumeClaim: %v", err)
  289. }
  290. t.Log("claim created")
  291. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound)
  292. t.Log("volume bound")
  293. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  294. t.Log("claim bound")
  295. pv, err := testClient.CoreV1().PersistentVolumes().Get("pv-false", metav1.GetOptions{})
  296. if err != nil {
  297. t.Fatalf("Unexpected error getting pv: %v", err)
  298. }
  299. if pv.Spec.ClaimRef != nil {
  300. t.Fatalf("False PV shouldn't be bound")
  301. }
  302. pv, err = testClient.CoreV1().PersistentVolumes().Get("pv-true", metav1.GetOptions{})
  303. if err != nil {
  304. t.Fatalf("Unexpected error getting pv: %v", err)
  305. }
  306. if pv.Spec.ClaimRef == nil {
  307. t.Fatalf("True PV should be bound")
  308. }
  309. if pv.Spec.ClaimRef.Namespace != pvc.Namespace || pv.Spec.ClaimRef.Name != pvc.Name {
  310. t.Fatalf("Bind mismatch! Expected %s/%s but got %s/%s", pvc.Namespace, pvc.Name, pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name)
  311. }
  312. }
  313. // TestPersistentVolumeClaimLabelSelectorMatchExpressions test binding using
  314. // MatchExpressions label selectors
  315. func TestPersistentVolumeClaimLabelSelectorMatchExpressions(t *testing.T) {
  316. _, s, closeFn := framework.RunAMaster(nil)
  317. defer closeFn()
  318. ns := framework.CreateTestingNamespace("pvc-match-expressions", s, t)
  319. defer framework.DeleteTestingNamespace(ns, s, t)
  320. testClient, controller, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  321. defer watchPV.Stop()
  322. defer watchPVC.Stop()
  323. // NOTE: This test cannot run in parallel, because it is creating and deleting
  324. // non-namespaced objects (PersistenceVolumes).
  325. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  326. stopCh := make(chan struct{})
  327. informers.Start(stopCh)
  328. go controller.Run(stopCh)
  329. defer close(stopCh)
  330. var (
  331. err error
  332. modes = []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}
  333. reclaim = v1.PersistentVolumeReclaimRetain
  334. pvTrue = createPV("pv-true", "/tmp/foo-label", "1G", modes, reclaim)
  335. pvFalse = createPV("pv-false", "/tmp/foo-label", "1G", modes, reclaim)
  336. pvc = createPVC("pvc-ls-1", ns.Name, "1G", modes, "")
  337. )
  338. pvTrue.ObjectMeta.SetLabels(map[string]string{"foo": "valA", "bar": ""})
  339. pvFalse.ObjectMeta.SetLabels(map[string]string{"foo": "valB", "baz": ""})
  340. _, err = testClient.CoreV1().PersistentVolumes().Create(pvTrue)
  341. if err != nil {
  342. t.Fatalf("Failed to create PersistentVolume: %v", err)
  343. }
  344. _, err = testClient.CoreV1().PersistentVolumes().Create(pvFalse)
  345. if err != nil {
  346. t.Fatalf("Failed to create PersistentVolume: %v", err)
  347. }
  348. t.Log("volumes created")
  349. pvc.Spec.Selector = &metav1.LabelSelector{
  350. MatchExpressions: []metav1.LabelSelectorRequirement{
  351. {
  352. Key: "foo",
  353. Operator: metav1.LabelSelectorOpIn,
  354. Values: []string{"valA"},
  355. },
  356. {
  357. Key: "foo",
  358. Operator: metav1.LabelSelectorOpNotIn,
  359. Values: []string{"valB"},
  360. },
  361. {
  362. Key: "bar",
  363. Operator: metav1.LabelSelectorOpExists,
  364. Values: []string{},
  365. },
  366. {
  367. Key: "baz",
  368. Operator: metav1.LabelSelectorOpDoesNotExist,
  369. Values: []string{},
  370. },
  371. },
  372. }
  373. _, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  374. if err != nil {
  375. t.Fatalf("Failed to create PersistentVolumeClaim: %v", err)
  376. }
  377. t.Log("claim created")
  378. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound)
  379. t.Log("volume bound")
  380. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  381. t.Log("claim bound")
  382. pv, err := testClient.CoreV1().PersistentVolumes().Get("pv-false", metav1.GetOptions{})
  383. if err != nil {
  384. t.Fatalf("Unexpected error getting pv: %v", err)
  385. }
  386. if pv.Spec.ClaimRef != nil {
  387. t.Fatalf("False PV shouldn't be bound")
  388. }
  389. pv, err = testClient.CoreV1().PersistentVolumes().Get("pv-true", metav1.GetOptions{})
  390. if err != nil {
  391. t.Fatalf("Unexpected error getting pv: %v", err)
  392. }
  393. if pv.Spec.ClaimRef == nil {
  394. t.Fatalf("True PV should be bound")
  395. }
  396. if pv.Spec.ClaimRef.Namespace != pvc.Namespace || pv.Spec.ClaimRef.Name != pvc.Name {
  397. t.Fatalf("Bind mismatch! Expected %s/%s but got %s/%s", pvc.Namespace, pvc.Name, pv.Spec.ClaimRef.Namespace, pv.Spec.ClaimRef.Name)
  398. }
  399. }
  400. // TestPersistentVolumeMultiPVs tests binding of one PVC to 100 PVs with
  401. // different size.
  402. func TestPersistentVolumeMultiPVs(t *testing.T) {
  403. _, s, closeFn := framework.RunAMaster(nil)
  404. defer closeFn()
  405. ns := framework.CreateTestingNamespace("multi-pvs", s, t)
  406. defer framework.DeleteTestingNamespace(ns, s, t)
  407. testClient, controller, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  408. defer watchPV.Stop()
  409. defer watchPVC.Stop()
  410. // NOTE: This test cannot run in parallel, because it is creating and deleting
  411. // non-namespaced objects (PersistenceVolumes).
  412. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  413. stopCh := make(chan struct{})
  414. informers.Start(stopCh)
  415. go controller.Run(stopCh)
  416. defer close(stopCh)
  417. maxPVs := getObjectCount()
  418. pvs := make([]*v1.PersistentVolume, maxPVs)
  419. for i := 0; i < maxPVs; i++ {
  420. // This PV will be claimed, released, and deleted
  421. pvs[i] = createPV("pv-"+strconv.Itoa(i), "/tmp/foo"+strconv.Itoa(i), strconv.Itoa(i+1)+"G",
  422. []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain)
  423. }
  424. pvc := createPVC("pvc-2", ns.Name, strconv.Itoa(maxPVs/2)+"G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  425. for i := 0; i < maxPVs; i++ {
  426. _, err := testClient.CoreV1().PersistentVolumes().Create(pvs[i])
  427. if err != nil {
  428. t.Errorf("Failed to create PersistentVolume %d: %v", i, err)
  429. }
  430. waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, v1.VolumeAvailable)
  431. }
  432. t.Log("volumes created")
  433. _, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  434. if err != nil {
  435. t.Errorf("Failed to create PersistentVolumeClaim: %v", err)
  436. }
  437. t.Log("claim created")
  438. // wait until the binder pairs the claim with a volume
  439. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound)
  440. t.Log("volume bound")
  441. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  442. t.Log("claim bound")
  443. // only one PV is bound
  444. bound := 0
  445. for i := 0; i < maxPVs; i++ {
  446. pv, err := testClient.CoreV1().PersistentVolumes().Get(pvs[i].Name, metav1.GetOptions{})
  447. if err != nil {
  448. t.Fatalf("Unexpected error getting pv: %v", err)
  449. }
  450. if pv.Spec.ClaimRef == nil {
  451. continue
  452. }
  453. // found a bounded PV
  454. p := pv.Spec.Capacity[v1.ResourceStorage]
  455. pvCap := p.Value()
  456. expectedCap := resource.MustParse(strconv.Itoa(maxPVs/2) + "G")
  457. expectedCapVal := expectedCap.Value()
  458. if pv.Spec.ClaimRef.Name != pvc.Name || pvCap != expectedCapVal {
  459. t.Fatalf("Bind mismatch! Expected %s capacity %d but got %s capacity %d", pvc.Name, expectedCapVal, pv.Spec.ClaimRef.Name, pvCap)
  460. }
  461. t.Logf("claim bounded to %s capacity %v", pv.Name, pv.Spec.Capacity[v1.ResourceStorage])
  462. bound++
  463. }
  464. t.Log("volumes checked")
  465. if bound != 1 {
  466. t.Fatalf("Only 1 PV should be bound but got %d", bound)
  467. }
  468. // deleting a claim releases the volume
  469. if err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Delete(pvc.Name, nil); err != nil {
  470. t.Errorf("error deleting claim %s", pvc.Name)
  471. }
  472. t.Log("claim deleted")
  473. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeReleased)
  474. t.Log("volumes released")
  475. }
  476. // TestPersistentVolumeMultiPVsPVCs tests binding of 100 PVC to 100 PVs.
  477. // This test is configurable by KUBE_INTEGRATION_PV_* variables.
  478. func TestPersistentVolumeMultiPVsPVCs(t *testing.T) {
  479. _, s, closeFn := framework.RunAMaster(nil)
  480. defer closeFn()
  481. ns := framework.CreateTestingNamespace("multi-pvs-pvcs", s, t)
  482. defer framework.DeleteTestingNamespace(ns, s, t)
  483. testClient, binder, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  484. defer watchPV.Stop()
  485. defer watchPVC.Stop()
  486. // NOTE: This test cannot run in parallel, because it is creating and deleting
  487. // non-namespaced objects (PersistenceVolumes).
  488. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  489. controllerStopCh := make(chan struct{})
  490. informers.Start(controllerStopCh)
  491. go binder.Run(controllerStopCh)
  492. defer close(controllerStopCh)
  493. objCount := getObjectCount()
  494. pvs := make([]*v1.PersistentVolume, objCount)
  495. pvcs := make([]*v1.PersistentVolumeClaim, objCount)
  496. for i := 0; i < objCount; i++ {
  497. // This PV will be claimed, released, and deleted
  498. pvs[i] = createPV("pv-"+strconv.Itoa(i), "/tmp/foo"+strconv.Itoa(i), "1G",
  499. []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain)
  500. pvcs[i] = createPVC("pvc-"+strconv.Itoa(i), ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  501. }
  502. // Create PVs first
  503. klog.V(2).Infof("TestPersistentVolumeMultiPVsPVCs: start")
  504. // Create the volumes in a separate goroutine to pop events from
  505. // watchPV early - it seems it has limited capacity and it gets stuck
  506. // with >3000 volumes.
  507. go func() {
  508. for i := 0; i < objCount; i++ {
  509. _, _ = testClient.CoreV1().PersistentVolumes().Create(pvs[i])
  510. }
  511. }()
  512. // Wait for them to get Available
  513. for i := 0; i < objCount; i++ {
  514. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeAvailable)
  515. klog.V(1).Infof("%d volumes available", i+1)
  516. }
  517. klog.V(2).Infof("TestPersistentVolumeMultiPVsPVCs: volumes are Available")
  518. // Start a separate goroutine that randomly modifies PVs and PVCs while the
  519. // binder is working. We test that the binder can bind volumes despite
  520. // users modifying objects underneath.
  521. stopCh := make(chan struct{}, 0)
  522. go func() {
  523. for {
  524. // Roll a dice and decide a PV or PVC to modify
  525. if rand.Intn(2) == 0 {
  526. // Modify PV
  527. i := rand.Intn(objCount)
  528. name := "pv-" + strconv.Itoa(i)
  529. pv, err := testClient.CoreV1().PersistentVolumes().Get(name, metav1.GetOptions{})
  530. if err != nil {
  531. // Silently ignore error, the PV may have be already deleted
  532. // or not exists yet.
  533. klog.V(4).Infof("Failed to read PV %s: %v", name, err)
  534. continue
  535. }
  536. if pv.Annotations == nil {
  537. pv.Annotations = map[string]string{"TestAnnotation": fmt.Sprint(rand.Int())}
  538. } else {
  539. pv.Annotations["TestAnnotation"] = fmt.Sprint(rand.Int())
  540. }
  541. _, err = testClient.CoreV1().PersistentVolumes().Update(pv)
  542. if err != nil {
  543. // Silently ignore error, the PV may have been updated by
  544. // the controller.
  545. klog.V(4).Infof("Failed to update PV %s: %v", pv.Name, err)
  546. continue
  547. }
  548. klog.V(4).Infof("Updated PV %s", pv.Name)
  549. } else {
  550. // Modify PVC
  551. i := rand.Intn(objCount)
  552. name := "pvc-" + strconv.Itoa(i)
  553. pvc, err := testClient.CoreV1().PersistentVolumeClaims(metav1.NamespaceDefault).Get(name, metav1.GetOptions{})
  554. if err != nil {
  555. // Silently ignore error, the PVC may have be already
  556. // deleted or not exists yet.
  557. klog.V(4).Infof("Failed to read PVC %s: %v", name, err)
  558. continue
  559. }
  560. if pvc.Annotations == nil {
  561. pvc.Annotations = map[string]string{"TestAnnotation": fmt.Sprint(rand.Int())}
  562. } else {
  563. pvc.Annotations["TestAnnotation"] = fmt.Sprint(rand.Int())
  564. }
  565. _, err = testClient.CoreV1().PersistentVolumeClaims(metav1.NamespaceDefault).Update(pvc)
  566. if err != nil {
  567. // Silently ignore error, the PVC may have been updated by
  568. // the controller.
  569. klog.V(4).Infof("Failed to update PVC %s: %v", pvc.Name, err)
  570. continue
  571. }
  572. klog.V(4).Infof("Updated PVC %s", pvc.Name)
  573. }
  574. select {
  575. case <-stopCh:
  576. break
  577. default:
  578. continue
  579. }
  580. }
  581. }()
  582. // Create the claims, again in a separate goroutine.
  583. go func() {
  584. for i := 0; i < objCount; i++ {
  585. _, _ = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvcs[i])
  586. }
  587. }()
  588. // wait until the binder pairs all claims
  589. for i := 0; i < objCount; i++ {
  590. waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound)
  591. klog.V(1).Infof("%d claims bound", i+1)
  592. }
  593. // wait until the binder pairs all volumes
  594. for i := 0; i < objCount; i++ {
  595. waitForPersistentVolumePhase(testClient, pvs[i].Name, watchPV, v1.VolumeBound)
  596. klog.V(1).Infof("%d claims bound", i+1)
  597. }
  598. klog.V(2).Infof("TestPersistentVolumeMultiPVsPVCs: claims are bound")
  599. stopCh <- struct{}{}
  600. // check that everything is bound to something
  601. for i := 0; i < objCount; i++ {
  602. pv, err := testClient.CoreV1().PersistentVolumes().Get(pvs[i].Name, metav1.GetOptions{})
  603. if err != nil {
  604. t.Fatalf("Unexpected error getting pv: %v", err)
  605. }
  606. if pv.Spec.ClaimRef == nil {
  607. t.Fatalf("PV %q is not bound", pv.Name)
  608. }
  609. klog.V(2).Infof("PV %q is bound to PVC %q", pv.Name, pv.Spec.ClaimRef.Name)
  610. pvc, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Get(pvcs[i].Name, metav1.GetOptions{})
  611. if err != nil {
  612. t.Fatalf("Unexpected error getting pvc: %v", err)
  613. }
  614. if pvc.Spec.VolumeName == "" {
  615. t.Fatalf("PVC %q is not bound", pvc.Name)
  616. }
  617. klog.V(2).Infof("PVC %q is bound to PV %q", pvc.Name, pvc.Spec.VolumeName)
  618. }
  619. testSleep()
  620. }
  621. // TestPersistentVolumeControllerStartup tests startup of the controller.
  622. // The controller should not unbind any volumes when it starts.
  623. func TestPersistentVolumeControllerStartup(t *testing.T) {
  624. _, s, closeFn := framework.RunAMaster(nil)
  625. defer closeFn()
  626. ns := framework.CreateTestingNamespace("controller-startup", s, t)
  627. defer framework.DeleteTestingNamespace(ns, s, t)
  628. objCount := getObjectCount()
  629. const shortSyncPeriod = 2 * time.Second
  630. syncPeriod := getSyncPeriod(shortSyncPeriod)
  631. testClient, binder, informers, watchPV, watchPVC := createClients(ns, t, s, shortSyncPeriod)
  632. defer watchPV.Stop()
  633. defer watchPVC.Stop()
  634. // Create *bound* volumes and PVCs
  635. pvs := make([]*v1.PersistentVolume, objCount)
  636. pvcs := make([]*v1.PersistentVolumeClaim, objCount)
  637. for i := 0; i < objCount; i++ {
  638. pvName := "pv-startup-" + strconv.Itoa(i)
  639. pvcName := "pvc-startup-" + strconv.Itoa(i)
  640. pvc := createPVC(pvcName, ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "")
  641. pvc.Annotations = map[string]string{"annBindCompleted": ""}
  642. pvc.Spec.VolumeName = pvName
  643. newPVC, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  644. if err != nil {
  645. t.Fatalf("Cannot create claim %q: %v", pvc.Name, err)
  646. }
  647. // Save Bound status as a separate transaction
  648. newPVC.Status.Phase = v1.ClaimBound
  649. newPVC, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).UpdateStatus(newPVC)
  650. if err != nil {
  651. t.Fatalf("Cannot update claim status %q: %v", pvc.Name, err)
  652. }
  653. pvcs[i] = newPVC
  654. // Drain watchPVC with all events generated by the PVC until it's bound
  655. // We don't want to catch "PVC created with Status.Phase == Pending"
  656. // later in this test.
  657. waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound)
  658. pv := createPV(pvName, "/tmp/foo"+strconv.Itoa(i), "1G",
  659. []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain)
  660. claimRef, err := ref.GetReference(legacyscheme.Scheme, newPVC)
  661. if err != nil {
  662. klog.V(3).Infof("unexpected error getting claim reference: %v", err)
  663. return
  664. }
  665. pv.Spec.ClaimRef = claimRef
  666. newPV, err := testClient.CoreV1().PersistentVolumes().Create(pv)
  667. if err != nil {
  668. t.Fatalf("Cannot create volume %q: %v", pv.Name, err)
  669. }
  670. // Save Bound status as a separate transaction
  671. newPV.Status.Phase = v1.VolumeBound
  672. newPV, err = testClient.CoreV1().PersistentVolumes().UpdateStatus(newPV)
  673. if err != nil {
  674. t.Fatalf("Cannot update volume status %q: %v", pv.Name, err)
  675. }
  676. pvs[i] = newPV
  677. // Drain watchPV with all events generated by the PV until it's bound
  678. // We don't want to catch "PV created with Status.Phase == Pending"
  679. // later in this test.
  680. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound)
  681. }
  682. // Start the controller when all PVs and PVCs are already saved in etcd
  683. stopCh := make(chan struct{})
  684. informers.Start(stopCh)
  685. go binder.Run(stopCh)
  686. defer close(stopCh)
  687. // wait for at least two sync periods for changes. No volume should be
  688. // Released and no claim should be Lost during this time.
  689. timer := time.NewTimer(2 * syncPeriod)
  690. defer timer.Stop()
  691. finished := false
  692. for !finished {
  693. select {
  694. case volumeEvent := <-watchPV.ResultChan():
  695. volume, ok := volumeEvent.Object.(*v1.PersistentVolume)
  696. if !ok {
  697. continue
  698. }
  699. if volume.Status.Phase != v1.VolumeBound {
  700. t.Errorf("volume %s unexpectedly changed state to %s", volume.Name, volume.Status.Phase)
  701. }
  702. case claimEvent := <-watchPVC.ResultChan():
  703. claim, ok := claimEvent.Object.(*v1.PersistentVolumeClaim)
  704. if !ok {
  705. continue
  706. }
  707. if claim.Status.Phase != v1.ClaimBound {
  708. t.Errorf("claim %s unexpectedly changed state to %s", claim.Name, claim.Status.Phase)
  709. }
  710. case <-timer.C:
  711. // Wait finished
  712. klog.V(2).Infof("Wait finished")
  713. finished = true
  714. }
  715. }
  716. // check that everything is bound to something
  717. for i := 0; i < objCount; i++ {
  718. pv, err := testClient.CoreV1().PersistentVolumes().Get(pvs[i].Name, metav1.GetOptions{})
  719. if err != nil {
  720. t.Fatalf("Unexpected error getting pv: %v", err)
  721. }
  722. if pv.Spec.ClaimRef == nil {
  723. t.Fatalf("PV %q is not bound", pv.Name)
  724. }
  725. klog.V(2).Infof("PV %q is bound to PVC %q", pv.Name, pv.Spec.ClaimRef.Name)
  726. pvc, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Get(pvcs[i].Name, metav1.GetOptions{})
  727. if err != nil {
  728. t.Fatalf("Unexpected error getting pvc: %v", err)
  729. }
  730. if pvc.Spec.VolumeName == "" {
  731. t.Fatalf("PVC %q is not bound", pvc.Name)
  732. }
  733. klog.V(2).Infof("PVC %q is bound to PV %q", pvc.Name, pvc.Spec.VolumeName)
  734. }
  735. }
  736. // TestPersistentVolumeProvisionMultiPVCs tests provisioning of many PVCs.
  737. // This test is configurable by KUBE_INTEGRATION_PV_* variables.
  738. func TestPersistentVolumeProvisionMultiPVCs(t *testing.T) {
  739. _, s, closeFn := framework.RunAMaster(nil)
  740. defer closeFn()
  741. ns := framework.CreateTestingNamespace("provision-multi-pvs", s, t)
  742. defer framework.DeleteTestingNamespace(ns, s, t)
  743. testClient, binder, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  744. defer watchPV.Stop()
  745. defer watchPVC.Stop()
  746. // NOTE: This test cannot run in parallel, because it is creating and deleting
  747. // non-namespaced objects (PersistenceVolumes and StorageClasses).
  748. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  749. defer testClient.StorageV1().StorageClasses().DeleteCollection(nil, metav1.ListOptions{})
  750. storageClass := storage.StorageClass{
  751. TypeMeta: metav1.TypeMeta{
  752. Kind: "StorageClass",
  753. },
  754. ObjectMeta: metav1.ObjectMeta{
  755. Name: "gold",
  756. },
  757. Provisioner: provisionerPluginName,
  758. }
  759. testClient.StorageV1().StorageClasses().Create(&storageClass)
  760. stopCh := make(chan struct{})
  761. informers.Start(stopCh)
  762. go binder.Run(stopCh)
  763. defer close(stopCh)
  764. objCount := getObjectCount()
  765. pvcs := make([]*v1.PersistentVolumeClaim, objCount)
  766. for i := 0; i < objCount; i++ {
  767. pvc := createPVC("pvc-provision-"+strconv.Itoa(i), ns.Name, "1G", []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, "gold")
  768. pvcs[i] = pvc
  769. }
  770. klog.V(2).Infof("TestPersistentVolumeProvisionMultiPVCs: start")
  771. // Create the claims in a separate goroutine to pop events from watchPVC
  772. // early. It gets stuck with >3000 claims.
  773. go func() {
  774. for i := 0; i < objCount; i++ {
  775. _, _ = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvcs[i])
  776. }
  777. }()
  778. // Wait until the controller provisions and binds all of them
  779. for i := 0; i < objCount; i++ {
  780. waitForAnyPersistentVolumeClaimPhase(watchPVC, v1.ClaimBound)
  781. klog.V(1).Infof("%d claims bound", i+1)
  782. }
  783. klog.V(2).Infof("TestPersistentVolumeProvisionMultiPVCs: claims are bound")
  784. // check that we have enough bound PVs
  785. pvList, err := testClient.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  786. if err != nil {
  787. t.Fatalf("Failed to list volumes: %s", err)
  788. }
  789. if len(pvList.Items) != objCount {
  790. t.Fatalf("Expected to get %d volumes, got %d", objCount, len(pvList.Items))
  791. }
  792. for i := 0; i < objCount; i++ {
  793. pv := &pvList.Items[i]
  794. if pv.Status.Phase != v1.VolumeBound {
  795. t.Fatalf("Expected volume %s to be bound, is %s instead", pv.Name, pv.Status.Phase)
  796. }
  797. klog.V(2).Infof("PV %q is bound to PVC %q", pv.Name, pv.Spec.ClaimRef.Name)
  798. }
  799. // Delete the claims
  800. for i := 0; i < objCount; i++ {
  801. _ = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Delete(pvcs[i].Name, nil)
  802. }
  803. // Wait for the PVs to get deleted by listing remaining volumes
  804. // (delete events were unreliable)
  805. for {
  806. volumes, err := testClient.CoreV1().PersistentVolumes().List(metav1.ListOptions{})
  807. if err != nil {
  808. t.Fatalf("Failed to list volumes: %v", err)
  809. }
  810. klog.V(1).Infof("%d volumes remaining", len(volumes.Items))
  811. if len(volumes.Items) == 0 {
  812. break
  813. }
  814. time.Sleep(time.Second)
  815. }
  816. klog.V(2).Infof("TestPersistentVolumeProvisionMultiPVCs: volumes are deleted")
  817. }
  818. // TestPersistentVolumeMultiPVsDiffAccessModes tests binding of one PVC to two
  819. // PVs with different access modes.
  820. func TestPersistentVolumeMultiPVsDiffAccessModes(t *testing.T) {
  821. _, s, closeFn := framework.RunAMaster(nil)
  822. defer closeFn()
  823. ns := framework.CreateTestingNamespace("multi-pvs-diff-access", s, t)
  824. defer framework.DeleteTestingNamespace(ns, s, t)
  825. testClient, controller, informers, watchPV, watchPVC := createClients(ns, t, s, defaultSyncPeriod)
  826. defer watchPV.Stop()
  827. defer watchPVC.Stop()
  828. // NOTE: This test cannot run in parallel, because it is creating and deleting
  829. // non-namespaced objects (PersistenceVolumes).
  830. defer testClient.CoreV1().PersistentVolumes().DeleteCollection(nil, metav1.ListOptions{})
  831. stopCh := make(chan struct{})
  832. informers.Start(stopCh)
  833. go controller.Run(stopCh)
  834. defer close(stopCh)
  835. // This PV will be claimed, released, and deleted
  836. pvRwo := createPV("pv-rwo", "/tmp/foo", "10G",
  837. []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce}, v1.PersistentVolumeReclaimRetain)
  838. pvRwm := createPV("pv-rwm", "/tmp/bar", "10G",
  839. []v1.PersistentVolumeAccessMode{v1.ReadWriteMany}, v1.PersistentVolumeReclaimRetain)
  840. pvc := createPVC("pvc-rwm", ns.Name, "5G", []v1.PersistentVolumeAccessMode{v1.ReadWriteMany}, "")
  841. _, err := testClient.CoreV1().PersistentVolumes().Create(pvRwm)
  842. if err != nil {
  843. t.Errorf("Failed to create PersistentVolume: %v", err)
  844. }
  845. _, err = testClient.CoreV1().PersistentVolumes().Create(pvRwo)
  846. if err != nil {
  847. t.Errorf("Failed to create PersistentVolume: %v", err)
  848. }
  849. t.Log("volumes created")
  850. _, err = testClient.CoreV1().PersistentVolumeClaims(ns.Name).Create(pvc)
  851. if err != nil {
  852. t.Errorf("Failed to create PersistentVolumeClaim: %v", err)
  853. }
  854. t.Log("claim created")
  855. // wait until the controller pairs the volume and claim
  856. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeBound)
  857. t.Log("volume bound")
  858. waitForPersistentVolumeClaimPhase(testClient, pvc.Name, ns.Name, watchPVC, v1.ClaimBound)
  859. t.Log("claim bound")
  860. // only RWM PV is bound
  861. pv, err := testClient.CoreV1().PersistentVolumes().Get("pv-rwo", metav1.GetOptions{})
  862. if err != nil {
  863. t.Fatalf("Unexpected error getting pv: %v", err)
  864. }
  865. if pv.Spec.ClaimRef != nil {
  866. t.Fatalf("ReadWriteOnce PV shouldn't be bound")
  867. }
  868. pv, err = testClient.CoreV1().PersistentVolumes().Get("pv-rwm", metav1.GetOptions{})
  869. if err != nil {
  870. t.Fatalf("Unexpected error getting pv: %v", err)
  871. }
  872. if pv.Spec.ClaimRef == nil {
  873. t.Fatalf("ReadWriteMany PV should be bound")
  874. }
  875. if pv.Spec.ClaimRef.Name != pvc.Name {
  876. t.Fatalf("Bind mismatch! Expected %s but got %s", pvc.Name, pv.Spec.ClaimRef.Name)
  877. }
  878. // deleting a claim releases the volume
  879. if err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Delete(pvc.Name, nil); err != nil {
  880. t.Errorf("error deleting claim %s", pvc.Name)
  881. }
  882. t.Log("claim deleted")
  883. waitForAnyPersistentVolumePhase(watchPV, v1.VolumeReleased)
  884. t.Log("volume released")
  885. }
  886. func waitForPersistentVolumePhase(client *clientset.Clientset, pvName string, w watch.Interface, phase v1.PersistentVolumePhase) {
  887. // Check if the volume is already in requested phase
  888. volume, err := client.CoreV1().PersistentVolumes().Get(pvName, metav1.GetOptions{})
  889. if err == nil && volume.Status.Phase == phase {
  890. return
  891. }
  892. // Wait for the phase
  893. for {
  894. event := <-w.ResultChan()
  895. volume, ok := event.Object.(*v1.PersistentVolume)
  896. if !ok {
  897. continue
  898. }
  899. if volume.Status.Phase == phase && volume.Name == pvName {
  900. klog.V(2).Infof("volume %q is %s", volume.Name, phase)
  901. break
  902. }
  903. }
  904. }
  905. func waitForPersistentVolumeClaimPhase(client *clientset.Clientset, claimName, namespace string, w watch.Interface, phase v1.PersistentVolumeClaimPhase) {
  906. // Check if the claim is already in requested phase
  907. claim, err := client.CoreV1().PersistentVolumeClaims(namespace).Get(claimName, metav1.GetOptions{})
  908. if err == nil && claim.Status.Phase == phase {
  909. return
  910. }
  911. // Wait for the phase
  912. for {
  913. event := <-w.ResultChan()
  914. claim, ok := event.Object.(*v1.PersistentVolumeClaim)
  915. if !ok {
  916. continue
  917. }
  918. if claim.Status.Phase == phase && claim.Name == claimName {
  919. klog.V(2).Infof("claim %q is %s", claim.Name, phase)
  920. break
  921. }
  922. }
  923. }
  924. func waitForAnyPersistentVolumePhase(w watch.Interface, phase v1.PersistentVolumePhase) {
  925. for {
  926. event := <-w.ResultChan()
  927. volume, ok := event.Object.(*v1.PersistentVolume)
  928. if !ok {
  929. continue
  930. }
  931. if volume.Status.Phase == phase {
  932. klog.V(2).Infof("volume %q is %s", volume.Name, phase)
  933. break
  934. }
  935. }
  936. }
  937. func waitForAnyPersistentVolumeClaimPhase(w watch.Interface, phase v1.PersistentVolumeClaimPhase) {
  938. for {
  939. event := <-w.ResultChan()
  940. claim, ok := event.Object.(*v1.PersistentVolumeClaim)
  941. if !ok {
  942. continue
  943. }
  944. if claim.Status.Phase == phase {
  945. klog.V(2).Infof("claim %q is %s", claim.Name, phase)
  946. break
  947. }
  948. }
  949. }
  950. func createClients(ns *v1.Namespace, t *testing.T, s *httptest.Server, syncPeriod time.Duration) (*clientset.Clientset, *persistentvolumecontroller.PersistentVolumeController, informers.SharedInformerFactory, watch.Interface, watch.Interface) {
  951. // Use higher QPS and Burst, there is a test for race conditions which
  952. // creates many objects and default values were too low.
  953. binderClient := clientset.NewForConfigOrDie(&restclient.Config{
  954. Host: s.URL,
  955. ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}},
  956. QPS: 1000000,
  957. Burst: 1000000,
  958. })
  959. testClient := clientset.NewForConfigOrDie(&restclient.Config{
  960. Host: s.URL,
  961. ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}},
  962. QPS: 1000000,
  963. Burst: 1000000,
  964. })
  965. host := volumetest.NewFakeVolumeHost("/tmp/fake", nil, nil)
  966. plugin := &volumetest.FakeVolumePlugin{
  967. PluginName: provisionerPluginName,
  968. Host: host,
  969. Config: volume.VolumeConfig{},
  970. LastProvisionerOptions: volume.VolumeOptions{},
  971. NewAttacherCallCount: 0,
  972. NewDetacherCallCount: 0,
  973. Mounters: nil,
  974. Unmounters: nil,
  975. Attachers: nil,
  976. Detachers: nil,
  977. }
  978. plugins := []volume.VolumePlugin{plugin}
  979. cloud := &fakecloud.Cloud{}
  980. informers := informers.NewSharedInformerFactory(testClient, getSyncPeriod(syncPeriod))
  981. ctrl, err := persistentvolumecontroller.NewController(
  982. persistentvolumecontroller.ControllerParameters{
  983. KubeClient: binderClient,
  984. SyncPeriod: getSyncPeriod(syncPeriod),
  985. VolumePlugins: plugins,
  986. Cloud: cloud,
  987. VolumeInformer: informers.Core().V1().PersistentVolumes(),
  988. ClaimInformer: informers.Core().V1().PersistentVolumeClaims(),
  989. ClassInformer: informers.Storage().V1().StorageClasses(),
  990. PodInformer: informers.Core().V1().Pods(),
  991. NodeInformer: informers.Core().V1().Nodes(),
  992. EnableDynamicProvisioning: true,
  993. })
  994. if err != nil {
  995. t.Fatalf("Failed to construct PersistentVolumes: %v", err)
  996. }
  997. watchPV, err := testClient.CoreV1().PersistentVolumes().Watch(metav1.ListOptions{})
  998. if err != nil {
  999. t.Fatalf("Failed to watch PersistentVolumes: %v", err)
  1000. }
  1001. watchPVC, err := testClient.CoreV1().PersistentVolumeClaims(ns.Name).Watch(metav1.ListOptions{})
  1002. if err != nil {
  1003. t.Fatalf("Failed to watch PersistentVolumeClaims: %v", err)
  1004. }
  1005. return testClient, ctrl, informers, watchPV, watchPVC
  1006. }
  1007. func createPV(name, path, cap string, mode []v1.PersistentVolumeAccessMode, reclaim v1.PersistentVolumeReclaimPolicy) *v1.PersistentVolume {
  1008. return &v1.PersistentVolume{
  1009. ObjectMeta: metav1.ObjectMeta{Name: name},
  1010. Spec: v1.PersistentVolumeSpec{
  1011. PersistentVolumeSource: v1.PersistentVolumeSource{HostPath: &v1.HostPathVolumeSource{Path: path}},
  1012. Capacity: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse(cap)},
  1013. AccessModes: mode,
  1014. PersistentVolumeReclaimPolicy: reclaim,
  1015. },
  1016. }
  1017. }
  1018. func createPVC(name, namespace, cap string, mode []v1.PersistentVolumeAccessMode, class string) *v1.PersistentVolumeClaim {
  1019. return &v1.PersistentVolumeClaim{
  1020. ObjectMeta: metav1.ObjectMeta{
  1021. Name: name,
  1022. Namespace: namespace,
  1023. },
  1024. Spec: v1.PersistentVolumeClaimSpec{
  1025. Resources: v1.ResourceRequirements{Requests: v1.ResourceList{v1.ResourceName(v1.ResourceStorage): resource.MustParse(cap)}},
  1026. AccessModes: mode,
  1027. StorageClassName: &class,
  1028. },
  1029. }
  1030. }