Repository navigation
Expand file tree
/
Copy pathclusteroperator_controller_test.go
More file actions
1411 lines (1223 loc) · 54.5 KB
/
Copy pathclusteroperator_controller_test.go
File metadata and controls
1411 lines (1223 loc) · 54.5 KB
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
package controllers
import (
"context"
"fmt"
"time"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
configv1 "github.com/openshift/api/config/v1"
"github.com/openshift/library-go/pkg/config/clusteroperator/v1helpers"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/record"
clocktesting "k8s.io/utils/clock/testing"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"github.com/openshift/cluster-cloud-controller-manager-operator/pkg/cloud"
"github.com/openshift/cluster-cloud-controller-manager-operator/pkg/cloud/common"
"github.com/openshift/cluster-cloud-controller-manager-operator/pkg/config"
"github.com/openshift/cluster-cloud-controller-manager-operator/pkg/controllers/resourceapply"
)
const (
timeout = time.Second * 10
testImagesFilePath = "./fixtures/images.json"
)
var _ = Describe("Cluster Operator status controller", func() {
var operator *configv1.ClusterOperator
var operatorController *CloudOperatorReconciler
BeforeEach(func() {
operatorController = &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: cl,
Clock: clocktesting.NewFakePassiveClock(time.Now()),
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
operator = &configv1.ClusterOperator{}
operator.SetName(clusterOperatorName)
})
AfterEach(func() {
deleteClusterOperator(context.Background(), cl)
})
type testCase struct {
releaseVersionEnvVariableValue string
namespace string
existingCO *configv1.ClusterOperator
}
DescribeTable("should ensure Cluster Operator status is present",
func(tc testCase) {
expectedVersion := "unknown"
if tc.releaseVersionEnvVariableValue != "" {
expectedVersion = tc.releaseVersionEnvVariableValue
operatorController.ReleaseVersion = tc.releaseVersionEnvVariableValue
}
if tc.namespace != "" {
operatorController.ManagedNamespace = tc.namespace
}
if tc.existingCO != nil {
err := cl.Create(context.Background(), tc.existingCO)
Expect(err).To(Succeed())
}
_, err := operatorController.Reconcile(context.Background(), reconcile.Request{})
Expect(err).To(Succeed())
getOp := &configv1.ClusterOperator{}
Eventually(func() error {
err := cl.Get(context.Background(), client.ObjectKey{Name: clusterOperatorName}, getOp)
if err != nil {
return err
}
// Successful sync means CO exists and the status is not empty
if getOp == nil || len(getOp.Status.Versions) == 0 {
return fmt.Errorf("ClusterOperator status versions not yet populated")
}
return nil
}, timeout).Should(Succeed())
// check version.
Expect(getOp.Status.Versions).To(HaveLen(1))
Expect(getOp.Status.Versions[0].Name).To(Equal(operatorVersionKey))
Expect(getOp.Status.Versions[0].Version).To(Equal(expectedVersion))
// check conditions.
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorAvailable).Status).To(Equal(configv1.ConditionTrue))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorAvailable).Reason).To(Equal(ReasonAsExpected))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorUpgradeable).Status).To(Equal(configv1.ConditionTrue))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorUpgradeable).Reason).To(Equal(ReasonAsExpected))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorDegraded).Status).To(Equal(configv1.ConditionFalse))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorDegraded).Reason).To(Equal(ReasonAsExpected))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorProgressing).Status).To(Equal(configv1.ConditionFalse))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, configv1.OperatorProgressing).Reason).To(Equal(ReasonAsExpected))
Expect(v1helpers.FindStatusCondition(getOp.Status.Conditions, cloudControllerOwnershipCondition)).To(BeNil())
// check related objects.
Expect(getOp.Status.RelatedObjects).To(Equal(operatorController.relatedObjects()))
},
Entry("when there's no existing cluster operator nor release version", testCase{
releaseVersionEnvVariableValue: "unknown",
existingCO: nil,
}),
Entry("when there's no existing cluster operator but there's release version", testCase{
releaseVersionEnvVariableValue: "a_cvo_given_version",
existingCO: nil,
}),
Entry("when there's no existing cluster operator but there's release version", testCase{
releaseVersionEnvVariableValue: "a_cvo_given_version",
existingCO: nil,
namespace: "different-ccm-namespace",
}),
Entry("when there's an existing cluster operator and a release version", testCase{
releaseVersionEnvVariableValue: "another_cvo_given_version",
existingCO: &configv1.ClusterOperator{
ObjectMeta: metav1.ObjectMeta{
Name: clusterOperatorName,
},
Status: configv1.ClusterOperatorStatus{
Conditions: []configv1.ClusterOperatorStatusCondition{
{
Type: configv1.OperatorAvailable,
Status: configv1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
{
Type: configv1.OperatorDegraded,
Status: configv1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
{
Type: configv1.OperatorProgressing,
Status: configv1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
{
Type: configv1.OperatorUpgradeable,
Status: configv1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
},
Versions: []configv1.OperandVersion{
{
Name: "anything",
Version: "anything",
},
},
RelatedObjects: []configv1.ObjectReference{
{
Group: "",
Resource: "anything",
Name: "anything",
},
},
},
},
}),
Entry("when there's a CloudControllerOwner condition with True status", testCase{
releaseVersionEnvVariableValue: "another_cvo_given_version",
existingCO: &configv1.ClusterOperator{
ObjectMeta: metav1.ObjectMeta{
Name: clusterOperatorName,
},
Status: configv1.ClusterOperatorStatus{
Conditions: []configv1.ClusterOperatorStatusCondition{
{
Type: cloudControllerOwnershipCondition,
Status: configv1.ConditionTrue,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
},
},
},
}),
Entry("when there's a CloudControllerOwner condition with False status", testCase{
releaseVersionEnvVariableValue: "another_cvo_given_version",
existingCO: &configv1.ClusterOperator{
ObjectMeta: metav1.ObjectMeta{
Name: clusterOperatorName,
},
Status: configv1.ClusterOperatorStatus{
Conditions: []configv1.ClusterOperatorStatusCondition{
{
Type: cloudControllerOwnershipCondition,
Status: configv1.ConditionFalse,
LastTransitionTime: metav1.Now(),
Reason: "",
Message: "",
},
},
},
},
}),
)
})
var _ = Describe("toClusterOperator mapping is targeting requests to 'cloud-controller-manager' clusterOperator", func() {
It("Should map reconciles to 'cloud-controller-manager' clusterOperator", func() {
object := &configv1.Infrastructure{}
requests := []reconcile.Request{{
NamespacedName: client.ObjectKey{
Name: clusterOperatorName,
},
}}
Expect(toClusterOperator(ctx, object)).To(Equal(requests))
})
})
var _ = Describe("Apply resources should", func() {
var resources []client.Object
var reconciler *CloudOperatorReconciler
var recorder *record.FakeRecorder
var getConfigForPlatform func(status *configv1.PlatformStatus) config.OperatorConfig
BeforeEach(func() {
c, err := cache.New(cfg, cache.Options{})
Expect(err).To(Succeed())
w, err := NewObjectWatcher(WatcherOptions{Cache: c})
Expect(err).To(Succeed())
ns := &corev1.Namespace{}
ns.SetName("cluster-cloud-controller-manager")
resources = []client.Object{}
if !apierrors.IsNotFound(cl.Get(context.TODO(), client.ObjectKeyFromObject(ns), ns.DeepCopy())) {
Expect(cl.Create(context.TODO(), ns.DeepCopy())).ShouldNot(HaveOccurred())
}
recorder = record.NewFakeRecorder(32)
recorder.IncludeObject = true
reconciler = &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Clock: clocktesting.NewFakePassiveClock(time.Now()),
Client: cl,
Recorder: recorder,
},
Scheme: scheme.Scheme,
watcher: w,
}
getConfigForPlatform = func(status *configv1.PlatformStatus) config.OperatorConfig {
return config.OperatorConfig{
ManagedNamespace: DefaultManagedNamespace,
ImagesReference: config.ImagesReference{
CloudControllerManagerOperator: "registry.ci.openshift.org/openshift:cluster-cloud-controller-manager-operator",
CloudControllerManagerAWS: "registry.ci.openshift.org/openshift:aws-cloud-controller-manager",
CloudControllerManagerAzure: "quay.io/openshift/origin-azure-cloud-controller-manager",
CloudNodeManagerAzure: "quay.io/openshift/origin-azure-cloud-node-manager",
CloudControllerManagerOpenStack: "registry.ci.openshift.org/openshift:openstack-cloud-controller-manager",
},
PlatformStatus: status,
}
}
})
It("Expect update when resources are not found", func() {
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
awsResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
resources = append(resources, awsResources...)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
// two resources should report successful update, deployment and pdb
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
})
It("Expect update when deployment generation have changed", func() {
var dep *appsv1.Deployment
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
freshResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
dep = deployment
break
}
}
resources = append(resources, dep)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
dep.Spec.Replicas = ptr.To[int32](20)
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully updated")))
// No update as resource didn't change
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeFalse())
})
It("Expect error when object requested is incorrect", func() {
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
objects, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
objects[0].SetNamespace("non-existent")
updated, err := reconciler.applyResources(context.TODO(), objects)
Expect(err).Should(HaveOccurred())
Expect(updated).To(BeFalse())
Eventually(recorder.Events).Should(Receive(ContainSubstring(resourceapply.ResourceCreateFailedEvent)))
})
It("Expect no update when resources are applied twice", func() {
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
awsResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
resources = append(resources, awsResources...)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
// three resources should report successful update, deployment, pdb and service
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeFalse())
})
It("Expect to have just one item in the port list after it's been updated", func() {
var dep *appsv1.Deployment
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
freshResources, err := cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
dep = deployment
break
}
}
resources = append(resources, dep)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
// Manually changing the port number
ports := []corev1.ContainerPort{
{
ContainerPort: 11258,
Name: "https",
Protocol: corev1.ProtocolTCP,
},
}
dep.Spec.Template.Spec.Containers[0].Ports = ports
err = reconciler.Update(context.TODO(), dep)
Expect(err).ShouldNot(HaveOccurred())
// Checking that the port has been updated and there is only one item in the list
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Spec.Template.Spec.Containers[0].Ports)).To(Equal(1))
Expect(dep.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort).To(Equal(int32(11258)))
// Apply resources again
freshResources, err = cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
resources = []client.Object{deployment}
break
}
}
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully updated")))
// Checking that the port has been reverted back and there is only one item in the list
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Spec.Template.Spec.Containers[0].Ports)).To(Equal(1))
Expect(dep.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort).To(Equal(int32(10258)))
})
It("Expect to have just one item in the port list after user added another one", func() {
var dep *appsv1.Deployment
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
freshResources, err := cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
dep = deployment
break
}
}
resources = append(resources, dep)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
// Manually adding another port
newPort := corev1.ContainerPort{
ContainerPort: 11258,
Name: "http",
Protocol: corev1.ProtocolTCP,
}
dep.Spec.Template.Spec.Containers[0].Ports = append(dep.Spec.Template.Spec.Containers[0].Ports, newPort)
err = reconciler.Update(context.TODO(), dep)
Expect(err).ShouldNot(HaveOccurred())
// Checking that the port has been added and there are two items in the list
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Spec.Template.Spec.Containers[0].Ports)).To(Equal(2))
Expect(dep.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort).To(Equal(int32(10258)))
Expect(dep.Spec.Template.Spec.Containers[0].Ports[1].ContainerPort).To(Equal(int32(11258)))
// Apply resources again
freshResources, err = cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
resources = []client.Object{deployment}
break
}
}
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully updated")))
// Checking that the port list has been reverted back and there is only one item in the list
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Spec.Template.Spec.Containers[0].Ports)).To(Equal(1))
Expect(dep.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort).To(Equal(int32(10258)))
})
It("Expect to have deployment labels merged with user ones", func() {
var dep *appsv1.Deployment
labelName := "my-label"
labelValue := "someValue"
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
freshResources, err := cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
dep = deployment
break
}
}
resources = append(resources, dep)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
// Manually inserting a new label
dep.Labels[labelName] = labelValue
err = reconciler.Update(context.TODO(), dep)
Expect(err).ShouldNot(HaveOccurred())
// Checking that the label has been added and there are two items in the map
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Labels)).To(Equal(3))
Expect(dep.Labels[labelName]).To(Equal(labelValue))
// Apply resources again
freshResources, err = cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
resources = []client.Object{deployment}
break
}
}
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully updated")))
// Checking that the new label is still there
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Labels)).To(Equal(3))
Expect(dep.Labels[labelName]).To(Equal(labelValue))
})
It("Expect to have modified system label reverted back", func() {
var dep *appsv1.Deployment
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
freshResources, err := cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
dep = deployment
break
}
}
resources = append(resources, dep)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully created")))
// Now the deployment has just one label "k8s-app: aws-cloud-controller-manager"
// Manually modifying the value
dep.Labels["k8s-app"] = "someValue"
dep.Labels[common.CloudControllerManagerProviderLabel] = "FOO"
err = reconciler.Update(context.TODO(), dep)
Expect(err).ShouldNot(HaveOccurred())
// Checking that the label has been updated
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Labels)).To(Equal(2))
Expect(dep.Labels["k8s-app"]).To(Equal("someValue"))
Expect(dep.Labels[common.CloudControllerManagerProviderLabel]).To(Equal("FOO"))
// Apply resources again
freshResources, err = cloud.GetResources(operatorConfig)
Expect(err).ShouldNot(HaveOccurred())
for _, res := range freshResources {
if deployment, ok := res.(*appsv1.Deployment); ok {
resources = []client.Object{deployment}
break
}
}
updated, err = reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "expected applyResources to report that at least one resource was created or updated")
Eventually(recorder.Events).Should(Receive(ContainSubstring("Resource was successfully updated")))
// Checking that the label value has been reverted and there is only one item in the map
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), dep)).To(Succeed())
Expect(len(dep.Labels)).To(Equal(2))
Expect(dep.Labels["k8s-app"]).To(Equal("aws-cloud-controller-manager"))
Expect(dep.Labels[common.CloudControllerManagerProviderLabel]).To(Equal("AWS"))
})
It("reports updated=true when only a non-final resource changed", func() {
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
awsResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
Expect(len(awsResources)).To(BeNumerically(">=", 2))
resources = append(resources, awsResources...)
updated, err := reconciler.applyResources(context.TODO(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue())
// Drain recorder events from initial creation
for len(recorder.Events) > 0 {
<-recorder.Events
}
// Modify only the deployment so it gets updated, while later resources remain unchanged
for i, res := range resources {
if dep, ok := res.(*appsv1.Deployment); ok {
dep.Spec.Replicas = ptr.To[int32](99)
resources[i] = dep
break
}
}
updated, err = reconciler.applyResources(context.Background(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue(), "should report updated even when only a non-final resource changed")
})
Context("operandsConverged", func() {
It("returns false when deployment rollout is not complete, true after patching status", func() {
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
awsResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
resources = append(resources, awsResources...)
updated, err := reconciler.applyResources(context.Background(), resources)
Expect(err).ShouldNot(HaveOccurred())
Expect(updated).To(BeTrue())
// envtest has no deployment controller, so no Progressing condition exists.
converged, err := reconciler.operandsConverged(context.Background(), resources)
Expect(err).To(Succeed())
Expect(converged).To(BeFalse(), "should not be converged when deployment has no Progressing condition")
// Patch the deployment status to mark rollout complete.
for _, res := range resources {
if dep, ok := res.(*appsv1.Deployment); ok {
live := &appsv1.Deployment{}
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), live)).To(Succeed())
live.Status.ObservedGeneration = live.Generation
live.Status.Conditions = []appsv1.DeploymentCondition{
{
Type: appsv1.DeploymentProgressing,
Status: corev1.ConditionTrue,
Reason: "NewReplicaSetAvailable",
},
}
Expect(cl.Status().Update(context.Background(), live)).To(Succeed())
}
}
converged, err = reconciler.operandsConverged(context.Background(), resources)
Expect(err).To(Succeed())
Expect(converged).To(BeTrue(), "should be converged after deployment rollout completes")
})
})
It("should set Progressing=True on first sync, remain progressing until rollout completes, then stop", func() {
reconciler.ManagedNamespace = DefaultManagedNamespace
co := &configv1.ClusterOperator{}
co.SetName(clusterOperatorName)
Expect(cl.Create(context.Background(), co)).To(Succeed())
operatorConfig := getConfigForPlatform(&configv1.PlatformStatus{Type: configv1.AWSPlatformType})
awsResources, err := cloud.GetResources(operatorConfig)
Expect(err).To(Succeed())
resources = append(resources, awsResources...)
// First sync: resources do not yet exist, so applyResources reports updated=true.
progressing, err := reconciler.sync(context.Background(), operatorConfig, nil)
Expect(err).To(Succeed())
Expect(progressing).To(BeTrue(), "sync should report progressing when resources are newly applied")
Expect(cl.Get(context.Background(), client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
progressingCond := v1helpers.FindStatusCondition(co.Status.Conditions, configv1.OperatorProgressing)
Expect(progressingCond).NotTo(BeNil(), "Progressing condition should exist after first sync")
Expect(progressingCond.Status).To(
Equal(configv1.ConditionTrue), "Progressing should be True after resources are first applied",
)
// Second sync: resources exist and are unchanged, but deployment rollout is
// not complete (envtest has no deployment controller). sync should still
// report progressing.
progressing, err = reconciler.sync(context.Background(), operatorConfig, nil)
Expect(err).To(Succeed())
Expect(progressing).To(BeTrue(), "sync should report progressing while deployment rollout is incomplete")
// Patch deployment status to mark rollout complete.
for _, res := range resources {
if dep, ok := res.(*appsv1.Deployment); ok {
live := &appsv1.Deployment{}
Expect(cl.Get(context.Background(), client.ObjectKeyFromObject(dep), live)).To(Succeed())
live.Status.ObservedGeneration = live.Generation
live.Status.Conditions = []appsv1.DeploymentCondition{
{
Type: appsv1.DeploymentProgressing,
Status: corev1.ConditionTrue,
Reason: "NewReplicaSetAvailable",
},
}
Expect(cl.Status().Update(context.Background(), live)).To(Succeed())
}
}
// Third sync: deployment rollout is complete, sync should report not progressing.
progressing, err = reconciler.sync(context.Background(), operatorConfig, nil)
Expect(err).To(Succeed())
Expect(progressing).To(BeFalse(), "sync should not report progressing once deployment rollout completes")
})
AfterEach(func() {
deleteClusterOperator(context.Background(), cl)
for _, operand := range resources {
Expect(cl.Delete(context.Background(), operand)).To(Succeed())
Eventually(func() error {
err := cl.Get(context.Background(), client.ObjectKeyFromObject(operand), operand)
if apierrors.IsNotFound(err) {
return nil
}
if err != nil {
return err
}
return fmt.Errorf("expected operand %s to be deleted", operand.GetName())
}, timeout).Should(Succeed())
}
})
})
var _ = Describe("CloudOperatorReconciler error handling", func() {
ctx := context.Background()
AfterEach(func() {
deleteClusterOperator(ctx, cl)
infra := &configv1.Infrastructure{ObjectMeta: metav1.ObjectMeta{Name: infrastructureResourceName}}
cl.Delete(ctx, infra) //nolint:errcheck
})
It("terminal error via finalizeReconcile should set OperatorDegraded=True immediately and return nil error", func() {
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: cl,
Clock: clocktesting.NewFakePassiveClock(time.Now()),
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
ImagesFile: "/nonexistent/images.json",
}
infra := &configv1.Infrastructure{
ObjectMeta: metav1.ObjectMeta{Name: infrastructureResourceName},
}
Expect(cl.Create(ctx, infra)).To(Succeed())
infra.Status = configv1.InfrastructureStatus{
PlatformStatus: &configv1.PlatformStatus{Type: configv1.AWSPlatformType},
Platform: configv1.AWSPlatformType,
InfrastructureTopology: configv1.HighlyAvailableTopologyMode,
ControlPlaneTopology: configv1.HighlyAvailableTopologyMode,
}
Expect(cl.Status().Update(ctx, infra)).To(Succeed())
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
co.Status.Conditions = []configv1.ClusterOperatorStatusCondition{
{Type: cloudConfigControllerAvailableCondition, Status: configv1.ConditionTrue, LastTransitionTime: metav1.Now()},
{Type: cloudConfigControllerDegradedCondition, Status: configv1.ConditionFalse, LastTransitionTime: metav1.Now()},
{Type: trustedCABundleControllerAvailableCondition, Status: configv1.ConditionTrue, LastTransitionTime: metav1.Now()},
{Type: trustedCABundleControllerDegradedCondition, Status: configv1.ConditionFalse, LastTransitionTime: metav1.Now()},
}
Expect(cl.Status().Update(ctx, co)).To(Succeed())
_, err := reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).NotTo(HaveOccurred(), "terminal errors should return nil so controller-runtime does not requeue")
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.FindStatusCondition(co.Status.Conditions, configv1.OperatorDegraded).Status).To(Equal(configv1.ConditionTrue))
})
It("transient error via finalizeReconcile should not degrade before threshold, but degrade after threshold", func() {
fakeClock := clocktesting.NewFakeClock(time.Now())
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: cl,
Clock: fakeClock,
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
transientErr := fmt.Errorf("test transient error")
conditionOverrides := []configv1.ClusterOperatorStatusCondition{}
// Simulate what Reconcile's defer does: call finalizeReconcile with
// the same closure that Reconcile constructs.
callFinalizeReconcile := func(retErr error) (ctrl.Result, error) {
result := ctrl.Result{}
finalizeReconcile(
&reconciler.failures, reconciler.Clock,
noStalenessWindow, aggregatedTransientDegradedThreshold,
"CloudOperatorReconciler",
reconciler.clearFailureWindow,
func() error { return reconciler.setStatusDegraded(ctx, retErr, conditionOverrides) },
&result, &retErr,
)
return result, retErr
}
// First call: transient failure starts; error returned but no OperatorDegraded set.
_, err := callFinalizeReconcile(transientErr)
Expect(err).To(HaveOccurred())
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.IsStatusConditionTrue(co.Status.Conditions, configv1.OperatorDegraded)).To(BeFalse(),
"should not be degraded before threshold")
// Advance clock past the degraded threshold.
fakeClock.Step(aggregatedTransientDegradedThreshold + time.Second)
// Second call: threshold exceeded, controller sets OperatorDegraded.
_, err = callFinalizeReconcile(transientErr)
Expect(err).To(HaveOccurred())
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.FindStatusCondition(co.Status.Conditions, configv1.OperatorDegraded).Status).To(Equal(configv1.ConditionTrue))
})
It("transient error should not set OperatorDegraded before threshold", func() {
fakeClock := clocktesting.NewFakeClock(time.Now())
getErr := fmt.Errorf("connection refused")
faultyClient := errorInjectingClient{Client: cl, getErr: &getErr, failType: &configv1.Infrastructure{}}
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: &faultyClient,
Clock: fakeClock,
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
// Reconcile several times, advancing the clock each iteration but
// staying under the threshold. OperatorDegraded must never be set.
stepSize := aggregatedTransientDegradedThreshold / 5
for range 4 {
_, err := reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).To(HaveOccurred(), "transient error should be returned for controller-runtime to requeue")
fakeClock.Step(stepSize)
}
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.IsStatusConditionTrue(co.Status.Conditions, configv1.OperatorDegraded)).To(BeFalse(),
"OperatorDegraded should not be True before the transient threshold elapses")
})
It("transient error should set OperatorDegraded after threshold is crossed", func() {
fakeClock := clocktesting.NewFakeClock(time.Now())
getErr := fmt.Errorf("connection refused")
faultyClient := errorInjectingClient{Client: cl, getErr: &getErr, failType: &configv1.Infrastructure{}}
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: &faultyClient,
Clock: fakeClock,
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
// First Reconcile opens the failure window.
_, err := reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).To(HaveOccurred())
// Advance past the threshold.
fakeClock.Step(aggregatedTransientDegradedThreshold + time.Second)
// Next Reconcile crosses the threshold and sets OperatorDegraded.
_, err = reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).To(HaveOccurred())
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
degradedCond := v1helpers.FindStatusCondition(co.Status.Conditions, configv1.OperatorDegraded)
Expect(degradedCond).NotTo(BeNil(), "OperatorDegraded condition should exist after threshold is crossed")
Expect(degradedCond.Status).To(Equal(configv1.ConditionTrue),
"OperatorDegraded should be True after threshold is crossed")
})
It("successful reconcile resets the failure window so transient errors must start fresh", func() {
fakeClock := clocktesting.NewFakeClock(time.Now())
getErr := fmt.Errorf("connection refused")
faultyClient := errorInjectingClient{Client: cl, getErr: &getErr, failType: &configv1.Infrastructure{}}
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: &faultyClient,
Clock: fakeClock,
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
By("opening the failure window with a transient error")
_, err := reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).To(HaveOccurred())
By("clearing the fault so Reconcile succeeds via the Infrastructure-not-found path")
getErr = nil
_, err = reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).NotTo(HaveOccurred())
By("advancing past the original threshold and re-injecting the fault")
fakeClock.Step(aggregatedTransientDegradedThreshold + time.Second)
getErr = fmt.Errorf("connection refused")
_, err = reconciler.Reconcile(ctx, reconcile.Request{})
Expect(err).To(HaveOccurred())
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.IsStatusConditionTrue(co.Status.Conditions, configv1.OperatorDegraded)).To(BeFalse(),
"OperatorDegraded should not be True because the failure window was reset by the successful reconcile")
})
It("successful finalizeReconcile clears the failure window so subsequent transient errors start fresh", func() {
fakeClock := clocktesting.NewFakeClock(time.Now())
reconciler := &CloudOperatorReconciler{
ClusterOperatorStatusClient: ClusterOperatorStatusClient{
Client: cl,
Clock: fakeClock,
ManagedNamespace: defaultManagementNamespace,
Recorder: record.NewFakeRecorder(32),
},
Scheme: scheme.Scheme,
}
co := &configv1.ClusterOperator{ObjectMeta: metav1.ObjectMeta{Name: clusterOperatorName}}
Expect(cl.Create(ctx, co)).To(Succeed())
transientErr := fmt.Errorf("test transient error")
conditionOverrides := []configv1.ClusterOperatorStatusCondition{}
callFinalizeReconcile := func(retErr error) (ctrl.Result, error) {
result := ctrl.Result{}
finalizeReconcile(
&reconciler.failures, reconciler.Clock,
noStalenessWindow, aggregatedTransientDegradedThreshold,
"CloudOperatorReconciler",
reconciler.clearFailureWindow,
func() error { return reconciler.setStatusDegraded(ctx, retErr, conditionOverrides) },
&result, &retErr,
)
return result, retErr
}
// Open the failure window with a transient error.
_, err := callFinalizeReconcile(transientErr)
Expect(err).To(HaveOccurred())
// Simulate a successful reconcile: nil error clears the window.
_, err = callFinalizeReconcile(nil)
Expect(err).NotTo(HaveOccurred())
// Advance clock past the original threshold.
fakeClock.Step(aggregatedTransientDegradedThreshold + time.Second)
// Despite the clock being past threshold, the window was cleared
// by the successful reconcile — this starts a fresh window.
_, err = callFinalizeReconcile(transientErr)
Expect(err).To(HaveOccurred())
Expect(cl.Get(ctx, client.ObjectKey{Name: clusterOperatorName}, co)).To(Succeed())
Expect(v1helpers.IsStatusConditionTrue(co.Status.Conditions, configv1.OperatorDegraded)).To(BeFalse(),
"should not be degraded because the failure window was reset by the successful reconcile")
})
})
var _ = Describe("Reconcile progressing flow", func() {