persistent_volumes.go 16 KB

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