rest.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. /*
  2. Copyright 2019 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 statefulset
  14. import (
  15. "context"
  16. "fmt"
  17. "path/filepath"
  18. "strings"
  19. "time"
  20. appsv1 "k8s.io/api/apps/v1"
  21. v1 "k8s.io/api/core/v1"
  22. apierrors "k8s.io/apimachinery/pkg/api/errors"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. "k8s.io/apimachinery/pkg/labels"
  25. "k8s.io/apimachinery/pkg/util/sets"
  26. "k8s.io/apimachinery/pkg/util/wait"
  27. clientset "k8s.io/client-go/kubernetes"
  28. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  29. "k8s.io/kubernetes/test/e2e/framework"
  30. "k8s.io/kubernetes/test/e2e/manifest"
  31. )
  32. // CreateStatefulSet creates a StatefulSet from the manifest at manifestPath in the Namespace ns using kubectl create.
  33. func CreateStatefulSet(c clientset.Interface, manifestPath, ns string) *appsv1.StatefulSet {
  34. mkpath := func(file string) string {
  35. return filepath.Join(manifestPath, file)
  36. }
  37. framework.Logf("Parsing statefulset from %v", mkpath("statefulset.yaml"))
  38. ss, err := manifest.StatefulSetFromManifest(mkpath("statefulset.yaml"), ns)
  39. framework.ExpectNoError(err)
  40. framework.Logf("Parsing service from %v", mkpath("service.yaml"))
  41. svc, err := manifest.SvcFromManifest(mkpath("service.yaml"))
  42. framework.ExpectNoError(err)
  43. framework.Logf(fmt.Sprintf("creating " + ss.Name + " service"))
  44. _, err = c.CoreV1().Services(ns).Create(context.TODO(), svc, metav1.CreateOptions{})
  45. framework.ExpectNoError(err)
  46. framework.Logf(fmt.Sprintf("creating statefulset %v/%v with %d replicas and selector %+v", ss.Namespace, ss.Name, *(ss.Spec.Replicas), ss.Spec.Selector))
  47. _, err = c.AppsV1().StatefulSets(ns).Create(context.TODO(), ss, metav1.CreateOptions{})
  48. framework.ExpectNoError(err)
  49. WaitForRunningAndReady(c, *ss.Spec.Replicas, ss)
  50. return ss
  51. }
  52. // GetPodList gets the current Pods in ss.
  53. func GetPodList(c clientset.Interface, ss *appsv1.StatefulSet) *v1.PodList {
  54. selector, err := metav1.LabelSelectorAsSelector(ss.Spec.Selector)
  55. framework.ExpectNoError(err)
  56. podList, err := c.CoreV1().Pods(ss.Namespace).List(context.TODO(), metav1.ListOptions{LabelSelector: selector.String()})
  57. framework.ExpectNoError(err)
  58. return podList
  59. }
  60. // DeleteAllStatefulSets deletes all StatefulSet API Objects in Namespace ns.
  61. func DeleteAllStatefulSets(c clientset.Interface, ns string) {
  62. ssList, err := c.AppsV1().StatefulSets(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
  63. framework.ExpectNoError(err)
  64. // Scale down each statefulset, then delete it completely.
  65. // Deleting a pvc without doing this will leak volumes, #25101.
  66. errList := []string{}
  67. for i := range ssList.Items {
  68. ss := &ssList.Items[i]
  69. var err error
  70. if ss, err = Scale(c, ss, 0); err != nil {
  71. errList = append(errList, fmt.Sprintf("%v", err))
  72. }
  73. WaitForStatusReplicas(c, ss, 0)
  74. framework.Logf("Deleting statefulset %v", ss.Name)
  75. // Use OrphanDependents=false so it's deleted synchronously.
  76. // We already made sure the Pods are gone inside Scale().
  77. if err := c.AppsV1().StatefulSets(ss.Namespace).Delete(context.TODO(), ss.Name, &metav1.DeleteOptions{OrphanDependents: new(bool)}); err != nil {
  78. errList = append(errList, fmt.Sprintf("%v", err))
  79. }
  80. }
  81. // pvs are global, so we need to wait for the exact ones bound to the statefulset pvcs.
  82. pvNames := sets.NewString()
  83. // TODO: Don't assume all pvcs in the ns belong to a statefulset
  84. pvcPollErr := wait.PollImmediate(StatefulSetPoll, StatefulSetTimeout, func() (bool, error) {
  85. pvcList, err := c.CoreV1().PersistentVolumeClaims(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
  86. if err != nil {
  87. framework.Logf("WARNING: Failed to list pvcs, retrying %v", err)
  88. return false, nil
  89. }
  90. for _, pvc := range pvcList.Items {
  91. pvNames.Insert(pvc.Spec.VolumeName)
  92. // TODO: Double check that there are no pods referencing the pvc
  93. framework.Logf("Deleting pvc: %v with volume %v", pvc.Name, pvc.Spec.VolumeName)
  94. if err := c.CoreV1().PersistentVolumeClaims(ns).Delete(context.TODO(), pvc.Name, nil); err != nil {
  95. return false, nil
  96. }
  97. }
  98. return true, nil
  99. })
  100. if pvcPollErr != nil {
  101. errList = append(errList, fmt.Sprintf("Timeout waiting for pvc deletion."))
  102. }
  103. pollErr := wait.PollImmediate(StatefulSetPoll, StatefulSetTimeout, func() (bool, error) {
  104. pvList, err := c.CoreV1().PersistentVolumes().List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
  105. if err != nil {
  106. framework.Logf("WARNING: Failed to list pvs, retrying %v", err)
  107. return false, nil
  108. }
  109. waitingFor := []string{}
  110. for _, pv := range pvList.Items {
  111. if pvNames.Has(pv.Name) {
  112. waitingFor = append(waitingFor, fmt.Sprintf("%v: %+v", pv.Name, pv.Status))
  113. }
  114. }
  115. if len(waitingFor) == 0 {
  116. return true, nil
  117. }
  118. framework.Logf("Still waiting for pvs of statefulset to disappear:\n%v", strings.Join(waitingFor, "\n"))
  119. return false, nil
  120. })
  121. if pollErr != nil {
  122. errList = append(errList, fmt.Sprintf("Timeout waiting for pv provisioner to delete pvs, this might mean the test leaked pvs."))
  123. }
  124. if len(errList) != 0 {
  125. framework.ExpectNoError(fmt.Errorf("%v", strings.Join(errList, "\n")))
  126. }
  127. }
  128. // Scale scales ss to count replicas.
  129. func Scale(c clientset.Interface, ss *appsv1.StatefulSet, count int32) (*appsv1.StatefulSet, error) {
  130. name := ss.Name
  131. ns := ss.Namespace
  132. framework.Logf("Scaling statefulset %s to %d", name, count)
  133. ss = update(c, ns, name, func(ss *appsv1.StatefulSet) { *(ss.Spec.Replicas) = count })
  134. var statefulPodList *v1.PodList
  135. pollErr := wait.PollImmediate(StatefulSetPoll, StatefulSetTimeout, func() (bool, error) {
  136. statefulPodList = GetPodList(c, ss)
  137. if int32(len(statefulPodList.Items)) == count {
  138. return true, nil
  139. }
  140. return false, nil
  141. })
  142. if pollErr != nil {
  143. unhealthy := []string{}
  144. for _, statefulPod := range statefulPodList.Items {
  145. delTs, phase, readiness := statefulPod.DeletionTimestamp, statefulPod.Status.Phase, podutil.IsPodReady(&statefulPod)
  146. if delTs != nil || phase != v1.PodRunning || !readiness {
  147. unhealthy = append(unhealthy, fmt.Sprintf("%v: deletion %v, phase %v, readiness %v", statefulPod.Name, delTs, phase, readiness))
  148. }
  149. }
  150. return ss, fmt.Errorf("Failed to scale statefulset to %d in %v. Remaining pods:\n%v", count, StatefulSetTimeout, unhealthy)
  151. }
  152. return ss, nil
  153. }
  154. // UpdateReplicas updates the replicas of ss to count.
  155. func UpdateReplicas(c clientset.Interface, ss *appsv1.StatefulSet, count int32) {
  156. update(c, ss.Namespace, ss.Name, func(ss *appsv1.StatefulSet) { *(ss.Spec.Replicas) = count })
  157. }
  158. // Restart scales ss to 0 and then back to its previous number of replicas.
  159. func Restart(c clientset.Interface, ss *appsv1.StatefulSet) {
  160. oldReplicas := *(ss.Spec.Replicas)
  161. ss, err := Scale(c, ss, 0)
  162. framework.ExpectNoError(err)
  163. // Wait for controller to report the desired number of Pods.
  164. // This way we know the controller has observed all Pod deletions
  165. // before we scale it back up.
  166. WaitForStatusReplicas(c, ss, 0)
  167. update(c, ss.Namespace, ss.Name, func(ss *appsv1.StatefulSet) { *(ss.Spec.Replicas) = oldReplicas })
  168. }
  169. // CheckHostname verifies that all Pods in ss have the correct Hostname. If the returned error is not nil than verification failed.
  170. func CheckHostname(c clientset.Interface, ss *appsv1.StatefulSet) error {
  171. cmd := "printf $(hostname)"
  172. podList := GetPodList(c, ss)
  173. for _, statefulPod := range podList.Items {
  174. hostname, err := framework.RunHostCmdWithRetries(statefulPod.Namespace, statefulPod.Name, cmd, StatefulSetPoll, StatefulPodTimeout)
  175. if err != nil {
  176. return err
  177. }
  178. if hostname != statefulPod.Name {
  179. return fmt.Errorf("unexpected hostname (%s) and stateful pod name (%s) not equal", hostname, statefulPod.Name)
  180. }
  181. }
  182. return nil
  183. }
  184. // CheckMount checks that the mount at mountPath is valid for all Pods in ss.
  185. func CheckMount(c clientset.Interface, ss *appsv1.StatefulSet, mountPath string) error {
  186. for _, cmd := range []string{
  187. // Print inode, size etc
  188. fmt.Sprintf("ls -idlh %v", mountPath),
  189. // Print subdirs
  190. fmt.Sprintf("find %v", mountPath),
  191. // Try writing
  192. fmt.Sprintf("touch %v", filepath.Join(mountPath, fmt.Sprintf("%v", time.Now().UnixNano()))),
  193. } {
  194. if err := ExecInStatefulPods(c, ss, cmd); err != nil {
  195. return fmt.Errorf("failed to execute %v, error: %v", cmd, err)
  196. }
  197. }
  198. return nil
  199. }
  200. // CheckServiceName asserts that the ServiceName for ss is equivalent to expectedServiceName.
  201. func CheckServiceName(ss *appsv1.StatefulSet, expectedServiceName string) error {
  202. framework.Logf("Checking if statefulset spec.serviceName is %s", expectedServiceName)
  203. if expectedServiceName != ss.Spec.ServiceName {
  204. return fmt.Errorf("wrong service name governing statefulset. Expected %s got %s",
  205. expectedServiceName, ss.Spec.ServiceName)
  206. }
  207. return nil
  208. }
  209. // ExecInStatefulPods executes cmd in all Pods in ss. If a error occurs it is returned and cmd is not execute in any subsequent Pods.
  210. func ExecInStatefulPods(c clientset.Interface, ss *appsv1.StatefulSet, cmd string) error {
  211. podList := GetPodList(c, ss)
  212. for _, statefulPod := range podList.Items {
  213. stdout, err := framework.RunHostCmdWithRetries(statefulPod.Namespace, statefulPod.Name, cmd, StatefulSetPoll, StatefulPodTimeout)
  214. framework.Logf("stdout of %v on %v: %v", cmd, statefulPod.Name, stdout)
  215. if err != nil {
  216. return err
  217. }
  218. }
  219. return nil
  220. }
  221. // udpate updates a statefulset, and it is only used within rest.go
  222. func update(c clientset.Interface, ns, name string, update func(ss *appsv1.StatefulSet)) *appsv1.StatefulSet {
  223. for i := 0; i < 3; i++ {
  224. ss, err := c.AppsV1().StatefulSets(ns).Get(context.TODO(), name, metav1.GetOptions{})
  225. if err != nil {
  226. framework.Failf("failed to get statefulset %q: %v", name, err)
  227. }
  228. update(ss)
  229. ss, err = c.AppsV1().StatefulSets(ns).Update(context.TODO(), ss, metav1.UpdateOptions{})
  230. if err == nil {
  231. return ss
  232. }
  233. if !apierrors.IsConflict(err) && !apierrors.IsServerTimeout(err) {
  234. framework.Failf("failed to update statefulset %q: %v", name, err)
  235. }
  236. }
  237. framework.Failf("too many retries draining statefulset %q", name)
  238. return nil
  239. }