rc.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 apps
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. v1 "k8s.io/api/core/v1"
  19. apierrors "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. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/pkg/controller/replication"
  27. "k8s.io/kubernetes/test/e2e/framework"
  28. e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
  29. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  30. imageutils "k8s.io/kubernetes/test/utils/image"
  31. "github.com/onsi/ginkgo"
  32. )
  33. var _ = SIGDescribe("ReplicationController", func() {
  34. f := framework.NewDefaultFramework("replication-controller")
  35. /*
  36. Release : v1.9
  37. Testname: Replication Controller, run basic image
  38. Description: Replication Controller MUST create a Pod with Basic Image and MUST run the service with the provided image. Image MUST be tested by dialing into the service listening through TCP, UDP and HTTP.
  39. */
  40. framework.ConformanceIt("should serve a basic image on each replica with a public image ", func() {
  41. TestReplicationControllerServeImageOrFail(f, "basic", framework.ServeHostnameImage)
  42. })
  43. ginkgo.It("should serve a basic image on each replica with a private image", func() {
  44. // requires private images
  45. e2eskipper.SkipUnlessProviderIs("gce", "gke")
  46. privateimage := imageutils.GetConfig(imageutils.AgnhostPrivate)
  47. TestReplicationControllerServeImageOrFail(f, "private", privateimage.GetE2EImage())
  48. })
  49. /*
  50. Release : v1.15
  51. Testname: Replication Controller, check for issues like exceeding allocated quota
  52. Description: Attempt to create a Replication Controller with pods exceeding the namespace quota. The creation MUST fail
  53. */
  54. framework.ConformanceIt("should surface a failure condition on a common issue like exceeded quota", func() {
  55. testReplicationControllerConditionCheck(f)
  56. })
  57. /*
  58. Release : v1.13
  59. Testname: Replication Controller, adopt matching pods
  60. Description: An ownerless Pod is created, then a Replication Controller (RC) is created whose label selector will match the Pod. The RC MUST either adopt the Pod or delete and replace it with a new Pod
  61. */
  62. framework.ConformanceIt("should adopt matching pods on creation", func() {
  63. testRCAdoptMatchingOrphans(f)
  64. })
  65. /*
  66. Release : v1.13
  67. Testname: Replication Controller, release pods
  68. Description: A Replication Controller (RC) is created, and its Pods are created. When the labels on one of the Pods change to no longer match the RC's label selector, the RC MUST release the Pod and update the Pod's owner references.
  69. */
  70. framework.ConformanceIt("should release no longer matching pods", func() {
  71. testRCReleaseControlledNotMatching(f)
  72. })
  73. })
  74. func newRC(rsName string, replicas int32, rcPodLabels map[string]string, imageName string, image string, args []string) *v1.ReplicationController {
  75. zero := int64(0)
  76. return &v1.ReplicationController{
  77. ObjectMeta: metav1.ObjectMeta{
  78. Name: rsName,
  79. },
  80. Spec: v1.ReplicationControllerSpec{
  81. Replicas: func(i int32) *int32 { return &i }(replicas),
  82. Template: &v1.PodTemplateSpec{
  83. ObjectMeta: metav1.ObjectMeta{
  84. Labels: rcPodLabels,
  85. },
  86. Spec: v1.PodSpec{
  87. TerminationGracePeriodSeconds: &zero,
  88. Containers: []v1.Container{
  89. {
  90. Name: imageName,
  91. Image: image,
  92. Args: args,
  93. },
  94. },
  95. },
  96. },
  97. },
  98. }
  99. }
  100. // TestReplicationControllerServeImageOrFail is a basic test to check
  101. // the deployment of an image using a replication controller.
  102. // The image serves its hostname which is checked for each replica.
  103. func TestReplicationControllerServeImageOrFail(f *framework.Framework, test string, image string) {
  104. name := "my-hostname-" + test + "-" + string(uuid.NewUUID())
  105. replicas := int32(1)
  106. // Create a replication controller for a service
  107. // that serves its hostname.
  108. // The source for the Docker container kubernetes/serve_hostname is
  109. // in contrib/for-demos/serve_hostname
  110. ginkgo.By(fmt.Sprintf("Creating replication controller %s", name))
  111. newRC := newRC(name, replicas, map[string]string{"name": name}, name, image, []string{"serve-hostname"})
  112. newRC.Spec.Template.Spec.Containers[0].Ports = []v1.ContainerPort{{ContainerPort: 9376}}
  113. _, err := f.ClientSet.CoreV1().ReplicationControllers(f.Namespace.Name).Create(context.TODO(), newRC, metav1.CreateOptions{})
  114. framework.ExpectNoError(err)
  115. // Check that pods for the new RC were created.
  116. // TODO: Maybe switch PodsCreated to just check owner references.
  117. pods, err := e2epod.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. framework.Logf("Ensuring all pods for ReplicationController %q are 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(context.TODO(), 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. framework.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. framework.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, e2epod.NewProxyResponseChecker(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 replication controller that wants to run 3 pods.
  156. // 3. Check replication controller conditions for a ReplicaFailure condition.
  157. // 4. Relax quota or scale down the controller and observe the condition is gone.
  158. func testReplicationControllerConditionCheck(f *framework.Framework) {
  159. c := f.ClientSet
  160. namespace := f.Namespace.Name
  161. name := "condition-test"
  162. framework.Logf("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(context.TODO(), quota, metav1.CreateOptions{})
  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(context.TODO(), name, metav1.GetOptions{})
  168. if err != nil {
  169. return false, err
  170. }
  171. podQuota := quota.Status.Hard[v1.ResourcePods]
  172. quantity := resource.MustParse("2")
  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 rc %q that asks for more than the allowed pod quota", name))
  180. rc := newRC(name, 3, map[string]string{"name": name}, WebserverImageName, WebserverImage, nil)
  181. rc, err = c.CoreV1().ReplicationControllers(namespace).Create(context.TODO(), rc, metav1.CreateOptions{})
  182. framework.ExpectNoError(err)
  183. ginkgo.By(fmt.Sprintf("Checking rc %q has the desired failure condition set", name))
  184. generation := rc.Generation
  185. conditions := rc.Status.Conditions
  186. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  187. rc, err = c.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  188. if err != nil {
  189. return false, err
  190. }
  191. if generation > rc.Status.ObservedGeneration {
  192. return false, nil
  193. }
  194. conditions = rc.Status.Conditions
  195. cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure)
  196. return cond != nil, nil
  197. })
  198. if err == wait.ErrWaitTimeout {
  199. err = fmt.Errorf("rc manager never added the failure condition for rc %q: %#v", name, conditions)
  200. }
  201. framework.ExpectNoError(err)
  202. ginkgo.By(fmt.Sprintf("Scaling down rc %q to satisfy pod quota", name))
  203. rc, err = updateReplicationControllerWithRetries(c, namespace, name, func(update *v1.ReplicationController) {
  204. x := int32(2)
  205. update.Spec.Replicas = &x
  206. })
  207. framework.ExpectNoError(err)
  208. ginkgo.By(fmt.Sprintf("Checking rc %q has no failure condition set", name))
  209. generation = rc.Generation
  210. conditions = rc.Status.Conditions
  211. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  212. rc, err = c.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), name, metav1.GetOptions{})
  213. if err != nil {
  214. return false, err
  215. }
  216. if generation > rc.Status.ObservedGeneration {
  217. return false, nil
  218. }
  219. conditions = rc.Status.Conditions
  220. cond := replication.GetCondition(rc.Status, v1.ReplicationControllerReplicaFailure)
  221. return cond == nil, nil
  222. })
  223. if err == wait.ErrWaitTimeout {
  224. err = fmt.Errorf("rc manager never removed the failure condition for rc %q: %#v", name, conditions)
  225. }
  226. framework.ExpectNoError(err)
  227. }
  228. func testRCAdoptMatchingOrphans(f *framework.Framework) {
  229. name := "pod-adoption"
  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: WebserverImage,
  243. },
  244. },
  245. },
  246. })
  247. ginkgo.By("When a replication controller with a matching selector is created")
  248. replicas := int32(1)
  249. rcSt := newRC(name, replicas, map[string]string{"name": name}, name, WebserverImage, nil)
  250. rcSt.Spec.Selector = map[string]string{"name": name}
  251. rc, err := f.ClientSet.CoreV1().ReplicationControllers(f.Namespace.Name).Create(context.TODO(), rcSt, metav1.CreateOptions{})
  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(context.TODO(), p.Name, metav1.GetOptions{})
  256. // The Pod p should either be adopted or deleted by the RC
  257. if apierrors.IsNotFound(err) {
  258. return true, nil
  259. }
  260. framework.ExpectNoError(err)
  261. for _, owner := range p2.OwnerReferences {
  262. if *owner.Controller && owner.UID == rc.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. }
  272. func testRCReleaseControlledNotMatching(f *framework.Framework) {
  273. name := "pod-release"
  274. ginkgo.By("Given a ReplicationController is created")
  275. replicas := int32(1)
  276. rcSt := newRC(name, replicas, map[string]string{"name": name}, name, WebserverImage, nil)
  277. rcSt.Spec.Selector = map[string]string{"name": name}
  278. rc, err := f.ClientSet.CoreV1().ReplicationControllers(f.Namespace.Name).Create(context.TODO(), rcSt, metav1.CreateOptions{})
  279. framework.ExpectNoError(err)
  280. ginkgo.By("When the matched label of one of its pods change")
  281. pods, err := e2epod.PodsCreated(f.ClientSet, f.Namespace.Name, rc.Name, replicas)
  282. framework.ExpectNoError(err)
  283. p := pods.Items[0]
  284. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  285. pod, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), p.Name, metav1.GetOptions{})
  286. framework.ExpectNoError(err)
  287. pod.Labels = map[string]string{"name": "not-matching-name"}
  288. _, err = f.ClientSet.CoreV1().Pods(f.Namespace.Name).Update(context.TODO(), pod, metav1.UpdateOptions{})
  289. if err != nil && apierrors.IsConflict(err) {
  290. return false, nil
  291. }
  292. if err != nil {
  293. return false, err
  294. }
  295. return true, nil
  296. })
  297. framework.ExpectNoError(err)
  298. ginkgo.By("Then the pod is released")
  299. err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
  300. p2, err := f.ClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), p.Name, metav1.GetOptions{})
  301. framework.ExpectNoError(err)
  302. for _, owner := range p2.OwnerReferences {
  303. if *owner.Controller && owner.UID == rc.UID {
  304. // pod still belonging to the replication controller
  305. return false, nil
  306. }
  307. }
  308. // pod already released
  309. return true, nil
  310. })
  311. framework.ExpectNoError(err)
  312. }
  313. type updateRcFunc func(d *v1.ReplicationController)
  314. // updateReplicationControllerWithRetries retries updating the given rc on conflict with the following steps:
  315. // 1. Get latest resource
  316. // 2. applyUpdate
  317. // 3. Update the resource
  318. func updateReplicationControllerWithRetries(c clientset.Interface, namespace, name string, applyUpdate updateRcFunc) (*v1.ReplicationController, error) {
  319. var rc *v1.ReplicationController
  320. var updateErr error
  321. pollErr := wait.PollImmediate(10*time.Millisecond, 1*time.Minute, func() (bool, error) {
  322. var err error
  323. if rc, err = c.CoreV1().ReplicationControllers(namespace).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
  324. return false, err
  325. }
  326. // Apply the update, then attempt to push it to the apiserver.
  327. applyUpdate(rc)
  328. if rc, err = c.CoreV1().ReplicationControllers(namespace).Update(context.TODO(), rc, metav1.UpdateOptions{}); err == nil {
  329. framework.Logf("Updating replication controller %q", name)
  330. return true, nil
  331. }
  332. updateErr = err
  333. return false, nil
  334. })
  335. if pollErr == wait.ErrWaitTimeout {
  336. pollErr = fmt.Errorf("couldn't apply the provided updated to rc %q: %v", name, updateErr)
  337. }
  338. return rc, pollErr
  339. }