fixtures.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. "fmt"
  16. "reflect"
  17. "regexp"
  18. "sort"
  19. "strconv"
  20. appsv1 "k8s.io/api/apps/v1"
  21. v1 "k8s.io/api/core/v1"
  22. "k8s.io/apimachinery/pkg/api/resource"
  23. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  24. clientset "k8s.io/client-go/kubernetes"
  25. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. imageutils "k8s.io/kubernetes/test/utils/image"
  28. )
  29. // NewStatefulSet creates a new Webserver StatefulSet for testing. The StatefulSet is named name, is in namespace ns,
  30. // statefulPodsMounts are the mounts that will be backed by PVs. podsMounts are the mounts that are mounted directly
  31. // to the Pod. labels are the labels that will be usd for the StatefulSet selector.
  32. func NewStatefulSet(name, ns, governingSvcName string, replicas int32, statefulPodMounts []v1.VolumeMount, podMounts []v1.VolumeMount, labels map[string]string) *appsv1.StatefulSet {
  33. mounts := append(statefulPodMounts, podMounts...)
  34. claims := []v1.PersistentVolumeClaim{}
  35. for _, m := range statefulPodMounts {
  36. claims = append(claims, NewStatefulSetPVC(m.Name))
  37. }
  38. vols := []v1.Volume{}
  39. for _, m := range podMounts {
  40. vols = append(vols, v1.Volume{
  41. Name: m.Name,
  42. VolumeSource: v1.VolumeSource{
  43. HostPath: &v1.HostPathVolumeSource{
  44. Path: fmt.Sprintf("/tmp/%v", m.Name),
  45. },
  46. },
  47. })
  48. }
  49. return &appsv1.StatefulSet{
  50. TypeMeta: metav1.TypeMeta{
  51. Kind: "StatefulSet",
  52. APIVersion: "apps/v1",
  53. },
  54. ObjectMeta: metav1.ObjectMeta{
  55. Name: name,
  56. Namespace: ns,
  57. },
  58. Spec: appsv1.StatefulSetSpec{
  59. Selector: &metav1.LabelSelector{
  60. MatchLabels: labels,
  61. },
  62. Replicas: func(i int32) *int32 { return &i }(replicas),
  63. Template: v1.PodTemplateSpec{
  64. ObjectMeta: metav1.ObjectMeta{
  65. Labels: labels,
  66. Annotations: map[string]string{},
  67. },
  68. Spec: v1.PodSpec{
  69. Containers: []v1.Container{
  70. {
  71. Name: "webserver",
  72. Image: imageutils.GetE2EImage(imageutils.Httpd),
  73. VolumeMounts: mounts,
  74. },
  75. },
  76. Volumes: vols,
  77. },
  78. },
  79. UpdateStrategy: appsv1.StatefulSetUpdateStrategy{Type: appsv1.RollingUpdateStatefulSetStrategyType},
  80. VolumeClaimTemplates: claims,
  81. ServiceName: governingSvcName,
  82. },
  83. }
  84. }
  85. // NewStatefulSetPVC returns a PersistentVolumeClaim named name, for testing StatefulSets.
  86. func NewStatefulSetPVC(name string) v1.PersistentVolumeClaim {
  87. return v1.PersistentVolumeClaim{
  88. ObjectMeta: metav1.ObjectMeta{
  89. Name: name,
  90. },
  91. Spec: v1.PersistentVolumeClaimSpec{
  92. AccessModes: []v1.PersistentVolumeAccessMode{
  93. v1.ReadWriteOnce,
  94. },
  95. Resources: v1.ResourceRequirements{
  96. Requests: v1.ResourceList{
  97. v1.ResourceStorage: *resource.NewQuantity(1, resource.BinarySI),
  98. },
  99. },
  100. },
  101. }
  102. }
  103. func hasPauseProbe(pod *v1.Pod) bool {
  104. probe := pod.Spec.Containers[0].ReadinessProbe
  105. return probe != nil && reflect.DeepEqual(probe.Exec.Command, pauseProbe.Exec.Command)
  106. }
  107. var pauseProbe = &v1.Probe{
  108. Handler: v1.Handler{
  109. Exec: &v1.ExecAction{Command: []string{"test", "-f", "/data/statefulset-continue"}},
  110. },
  111. PeriodSeconds: 1,
  112. SuccessThreshold: 1,
  113. FailureThreshold: 1,
  114. }
  115. type statefulPodsByOrdinal []v1.Pod
  116. func (sp statefulPodsByOrdinal) Len() int {
  117. return len(sp)
  118. }
  119. func (sp statefulPodsByOrdinal) Swap(i, j int) {
  120. sp[i], sp[j] = sp[j], sp[i]
  121. }
  122. func (sp statefulPodsByOrdinal) Less(i, j int) bool {
  123. return getStatefulPodOrdinal(&sp[i]) < getStatefulPodOrdinal(&sp[j])
  124. }
  125. // PauseNewPods adds an always-failing ReadinessProbe to the StatefulSet PodTemplate.
  126. // This causes all newly-created Pods to stay Unready until they are manually resumed
  127. // with ResumeNextPod().
  128. // Note that this cannot be used together with SetHTTPProbe().
  129. func PauseNewPods(ss *appsv1.StatefulSet) {
  130. ss.Spec.Template.Spec.Containers[0].ReadinessProbe = pauseProbe
  131. }
  132. // ResumeNextPod allows the next Pod in the StatefulSet to continue by removing the ReadinessProbe
  133. // added by PauseNewPods(), if it's still there.
  134. // It fails the test if it finds any pods that are not in phase Running,
  135. // or if it finds more than one paused Pod existing at the same time.
  136. // This is a no-op if there are no paused pods.
  137. func ResumeNextPod(c clientset.Interface, ss *appsv1.StatefulSet) {
  138. podList := GetPodList(c, ss)
  139. resumedPod := ""
  140. for _, pod := range podList.Items {
  141. if pod.Status.Phase != v1.PodRunning {
  142. framework.Failf("Found pod in phase %q, cannot resume", pod.Status.Phase)
  143. }
  144. if podutil.IsPodReady(&pod) || !hasPauseProbe(&pod) {
  145. continue
  146. }
  147. if resumedPod != "" {
  148. framework.Failf("Found multiple paused stateful pods: %v and %v", pod.Name, resumedPod)
  149. }
  150. _, err := framework.RunHostCmdWithRetries(pod.Namespace, pod.Name, "dd if=/dev/zero of=/data/statefulset-continue bs=1 count=1 conv=fsync", StatefulSetPoll, StatefulPodTimeout)
  151. framework.ExpectNoError(err)
  152. framework.Logf("Resumed pod %v", pod.Name)
  153. resumedPod = pod.Name
  154. }
  155. }
  156. // SortStatefulPods sorts pods by their ordinals
  157. func SortStatefulPods(pods *v1.PodList) {
  158. sort.Sort(statefulPodsByOrdinal(pods.Items))
  159. }
  160. var statefulPodRegex = regexp.MustCompile("(.*)-([0-9]+)$")
  161. func getStatefulPodOrdinal(pod *v1.Pod) int {
  162. ordinal := -1
  163. subMatches := statefulPodRegex.FindStringSubmatch(pod.Name)
  164. if len(subMatches) < 3 {
  165. return ordinal
  166. }
  167. if i, err := strconv.ParseInt(subMatches[2], 10, 32); err == nil {
  168. ordinal = int(i)
  169. }
  170. return ordinal
  171. }