persistent_volumes.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. Copyright 2015 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 storage
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "time"
  19. "github.com/onsi/ginkgo"
  20. appsv1 "k8s.io/api/apps/v1"
  21. v1 "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  28. e2epv "k8s.io/kubernetes/test/e2e/framework/pv"
  29. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  30. e2esset "k8s.io/kubernetes/test/e2e/framework/statefulset"
  31. "k8s.io/kubernetes/test/e2e/framework/volume"
  32. "k8s.io/kubernetes/test/e2e/storage/utils"
  33. imageutils "k8s.io/kubernetes/test/utils/image"
  34. )
  35. // Validate PV/PVC, create and verify writer pod, delete the PVC, and validate the PV's
  36. // phase. Note: the PV is deleted in the AfterEach, not here.
  37. func completeTest(f *framework.Framework, c clientset.Interface, ns string, pv *v1.PersistentVolume, pvc *v1.PersistentVolumeClaim) {
  38. // 1. verify that the PV and PVC have bound correctly
  39. ginkgo.By("Validating the PV-PVC binding")
  40. framework.ExpectNoError(e2epv.WaitOnPVandPVC(c, ns, pv, pvc))
  41. // 2. create the nfs writer pod, test if the write was successful,
  42. // then delete the pod and verify that it was deleted
  43. ginkgo.By("Checking pod has write access to PersistentVolume")
  44. framework.ExpectNoError(createWaitAndDeletePod(c, ns, pvc, "touch /mnt/volume1/SUCCESS && (id -G | grep -E '\\b777\\b')"))
  45. // 3. delete the PVC, wait for PV to become "Released"
  46. ginkgo.By("Deleting the PVC to invoke the reclaim policy.")
  47. framework.ExpectNoError(e2epv.DeletePVCandValidatePV(c, ns, pvc, pv, v1.VolumeReleased))
  48. }
  49. // Validate pairs of PVs and PVCs, create and verify writer pod, delete PVC and validate
  50. // PV. Ensure each step succeeds.
  51. // Note: the PV is deleted in the AfterEach, not here.
  52. // Note: this func is serialized, we wait for each pod to be deleted before creating the
  53. // next pod. Adding concurrency is a TODO item.
  54. func completeMultiTest(f *framework.Framework, c clientset.Interface, ns string, pvols e2epv.PVMap, claims e2epv.PVCMap, expectPhase v1.PersistentVolumePhase) error {
  55. var err error
  56. // 1. verify each PV permits write access to a client pod
  57. ginkgo.By("Checking pod has write access to PersistentVolumes")
  58. for pvcKey := range claims {
  59. pvc, err := c.CoreV1().PersistentVolumeClaims(pvcKey.Namespace).Get(context.TODO(), pvcKey.Name, metav1.GetOptions{})
  60. if err != nil {
  61. return fmt.Errorf("error getting pvc %q: %v", pvcKey.Name, err)
  62. }
  63. if len(pvc.Spec.VolumeName) == 0 {
  64. continue // claim is not bound
  65. }
  66. // sanity test to ensure our maps are in sync
  67. _, found := pvols[pvc.Spec.VolumeName]
  68. if !found {
  69. return fmt.Errorf("internal: pvols map is missing volume %q", pvc.Spec.VolumeName)
  70. }
  71. // TODO: currently a serialized test of each PV
  72. if err = createWaitAndDeletePod(c, pvcKey.Namespace, pvc, "touch /mnt/volume1/SUCCESS && (id -G | grep -E '\\b777\\b')"); err != nil {
  73. return err
  74. }
  75. }
  76. // 2. delete each PVC, wait for its bound PV to reach `expectedPhase`
  77. ginkgo.By("Deleting PVCs to invoke reclaim policy")
  78. if err = e2epv.DeletePVCandValidatePVGroup(c, ns, pvols, claims, expectPhase); err != nil {
  79. return err
  80. }
  81. return nil
  82. }
  83. var _ = utils.SIGDescribe("PersistentVolumes", func() {
  84. // global vars for the ginkgo.Context()s and ginkgo.It()'s below
  85. f := framework.NewDefaultFramework("pv")
  86. var (
  87. c clientset.Interface
  88. ns string
  89. pvConfig e2epv.PersistentVolumeConfig
  90. pvcConfig e2epv.PersistentVolumeClaimConfig
  91. volLabel labels.Set
  92. selector *metav1.LabelSelector
  93. pv *v1.PersistentVolume
  94. pvc *v1.PersistentVolumeClaim
  95. err error
  96. )
  97. ginkgo.BeforeEach(func() {
  98. c = f.ClientSet
  99. ns = f.Namespace.Name
  100. // Enforce binding only within test space via selector labels
  101. volLabel = labels.Set{e2epv.VolumeSelectorKey: ns}
  102. selector = metav1.SetAsLabelSelector(volLabel)
  103. })
  104. // Testing configurations of a single a PV/PVC pair, multiple evenly paired PVs/PVCs,
  105. // and multiple unevenly paired PV/PVCs
  106. ginkgo.Describe("NFS", func() {
  107. var (
  108. nfsServerPod *v1.Pod
  109. serverIP string
  110. )
  111. ginkgo.BeforeEach(func() {
  112. _, nfsServerPod, serverIP = volume.NewNFSServer(c, ns, []string{"-G", "777", "/exports"})
  113. pvConfig = e2epv.PersistentVolumeConfig{
  114. NamePrefix: "nfs-",
  115. Labels: volLabel,
  116. PVSource: v1.PersistentVolumeSource{
  117. NFS: &v1.NFSVolumeSource{
  118. Server: serverIP,
  119. Path: "/exports",
  120. ReadOnly: false,
  121. },
  122. },
  123. }
  124. emptyStorageClass := ""
  125. pvcConfig = e2epv.PersistentVolumeClaimConfig{
  126. Selector: selector,
  127. StorageClassName: &emptyStorageClass,
  128. }
  129. })
  130. ginkgo.AfterEach(func() {
  131. framework.ExpectNoError(e2epod.DeletePodWithWait(c, nfsServerPod), "AfterEach: Failed to delete pod ", nfsServerPod.Name)
  132. pv, pvc = nil, nil
  133. pvConfig, pvcConfig = e2epv.PersistentVolumeConfig{}, e2epv.PersistentVolumeClaimConfig{}
  134. })
  135. ginkgo.Context("with Single PV - PVC pairs", func() {
  136. // Note: this is the only code where the pv is deleted.
  137. ginkgo.AfterEach(func() {
  138. framework.Logf("AfterEach: Cleaning up test resources.")
  139. if errs := e2epv.PVPVCCleanup(c, ns, pv, pvc); len(errs) > 0 {
  140. framework.Failf("AfterEach: Failed to delete PVC and/or PV. Errors: %v", utilerrors.NewAggregate(errs))
  141. }
  142. })
  143. // Individual tests follow:
  144. //
  145. // Create an nfs PV, then a claim that matches the PV, and a pod that
  146. // contains the claim. Verify that the PV and PVC bind correctly, and
  147. // that the pod can write to the nfs volume.
  148. ginkgo.It("should create a non-pre-bound PV and PVC: test write access ", func() {
  149. pv, pvc, err = e2epv.CreatePVPVC(c, pvConfig, pvcConfig, ns, false)
  150. framework.ExpectNoError(err)
  151. completeTest(f, c, ns, pv, pvc)
  152. })
  153. // Create a claim first, then a nfs PV that matches the claim, and a
  154. // pod that contains the claim. Verify that the PV and PVC bind
  155. // correctly, and that the pod can write to the nfs volume.
  156. ginkgo.It("create a PVC and non-pre-bound PV: test write access", func() {
  157. pv, pvc, err = e2epv.CreatePVCPV(c, pvConfig, pvcConfig, ns, false)
  158. framework.ExpectNoError(err)
  159. completeTest(f, c, ns, pv, pvc)
  160. })
  161. // Create a claim first, then a pre-bound nfs PV that matches the claim,
  162. // and a pod that contains the claim. Verify that the PV and PVC bind
  163. // correctly, and that the pod can write to the nfs volume.
  164. ginkgo.It("create a PVC and a pre-bound PV: test write access", func() {
  165. pv, pvc, err = e2epv.CreatePVCPV(c, pvConfig, pvcConfig, ns, true)
  166. framework.ExpectNoError(err)
  167. completeTest(f, c, ns, pv, pvc)
  168. })
  169. // Create a nfs PV first, then a pre-bound PVC that matches the PV,
  170. // and a pod that contains the claim. Verify that the PV and PVC bind
  171. // correctly, and that the pod can write to the nfs volume.
  172. ginkgo.It("create a PV and a pre-bound PVC: test write access", func() {
  173. pv, pvc, err = e2epv.CreatePVPVC(c, pvConfig, pvcConfig, ns, true)
  174. framework.ExpectNoError(err)
  175. completeTest(f, c, ns, pv, pvc)
  176. })
  177. })
  178. // Create multiple pvs and pvcs, all in the same namespace. The PVs-PVCs are
  179. // verified to bind, though it's not known in advanced which PV will bind to
  180. // which claim. For each pv-pvc pair create a pod that writes to the nfs mount.
  181. // Note: when the number of PVs exceeds the number of PVCs the max binding wait
  182. // time will occur for each PV in excess. This is expected but the delta
  183. // should be kept small so that the tests aren't unnecessarily slow.
  184. // Note: future tests may wish to incorporate the following:
  185. // a) pre-binding, b) create pvcs before pvs, c) create pvcs and pods
  186. // in different namespaces.
  187. ginkgo.Context("with multiple PVs and PVCs all in same ns", func() {
  188. // scope the pv and pvc maps to be available in the AfterEach
  189. // note: these maps are created fresh in CreatePVsPVCs()
  190. var pvols e2epv.PVMap
  191. var claims e2epv.PVCMap
  192. ginkgo.AfterEach(func() {
  193. framework.Logf("AfterEach: deleting %v PVCs and %v PVs...", len(claims), len(pvols))
  194. errs := e2epv.PVPVCMapCleanup(c, ns, pvols, claims)
  195. if len(errs) > 0 {
  196. errmsg := []string{}
  197. for _, e := range errs {
  198. errmsg = append(errmsg, e.Error())
  199. }
  200. framework.Failf("AfterEach: Failed to delete 1 or more PVs/PVCs. Errors: %v", strings.Join(errmsg, "; "))
  201. }
  202. })
  203. // Create 2 PVs and 4 PVCs.
  204. // Note: PVs are created before claims and no pre-binding
  205. ginkgo.It("should create 2 PVs and 4 PVCs: test write access", func() {
  206. numPVs, numPVCs := 2, 4
  207. pvols, claims, err = e2epv.CreatePVsPVCs(numPVs, numPVCs, c, ns, pvConfig, pvcConfig)
  208. framework.ExpectNoError(err)
  209. framework.ExpectNoError(e2epv.WaitAndVerifyBinds(c, ns, pvols, claims, true))
  210. framework.ExpectNoError(completeMultiTest(f, c, ns, pvols, claims, v1.VolumeReleased))
  211. })
  212. // Create 3 PVs and 3 PVCs.
  213. // Note: PVs are created before claims and no pre-binding
  214. ginkgo.It("should create 3 PVs and 3 PVCs: test write access", func() {
  215. numPVs, numPVCs := 3, 3
  216. pvols, claims, err = e2epv.CreatePVsPVCs(numPVs, numPVCs, c, ns, pvConfig, pvcConfig)
  217. framework.ExpectNoError(err)
  218. framework.ExpectNoError(e2epv.WaitAndVerifyBinds(c, ns, pvols, claims, true))
  219. framework.ExpectNoError(completeMultiTest(f, c, ns, pvols, claims, v1.VolumeReleased))
  220. })
  221. // Create 4 PVs and 2 PVCs.
  222. // Note: PVs are created before claims and no pre-binding.
  223. ginkgo.It("should create 4 PVs and 2 PVCs: test write access [Slow]", func() {
  224. numPVs, numPVCs := 4, 2
  225. pvols, claims, err = e2epv.CreatePVsPVCs(numPVs, numPVCs, c, ns, pvConfig, pvcConfig)
  226. framework.ExpectNoError(err)
  227. framework.ExpectNoError(e2epv.WaitAndVerifyBinds(c, ns, pvols, claims, true))
  228. framework.ExpectNoError(completeMultiTest(f, c, ns, pvols, claims, v1.VolumeReleased))
  229. })
  230. })
  231. // This Context isolates and tests the "Recycle" reclaim behavior. On deprecation of the
  232. // Recycler, this entire context can be removed without affecting the test suite or leaving behind
  233. // dead code.
  234. ginkgo.Context("when invoking the Recycle reclaim policy", func() {
  235. ginkgo.BeforeEach(func() {
  236. pvConfig.ReclaimPolicy = v1.PersistentVolumeReclaimRecycle
  237. pv, pvc, err = e2epv.CreatePVPVC(c, pvConfig, pvcConfig, ns, false)
  238. framework.ExpectNoError(err, "BeforeEach: Failed to create PV/PVC")
  239. framework.ExpectNoError(e2epv.WaitOnPVandPVC(c, ns, pv, pvc), "BeforeEach: WaitOnPVandPVC failed")
  240. })
  241. ginkgo.AfterEach(func() {
  242. framework.Logf("AfterEach: Cleaning up test resources.")
  243. if errs := e2epv.PVPVCCleanup(c, ns, pv, pvc); len(errs) > 0 {
  244. framework.Failf("AfterEach: Failed to delete PVC and/or PV. Errors: %v", utilerrors.NewAggregate(errs))
  245. }
  246. })
  247. // This ginkgo.It() tests a scenario where a PV is written to by a Pod, recycled, then the volume checked
  248. // for files. If files are found, the checking Pod fails, failing the test. Otherwise, the pod
  249. // (and test) succeed.
  250. ginkgo.It("should test that a PV becomes Available and is clean after the PVC is deleted.", func() {
  251. ginkgo.By("Writing to the volume.")
  252. pod := e2epod.MakePod(ns, nil, []*v1.PersistentVolumeClaim{pvc}, true, "touch /mnt/volume1/SUCCESS && (id -G | grep -E '\\b777\\b')")
  253. pod, err = c.CoreV1().Pods(ns).Create(context.TODO(), pod, metav1.CreateOptions{})
  254. framework.ExpectNoError(err)
  255. framework.ExpectNoError(e2epod.WaitForPodSuccessInNamespace(c, pod.Name, ns))
  256. ginkgo.By("Deleting the claim")
  257. framework.ExpectNoError(e2epod.DeletePodWithWait(c, pod))
  258. framework.ExpectNoError(e2epv.DeletePVCandValidatePV(c, ns, pvc, pv, v1.VolumeAvailable))
  259. ginkgo.By("Re-mounting the volume.")
  260. pvc = e2epv.MakePersistentVolumeClaim(pvcConfig, ns)
  261. pvc, err = e2epv.CreatePVC(c, ns, pvc)
  262. framework.ExpectNoError(err)
  263. framework.ExpectNoError(e2epv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, c, ns, pvc.Name, 2*time.Second, 60*time.Second), "Failed to reach 'Bound' for PVC ", pvc.Name)
  264. // If a file is detected in /mnt, fail the pod and do not restart it.
  265. ginkgo.By("Verifying the mount has been cleaned.")
  266. mount := pod.Spec.Containers[0].VolumeMounts[0].MountPath
  267. pod = e2epod.MakePod(ns, nil, []*v1.PersistentVolumeClaim{pvc}, true, fmt.Sprintf("[ $(ls -A %s | wc -l) -eq 0 ] && exit 0 || exit 1", mount))
  268. pod, err = c.CoreV1().Pods(ns).Create(context.TODO(), pod, metav1.CreateOptions{})
  269. framework.ExpectNoError(err)
  270. framework.ExpectNoError(e2epod.WaitForPodSuccessInNamespace(c, pod.Name, ns))
  271. framework.ExpectNoError(e2epod.DeletePodWithWait(c, pod))
  272. framework.Logf("Pod exited without failure; the volume has been recycled.")
  273. })
  274. })
  275. })
  276. ginkgo.Describe("Default StorageClass", func() {
  277. ginkgo.Context("pods that use multiple volumes", func() {
  278. ginkgo.AfterEach(func() {
  279. e2esset.DeleteAllStatefulSets(c, ns)
  280. })
  281. ginkgo.It("should be reschedulable [Slow]", func() {
  282. // Only run on providers with default storageclass
  283. e2eskipper.SkipUnlessProviderIs("openstack", "gce", "gke", "vsphere", "azure")
  284. numVols := 4
  285. ginkgo.By("Creating a StatefulSet pod to initialize data")
  286. writeCmd := "true"
  287. for i := 0; i < numVols; i++ {
  288. writeCmd += fmt.Sprintf("&& touch %v", getVolumeFile(i))
  289. }
  290. writeCmd += "&& sleep 10000"
  291. probe := &v1.Probe{
  292. Handler: v1.Handler{
  293. Exec: &v1.ExecAction{
  294. // Check that the last file got created
  295. Command: []string{"test", "-f", getVolumeFile(numVols - 1)},
  296. },
  297. },
  298. InitialDelaySeconds: 1,
  299. PeriodSeconds: 1,
  300. }
  301. mounts := []v1.VolumeMount{}
  302. claims := []v1.PersistentVolumeClaim{}
  303. for i := 0; i < numVols; i++ {
  304. pvc := e2epv.MakePersistentVolumeClaim(e2epv.PersistentVolumeClaimConfig{}, ns)
  305. pvc.Name = getVolName(i)
  306. mounts = append(mounts, v1.VolumeMount{Name: pvc.Name, MountPath: getMountPath(i)})
  307. claims = append(claims, *pvc)
  308. }
  309. spec := makeStatefulSetWithPVCs(ns, writeCmd, mounts, claims, probe)
  310. ss, err := c.AppsV1().StatefulSets(ns).Create(context.TODO(), spec, metav1.CreateOptions{})
  311. framework.ExpectNoError(err)
  312. e2esset.WaitForRunningAndReady(c, 1, ss)
  313. ginkgo.By("Deleting the StatefulSet but not the volumes")
  314. // Scale down to 0 first so that the Delete is quick
  315. ss, err = e2esset.Scale(c, ss, 0)
  316. framework.ExpectNoError(err)
  317. e2esset.WaitForStatusReplicas(c, ss, 0)
  318. err = c.AppsV1().StatefulSets(ns).Delete(context.TODO(), ss.Name, &metav1.DeleteOptions{})
  319. framework.ExpectNoError(err)
  320. ginkgo.By("Creating a new Statefulset and validating the data")
  321. validateCmd := "true"
  322. for i := 0; i < numVols; i++ {
  323. validateCmd += fmt.Sprintf("&& test -f %v", getVolumeFile(i))
  324. }
  325. validateCmd += "&& sleep 10000"
  326. spec = makeStatefulSetWithPVCs(ns, validateCmd, mounts, claims, probe)
  327. ss, err = c.AppsV1().StatefulSets(ns).Create(context.TODO(), spec, metav1.CreateOptions{})
  328. framework.ExpectNoError(err)
  329. e2esset.WaitForRunningAndReady(c, 1, ss)
  330. })
  331. })
  332. })
  333. })
  334. func getVolName(i int) string {
  335. return fmt.Sprintf("vol%v", i)
  336. }
  337. func getMountPath(i int) string {
  338. return fmt.Sprintf("/mnt/%v", getVolName(i))
  339. }
  340. func getVolumeFile(i int) string {
  341. return fmt.Sprintf("%v/data%v", getMountPath(i), i)
  342. }
  343. func makeStatefulSetWithPVCs(ns, cmd string, mounts []v1.VolumeMount, claims []v1.PersistentVolumeClaim, readyProbe *v1.Probe) *appsv1.StatefulSet {
  344. ssReplicas := int32(1)
  345. labels := map[string]string{"app": "many-volumes-test"}
  346. return &appsv1.StatefulSet{
  347. ObjectMeta: metav1.ObjectMeta{
  348. Name: "many-volumes-test",
  349. Namespace: ns,
  350. },
  351. Spec: appsv1.StatefulSetSpec{
  352. Selector: &metav1.LabelSelector{
  353. MatchLabels: map[string]string{"app": "many-volumes-test"},
  354. },
  355. Replicas: &ssReplicas,
  356. Template: v1.PodTemplateSpec{
  357. ObjectMeta: metav1.ObjectMeta{
  358. Labels: labels,
  359. },
  360. Spec: v1.PodSpec{
  361. Containers: []v1.Container{
  362. {
  363. Name: "nginx",
  364. Image: imageutils.GetE2EImage(imageutils.Nginx),
  365. Command: []string{"/bin/sh"},
  366. Args: []string{"-c", cmd},
  367. VolumeMounts: mounts,
  368. ReadinessProbe: readyProbe,
  369. },
  370. },
  371. },
  372. },
  373. VolumeClaimTemplates: claims,
  374. },
  375. }
  376. }
  377. // createWaitAndDeletePod creates the test pod, wait for (hopefully) success, and then delete the pod.
  378. // Note: need named return value so that the err assignment in the defer sets the returned error.
  379. // Has been shown to be necessary using Go 1.7.
  380. func createWaitAndDeletePod(c clientset.Interface, ns string, pvc *v1.PersistentVolumeClaim, command string) (err error) {
  381. framework.Logf("Creating nfs test pod")
  382. pod := e2epod.MakePod(ns, nil, []*v1.PersistentVolumeClaim{pvc}, true, command)
  383. runPod, err := c.CoreV1().Pods(ns).Create(context.TODO(), pod, metav1.CreateOptions{})
  384. if err != nil {
  385. return fmt.Errorf("pod Create API error: %v", err)
  386. }
  387. defer func() {
  388. delErr := e2epod.DeletePodWithWait(c, runPod)
  389. if err == nil { // don't override previous err value
  390. err = delErr // assign to returned err, can be nil
  391. }
  392. }()
  393. err = testPodSuccessOrFail(c, ns, runPod)
  394. if err != nil {
  395. return fmt.Errorf("pod %q did not exit with Success: %v", runPod.Name, err)
  396. }
  397. return // note: named return value
  398. }
  399. // testPodSuccessOrFail tests whether the pod's exit code is zero.
  400. func testPodSuccessOrFail(c clientset.Interface, ns string, pod *v1.Pod) error {
  401. framework.Logf("Pod should terminate with exitcode 0 (success)")
  402. if err := e2epod.WaitForPodSuccessInNamespace(c, pod.Name, ns); err != nil {
  403. return fmt.Errorf("pod %q failed to reach Success: %v", pod.Name, err)
  404. }
  405. framework.Logf("Pod %v succeeded ", pod.Name)
  406. return nil
  407. }