forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pods.go
1603 lines (1471 loc) · 49.6 KB
/
pods.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package e2e
import (
"bytes"
"fmt"
"io"
"strconv"
"strings"
"time"
"golang.org/x/net/websocket"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/resource"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/kubelet"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/intstr"
"k8s.io/kubernetes/pkg/util/wait"
"k8s.io/kubernetes/pkg/watch"
"k8s.io/kubernetes/test/e2e/framework"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
const (
defaultObservationTimeout = time.Minute * 2
)
var (
buildBackOffDuration = time.Minute
syncLoopFrequency = 10 * time.Second
maxBackOffTolerance = time.Duration(1.3 * float64(kubelet.MaxContainerBackOff))
)
func runLivenessTest(c *client.Client, ns string, podDescr *api.Pod, expectNumRestarts int, timeout time.Duration) {
By(fmt.Sprintf("Creating pod %s in namespace %s", podDescr.Name, ns))
_, err := c.Pods(ns).Create(podDescr)
framework.ExpectNoError(err, fmt.Sprintf("creating pod %s", podDescr.Name))
// At the end of the test, clean up by removing the pod.
defer func() {
By("deleting the pod")
c.Pods(ns).Delete(podDescr.Name, api.NewDeleteOptions(0))
}()
// Wait until the pod is not pending. (Here we need to check for something other than
// 'Pending' other than checking for 'Running', since when failures occur, we go to
// 'Terminated' which can cause indefinite blocking.)
framework.ExpectNoError(framework.WaitForPodNotPending(c, ns, podDescr.Name),
fmt.Sprintf("starting pod %s in namespace %s", podDescr.Name, ns))
framework.Logf("Started pod %s in namespace %s", podDescr.Name, ns)
// Check the pod's current state and verify that restartCount is present.
By("checking the pod's current state and verifying that restartCount is present")
pod, err := c.Pods(ns).Get(podDescr.Name)
framework.ExpectNoError(err, fmt.Sprintf("getting pod %s in namespace %s", podDescr.Name, ns))
initialRestartCount := api.GetExistingContainerStatus(pod.Status.ContainerStatuses, "liveness").RestartCount
framework.Logf("Initial restart count of pod %s is %d", podDescr.Name, initialRestartCount)
// Wait for the restart state to be as desired.
deadline := time.Now().Add(timeout)
lastRestartCount := initialRestartCount
observedRestarts := int32(0)
for start := time.Now(); time.Now().Before(deadline); time.Sleep(2 * time.Second) {
pod, err = c.Pods(ns).Get(podDescr.Name)
framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", podDescr.Name))
restartCount := api.GetExistingContainerStatus(pod.Status.ContainerStatuses, "liveness").RestartCount
if restartCount != lastRestartCount {
framework.Logf("Restart count of pod %s/%s is now %d (%v elapsed)",
ns, podDescr.Name, restartCount, time.Since(start))
if restartCount < lastRestartCount {
framework.Failf("Restart count should increment monotonically: restart cont of pod %s/%s changed from %d to %d",
ns, podDescr.Name, lastRestartCount, restartCount)
}
}
observedRestarts = restartCount - initialRestartCount
if expectNumRestarts > 0 && int(observedRestarts) >= expectNumRestarts {
// Stop if we have observed more than expectNumRestarts restarts.
break
}
lastRestartCount = restartCount
}
// If we expected 0 restarts, fail if observed any restart.
// If we expected n restarts (n > 0), fail if we observed < n restarts.
if (expectNumRestarts == 0 && observedRestarts > 0) || (expectNumRestarts > 0 &&
int(observedRestarts) < expectNumRestarts) {
framework.Failf("pod %s/%s - expected number of restarts: %t, found restarts: %t",
ns, podDescr.Name, expectNumRestarts, observedRestarts)
}
}
// testHostIP tests that a pod gets a host IP
func testHostIP(c *client.Client, ns string, pod *api.Pod) {
podClient := c.Pods(ns)
By("creating pod")
defer podClient.Delete(pod.Name, api.NewDeleteOptions(0))
if _, err := podClient.Create(pod); err != nil {
framework.Failf("Failed to create pod: %v", err)
}
By("ensuring that pod is running and has a hostIP")
// Wait for the pods to enter the running state. Waiting loops until the pods
// are running so non-running pods cause a timeout for this test.
err := framework.WaitForPodRunningInNamespace(c, pod.Name, ns)
Expect(err).NotTo(HaveOccurred())
// Try to make sure we get a hostIP for each pod.
hostIPTimeout := 2 * time.Minute
t := time.Now()
for {
p, err := podClient.Get(pod.Name)
Expect(err).NotTo(HaveOccurred())
if p.Status.HostIP != "" {
framework.Logf("Pod %s has hostIP: %s", p.Name, p.Status.HostIP)
break
}
if time.Since(t) >= hostIPTimeout {
framework.Failf("Gave up waiting for hostIP of pod %s after %v seconds",
p.Name, time.Since(t).Seconds())
}
framework.Logf("Retrying to get the hostIP of pod %s", p.Name)
time.Sleep(5 * time.Second)
}
}
func runPodFromStruct(f *framework.Framework, pod *api.Pod) {
By("submitting the pod to kubernetes")
podClient := f.Client.Pods(f.Namespace.Name)
pod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Failed to create pod: %v", err)
}
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
By("verifying the pod is in kubernetes")
pod, err = podClient.Get(pod.Name)
if err != nil {
framework.Failf("failed to get pod: %v", err)
}
}
func startPodAndGetBackOffs(f *framework.Framework, pod *api.Pod, podName string, containerName string, sleepAmount time.Duration) (time.Duration, time.Duration) {
runPodFromStruct(f, pod)
time.Sleep(sleepAmount)
By("getting restart delay-0")
_, err := getRestartDelay(f.Client, pod, f.Namespace.Name, podName, containerName)
if err != nil {
framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
}
By("getting restart delay-1")
delay1, err := getRestartDelay(f.Client, pod, f.Namespace.Name, podName, containerName)
if err != nil {
framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
}
By("getting restart delay-2")
delay2, err := getRestartDelay(f.Client, pod, f.Namespace.Name, podName, containerName)
if err != nil {
framework.Failf("timed out waiting for container restart in pod=%s/%s", podName, containerName)
}
return delay1, delay2
}
func getRestartDelay(c *client.Client, pod *api.Pod, ns string, name string, containerName string) (time.Duration, error) {
beginTime := time.Now()
for time.Since(beginTime) < (2 * maxBackOffTolerance) { // may just miss the 1st MaxContainerBackOff delay
time.Sleep(time.Second)
pod, err := c.Pods(ns).Get(name)
framework.ExpectNoError(err, fmt.Sprintf("getting pod %s", name))
status, ok := api.GetContainerStatus(pod.Status.ContainerStatuses, containerName)
if !ok {
framework.Logf("getRestartDelay: status missing")
continue
}
if status.State.Waiting == nil && status.State.Running != nil && status.LastTerminationState.Terminated != nil && status.State.Running.StartedAt.Time.After(beginTime) {
startedAt := status.State.Running.StartedAt.Time
finishedAt := status.LastTerminationState.Terminated.FinishedAt.Time
framework.Logf("getRestartDelay: restartCount = %d, finishedAt=%s restartedAt=%s (%s)", status.RestartCount, finishedAt, startedAt, startedAt.Sub(finishedAt))
return startedAt.Sub(finishedAt), nil
}
}
return 0, fmt.Errorf("timeout getting pod restart delay")
}
var _ = framework.KubeDescribe("Pods", func() {
f := framework.NewDefaultFramework("pods")
It("should get a host IP [Conformance]", func() {
name := "pod-hostip-" + string(util.NewUUID())
testHostIP(f.Client, f.Namespace.Name, &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "test",
Image: framework.GetPauseImageName(f.Client),
},
},
},
})
})
It("should be schedule with cpu and memory limits [Conformance]", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-update-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "nginx",
Image: framework.GetPauseImageName(f.Client),
Resources: api.ResourceRequirements{
Limits: api.ResourceList{
api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
api.ResourceMemory: *resource.NewQuantity(10*1024*1024, resource.DecimalSI),
},
},
},
},
},
}
defer podClient.Delete(pod.Name, nil)
_, err := podClient.Create(pod)
if err != nil {
framework.Failf("Error creating a pod: %v", err)
}
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
})
It("should be submitted and removed [Conformance]", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-update-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "nginx",
Image: "gcr.io/google_containers/nginx:1.7.9",
Ports: []api.ContainerPort{{ContainerPort: 80}},
LivenessProbe: &api.Probe{
Handler: api.Handler{
HTTPGet: &api.HTTPGetAction{
Path: "/index.html",
Port: intstr.FromInt(8080),
},
},
InitialDelaySeconds: 30,
},
},
},
},
}
By("setting up watch")
selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options := api.ListOptions{LabelSelector: selector}
pods, err := podClient.List(options)
if err != nil {
framework.Failf("Failed to query for pods: %v", err)
}
Expect(len(pods.Items)).To(Equal(0))
options = api.ListOptions{
LabelSelector: selector,
ResourceVersion: pods.ListMeta.ResourceVersion,
}
w, err := podClient.Watch(options)
if err != nil {
framework.Failf("Failed to set up watch: %v", err)
}
By("submitting the pod to kubernetes")
// We call defer here in case there is a problem with
// the test so we can ensure that we clean up after
// ourselves
defer podClient.Delete(pod.Name, api.NewDeleteOptions(0))
_, err = podClient.Create(pod)
if err != nil {
framework.Failf("Failed to create pod: %v", err)
}
By("verifying the pod is in kubernetes")
selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options = api.ListOptions{LabelSelector: selector}
pods, err = podClient.List(options)
if err != nil {
framework.Failf("Failed to query for pods: %v", err)
}
Expect(len(pods.Items)).To(Equal(1))
By("verifying pod creation was observed")
select {
case event, _ := <-w.ResultChan():
if event.Type != watch.Added {
framework.Failf("Failed to observe pod creation: %v", event)
}
case <-time.After(framework.PodStartTimeout):
Fail("Timeout while waiting for pod creation")
}
// We need to wait for the pod to be scheduled, otherwise the deletion
// will be carried out immediately rather than gracefully.
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
By("deleting the pod gracefully")
if err := podClient.Delete(pod.Name, api.NewDeleteOptions(30)); err != nil {
framework.Failf("Failed to delete pod: %v", err)
}
By("verifying the kubelet observed the termination notice")
pod, err = podClient.Get(pod.Name)
Expect(wait.Poll(time.Second*5, time.Second*30, func() (bool, error) {
podList, err := framework.GetKubeletPods(f.Client, pod.Spec.NodeName)
if err != nil {
framework.Logf("Unable to retrieve kubelet pods for node %v: %v", pod.Spec.NodeName, err)
return false, nil
}
for _, kubeletPod := range podList.Items {
if pod.Name != kubeletPod.Name {
continue
}
if kubeletPod.ObjectMeta.DeletionTimestamp == nil {
framework.Logf("deletion has not yet been observed")
return false, nil
}
return true, nil
}
framework.Logf("no pod exists with the name we were looking for, assuming the termination request was observed and completed")
return true, nil
})).NotTo(HaveOccurred(), "kubelet never observed the termination notice")
By("verifying pod deletion was observed")
deleted := false
timeout := false
var lastPod *api.Pod
timer := time.After(30 * time.Second)
for !deleted && !timeout {
select {
case event, _ := <-w.ResultChan():
if event.Type == watch.Deleted {
lastPod = event.Object.(*api.Pod)
deleted = true
}
case <-timer:
timeout = true
}
}
if !deleted {
Fail("Failed to observe pod deletion")
}
Expect(lastPod.DeletionTimestamp).ToNot(BeNil())
Expect(lastPod.Spec.TerminationGracePeriodSeconds).ToNot(BeZero())
selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options = api.ListOptions{LabelSelector: selector}
pods, err = podClient.List(options)
if err != nil {
Fail(fmt.Sprintf("Failed to list pods to verify deletion: %v", err))
}
Expect(len(pods.Items)).To(Equal(0))
})
It("should be updated [Conformance]", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-update-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "nginx",
Image: "gcr.io/google_containers/nginx:1.7.9",
Ports: []api.ContainerPort{{ContainerPort: 80}},
LivenessProbe: &api.Probe{
Handler: api.Handler{
HTTPGet: &api.HTTPGetAction{
Path: "/index.html",
Port: intstr.FromInt(8080),
},
},
InitialDelaySeconds: 30,
},
},
},
},
}
By("submitting the pod to kubernetes")
defer func() {
By("deleting the pod")
podClient.Delete(pod.Name, api.NewDeleteOptions(0))
}()
pod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Failed to create pod: %v", err)
}
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
By("verifying the pod is in kubernetes")
selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options := api.ListOptions{LabelSelector: selector}
pods, err := podClient.List(options)
Expect(len(pods.Items)).To(Equal(1))
// Standard get, update retry loop
framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*30, func() (bool, error) {
By("updating the pod")
value = strconv.Itoa(time.Now().Nanosecond())
if pod == nil { // on retries we need to re-get
pod, err = podClient.Get(name)
if err != nil {
return false, fmt.Errorf("failed to get pod: %v", err)
}
}
pod.Labels["time"] = value
pod, err = podClient.Update(pod)
if err == nil {
framework.Logf("Successfully updated pod")
return true, nil
}
if errors.IsConflict(err) {
framework.Logf("Conflicting update to pod, re-get and re-update: %v", err)
pod = nil // re-get it when we retry
return false, nil
}
return false, fmt.Errorf("failed to update pod: %v", err)
}))
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
By("verifying the updated pod is in kubernetes")
selector = labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options = api.ListOptions{LabelSelector: selector}
pods, err = podClient.List(options)
Expect(len(pods.Items)).To(Equal(1))
framework.Logf("Pod update OK")
})
It("should allow activeDeadlineSeconds to be updated [Conformance]", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-update-activedeadlineseconds-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "nginx",
Image: "gcr.io/google_containers/nginx:1.7.9",
Ports: []api.ContainerPort{{ContainerPort: 80}},
LivenessProbe: &api.Probe{
Handler: api.Handler{
HTTPGet: &api.HTTPGetAction{
Path: "/index.html",
Port: intstr.FromInt(8080),
},
},
InitialDelaySeconds: 30,
},
},
},
},
}
By("submitting the pod to kubernetes")
defer func() {
By("deleting the pod")
podClient.Delete(pod.Name, api.NewDeleteOptions(0))
}()
pod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Failed to create pod: %v", err)
}
framework.ExpectNoError(f.WaitForPodRunning(pod.Name))
By("verifying the pod is in kubernetes")
selector := labels.SelectorFromSet(labels.Set(map[string]string{"time": value}))
options := api.ListOptions{LabelSelector: selector}
pods, err := podClient.List(options)
Expect(len(pods.Items)).To(Equal(1))
// Standard get, update retry loop
framework.ExpectNoError(wait.Poll(time.Millisecond*500, time.Second*30, func() (bool, error) {
By("updating the pod")
value = strconv.Itoa(time.Now().Nanosecond())
if pod == nil { // on retries we need to re-get
pod, err = podClient.Get(name)
if err != nil {
return false, fmt.Errorf("failed to get pod: %v", err)
}
}
newDeadline := int64(5)
pod.Spec.ActiveDeadlineSeconds = &newDeadline
pod, err = podClient.Update(pod)
if err == nil {
framework.Logf("Successfully updated pod")
return true, nil
}
if errors.IsConflict(err) {
framework.Logf("Conflicting update to pod, re-get and re-update: %v", err)
pod = nil // re-get it when we retry
return false, nil
}
return false, fmt.Errorf("failed to update pod: %v", err)
}))
framework.ExpectNoError(f.WaitForPodTerminated(pod.Name, "DeadlineExceeded"))
})
It("should contain environment variables for services [Conformance]", func() {
// Make a pod that will be a service.
// This pod serves its hostname via HTTP.
serverName := "server-envvars-" + string(util.NewUUID())
serverPod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: serverName,
Labels: map[string]string{"name": serverName},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "srv",
Image: "gcr.io/google_containers/serve_hostname:v1.4",
Ports: []api.ContainerPort{{ContainerPort: 9376}},
},
},
},
}
defer f.Client.Pods(f.Namespace.Name).Delete(serverPod.Name, api.NewDeleteOptions(0))
_, err := f.Client.Pods(f.Namespace.Name).Create(serverPod)
if err != nil {
framework.Failf("Failed to create serverPod: %v", err)
}
framework.ExpectNoError(f.WaitForPodRunning(serverPod.Name))
// This service exposes port 8080 of the test pod as a service on port 8765
// TODO(filbranden): We would like to use a unique service name such as:
// svcName := "svc-envvars-" + randomSuffix()
// However, that affects the name of the environment variables which are the capitalized
// service name, so that breaks this test. One possibility is to tweak the variable names
// to match the service. Another is to rethink environment variable names and possibly
// allow overriding the prefix in the service manifest.
svcName := "fooservice"
svc := &api.Service{
ObjectMeta: api.ObjectMeta{
Name: svcName,
Labels: map[string]string{
"name": svcName,
},
},
Spec: api.ServiceSpec{
Ports: []api.ServicePort{{
Port: 8765,
TargetPort: intstr.FromInt(8080),
}},
Selector: map[string]string{
"name": serverName,
},
},
}
defer f.Client.Services(f.Namespace.Name).Delete(svc.Name)
_, err = f.Client.Services(f.Namespace.Name).Create(svc)
if err != nil {
framework.Failf("Failed to create service: %v", err)
}
// Make a client pod that verifies that it has the service environment variables.
podName := "client-envvars-" + string(util.NewUUID())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: podName,
Labels: map[string]string{"name": podName},
},
Spec: api.PodSpec{
Containers: []api.Container{
{
Name: "env3cont",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"sh", "-c", "env"},
},
},
RestartPolicy: api.RestartPolicyNever,
},
}
f.TestContainerOutput("service env", pod, 0, []string{
"FOOSERVICE_SERVICE_HOST=",
"FOOSERVICE_SERVICE_PORT=",
"FOOSERVICE_PORT=",
"FOOSERVICE_PORT_8765_TCP_PORT=",
"FOOSERVICE_PORT_8765_TCP_PROTO=",
"FOOSERVICE_PORT_8765_TCP=",
"FOOSERVICE_PORT_8765_TCP_ADDR=",
})
})
It("should invoke init containers on a RestartNever pod", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-init-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyNever,
InitContainers: []api.Container{
{
Name: "init1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
{
Name: "init2",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
},
Containers: []api.Container{
{
Name: "run1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
},
},
}
defer podClient.Delete(pod.Name, nil)
startedPod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Error creating a pod: %v", err)
}
w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta))
if err != nil {
framework.Failf("Error watching a pod: %v", err)
}
wr := watch.NewRecorder(w)
event, err := watch.Until(framework.PodStartTimeout, wr, client.PodCompleted)
Expect(err).To(BeNil())
framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant)
endPod := event.Object.(*api.Pod)
Expect(endPod.Status.Phase).To(Equal(api.PodSucceeded))
_, init := api.GetPodCondition(&endPod.Status, api.PodInitialized)
Expect(init).NotTo(BeNil())
Expect(init.Status).To(Equal(api.ConditionTrue))
Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2))
for _, status := range endPod.Status.InitContainerStatuses {
Expect(status.Ready).To(BeTrue())
Expect(status.State.Terminated).NotTo(BeNil())
Expect(status.State.Terminated.ExitCode).To(BeZero())
}
})
It("should invoke init containers on a RestartAlways pod", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-init-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
InitContainers: []api.Container{
{
Name: "init1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
{
Name: "init2",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
},
Containers: []api.Container{
{
Name: "run1",
Image: framework.GetPauseImageName(f.Client),
Resources: api.ResourceRequirements{
Limits: api.ResourceList{
api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
api.ResourceMemory: *resource.NewQuantity(10*1024*1024, resource.DecimalSI),
},
},
},
},
},
}
defer podClient.Delete(pod.Name, nil)
startedPod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Error creating a pod: %v", err)
}
w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta))
if err != nil {
framework.Failf("Error watching a pod: %v", err)
}
wr := watch.NewRecorder(w)
event, err := watch.Until(framework.PodStartTimeout, wr, client.PodRunning)
Expect(err).To(BeNil())
framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant)
endPod := event.Object.(*api.Pod)
Expect(endPod.Status.Phase).To(Equal(api.PodRunning))
_, init := api.GetPodCondition(&endPod.Status, api.PodInitialized)
Expect(init).NotTo(BeNil())
Expect(init.Status).To(Equal(api.ConditionTrue))
Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2))
for _, status := range endPod.Status.InitContainerStatuses {
Expect(status.Ready).To(BeTrue())
Expect(status.State.Terminated).NotTo(BeNil())
Expect(status.State.Terminated.ExitCode).To(BeZero())
}
})
It("should not start app containers if init containers fail on a RestartAlways pod", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-init-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
InitContainers: []api.Container{
{
Name: "init1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/false"},
},
{
Name: "init2",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
},
Containers: []api.Container{
{
Name: "run1",
Image: framework.GetPauseImageName(f.Client),
Resources: api.ResourceRequirements{
Limits: api.ResourceList{
api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
api.ResourceMemory: *resource.NewQuantity(10*1024*1024, resource.DecimalSI),
},
},
},
},
},
}
defer podClient.Delete(pod.Name, nil)
startedPod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Error creating a pod: %v", err)
}
w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta))
if err != nil {
framework.Failf("Error watching a pod: %v", err)
}
wr := watch.NewRecorder(w)
event, err := watch.Until(
framework.PodStartTimeout, wr,
// check for the first container to fail at least once
func(evt watch.Event) (bool, error) {
switch t := evt.Object.(type) {
case *api.Pod:
for _, status := range t.Status.ContainerStatuses {
if status.State.Waiting == nil {
return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status)
}
if status.State.Waiting.Reason != "PodInitializing" {
return false, fmt.Errorf("container %q should have reason PodInitializing: %#v", status.Name, status)
}
}
if len(t.Status.InitContainerStatuses) != 2 {
return false, nil
}
status := t.Status.InitContainerStatuses[1]
if status.State.Waiting == nil {
return false, fmt.Errorf("second init container should not be out of waiting: %#v", status)
}
if status.State.Waiting.Reason != "PodInitializing" {
return false, fmt.Errorf("second init container should have reason PodInitializing: %#v", status)
}
status = t.Status.InitContainerStatuses[0]
if status.State.Terminated != nil && status.State.Terminated.ExitCode == 0 {
return false, fmt.Errorf("first init container should have exitCode != 0: %#v", status)
}
// continue until we see an attempt to restart the pod
return status.LastTerminationState.Terminated != nil, nil
default:
return false, fmt.Errorf("unexpected object: %#v", t)
}
},
// verify we get two restarts
func(evt watch.Event) (bool, error) {
switch t := evt.Object.(type) {
case *api.Pod:
status := t.Status.InitContainerStatuses[0]
if status.RestartCount < 3 {
return false, nil
}
framework.Logf("init container has failed twice: %#v", t)
// TODO: more conditions
return true, nil
default:
return false, fmt.Errorf("unexpected object: %#v", t)
}
},
)
Expect(err).To(BeNil())
framework.CheckInvariants(wr.Events(), framework.ContainerInitInvariant)
endPod := event.Object.(*api.Pod)
Expect(endPod.Status.Phase).To(Equal(api.PodPending))
_, init := api.GetPodCondition(&endPod.Status, api.PodInitialized)
Expect(init).NotTo(BeNil())
Expect(init.Status).To(Equal(api.ConditionFalse))
Expect(init.Reason).To(Equal("ContainersNotInitialized"))
Expect(init.Message).To(Equal("containers with incomplete status: [init1 init2]"))
Expect(len(endPod.Status.InitContainerStatuses)).To(Equal(2))
})
It("should not start app containers and fail the pod if init containers fail on a RestartNever pod", func() {
podClient := f.Client.Pods(f.Namespace.Name)
By("creating the pod")
name := "pod-init-" + string(util.NewUUID())
value := strconv.Itoa(time.Now().Nanosecond())
pod := &api.Pod{
ObjectMeta: api.ObjectMeta{
Name: name,
Labels: map[string]string{
"name": "foo",
"time": value,
},
},
Spec: api.PodSpec{
RestartPolicy: api.RestartPolicyNever,
InitContainers: []api.Container{
{
Name: "init1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
},
{
Name: "init2",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/false"},
},
},
Containers: []api.Container{
{
Name: "run1",
Image: "gcr.io/google_containers/busybox:1.24",
Command: []string{"/bin/true"},
Resources: api.ResourceRequirements{
Limits: api.ResourceList{
api.ResourceCPU: *resource.NewMilliQuantity(100, resource.DecimalSI),
api.ResourceMemory: *resource.NewQuantity(10*1024*1024, resource.DecimalSI),
},
},
},
},
},
}
defer podClient.Delete(pod.Name, nil)
startedPod, err := podClient.Create(pod)
if err != nil {
framework.Failf("Error creating a pod: %v", err)
}
w, err := podClient.Watch(api.SingleObject(startedPod.ObjectMeta))
if err != nil {
framework.Failf("Error watching a pod: %v", err)
}
wr := watch.NewRecorder(w)
event, err := watch.Until(
framework.PodStartTimeout, wr,
// check for the second container to fail at least once
func(evt watch.Event) (bool, error) {
switch t := evt.Object.(type) {
case *api.Pod:
for _, status := range t.Status.ContainerStatuses {
if status.State.Waiting == nil {
return false, fmt.Errorf("container %q should not be out of waiting: %#v", status.Name, status)
}
if status.State.Waiting.Reason != "PodInitializing" {
return false, fmt.Errorf("container %q should have reason PodInitializing: %#v", status.Name, status)
}
}
if len(t.Status.InitContainerStatuses) != 2 {
return false, nil
}
status := t.Status.InitContainerStatuses[0]
if status.State.Terminated == nil {
if status.State.Waiting != nil && status.State.Waiting.Reason != "PodInitializing" {
return false, fmt.Errorf("second init container should have reason PodInitializing: %#v", status)
}
return false, nil
}
if status.State.Terminated != nil && status.State.Terminated.ExitCode != 0 {
return false, fmt.Errorf("first init container should have exitCode != 0: %#v", status)
}
status = t.Status.InitContainerStatuses[1]
if status.State.Terminated == nil {
return false, nil
}
if status.State.Terminated.ExitCode == 0 {
return false, fmt.Errorf("second init container should have failed: %#v", status)
}
return true, nil
default: