init_container.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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 common
  14. import (
  15. "context"
  16. "fmt"
  17. "strconv"
  18. "strings"
  19. "time"
  20. v1 "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/api/resource"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/runtime"
  24. "k8s.io/apimachinery/pkg/util/sets"
  25. "k8s.io/apimachinery/pkg/util/uuid"
  26. "k8s.io/apimachinery/pkg/watch"
  27. watchtools "k8s.io/client-go/tools/watch"
  28. podutil "k8s.io/kubernetes/pkg/api/v1/pod"
  29. "k8s.io/kubernetes/pkg/client/conditions"
  30. "k8s.io/kubernetes/test/e2e/framework"
  31. imageutils "k8s.io/kubernetes/test/utils/image"
  32. "github.com/onsi/ginkgo"
  33. "github.com/onsi/gomega"
  34. )
  35. // invariantFunc is a func that checks for invariant.
  36. type invariantFunc func(older, newer runtime.Object) error
  37. // checkInvariants checks for invariant of the each events.
  38. func checkInvariants(events []watch.Event, fns ...invariantFunc) error {
  39. errs := sets.NewString()
  40. for i := range events {
  41. j := i + 1
  42. if j >= len(events) {
  43. continue
  44. }
  45. for _, fn := range fns {
  46. if err := fn(events[i].Object, events[j].Object); err != nil {
  47. errs.Insert(err.Error())
  48. }
  49. }
  50. }
  51. if errs.Len() > 0 {
  52. return fmt.Errorf("invariants violated:\n* %s", strings.Join(errs.List(), "\n* "))
  53. }
  54. return nil
  55. }
  56. // containerInitInvariant checks for an init containers are initialized and invariant on both older and newer.
  57. func containerInitInvariant(older, newer runtime.Object) error {
  58. oldPod := older.(*v1.Pod)
  59. newPod := newer.(*v1.Pod)
  60. if len(oldPod.Spec.InitContainers) == 0 {
  61. return nil
  62. }
  63. if len(oldPod.Spec.InitContainers) != len(newPod.Spec.InitContainers) {
  64. return fmt.Errorf("init container list changed")
  65. }
  66. if oldPod.UID != newPod.UID {
  67. return fmt.Errorf("two different pods exist in the condition: %s vs %s", oldPod.UID, newPod.UID)
  68. }
  69. if err := initContainersInvariants(oldPod); err != nil {
  70. return err
  71. }
  72. if err := initContainersInvariants(newPod); err != nil {
  73. return err
  74. }
  75. oldInit, _, _ := initialized(oldPod)
  76. newInit, _, _ := initialized(newPod)
  77. if oldInit && !newInit {
  78. // TODO: we may in the future enable resetting initialized = false if the kubelet needs to restart it
  79. // from scratch
  80. return fmt.Errorf("pod cannot be initialized and then regress to not being initialized")
  81. }
  82. return nil
  83. }
  84. // initialized checks the state of all init containers in the pod.
  85. func initialized(pod *v1.Pod) (ok bool, failed bool, err error) {
  86. allInit := true
  87. initFailed := false
  88. for _, s := range pod.Status.InitContainerStatuses {
  89. switch {
  90. case initFailed && s.State.Waiting == nil:
  91. return allInit, initFailed, fmt.Errorf("container %s is after a failed container but isn't waiting", s.Name)
  92. case allInit && s.State.Waiting == nil:
  93. return allInit, initFailed, fmt.Errorf("container %s is after an initializing container but isn't waiting", s.Name)
  94. case s.State.Terminated == nil:
  95. allInit = false
  96. case s.State.Terminated.ExitCode != 0:
  97. allInit = false
  98. initFailed = true
  99. case !s.Ready:
  100. return allInit, initFailed, fmt.Errorf("container %s initialized but isn't marked as ready", s.Name)
  101. }
  102. }
  103. return allInit, initFailed, nil
  104. }
  105. func initContainersInvariants(pod *v1.Pod) error {
  106. allInit, initFailed, err := initialized(pod)
  107. if err != nil {
  108. return err
  109. }
  110. if !allInit || initFailed {
  111. for _, s := range pod.Status.ContainerStatuses {
  112. if s.State.Waiting == nil || s.RestartCount != 0 {
  113. return fmt.Errorf("container %s is not waiting but initialization not complete", s.Name)
  114. }
  115. if s.State.Waiting.Reason != "PodInitializing" {
  116. return fmt.Errorf("container %s should have reason PodInitializing: %s", s.Name, s.State.Waiting.Reason)
  117. }
  118. }
  119. }
  120. _, c := podutil.GetPodCondition(&pod.Status, v1.PodInitialized)
  121. if c == nil {
  122. return fmt.Errorf("pod does not have initialized condition")
  123. }
  124. if c.LastTransitionTime.IsZero() {
  125. return fmt.Errorf("PodInitialized condition should always have a transition time")
  126. }
  127. switch {
  128. case c.Status == v1.ConditionUnknown:
  129. return fmt.Errorf("PodInitialized condition should never be Unknown")
  130. case c.Status == v1.ConditionTrue && (initFailed || !allInit):
  131. return fmt.Errorf("PodInitialized condition was True but all not all containers initialized")
  132. case c.Status == v1.ConditionFalse && (!initFailed && allInit):
  133. return fmt.Errorf("PodInitialized condition was False but all containers initialized")
  134. }
  135. return nil
  136. }
  137. var _ = framework.KubeDescribe("InitContainer [NodeConformance]", func() {
  138. f := framework.NewDefaultFramework("init-container")
  139. var podClient *framework.PodClient
  140. ginkgo.BeforeEach(func() {
  141. podClient = f.PodClient()
  142. })
  143. /*
  144. Release: v1.12
  145. Testname: init-container-starts-app-restartnever-pod
  146. Description: Ensure that all InitContainers are started
  147. and all containers in pod are voluntarily terminated with exit status 0,
  148. and the system is not going to restart any of these containers
  149. when Pod has restart policy as RestartNever.
  150. */
  151. framework.ConformanceIt("should invoke init containers on a RestartNever pod", func() {
  152. ginkgo.By("creating the pod")
  153. name := "pod-init-" + string(uuid.NewUUID())
  154. value := strconv.Itoa(time.Now().Nanosecond())
  155. pod := &v1.Pod{
  156. ObjectMeta: metav1.ObjectMeta{
  157. Name: name,
  158. Labels: map[string]string{
  159. "name": "foo",
  160. "time": value,
  161. },
  162. },
  163. Spec: v1.PodSpec{
  164. RestartPolicy: v1.RestartPolicyNever,
  165. InitContainers: []v1.Container{
  166. {
  167. Name: "init1",
  168. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  169. Command: []string{"/bin/true"},
  170. },
  171. {
  172. Name: "init2",
  173. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  174. Command: []string{"/bin/true"},
  175. },
  176. },
  177. Containers: []v1.Container{
  178. {
  179. Name: "run1",
  180. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  181. Command: []string{"/bin/true"},
  182. },
  183. },
  184. },
  185. }
  186. framework.Logf("PodSpec: initContainers in spec.initContainers")
  187. startedPod := podClient.Create(pod)
  188. w, err := podClient.Watch(context.TODO(), metav1.SingleObject(startedPod.ObjectMeta))
  189. framework.ExpectNoError(err, "error watching a pod")
  190. wr := watch.NewRecorder(w)
  191. ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), framework.PodStartTimeout)
  192. defer cancel()
  193. event, err := watchtools.UntilWithoutRetry(ctx, wr, conditions.PodCompleted)
  194. gomega.Expect(err).To(gomega.BeNil())
  195. checkInvariants(wr.Events(), containerInitInvariant)
  196. endPod := event.Object.(*v1.Pod)
  197. framework.ExpectEqual(endPod.Status.Phase, v1.PodSucceeded)
  198. _, init := podutil.GetPodCondition(&endPod.Status, v1.PodInitialized)
  199. gomega.Expect(init).NotTo(gomega.BeNil())
  200. framework.ExpectEqual(init.Status, v1.ConditionTrue)
  201. framework.ExpectEqual(len(endPod.Status.InitContainerStatuses), 2)
  202. for _, status := range endPod.Status.InitContainerStatuses {
  203. framework.ExpectEqual(status.Ready, true)
  204. gomega.Expect(status.State.Terminated).NotTo(gomega.BeNil())
  205. gomega.Expect(status.State.Terminated.ExitCode).To(gomega.BeZero())
  206. }
  207. })
  208. /*
  209. Release: v1.12
  210. Testname: init-container-starts-app-restartalways-pod
  211. Description: Ensure that all InitContainers are started
  212. and all containers in pod started
  213. and at least one container is still running or is in the process of being restarted
  214. when Pod has restart policy as RestartAlways.
  215. */
  216. framework.ConformanceIt("should invoke init containers on a RestartAlways pod", func() {
  217. ginkgo.By("creating the pod")
  218. name := "pod-init-" + string(uuid.NewUUID())
  219. value := strconv.Itoa(time.Now().Nanosecond())
  220. pod := &v1.Pod{
  221. ObjectMeta: metav1.ObjectMeta{
  222. Name: name,
  223. Labels: map[string]string{
  224. "name": "foo",
  225. "time": value,
  226. },
  227. },
  228. Spec: v1.PodSpec{
  229. InitContainers: []v1.Container{
  230. {
  231. Name: "init1",
  232. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  233. Command: []string{"/bin/true"},
  234. },
  235. {
  236. Name: "init2",
  237. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  238. Command: []string{"/bin/true"},
  239. },
  240. },
  241. Containers: []v1.Container{
  242. {
  243. Name: "run1",
  244. Image: imageutils.GetPauseImageName(),
  245. Resources: v1.ResourceRequirements{
  246. Limits: v1.ResourceList{
  247. v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
  248. },
  249. },
  250. },
  251. },
  252. },
  253. }
  254. framework.Logf("PodSpec: initContainers in spec.initContainers")
  255. startedPod := podClient.Create(pod)
  256. w, err := podClient.Watch(context.TODO(), metav1.SingleObject(startedPod.ObjectMeta))
  257. framework.ExpectNoError(err, "error watching a pod")
  258. wr := watch.NewRecorder(w)
  259. ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), framework.PodStartTimeout)
  260. defer cancel()
  261. event, err := watchtools.UntilWithoutRetry(ctx, wr, conditions.PodRunning)
  262. gomega.Expect(err).To(gomega.BeNil())
  263. checkInvariants(wr.Events(), containerInitInvariant)
  264. endPod := event.Object.(*v1.Pod)
  265. framework.ExpectEqual(endPod.Status.Phase, v1.PodRunning)
  266. _, init := podutil.GetPodCondition(&endPod.Status, v1.PodInitialized)
  267. gomega.Expect(init).NotTo(gomega.BeNil())
  268. framework.ExpectEqual(init.Status, v1.ConditionTrue)
  269. framework.ExpectEqual(len(endPod.Status.InitContainerStatuses), 2)
  270. for _, status := range endPod.Status.InitContainerStatuses {
  271. framework.ExpectEqual(status.Ready, true)
  272. gomega.Expect(status.State.Terminated).NotTo(gomega.BeNil())
  273. gomega.Expect(status.State.Terminated.ExitCode).To(gomega.BeZero())
  274. }
  275. })
  276. /*
  277. Release: v1.12
  278. Testname: init-container-fails-stops-app-restartalways-pod
  279. Description: Ensure that app container is not started
  280. when all InitContainers failed to start
  281. and Pod has restarted for few occurrences
  282. and pod has restart policy as RestartAlways.
  283. */
  284. framework.ConformanceIt("should not start app containers if init containers fail on a RestartAlways pod", func() {
  285. ginkgo.By("creating the pod")
  286. name := "pod-init-" + string(uuid.NewUUID())
  287. value := strconv.Itoa(time.Now().Nanosecond())
  288. pod := &v1.Pod{
  289. ObjectMeta: metav1.ObjectMeta{
  290. Name: name,
  291. Labels: map[string]string{
  292. "name": "foo",
  293. "time": value,
  294. },
  295. },
  296. Spec: v1.PodSpec{
  297. InitContainers: []v1.Container{
  298. {
  299. Name: "init1",
  300. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  301. Command: []string{"/bin/false"},
  302. },
  303. {
  304. Name: "init2",
  305. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  306. Command: []string{"/bin/true"},
  307. },
  308. },
  309. Containers: []v1.Container{
  310. {
  311. Name: "run1",
  312. Image: imageutils.GetPauseImageName(),
  313. Resources: v1.ResourceRequirements{
  314. Limits: v1.ResourceList{
  315. v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
  316. },
  317. },
  318. },
  319. },
  320. },
  321. }
  322. framework.Logf("PodSpec: initContainers in spec.initContainers")
  323. startedPod := podClient.Create(pod)
  324. w, err := podClient.Watch(context.TODO(), metav1.SingleObject(startedPod.ObjectMeta))
  325. framework.ExpectNoError(err, "error watching a pod")
  326. wr := watch.NewRecorder(w)
  327. ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), framework.PodStartTimeout)
  328. defer cancel()
  329. event, err := watchtools.UntilWithoutRetry(
  330. ctx, wr,
  331. // check for the first container to fail at least once
  332. func(evt watch.Event) (bool, error) {
  333. switch t := evt.Object.(type) {
  334. case *v1.Pod:
  335. for _, status := range t.Status.ContainerStatuses {
  336. if status.State.Waiting == nil {
  337. return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status)
  338. }
  339. if status.State.Waiting.Reason != "PodInitializing" {
  340. return false, fmt.Errorf("container %q should have reason PodInitializing: %#v", status.Name, status)
  341. }
  342. }
  343. if len(t.Status.InitContainerStatuses) != 2 {
  344. return false, nil
  345. }
  346. status := t.Status.InitContainerStatuses[1]
  347. if status.State.Waiting == nil {
  348. return false, fmt.Errorf("second init container should not be out of waiting: %#v", status)
  349. }
  350. if status.State.Waiting.Reason != "PodInitializing" {
  351. return false, fmt.Errorf("second init container should have reason PodInitializing: %#v", status)
  352. }
  353. status = t.Status.InitContainerStatuses[0]
  354. if status.State.Terminated != nil && status.State.Terminated.ExitCode == 0 {
  355. return false, fmt.Errorf("first init container should have exitCode != 0: %#v", status)
  356. }
  357. // continue until we see an attempt to restart the pod
  358. return status.LastTerminationState.Terminated != nil, nil
  359. default:
  360. return false, fmt.Errorf("unexpected object: %#v", t)
  361. }
  362. },
  363. // verify we get two restarts
  364. func(evt watch.Event) (bool, error) {
  365. switch t := evt.Object.(type) {
  366. case *v1.Pod:
  367. status := t.Status.InitContainerStatuses[0]
  368. if status.RestartCount < 3 {
  369. return false, nil
  370. }
  371. framework.Logf("init container has failed twice: %#v", t)
  372. // TODO: more conditions
  373. return true, nil
  374. default:
  375. return false, fmt.Errorf("unexpected object: %#v", t)
  376. }
  377. },
  378. )
  379. gomega.Expect(err).To(gomega.BeNil())
  380. checkInvariants(wr.Events(), containerInitInvariant)
  381. endPod := event.Object.(*v1.Pod)
  382. framework.ExpectEqual(endPod.Status.Phase, v1.PodPending)
  383. _, init := podutil.GetPodCondition(&endPod.Status, v1.PodInitialized)
  384. gomega.Expect(init).NotTo(gomega.BeNil())
  385. framework.ExpectEqual(init.Status, v1.ConditionFalse)
  386. framework.ExpectEqual(init.Reason, "ContainersNotInitialized")
  387. framework.ExpectEqual(init.Message, "containers with incomplete status: [init1 init2]")
  388. framework.ExpectEqual(len(endPod.Status.InitContainerStatuses), 2)
  389. })
  390. /*
  391. Release: v1.12
  392. Testname: init-container-fails-stops-app-restartnever-pod
  393. Description: Ensure that app container is not started
  394. when at least one InitContainer fails to start and Pod has restart policy as RestartNever.
  395. */
  396. framework.ConformanceIt("should not start app containers and fail the pod if init containers fail on a RestartNever pod", func() {
  397. ginkgo.By("creating the pod")
  398. name := "pod-init-" + string(uuid.NewUUID())
  399. value := strconv.Itoa(time.Now().Nanosecond())
  400. pod := &v1.Pod{
  401. ObjectMeta: metav1.ObjectMeta{
  402. Name: name,
  403. Labels: map[string]string{
  404. "name": "foo",
  405. "time": value,
  406. },
  407. },
  408. Spec: v1.PodSpec{
  409. RestartPolicy: v1.RestartPolicyNever,
  410. InitContainers: []v1.Container{
  411. {
  412. Name: "init1",
  413. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  414. Command: []string{"/bin/true"},
  415. },
  416. {
  417. Name: "init2",
  418. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  419. Command: []string{"/bin/false"},
  420. },
  421. },
  422. Containers: []v1.Container{
  423. {
  424. Name: "run1",
  425. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  426. Command: []string{"/bin/true"},
  427. Resources: v1.ResourceRequirements{
  428. Limits: v1.ResourceList{
  429. v1.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
  430. },
  431. },
  432. },
  433. },
  434. },
  435. }
  436. framework.Logf("PodSpec: initContainers in spec.initContainers")
  437. startedPod := podClient.Create(pod)
  438. w, err := podClient.Watch(context.TODO(), metav1.SingleObject(startedPod.ObjectMeta))
  439. framework.ExpectNoError(err, "error watching a pod")
  440. wr := watch.NewRecorder(w)
  441. ctx, cancel := watchtools.ContextWithOptionalTimeout(context.Background(), framework.PodStartTimeout)
  442. defer cancel()
  443. event, err := watchtools.UntilWithoutRetry(
  444. ctx, wr,
  445. // check for the second container to fail at least once
  446. func(evt watch.Event) (bool, error) {
  447. switch t := evt.Object.(type) {
  448. case *v1.Pod:
  449. for _, status := range t.Status.ContainerStatuses {
  450. if status.State.Waiting == nil {
  451. return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status)
  452. }
  453. if status.State.Waiting.Reason != "PodInitializing" {
  454. return false, fmt.Errorf("container %q should have reason PodInitializing: %#v", status.Name, status)
  455. }
  456. }
  457. if len(t.Status.InitContainerStatuses) != 2 {
  458. return false, nil
  459. }
  460. status := t.Status.InitContainerStatuses[0]
  461. if status.State.Terminated == nil {
  462. if status.State.Waiting != nil && status.State.Waiting.Reason != "PodInitializing" {
  463. return false, fmt.Errorf("second init container should have reason PodInitializing: %#v", status)
  464. }
  465. return false, nil
  466. }
  467. if status.State.Terminated != nil && status.State.Terminated.ExitCode != 0 {
  468. return false, fmt.Errorf("first init container should have exitCode != 0: %#v", status)
  469. }
  470. status = t.Status.InitContainerStatuses[1]
  471. if status.State.Terminated == nil {
  472. return false, nil
  473. }
  474. if status.State.Terminated.ExitCode == 0 {
  475. return false, fmt.Errorf("second init container should have failed: %#v", status)
  476. }
  477. return true, nil
  478. default:
  479. return false, fmt.Errorf("unexpected object: %#v", t)
  480. }
  481. },
  482. conditions.PodCompleted,
  483. )
  484. gomega.Expect(err).To(gomega.BeNil())
  485. checkInvariants(wr.Events(), containerInitInvariant)
  486. endPod := event.Object.(*v1.Pod)
  487. framework.ExpectEqual(endPod.Status.Phase, v1.PodFailed)
  488. _, init := podutil.GetPodCondition(&endPod.Status, v1.PodInitialized)
  489. gomega.Expect(init).NotTo(gomega.BeNil())
  490. framework.ExpectEqual(init.Status, v1.ConditionFalse)
  491. framework.ExpectEqual(init.Reason, "ContainersNotInitialized")
  492. framework.ExpectEqual(init.Message, "containers with incomplete status: [init2]")
  493. framework.ExpectEqual(len(endPod.Status.InitContainerStatuses), 2)
  494. gomega.Expect(endPod.Status.ContainerStatuses[0].State.Waiting).ToNot(gomega.BeNil())
  495. })
  496. })