replica_set.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. /*
  2. Copyright 2016 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 apps
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. appsv1 "k8s.io/api/apps/v1"
  19. v1 "k8s.io/api/core/v1"
  20. apierrors "k8s.io/apimachinery/pkg/api/errors"
  21. "k8s.io/apimachinery/pkg/api/resource"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/labels"
  24. "k8s.io/apimachinery/pkg/util/uuid"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. "k8s.io/kubernetes/pkg/controller/replicaset"
  27. "k8s.io/kubernetes/test/e2e/framework"
  28. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  29. replicasetutil "k8s.io/kubernetes/test/e2e/framework/replicaset"
  30. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  31. "github.com/onsi/ginkgo"
  32. imageutils "k8s.io/kubernetes/test/utils/image"
  33. )
  34. func newRS(rsName string, replicas int32, rsPodLabels map[string]string, imageName string, image string, args []string) *appsv1.ReplicaSet {
  35. zero := int64(0)
  36. return &appsv1.ReplicaSet{
  37. ObjectMeta: metav1.ObjectMeta{
  38. Name: rsName,
  39. Labels: rsPodLabels,
  40. },
  41. Spec: appsv1.ReplicaSetSpec{
  42. Selector: &metav1.LabelSelector{
  43. MatchLabels: rsPodLabels,
  44. },
  45. Replicas: &replicas,
  46. Template: v1.PodTemplateSpec{
  47. ObjectMeta: metav1.ObjectMeta{
  48. Labels: rsPodLabels,
  49. },
  50. Spec: v1.PodSpec{
  51. TerminationGracePeriodSeconds: &zero,
  52. Containers: []v1.Container{
  53. {
  54. Name: imageName,
  55. Image: image,
  56. Args: args,
  57. },
  58. },
  59. },
  60. },
  61. },
  62. }
  63. }
  64. func newPodQuota(name, number string) *v1.ResourceQuota {
  65. return &v1.ResourceQuota{
  66. ObjectMeta: metav1.ObjectMeta{
  67. Name: name,
  68. },
  69. Spec: v1.ResourceQuotaSpec{
  70. Hard: v1.ResourceList{
  71. v1.ResourcePods: resource.MustParse(number),
  72. },
  73. },
  74. }
  75. }
  76. var _ = SIGDescribe("ReplicaSet", func() {
  77. f := framework.NewDefaultFramework("replicaset")
  78. /*
  79. Release : v1.9
  80. Testname: Replica Set, run basic image
  81. Description: Create a ReplicaSet with a Pod and a single Container. Make sure that the Pod is running. Pod SHOULD send a valid response when queried.
  82. */
  83. framework.ConformanceIt("should serve a basic image on each replica with a public image ", func() {
  84. testReplicaSetServeImageOrFail(f, "basic", framework.ServeHostnameImage)
  85. })
  86. ginkgo.It("should serve a basic image on each replica with a private image", func() {
  87. // requires private images
  88. e2eskipper.SkipUnlessProviderIs("gce", "gke")
  89. privateimage := imageutils.GetConfig(imageutils.AgnhostPrivate)
  90. testReplicaSetServeImageOrFail(f, "private", privateimage.GetE2EImage())
  91. })
  92. ginkgo.It("should surface a failure condition on a common issue like exceeded quota", func() {
  93. testReplicaSetConditionCheck(f)
  94. })
  95. /*
  96. Release : v1.13
  97. Testname: Replica Set, adopt matching pods and release non matching pods
  98. Description: A Pod is created, then a Replica Set (RS) whose label selector will match the Pod. The RS MUST either adopt the Pod or delete and replace it with a new Pod. When the labels on one of the Pods owned by the RS change to no longer match the RS's label selector, the RS MUST release the Pod and update the Pod's owner references
  99. */
  100. framework.ConformanceIt("should adopt matching pods on creation and release no longer matching pods", func() {
  101. testRSAdoptMatchingAndReleaseNotMatching(f)
  102. })
  103. })
  104. // A basic test to check the deployment of an image using a ReplicaSet. The
  105. // image serves its hostname which is checked for each replica.
  106. func testReplicaSetServeImageOrFail(f *framework.Framework, test string, image string) {
  107. name := "my-hostname-" + test + "-" + string(uuid.NewUUID())
  108. replicas := int32(1)
  109. // Create a ReplicaSet for a service that serves its hostname.
  110. // The source for the Docker containter kubernetes/serve_hostname is
  111. // in contrib/for-demos/serve_hostname
  112. framework.Logf("Creating ReplicaSet %s", name)
  113. newRS := newRS(name, replicas, map[string]string{"name": name}, name, image, []string{"serve-hostname"})
  114. newRS.Spec.Template.Spec.Containers[0].Ports = []v1.ContainerPort{{ContainerPort: 9376}}
  115. _, err := f.ClientSet.AppsV1().ReplicaSets(f.Namespace.Name).Create(context.TODO(), newRS, metav1.CreateOptions{})
  116. framework.ExpectNoError(err)
  117. // Check that pods for the new RS were created.
  118. // TODO: Maybe switch PodsCreated to just check owner references.
  119. pods, err := e2epod.PodsCreated(f.ClientSet, f.Namespace.Name, name, replicas)
  120. framework.ExpectNoError(err)
  121. // Wait for the pods to enter the running state. Waiting loops until the pods
  122. // are running so non-running pods cause a timeout for this test.
  123. framework.Logf("Ensuring a pod for ReplicaSet %q is running", name)
  124. running := int32(0)
  125. for _, pod := range pods.Items {
  126. if pod.DeletionTimestamp != nil {
  127. continue
  128. }
  129. err = f.WaitForPodRunning(pod.Name)
  130. if err != nil {
  131. updatePod, getErr := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), pod.Name, metav1.GetOptions{})
  132. if getErr == nil {
  133. err = fmt.Errorf("Pod %q never run (phase: %s, conditions: %+v): %v", updatePod.Name, updatePod.Status.Phase, updatePod.Status.Conditions, err)
  134. } else {
  135. err = fmt.Errorf("Pod %q never run: %v", pod.Name, err)
  136. }
  137. }
  138. framework.ExpectNoError(err)
  139. framework.Logf("Pod %q is running (conditions: %+v)", pod.Name, pod.Status.Conditions)
  140. running++
  141. }
  142. // Sanity check
  143. if running != replicas {
  144. framework.ExpectNoError(fmt.Errorf("unexpected number of running pods: %+v", pods.Items))
  145. }
  146. // Verify that something is listening.
  147. framework.Logf("Trying to dial the pod")
  148. retryTimeout := 2 * time.Minute
  149. retryInterval := 5 * time.Second
  150. label := labels.SelectorFromSet(labels.Set(map[string]string{"name": name}))
  151. err = wait.Poll(retryInterval, retryTimeout, e2epod.NewProxyResponseChecker(f.ClientSet, f.Namespace.Name, label, name, true, pods).CheckAllResponses)
  152. if err != nil {
  153. framework.Failf("Did not get expected responses within the timeout period of %.2f seconds.", retryTimeout.Seconds())
  154. }
  155. }
  156. // 1. Create a quota restricting pods in the current namespace to 2.
  157. // 2. Create a replica set that wants to run 3 pods.
  158. // 3. Check replica set conditions for a ReplicaFailure condition.
  159. // 4. Scale down the replica set and observe the condition is gone.
  160. func testReplicaSetConditionCheck(f *framework.Framework) {
  161. c := f.ClientSet
  162. namespace := f.Namespace.Name
  163. name := "condition-test"
  164. ginkgo.By(fmt.Sprintf("Creating quota %q that allows only two pods to run in the current namespace", name))
  165. quota := newPodQuota(name, "2")
  166. _, err := c.CoreV1().ResourceQuotas(namespace).Create(context.TODO(), quota, metav1.CreateOptions{})
  167. framework.ExpectNoError(err)
  168. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  169. quota, err = c.CoreV1().ResourceQuotas(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  170. if err != nil {
  171. return false, err
  172. }
  173. quantity := resource.MustParse("2")
  174. podQuota := quota.Status.Hard[v1.ResourcePods]
  175. return (&podQuota).Cmp(quantity) == 0, nil
  176. })
  177. if err == wait.ErrWaitTimeout {
  178. err = fmt.Errorf("resource quota %q never synced", name)
  179. }
  180. framework.ExpectNoError(err)
  181. ginkgo.By(fmt.Sprintf("Creating replica set %q that asks for more than the allowed pod quota", name))
  182. rs := newRS(name, 3, map[string]string{"name": name}, WebserverImageName, WebserverImage, nil)
  183. rs, err = c.AppsV1().ReplicaSets(namespace).Create(context.TODO(), rs, metav1.CreateOptions{})
  184. framework.ExpectNoError(err)
  185. ginkgo.By(fmt.Sprintf("Checking replica set %q has the desired failure condition set", name))
  186. generation := rs.Generation
  187. conditions := rs.Status.Conditions
  188. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  189. rs, err = c.AppsV1().ReplicaSets(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  190. if err != nil {
  191. return false, err
  192. }
  193. if generation > rs.Status.ObservedGeneration {
  194. return false, nil
  195. }
  196. conditions = rs.Status.Conditions
  197. cond := replicaset.GetCondition(rs.Status, appsv1.ReplicaSetReplicaFailure)
  198. return cond != nil, nil
  199. })
  200. if err == wait.ErrWaitTimeout {
  201. err = fmt.Errorf("rs controller never added the failure condition for replica set %q: %#v", name, conditions)
  202. }
  203. framework.ExpectNoError(err)
  204. ginkgo.By(fmt.Sprintf("Scaling down replica set %q to satisfy pod quota", name))
  205. rs, err = replicasetutil.UpdateReplicaSetWithRetries(c, namespace, name, func(update *appsv1.ReplicaSet) {
  206. x := int32(2)
  207. update.Spec.Replicas = &x
  208. })
  209. framework.ExpectNoError(err)
  210. ginkgo.By(fmt.Sprintf("Checking replica set %q has no failure condition set", name))
  211. generation = rs.Generation
  212. conditions = rs.Status.Conditions
  213. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  214. rs, err = c.AppsV1().ReplicaSets(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  215. if err != nil {
  216. return false, err
  217. }
  218. if generation > rs.Status.ObservedGeneration {
  219. return false, nil
  220. }
  221. conditions = rs.Status.Conditions
  222. cond := replicaset.GetCondition(rs.Status, appsv1.ReplicaSetReplicaFailure)
  223. return cond == nil, nil
  224. })
  225. if err == wait.ErrWaitTimeout {
  226. err = fmt.Errorf("rs controller never removed the failure condition for rs %q: %#v", name, conditions)
  227. }
  228. framework.ExpectNoError(err)
  229. }
  230. func testRSAdoptMatchingAndReleaseNotMatching(f *framework.Framework) {
  231. name := "pod-adoption-release"
  232. ginkgo.By(fmt.Sprintf("Given a Pod with a 'name' label %s is created", name))
  233. p := f.PodClient().CreateSync(&v1.Pod{
  234. ObjectMeta: metav1.ObjectMeta{
  235. Name: name,
  236. Labels: map[string]string{
  237. "name": name,
  238. },
  239. },
  240. Spec: v1.PodSpec{
  241. Containers: []v1.Container{
  242. {
  243. Name: name,
  244. Image: WebserverImage,
  245. },
  246. },
  247. },
  248. })
  249. ginkgo.By("When a replicaset with a matching selector is created")
  250. replicas := int32(1)
  251. rsSt := newRS(name, replicas, map[string]string{"name": name}, name, WebserverImage, nil)
  252. rsSt.Spec.Selector = &metav1.LabelSelector{MatchLabels: map[string]string{"name": name}}
  253. rs, err := f.ClientSet.AppsV1().ReplicaSets(f.Namespace.Name).Create(context.TODO(), rsSt, metav1.CreateOptions{})
  254. framework.ExpectNoError(err)
  255. ginkgo.By("Then the orphan pod is adopted")
  256. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  257. p2, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), p.Name, metav1.GetOptions{})
  258. // The Pod p should either be adopted or deleted by the ReplicaSet
  259. if apierrors.IsNotFound(err) {
  260. return true, nil
  261. }
  262. framework.ExpectNoError(err)
  263. for _, owner := range p2.OwnerReferences {
  264. if *owner.Controller && owner.UID == rs.UID {
  265. // pod adopted
  266. return true, nil
  267. }
  268. }
  269. // pod still not adopted
  270. return false, nil
  271. })
  272. framework.ExpectNoError(err)
  273. ginkgo.By("When the matched label of one of its pods change")
  274. pods, err := e2epod.PodsCreated(f.ClientSet, f.Namespace.Name, rs.Name, replicas)
  275. framework.ExpectNoError(err)
  276. p = &pods.Items[0]
  277. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  278. pod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), p.Name, metav1.GetOptions{})
  279. framework.ExpectNoError(err)
  280. pod.Labels = map[string]string{"name": "not-matching-name"}
  281. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Update(context.TODO(), pod, metav1.UpdateOptions{})
  282. if err != nil && apierrors.IsConflict(err) {
  283. return false, nil
  284. }
  285. if err != nil {
  286. return false, err
  287. }
  288. return true, nil
  289. })
  290. framework.ExpectNoError(err)
  291. ginkgo.By("Then the pod is released")
  292. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  293. p2, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), p.Name, metav1.GetOptions{})
  294. framework.ExpectNoError(err)
  295. for _, owner := range p2.OwnerReferences {
  296. if *owner.Controller && owner.UID == rs.UID {
  297. // pod still belonging to the replicaset
  298. return false, nil
  299. }
  300. }
  301. // pod already released
  302. return true, nil
  303. })
  304. framework.ExpectNoError(err)
  305. }