-
Notifications
You must be signed in to change notification settings - Fork 39.7k
/
deployment.go
1688 lines (1504 loc) · 76.5 KB
/
deployment.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 2015 The Kubernetes Authors.
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 apps
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/onsi/ginkgo"
"github.com/onsi/gomega"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/tools/cache"
appsv1 "k8s.io/api/apps/v1"
autoscalingv1 "k8s.io/api/autoscaling/v1" //Added new
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
unstructuredv1 "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
appsclient "k8s.io/client-go/kubernetes/typed/apps/v1"
watchtools "k8s.io/client-go/tools/watch"
"k8s.io/client-go/util/retry"
appsinternal "k8s.io/kubernetes/pkg/apis/apps"
deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util"
"k8s.io/kubernetes/test/e2e/framework"
e2edeployment "k8s.io/kubernetes/test/e2e/framework/deployment"
e2enode "k8s.io/kubernetes/test/e2e/framework/node"
e2epod "k8s.io/kubernetes/test/e2e/framework/pod"
e2ereplicaset "k8s.io/kubernetes/test/e2e/framework/replicaset"
e2eresource "k8s.io/kubernetes/test/e2e/framework/resource"
e2eservice "k8s.io/kubernetes/test/e2e/framework/service"
e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
testutil "k8s.io/kubernetes/test/utils"
imageutils "k8s.io/kubernetes/test/utils/image"
utilpointer "k8s.io/utils/pointer"
)
const (
poll = 2 * time.Second
pollLongTimeout = 5 * time.Minute
dRetryPeriod = 2 * time.Second
dRetryTimeout = 5 * time.Minute
)
var (
nilRs *appsv1.ReplicaSet
)
var _ = SIGDescribe("Deployment", func() {
var ns string
var c clientset.Interface
var dc dynamic.Interface
ginkgo.AfterEach(func() {
failureTrap(c, ns)
})
f := framework.NewDefaultFramework("deployment")
ginkgo.BeforeEach(func() {
c = f.ClientSet
ns = f.Namespace.Name
dc = f.DynamicClient
})
ginkgo.It("deployment reaping should cascade to its replica sets and pods", func() {
testDeleteDeployment(f)
})
/*
Release: v1.12
Testname: Deployment RollingUpdate
Description: A conformant Kubernetes distribution MUST support the Deployment with RollingUpdate strategy.
*/
framework.ConformanceIt("RollingUpdateDeployment should delete old pods and create new ones", func() {
testRollingUpdateDeployment(f)
})
/*
Release: v1.12
Testname: Deployment Recreate
Description: A conformant Kubernetes distribution MUST support the Deployment with Recreate strategy.
*/
framework.ConformanceIt("RecreateDeployment should delete old pods and create new ones", func() {
testRecreateDeployment(f)
})
/*
Release: v1.12
Testname: Deployment RevisionHistoryLimit
Description: A conformant Kubernetes distribution MUST clean up Deployment's ReplicaSets based on
the Deployment's `.spec.revisionHistoryLimit`.
*/
framework.ConformanceIt("deployment should delete old replica sets", func() {
testDeploymentCleanUpPolicy(f)
})
/*
Release: v1.12
Testname: Deployment Rollover
Description: A conformant Kubernetes distribution MUST support Deployment rollover,
i.e. allow arbitrary number of changes to desired state during rolling update
before the rollout finishes.
*/
framework.ConformanceIt("deployment should support rollover", func() {
testRolloverDeployment(f)
})
ginkgo.It("iterative rollouts should eventually progress", func() {
testIterativeDeployments(f)
})
ginkgo.It("test Deployment ReplicaSet orphaning and adoption regarding controllerRef", func() {
testDeploymentsControllerRef(f)
})
/*
Release: v1.21
Testname: Deployment, completes the scaling of a Deployment subresource
Description: Create a Deployment with a single Pod. The Pod MUST be verified
that it is running. The Deployment MUST get and verify the scale subresource count.
The Deployment MUST update and verify the scale subresource. The Deployment MUST patch and verify
a scale subresource.
*/
framework.ConformanceIt("Deployment should have a working scale subresource", func() {
testDeploymentSubresources(f)
})
/*
Release: v1.12
Testname: Deployment Proportional Scaling
Description: A conformant Kubernetes distribution MUST support Deployment
proportional scaling, i.e. proportionally scale a Deployment's ReplicaSets
when a Deployment is scaled.
*/
framework.ConformanceIt("deployment should support proportional scaling", func() {
testProportionalScalingDeployment(f)
})
ginkgo.It("should not disrupt a cloud load-balancer's connectivity during rollout", func() {
e2eskipper.SkipUnlessProviderIs("aws", "azure", "gce", "gke")
nodes, err := e2enode.GetReadySchedulableNodes(c)
framework.ExpectNoError(err)
e2eskipper.SkipUnlessAtLeast(len(nodes.Items), 3, "load-balancer test requires at least 3 schedulable nodes")
testRollingUpdateDeploymentWithLocalTrafficLoadBalancer(f)
})
// TODO: add tests that cover deployment.Spec.MinReadySeconds once we solved clock-skew issues
// See https://github.com/kubernetes/kubernetes/issues/29229
// Add UnavailableReplicas check because ReadyReplicas or UpdatedReplicas might not represent
// the actual number of pods running successfully if some pods failed to start after update or patch.
// See issue ##100192
/*
Release: v1.20
Testname: Deployment, completes the lifecycle of a Deployment
Description: When a Deployment is created it MUST succeed with the required number of replicas.
It MUST succeed when the Deployment is patched. When scaling the deployment is MUST succeed.
When fetching and patching the DeploymentStatus it MUST succeed. It MUST succeed when deleting
the Deployment.
*/
framework.ConformanceIt("should run the lifecycle of a Deployment", func() {
one := int64(1)
deploymentResource := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
testNamespaceName := f.Namespace.Name
testDeploymentName := "test-deployment"
testDeploymentInitialImage := imageutils.GetE2EImage(imageutils.Agnhost)
testDeploymentPatchImage := imageutils.GetE2EImage(imageutils.Pause)
testDeploymentUpdateImage := imageutils.GetE2EImage(imageutils.Httpd)
testDeploymentDefaultReplicas := int32(2)
testDeploymentMinimumReplicas := int32(1)
testDeploymentNoReplicas := int32(0)
testDeploymentLabels := map[string]string{"test-deployment-static": "true"}
testDeploymentLabelsFlat := "test-deployment-static=true"
w := &cache.ListWatch{
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = testDeploymentLabelsFlat
return f.ClientSet.AppsV1().Deployments(testNamespaceName).Watch(context.TODO(), options)
},
}
deploymentsList, err := f.ClientSet.AppsV1().Deployments("").List(context.TODO(), metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat})
framework.ExpectNoError(err, "failed to list Deployments")
ginkgo.By("creating a Deployment")
testDeployment := e2edeployment.NewDeployment(
testDeploymentName, testDeploymentDefaultReplicas, testDeploymentLabels,
testDeploymentName, testDeploymentInitialImage, appsv1.RollingUpdateDeploymentStrategyType)
testDeployment.ObjectMeta.Labels = map[string]string{"test-deployment-static": "true"}
testDeployment.Spec.Template.Spec.TerminationGracePeriodSeconds = &one
_, err = f.ClientSet.AppsV1().Deployments(testNamespaceName).Create(context.TODO(), testDeployment, metav1.CreateOptions{})
framework.ExpectNoError(err, "failed to create Deployment %v in namespace %v", testDeploymentName, testNamespaceName)
ginkgo.By("waiting for Deployment to be created")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Added:
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true"
return found, nil
}
default:
framework.Logf("observed event type %v", event.Type)
}
return false, nil
})
framework.ExpectNoError(err, "failed to see %v event", watch.Added)
ginkgo.By("waiting for all Replicas to be Ready")
ctx, cancel = context.WithTimeout(context.Background(), f.Timeouts.PodStart)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true" &&
deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v and labels %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas, deployment.ObjectMeta.Labels)
}
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v and labels %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas, deployment.ObjectMeta.Labels)
return found, nil
}
return false, nil
})
framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas)
ginkgo.By("patching the Deployment")
deploymentPatch, err := json.Marshal(map[string]interface{}{
"metadata": map[string]interface{}{
"labels": map[string]string{"test-deployment": "patched"},
},
"spec": map[string]interface{}{
"replicas": testDeploymentMinimumReplicas,
"template": map[string]interface{}{
"spec": map[string]interface{}{
"TerminationGracePeriodSeconds": &one,
"containers": [1]map[string]interface{}{{
"name": testDeploymentName,
"image": testDeploymentPatchImage,
}},
},
},
},
})
framework.ExpectNoError(err, "failed to Marshal Deployment JSON patch")
_, err = f.ClientSet.AppsV1().Deployments(testNamespaceName).Patch(context.TODO(), testDeploymentName, types.StrategicMergePatchType, []byte(deploymentPatch), metav1.PatchOptions{})
framework.ExpectNoError(err, "failed to patch Deployment")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Modified:
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true"
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
}
return found, nil
}
default:
framework.Logf("observed event type %v", event.Type)
}
return false, nil
})
framework.ExpectNoError(err, "failed to see %v event", watch.Modified)
ginkgo.By("waiting for Replicas to scale")
ctx, cancel = context.WithTimeout(context.Background(), f.Timeouts.PodStart)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true" &&
deployment.Status.ReadyReplicas == testDeploymentMinimumReplicas &&
deployment.Status.UpdatedReplicas == testDeploymentMinimumReplicas &&
deployment.Status.UnavailableReplicas == 0 &&
deployment.Spec.Template.Spec.Containers[0].Image == testDeploymentPatchImage
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
}
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
return found, nil
}
return false, nil
})
framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentMinimumReplicas)
ginkgo.By("listing Deployments")
deploymentsList, err = f.ClientSet.AppsV1().Deployments("").List(context.TODO(), metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat})
framework.ExpectNoError(err, "failed to list Deployments")
foundDeployment := false
for _, deploymentItem := range deploymentsList.Items {
if deploymentItem.ObjectMeta.Name == testDeploymentName &&
deploymentItem.ObjectMeta.Namespace == testNamespaceName &&
deploymentItem.ObjectMeta.Labels["test-deployment-static"] == "true" {
foundDeployment = true
framework.Logf("Found %v with labels: %v", deploymentItem.ObjectMeta.Name, deploymentItem.ObjectMeta.Labels)
break
}
}
framework.ExpectEqual(foundDeployment, true, "unable to find the Deployment in list", deploymentsList)
ginkgo.By("updating the Deployment")
testDeploymentUpdate := testDeployment
testDeploymentUpdate.ObjectMeta.Labels["test-deployment"] = "updated"
testDeploymentUpdate.Spec.Template.Spec.Containers[0].Image = testDeploymentUpdateImage
testDeploymentDefaultReplicasPointer := &testDeploymentDefaultReplicas
testDeploymentUpdate.Spec.Replicas = testDeploymentDefaultReplicasPointer
testDeploymentUpdateUnstructuredMap, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&testDeploymentUpdate)
framework.ExpectNoError(err, "failed to convert to unstructured")
testDeploymentUpdateUnstructured := unstructuredv1.Unstructured{
Object: testDeploymentUpdateUnstructuredMap,
}
// currently this hasn't been able to hit the endpoint replaceAppsV1NamespacedDeploymentStatus
_, err = dc.Resource(deploymentResource).Namespace(testNamespaceName).Update(context.TODO(), &testDeploymentUpdateUnstructured, metav1.UpdateOptions{}) //, "status")
framework.ExpectNoError(err, "failed to update the DeploymentStatus")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Modified:
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true"
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
}
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
return found, nil
}
default:
framework.Logf("observed event type %v", event.Type)
}
return false, nil
})
framework.ExpectNoError(err, "failed to see %v event", watch.Modified)
ginkgo.By("fetching the DeploymentStatus")
deploymentGetUnstructured, err := dc.Resource(deploymentResource).Namespace(testNamespaceName).Get(context.TODO(), testDeploymentName, metav1.GetOptions{}, "status")
framework.ExpectNoError(err, "failed to fetch the Deployment")
deploymentGet := appsv1.Deployment{}
err = runtime.DefaultUnstructuredConverter.FromUnstructured(deploymentGetUnstructured.Object, &deploymentGet)
framework.ExpectNoError(err, "failed to convert the unstructured response to a Deployment")
framework.ExpectEqual(deploymentGet.Spec.Template.Spec.Containers[0].Image, testDeploymentUpdateImage, "failed to update image")
framework.ExpectEqual(deploymentGet.ObjectMeta.Labels["test-deployment"], "updated", "failed to update labels")
ctx, cancel = context.WithTimeout(context.Background(), f.Timeouts.PodStart)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true" &&
deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas &&
deployment.Status.UpdatedReplicas == testDeploymentDefaultReplicas &&
deployment.Status.UnavailableReplicas == 0
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v and labels %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas, deployment.ObjectMeta.Labels)
}
return found, nil
}
return false, nil
})
framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas)
ginkgo.By("patching the DeploymentStatus")
deploymentStatusPatch, err := json.Marshal(map[string]interface{}{
"metadata": map[string]interface{}{
"labels": map[string]string{"test-deployment": "patched-status"},
},
"status": map[string]interface{}{
"readyReplicas": testDeploymentNoReplicas,
},
})
framework.ExpectNoError(err, "failed to Marshal Deployment JSON patch")
dc.Resource(deploymentResource).Namespace(testNamespaceName).Patch(context.TODO(), testDeploymentName, types.StrategicMergePatchType, []byte(deploymentStatusPatch), metav1.PatchOptions{}, "status")
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Modified:
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true"
return found, nil
}
default:
framework.Logf("observed event type %v", event.Type)
}
return false, nil
})
framework.ExpectNoError(err, "failed to see %v event", watch.Modified)
ginkgo.By("fetching the DeploymentStatus")
deploymentGetUnstructured, err = dc.Resource(deploymentResource).Namespace(testNamespaceName).Get(context.TODO(), testDeploymentName, metav1.GetOptions{}, "status")
framework.ExpectNoError(err, "failed to fetch the DeploymentStatus")
deploymentGet = appsv1.Deployment{}
err = runtime.DefaultUnstructuredConverter.FromUnstructured(deploymentGetUnstructured.Object, &deploymentGet)
framework.ExpectNoError(err, "failed to convert the unstructured response to a Deployment")
framework.ExpectEqual(deploymentGet.Spec.Template.Spec.Containers[0].Image, testDeploymentUpdateImage, "failed to update image")
framework.ExpectEqual(deploymentGet.ObjectMeta.Labels["test-deployment"], "updated", "failed to update labels")
ctx, cancel = context.WithTimeout(context.Background(), f.Timeouts.PodStart)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true" &&
deployment.Status.ReadyReplicas == testDeploymentDefaultReplicas &&
deployment.Status.UpdatedReplicas == testDeploymentDefaultReplicas &&
deployment.Status.UnavailableReplicas == 0 &&
deployment.Spec.Template.Spec.Containers[0].Image == testDeploymentUpdateImage
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
}
return found, nil
}
return false, nil
})
framework.ExpectNoError(err, "failed to see replicas of %v in namespace %v scale to requested amount of %v", testDeployment.Name, testNamespaceName, testDeploymentDefaultReplicas)
ginkgo.By("deleting the Deployment")
err = f.ClientSet.AppsV1().Deployments(testNamespaceName).DeleteCollection(context.TODO(), metav1.DeleteOptions{GracePeriodSeconds: &one}, metav1.ListOptions{LabelSelector: testDeploymentLabelsFlat})
framework.ExpectNoError(err, "failed to delete Deployment via collection")
ctx, cancel = context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
_, err = watchtools.Until(ctx, deploymentsList.ResourceVersion, w, func(event watch.Event) (bool, error) {
switch event.Type {
case watch.Deleted:
if deployment, ok := event.Object.(*appsv1.Deployment); ok {
found := deployment.ObjectMeta.Name == testDeployment.Name &&
deployment.ObjectMeta.Labels["test-deployment-static"] == "true"
if !found {
framework.Logf("observed Deployment %v in namespace %v with ReadyReplicas %v", deployment.ObjectMeta.Name, deployment.ObjectMeta.Namespace, deployment.Status.ReadyReplicas)
}
return found, nil
}
default:
framework.Logf("observed event type %v", event.Type)
}
return false, nil
})
framework.ExpectNoError(err, "failed to see %v event", watch.Deleted)
})
/*
Release: v1.22
Testname: Deployment, status sub-resource
Description: When a Deployment is created it MUST succeed.
Attempt to read, update and patch its status sub-resource; all
mutating sub-resource operations MUST be visible to subsequent reads.
*/
framework.ConformanceIt("should validate Deployment Status endpoints", func() {
dClient := c.AppsV1().Deployments(ns)
dName := "test-deployment-" + utilrand.String(5)
labelSelector := "e2e=testing"
w := &cache.ListWatch{
WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
options.LabelSelector = labelSelector
return dClient.Watch(context.TODO(), options)
},
}
dList, err := c.AppsV1().Deployments("").List(context.TODO(), metav1.ListOptions{LabelSelector: labelSelector})
framework.ExpectNoError(err, "failed to list Deployments")
ginkgo.By("creating a Deployment")
podLabels := map[string]string{"name": WebserverImageName, "e2e": "testing"}
replicas := int32(1)
framework.Logf("Creating simple deployment %s", dName)
d := e2edeployment.NewDeployment(dName, replicas, podLabels, WebserverImageName, WebserverImage, appsv1.RollingUpdateDeploymentStrategyType)
deploy, err := c.AppsV1().Deployments(ns).Create(context.TODO(), d, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Wait for it to be updated to revision 1
err = e2edeployment.WaitForDeploymentRevisionAndImage(c, ns, dName, "1", WebserverImage)
framework.ExpectNoError(err)
err = e2edeployment.WaitForDeploymentComplete(c, deploy)
framework.ExpectNoError(err)
testDeployment, err := dClient.Get(context.TODO(), dName, metav1.GetOptions{})
framework.ExpectNoError(err)
ginkgo.By("Getting /status")
dResource := schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}
dStatusUnstructured, err := f.DynamicClient.Resource(dResource).Namespace(ns).Get(context.TODO(), dName, metav1.GetOptions{}, "status")
framework.ExpectNoError(err, "Failed to fetch the status of deployment %s in namespace %s", dName, ns)
dStatusBytes, err := json.Marshal(dStatusUnstructured)
framework.ExpectNoError(err, "Failed to marshal unstructured response. %v", err)
var dStatus appsv1.Deployment
err = json.Unmarshal(dStatusBytes, &dStatus)
framework.ExpectNoError(err, "Failed to unmarshal JSON bytes to a deployment object type")
framework.Logf("Deployment %s has Conditions: %v", dName, dStatus.Status.Conditions)
ginkgo.By("updating Deployment Status")
var statusToUpdate, updatedStatus *appsv1.Deployment
err = retry.RetryOnConflict(retry.DefaultRetry, func() error {
statusToUpdate, err = dClient.Get(context.TODO(), dName, metav1.GetOptions{})
framework.ExpectNoError(err, "Unable to retrieve deployment %s", dName)
statusToUpdate.Status.Conditions = append(statusToUpdate.Status.Conditions, appsv1.DeploymentCondition{
Type: "StatusUpdate",
Status: "True",
Reason: "E2E",
Message: "Set from e2e test",
})
updatedStatus, err = dClient.UpdateStatus(context.TODO(), statusToUpdate, metav1.UpdateOptions{})
return err
})
framework.ExpectNoError(err, "Failed to update status. %v", err)
framework.Logf("updatedStatus.Conditions: %#v", updatedStatus.Status.Conditions)
ginkgo.By("watching for the Deployment status to be updated")
ctx, cancel := context.WithTimeout(context.Background(), dRetryTimeout)
defer cancel()
_, err = watchtools.Until(ctx, dList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if d, ok := event.Object.(*appsv1.Deployment); ok {
found := d.ObjectMeta.Name == testDeployment.ObjectMeta.Name &&
d.ObjectMeta.Namespace == testDeployment.ObjectMeta.Namespace &&
d.Labels["e2e"] == "testing"
if !found {
framework.Logf("Observed Deployment %v in namespace %v with annotations: %v & Conditions: %v\n", d.ObjectMeta.Name, d.ObjectMeta.Namespace, d.Annotations, d.Status.Conditions)
return false, nil
}
for _, cond := range d.Status.Conditions {
if cond.Type == "StatusUpdate" &&
cond.Reason == "E2E" &&
cond.Message == "Set from e2e test" {
framework.Logf("Found Deployment %v in namespace %v with labels: %v annotations: %v & Conditions: %v", d.ObjectMeta.Name, d.ObjectMeta.Namespace, d.ObjectMeta.Labels, d.Annotations, cond)
return found, nil
}
framework.Logf("Observed Deployment %v in namespace %v with annotations: %v & Conditions: %v", d.ObjectMeta.Name, d.ObjectMeta.Namespace, d.Annotations, cond)
}
}
object := strings.Split(fmt.Sprintf("%v", event.Object), "{")[0]
framework.Logf("Observed %v event: %+v", object, event.Type)
return false, nil
})
framework.ExpectNoError(err, "failed to locate Deployment %v in namespace %v", testDeployment.ObjectMeta.Name, ns)
framework.Logf("Deployment %s has an updated status", dName)
ginkgo.By("patching the Statefulset Status")
payload := []byte(`{"status":{"conditions":[{"type":"StatusPatched","status":"True"}]}}`)
framework.Logf("Patch payload: %v", string(payload))
patchedDeployment, err := dClient.Patch(context.TODO(), dName, types.MergePatchType, payload, metav1.PatchOptions{}, "status")
framework.ExpectNoError(err, "Failed to patch status. %v", err)
framework.Logf("Patched status conditions: %#v", patchedDeployment.Status.Conditions)
ginkgo.By("watching for the Deployment status to be patched")
ctx, cancel = context.WithTimeout(context.Background(), dRetryTimeout)
defer cancel()
_, err = watchtools.Until(ctx, dList.ResourceVersion, w, func(event watch.Event) (bool, error) {
if e, ok := event.Object.(*appsv1.Deployment); ok {
found := e.ObjectMeta.Name == testDeployment.ObjectMeta.Name &&
e.ObjectMeta.Namespace == testDeployment.ObjectMeta.Namespace &&
e.ObjectMeta.Labels["e2e"] == testDeployment.ObjectMeta.Labels["e2e"]
if !found {
framework.Logf("Observed deployment %v in namespace %v with annotations: %v & Conditions: %v", testDeployment.ObjectMeta.Name, testDeployment.ObjectMeta.Namespace, testDeployment.Annotations, testDeployment.Status.Conditions)
return false, nil
}
for _, cond := range e.Status.Conditions {
if cond.Type == "StatusPatched" {
framework.Logf("Found deployment %v in namespace %v with labels: %v annotations: %v & Conditions: %v", testDeployment.ObjectMeta.Name, testDeployment.ObjectMeta.Namespace, testDeployment.ObjectMeta.Labels, testDeployment.Annotations, cond)
return found, nil
}
framework.Logf("Observed deployment %v in namespace %v with annotations: %v & Conditions: %v", testDeployment.ObjectMeta.Name, testDeployment.ObjectMeta.Namespace, testDeployment.Annotations, cond)
}
}
object := strings.Split(fmt.Sprintf("%v", event.Object), "{")[0]
framework.Logf("Observed %v event: %+v", object, event.Type)
return false, nil
})
framework.ExpectNoError(err, "failed to locate deployment %v in namespace %v", testDeployment.ObjectMeta.Name, ns)
framework.Logf("Deployment %s has a patched status", dName)
})
})
func failureTrap(c clientset.Interface, ns string) {
deployments, err := c.AppsV1().Deployments(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
if err != nil {
framework.Logf("Could not list Deployments in namespace %q: %v", ns, err)
return
}
for i := range deployments.Items {
d := deployments.Items[i]
framework.Logf(spew.Sprintf("Deployment %q:\n%+v\n", d.Name, d))
_, allOldRSs, newRS, err := testutil.GetAllReplicaSets(&d, c)
if err != nil {
framework.Logf("Could not list ReplicaSets for Deployment %q: %v", d.Name, err)
return
}
testutil.LogReplicaSetsOfDeployment(&d, allOldRSs, newRS, framework.Logf)
rsList := allOldRSs
if newRS != nil {
rsList = append(rsList, newRS)
}
testutil.LogPodsOfDeployment(c, &d, rsList, framework.Logf)
}
// We need print all the ReplicaSets if there are no Deployment object created
if len(deployments.Items) != 0 {
return
}
framework.Logf("Log out all the ReplicaSets if there is no deployment created")
rss, err := c.AppsV1().ReplicaSets(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
if err != nil {
framework.Logf("Could not list ReplicaSets in namespace %q: %v", ns, err)
return
}
for _, rs := range rss.Items {
framework.Logf(spew.Sprintf("ReplicaSet %q:\n%+v\n", rs.Name, rs))
selector, err := metav1.LabelSelectorAsSelector(rs.Spec.Selector)
if err != nil {
framework.Logf("failed to get selector of ReplicaSet %s: %v", rs.Name, err)
}
options := metav1.ListOptions{LabelSelector: selector.String()}
podList, err := c.CoreV1().Pods(rs.Namespace).List(context.TODO(), options)
if err != nil {
framework.Logf("Failed to list Pods in namespace %s: %v", rs.Namespace, err)
continue
}
for _, pod := range podList.Items {
framework.Logf(spew.Sprintf("pod: %q:\n%+v\n", pod.Name, pod))
}
}
}
func intOrStrP(num int) *intstr.IntOrString {
intstr := intstr.FromInt(num)
return &intstr
}
func stopDeployment(c clientset.Interface, ns, deploymentName string) {
deployment, err := c.AppsV1().Deployments(ns).Get(context.TODO(), deploymentName, metav1.GetOptions{})
framework.ExpectNoError(err)
framework.Logf("Deleting deployment %s", deploymentName)
err = e2eresource.DeleteResourceAndWaitForGC(c, appsinternal.Kind("Deployment"), ns, deployment.Name)
framework.ExpectNoError(err)
framework.Logf("Ensuring deployment %s was deleted", deploymentName)
_, err = c.AppsV1().Deployments(ns).Get(context.TODO(), deployment.Name, metav1.GetOptions{})
framework.ExpectError(err)
framework.ExpectEqual(apierrors.IsNotFound(err), true)
framework.Logf("Ensuring deployment %s's RSes were deleted", deploymentName)
selector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
framework.ExpectNoError(err)
options := metav1.ListOptions{LabelSelector: selector.String()}
rss, err := c.AppsV1().ReplicaSets(ns).List(context.TODO(), options)
framework.ExpectNoError(err)
gomega.Expect(rss.Items).Should(gomega.HaveLen(0))
framework.Logf("Ensuring deployment %s's Pods were deleted", deploymentName)
var pods *v1.PodList
if err := wait.PollImmediate(time.Second, timeout, func() (bool, error) {
pods, err = c.CoreV1().Pods(ns).List(context.TODO(), options)
if err != nil {
return false, err
}
// Pods may be created by overlapping deployments right after this deployment is deleted, ignore them
if len(pods.Items) == 0 {
return true, nil
}
return false, nil
}); err != nil {
framework.Failf("Err : %s\n. Failed to remove deployment %s pods : %+v", err, deploymentName, pods)
}
}
func testDeleteDeployment(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
deploymentName := "test-new-deployment"
podLabels := map[string]string{"name": WebserverImageName}
replicas := int32(1)
framework.Logf("Creating simple deployment %s", deploymentName)
d := e2edeployment.NewDeployment(deploymentName, replicas, podLabels, WebserverImageName, WebserverImage, appsv1.RollingUpdateDeploymentStrategyType)
d.Annotations = map[string]string{"test": "should-copy-to-replica-set", v1.LastAppliedConfigAnnotation: "should-not-copy-to-replica-set"}
deploy, err := c.AppsV1().Deployments(ns).Create(context.TODO(), d, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Wait for it to be updated to revision 1
err = e2edeployment.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", WebserverImage)
framework.ExpectNoError(err)
err = e2edeployment.WaitForDeploymentComplete(c, deploy)
framework.ExpectNoError(err)
deployment, err := c.AppsV1().Deployments(ns).Get(context.TODO(), deploymentName, metav1.GetOptions{})
framework.ExpectNoError(err)
newRS, err := testutil.GetNewReplicaSet(deployment, c)
framework.ExpectNoError(err)
framework.ExpectNotEqual(newRS, nilRs)
stopDeployment(c, ns, deploymentName)
}
func testRollingUpdateDeployment(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
// Create webserver pods.
deploymentPodLabels := map[string]string{"name": "sample-pod"}
rsPodLabels := map[string]string{
"name": "sample-pod",
"pod": WebserverImageName,
}
rsName := "test-rolling-update-controller"
replicas := int32(1)
rsRevision := "3546343826724305832"
annotations := make(map[string]string)
annotations[deploymentutil.RevisionAnnotation] = rsRevision
rs := newRS(rsName, replicas, rsPodLabels, WebserverImageName, WebserverImage, nil)
rs.Annotations = annotations
framework.Logf("Creating replica set %q (going to be adopted)", rs.Name)
_, err := c.AppsV1().ReplicaSets(ns).Create(context.TODO(), rs, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Verify that the required pods have come up.
err = e2epod.VerifyPodsRunning(c, ns, "sample-pod", false, replicas)
framework.ExpectNoError(err, "error in waiting for pods to come up: %s", err)
// Create a deployment to delete webserver pods and instead bring up agnhost pods.
deploymentName := "test-rolling-update-deployment"
framework.Logf("Creating deployment %q", deploymentName)
d := e2edeployment.NewDeployment(deploymentName, replicas, deploymentPodLabels, AgnhostImageName, AgnhostImage, appsv1.RollingUpdateDeploymentStrategyType)
deploy, err := c.AppsV1().Deployments(ns).Create(context.TODO(), d, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Wait for it to be updated to revision 3546343826724305833.
framework.Logf("Ensuring deployment %q gets the next revision from the one the adopted replica set %q has", deploy.Name, rs.Name)
err = e2edeployment.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "3546343826724305833", AgnhostImage)
framework.ExpectNoError(err)
framework.Logf("Ensuring status for deployment %q is the expected", deploy.Name)
err = e2edeployment.WaitForDeploymentComplete(c, deploy)
framework.ExpectNoError(err)
// There should be 1 old RS (webserver-controller, which is adopted)
framework.Logf("Ensuring deployment %q has one old replica set (the one it adopted)", deploy.Name)
deployment, err := c.AppsV1().Deployments(ns).Get(context.TODO(), deploymentName, metav1.GetOptions{})
framework.ExpectNoError(err)
_, allOldRSs, err := testutil.GetOldReplicaSets(deployment, c)
framework.ExpectNoError(err)
framework.ExpectEqual(len(allOldRSs), 1)
}
func testRecreateDeployment(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
// Create a deployment that brings up agnhost pods.
deploymentName := "test-recreate-deployment"
framework.Logf("Creating deployment %q", deploymentName)
d := e2edeployment.NewDeployment(deploymentName, int32(1), map[string]string{"name": "sample-pod-3"}, AgnhostImageName, AgnhostImage, appsv1.RecreateDeploymentStrategyType)
deployment, err := c.AppsV1().Deployments(ns).Create(context.TODO(), d, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Wait for it to be updated to revision 1
framework.Logf("Waiting deployment %q to be updated to revision 1", deploymentName)
err = e2edeployment.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "1", AgnhostImage)
framework.ExpectNoError(err)
framework.Logf("Waiting deployment %q to complete", deploymentName)
err = e2edeployment.WaitForDeploymentComplete(c, deployment)
framework.ExpectNoError(err)
// Update deployment to delete agnhost pods and bring up webserver pods.
framework.Logf("Triggering a new rollout for deployment %q", deploymentName)
deployment, err = e2edeployment.UpdateDeploymentWithRetries(c, ns, deploymentName, func(update *appsv1.Deployment) {
update.Spec.Template.Spec.Containers[0].Name = WebserverImageName
update.Spec.Template.Spec.Containers[0].Image = WebserverImage
})
framework.ExpectNoError(err)
framework.Logf("Watching deployment %q to verify that new pods will not run with olds pods", deploymentName)
err = watchRecreateDeployment(c, deployment)
framework.ExpectNoError(err)
}
// testDeploymentCleanUpPolicy tests that deployment supports cleanup policy
func testDeploymentCleanUpPolicy(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
// Create webserver pods.
deploymentPodLabels := map[string]string{"name": "cleanup-pod"}
rsPodLabels := map[string]string{
"name": "cleanup-pod",
"pod": WebserverImageName,
}
rsName := "test-cleanup-controller"
replicas := int32(1)
revisionHistoryLimit := utilpointer.Int32Ptr(0)
_, err := c.AppsV1().ReplicaSets(ns).Create(context.TODO(), newRS(rsName, replicas, rsPodLabels, WebserverImageName, WebserverImage, nil), metav1.CreateOptions{})
framework.ExpectNoError(err)
// Verify that the required pods have come up.
err = e2epod.VerifyPodsRunning(c, ns, "cleanup-pod", false, replicas)
framework.ExpectNoError(err, "error in waiting for pods to come up: %v", err)
// Create a deployment to delete webserver pods and instead bring up agnhost pods.
deploymentName := "test-cleanup-deployment"
framework.Logf("Creating deployment %s", deploymentName)
pods, err := c.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{LabelSelector: labels.Everything().String()})
framework.ExpectNoError(err, "Failed to query for pods: %v", err)
options := metav1.ListOptions{
ResourceVersion: pods.ListMeta.ResourceVersion,
}
stopCh := make(chan struct{})
defer close(stopCh)
w, err := c.CoreV1().Pods(ns).Watch(context.TODO(), options)
framework.ExpectNoError(err)
go func() {
defer ginkgo.GinkgoRecover()
// There should be only one pod being created, which is the pod with the agnhost image.
// The old RS shouldn't create new pod when deployment controller adding pod template hash label to its selector.
numPodCreation := 1
for {
select {
case event := <-w.ResultChan():
if event.Type != watch.Added {
continue
}
numPodCreation--
if numPodCreation < 0 {
framework.Failf("Expect only one pod creation, the second creation event: %#v\n", event)
}
pod, ok := event.Object.(*v1.Pod)
if !ok {
framework.Failf("Expect event Object to be a pod")
}
if pod.Spec.Containers[0].Name != AgnhostImageName {
framework.Failf("Expect the created pod to have container name %s, got pod %#v\n", AgnhostImageName, pod)
}
case <-stopCh:
return
}
}
}()
d := e2edeployment.NewDeployment(deploymentName, replicas, deploymentPodLabels, AgnhostImageName, AgnhostImage, appsv1.RollingUpdateDeploymentStrategyType)
d.Spec.RevisionHistoryLimit = revisionHistoryLimit
_, err = c.AppsV1().Deployments(ns).Create(context.TODO(), d, metav1.CreateOptions{})
framework.ExpectNoError(err)
ginkgo.By(fmt.Sprintf("Waiting for deployment %s history to be cleaned up", deploymentName))
err = waitForDeploymentOldRSsNum(c, ns, deploymentName, int(*revisionHistoryLimit))
framework.ExpectNoError(err)
}
// testRolloverDeployment tests that deployment supports rollover.
// i.e. we can change desired state and kick off rolling update, then change desired state again before it finishes.
func testRolloverDeployment(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
podName := "rollover-pod"
deploymentPodLabels := map[string]string{"name": podName}
rsPodLabels := map[string]string{
"name": podName,
"pod": WebserverImageName,
}
rsName := "test-rollover-controller"
rsReplicas := int32(1)
_, err := c.AppsV1().ReplicaSets(ns).Create(context.TODO(), newRS(rsName, rsReplicas, rsPodLabels, WebserverImageName, WebserverImage, nil), metav1.CreateOptions{})
framework.ExpectNoError(err)
// Verify that the required pods have come up.
err = e2epod.VerifyPodsRunning(c, ns, podName, false, rsReplicas)
framework.ExpectNoError(err, "error in waiting for pods to come up: %v", err)
// Wait for replica set to become ready before adopting it.
framework.Logf("Waiting for pods owned by replica set %q to become ready", rsName)
err = e2ereplicaset.WaitForReadyReplicaSet(c, ns, rsName)
framework.ExpectNoError(err)
// Create a deployment to delete webserver pods and instead bring up redis-slave pods.
// We use a nonexistent image here, so that we make sure it won't finish
deploymentName, deploymentImageName := "test-rollover-deployment", "redis-slave"
deploymentReplicas := int32(1)
deploymentImage := "gcr.io/google_samples/gb-redisslave:nonexistent"
deploymentStrategyType := appsv1.RollingUpdateDeploymentStrategyType
framework.Logf("Creating deployment %q", deploymentName)
newDeployment := e2edeployment.NewDeployment(deploymentName, deploymentReplicas, deploymentPodLabels, deploymentImageName, deploymentImage, deploymentStrategyType)
newDeployment.Spec.Strategy.RollingUpdate = &appsv1.RollingUpdateDeployment{
MaxUnavailable: intOrStrP(0),
MaxSurge: intOrStrP(1),
}
newDeployment.Spec.MinReadySeconds = int32(10)
_, err = c.AppsV1().Deployments(ns).Create(context.TODO(), newDeployment, metav1.CreateOptions{})
framework.ExpectNoError(err)
// Verify that the pods were scaled up and down as expected.
deployment, err := c.AppsV1().Deployments(ns).Get(context.TODO(), deploymentName, metav1.GetOptions{})
framework.ExpectNoError(err)
framework.Logf("Make sure deployment %q performs scaling operations", deploymentName)
// Make sure the deployment starts to scale up and down replica sets by checking if its updated replicas >= 1
err = waitForDeploymentUpdatedReplicasGTE(c, ns, deploymentName, deploymentReplicas, deployment.Generation)
framework.ExpectNoError(err)
// Check if it's updated to revision 1 correctly
framework.Logf("Check revision of new replica set for deployment %q", deploymentName)
err = checkDeploymentRevisionAndImage(c, ns, deploymentName, "1", deploymentImage)
framework.ExpectNoError(err)
framework.Logf("Ensure that both replica sets have 1 created replica")
oldRS, err := c.AppsV1().ReplicaSets(ns).Get(context.TODO(), rsName, metav1.GetOptions{})
framework.ExpectNoError(err)
ensureReplicas(oldRS, int32(1))
newRS, err := testutil.GetNewReplicaSet(deployment, c)
framework.ExpectNoError(err)
ensureReplicas(newRS, int32(1))
// The deployment is stuck, update it to rollover the above 2 ReplicaSets and bring up agnhost pods.
framework.Logf("Rollover old replica sets for deployment %q with new image update", deploymentName)
updatedDeploymentImageName, updatedDeploymentImage := AgnhostImageName, AgnhostImage
deployment, err = e2edeployment.UpdateDeploymentWithRetries(c, ns, newDeployment.Name, func(update *appsv1.Deployment) {
update.Spec.Template.Spec.Containers[0].Name = updatedDeploymentImageName
update.Spec.Template.Spec.Containers[0].Image = updatedDeploymentImage
})
framework.ExpectNoError(err)
// Use observedGeneration to determine if the controller noticed the pod template update.
framework.Logf("Wait deployment %q to be observed by the deployment controller", deploymentName)
err = waitForObservedDeployment(c, ns, deploymentName, deployment.Generation)
framework.ExpectNoError(err)
// Wait for it to be updated to revision 2
framework.Logf("Wait for revision update of deployment %q to 2", deploymentName)
err = e2edeployment.WaitForDeploymentRevisionAndImage(c, ns, deploymentName, "2", updatedDeploymentImage)
framework.ExpectNoError(err)
framework.Logf("Make sure deployment %q is complete", deploymentName)
err = waitForDeploymentCompleteAndCheckRolling(c, deployment)
framework.ExpectNoError(err)
framework.Logf("Ensure that both old replica sets have no replicas")
oldRS, err = c.AppsV1().ReplicaSets(ns).Get(context.TODO(), rsName, metav1.GetOptions{})
framework.ExpectNoError(err)
ensureReplicas(oldRS, int32(0))
// Not really the new replica set anymore but we GET by name so that's fine.
newRS, err = c.AppsV1().ReplicaSets(ns).Get(context.TODO(), newRS.Name, metav1.GetOptions{})
framework.ExpectNoError(err)
ensureReplicas(newRS, int32(0))
}
func ensureReplicas(rs *appsv1.ReplicaSet, replicas int32) {
framework.ExpectEqual(*rs.Spec.Replicas, replicas)
framework.ExpectEqual(rs.Status.Replicas, replicas)
}
func randomScale(d *appsv1.Deployment, i int) {
switch r := rand.Float32(); {
case r < 0.3:
framework.Logf("%02d: scaling up", i)
*(d.Spec.Replicas)++
case r < 0.6:
if *(d.Spec.Replicas) > 1 {
framework.Logf("%02d: scaling down", i)
*(d.Spec.Replicas)--
}
}
}
func testIterativeDeployments(f *framework.Framework) {
ns := f.Namespace.Name
c := f.ClientSet
podLabels := map[string]string{"name": WebserverImageName}
replicas := int32(6)