replica_set.go 12 KB

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