-
Notifications
You must be signed in to change notification settings - Fork 181
/
operator_test.go
2871 lines (2631 loc) · 113 KB
/
operator_test.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
//go:build e2e
// +build e2e
package e2e
import (
"bufio"
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"reflect"
"sort"
"strconv"
"strings"
"testing"
"time"
"gopkg.in/yaml.v2"
configv1 "github.com/openshift/api/config/v1"
operatorv1 "github.com/openshift/api/operator/v1"
routev1 "github.com/openshift/api/route/v1"
iov1 "github.com/openshift/api/operatoringress/v1"
"github.com/openshift/cluster-ingress-operator/pkg/manifests"
operatorclient "github.com/openshift/cluster-ingress-operator/pkg/operator/client"
"github.com/openshift/cluster-ingress-operator/pkg/operator/controller"
operatorcontroller "github.com/openshift/cluster-ingress-operator/pkg/operator/controller"
ingresscontroller "github.com/openshift/cluster-ingress-operator/pkg/operator/controller/ingress"
"github.com/aws/aws-sdk-go/aws/endpoints"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/config"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
policyv1 "k8s.io/api/policy/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apiserver/pkg/storage/names"
discocache "k8s.io/client-go/discovery/cached"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/scale"
)
var (
availableConditionsForPrivateIngressController = []operatorv1.OperatorCondition{
{Type: operatorv1.IngressControllerAvailableConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.LoadBalancerManagedIngressConditionType, Status: operatorv1.ConditionFalse},
{Type: operatorv1.DNSManagedIngressConditionType, Status: operatorv1.ConditionFalse},
}
availableConditionsForIngressControllerWithNodePort = []operatorv1.OperatorCondition{
{Type: operatorv1.IngressControllerAvailableConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.LoadBalancerManagedIngressConditionType, Status: operatorv1.ConditionFalse},
{Type: operatorv1.DNSManagedIngressConditionType, Status: operatorv1.ConditionFalse},
{Type: ingresscontroller.IngressControllerAdmittedConditionType, Status: operatorv1.ConditionTrue},
}
availableConditionsForIngressControllerWithLoadBalancer = []operatorv1.OperatorCondition{
{Type: operatorv1.IngressControllerAvailableConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.LoadBalancerManagedIngressConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.LoadBalancerReadyIngressConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.DNSManagedIngressConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.DNSReadyIngressConditionType, Status: operatorv1.ConditionTrue},
{Type: ingresscontroller.IngressControllerAdmittedConditionType, Status: operatorv1.ConditionTrue},
}
// The ingress canary check status condition only applies to the default ingress controller.
defaultAvailableConditions = append(availableConditionsForIngressControllerWithLoadBalancer, operatorv1.OperatorCondition{Type: ingresscontroller.IngressControllerCanaryCheckSuccessConditionType, Status: operatorv1.ConditionTrue})
)
var kclient client.Client
var dnsConfig configv1.DNS
var infraConfig configv1.Infrastructure
var operatorNamespace = operatorcontroller.DefaultOperatorNamespace
var defaultName = types.NamespacedName{Namespace: operatorNamespace, Name: manifests.DefaultIngressControllerName}
var clusterConfigName = types.NamespacedName{Namespace: operatorNamespace, Name: manifests.ClusterIngressConfigName}
func TestMain(m *testing.M) {
kubeConfig, err := config.GetConfig()
if err != nil {
fmt.Printf("failed to get kube config: %s\n", err)
os.Exit(1)
}
kubeClient, err := operatorclient.NewClient(kubeConfig)
if err != nil {
fmt.Printf("failed to create kube client: %s\n", err)
os.Exit(1)
}
kclient = kubeClient
if err := kclient.Get(context.TODO(), types.NamespacedName{Name: "cluster"}, &dnsConfig); err != nil {
fmt.Printf("failed to get DNS config: %v\n", err)
os.Exit(1)
}
if err := kclient.Get(context.TODO(), types.NamespacedName{Name: "cluster"}, &infraConfig); err != nil {
fmt.Printf("failed to get infrastructure config: %v\n", err)
os.Exit(1)
}
os.Exit(m.Run())
}
func TestOperatorSteadyConditions(t *testing.T) {
expected := []configv1.ClusterOperatorStatusCondition{
{Type: configv1.OperatorAvailable, Status: configv1.ConditionTrue},
}
if err := waitForClusterOperatorConditions(t, kclient, expected...); err != nil {
t.Errorf("did not get expected available condition: %v", err)
}
}
func TestClusterOperatorStatusRelatedObjects(t *testing.T) {
expected := []configv1.ObjectReference{
{
Resource: "namespaces",
Name: operatorNamespace,
},
{
Group: operatorv1.GroupName,
Resource: "IngressController",
Namespace: operatorNamespace,
},
{
Group: iov1.GroupVersion.Group,
Resource: "DNSRecord",
Namespace: operatorNamespace,
},
{
Resource: "namespaces",
Name: "openshift-ingress",
},
{
Resource: "namespaces",
Name: "openshift-ingress-canary",
},
}
coName := controller.IngressClusterOperatorName()
err := wait.PollImmediate(1*time.Second, 5*time.Minute, func() (bool, error) {
co := &configv1.ClusterOperator{}
if err := kclient.Get(context.TODO(), coName, co); err != nil {
t.Logf("failed to get ingress cluster operator %s: %v", coName, err)
return false, nil
}
return reflect.DeepEqual(expected, co.Status.RelatedObjects), nil
})
if err != nil {
t.Errorf("did not get expected status related objects: %v", err)
}
}
func TestDefaultIngressControllerSteadyConditions(t *testing.T) {
if err := waitForIngressControllerCondition(t, kclient, 10*time.Second, defaultName, defaultAvailableConditions...); err != nil {
t.Errorf("did not get expected conditions: %v", err)
}
}
// TestDefaultIngressClass verifies that the ingressclass controller has created
// an ingressclass for the default ingresscontroller and recreates the
// ingressclass if it is deleted.
func TestDefaultIngressClass(t *testing.T) {
// The controller should create a "openshift-default" ingressclass.
name := controller.IngressClassName(manifests.DefaultIngressControllerName)
ingressclass := &networkingv1.IngressClass{}
if err := kclient.Get(context.TODO(), name, ingressclass); err != nil {
t.Fatalf("failed to get ingressclass %q: %v", name.Name, err)
}
// The controller should have made the "openshift-default" ingressclass
// the default ingressclass.
//
// TODO This is commented out because it breaks "[sig-network]
// IngressClass [Feature:Ingress] should not set default value if no
// default IngressClass"; we need to fix that test and then re-enable
// this one.
//
// const (
// defaultAnnotation = "ingressclass.kubernetes.io/is-default-class"
// expected = "true"
// )
// if actual, ok := ingressclass.Annotations[defaultAnnotation]; !ok {
// t.Fatalf("ingressclass %q has no %q annotation", name.Name, defaultAnnotation)
// } else if actual != expected {
// t.Fatalf("expected %q annotation to have value %q, found %q", defaultAnnotation, expected, actual)
// }
// The controller should recreate the ingressclass if it is deleted.
if err := kclient.Delete(context.TODO(), ingressclass); err != nil {
t.Fatalf("failed to delete ingressclass %q: %v", name.Name, err)
}
err := wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
if err := kclient.Get(context.TODO(), name, ingressclass); err != nil {
t.Logf("failed to get ingressclass %q: %v", name.Name, err)
return false, nil
}
return true, nil
})
if err != nil {
t.Fatalf("failed to observe recreated ingressclass %q: %v", name.Name, err)
}
}
// TestCustomIngressClass verifies that the ingressclass controller creates an
// ingressclass for a custom ingresscontroller and deletes the ingressclass if
// the ingresscontroller is deleted.
func TestCustomIngressClass(t *testing.T) {
icName := types.NamespacedName{
Namespace: operatorNamespace,
Name: "testcustomingressclass",
}
domain := icName.Name + "." + dnsConfig.Spec.BaseDomain
ic := newPrivateController(icName, domain)
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller %s: %v", icName, err)
}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, icName, availableConditionsForPrivateIngressController...); err != nil {
t.Errorf("failed to observe expected conditions: %w", err)
assertIngressControllerDeleted(t, kclient, ic)
t.FailNow()
}
// The controller should create an ingressclass named
// "openshift-testcustomingressclass".
ingressclassName := controller.IngressClassName(icName.Name)
ingressclass := &networkingv1.IngressClass{}
err := wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
if err := kclient.Get(context.TODO(), ingressclassName, ingressclass); err != nil {
t.Logf("failed to get ingressclass %q: %v", ingressclassName.Name, err)
return false, nil
}
return true, nil
})
if err != nil {
t.Errorf("failed to get ingressclass %q: %v", ingressclassName.Name, err)
assertIngressControllerDeleted(t, kclient, ic)
t.FailNow()
}
// The controller should *not* have made the
// "openshift-testcustomingressclass" ingressclass the default
// ingressclass.
const defaultAnnotation = "ingressclass.kubernetes.io/is-default-class"
if actual, ok := ingressclass.Annotations[defaultAnnotation]; ok && actual != "false" {
t.Errorf("ingressclass %q has annotation %q with value %q", ingressclassName.Name, defaultAnnotation, actual)
}
// The controller should delete the ingressclass if the
// ingresscontroller is deleted.
assertIngressControllerDeleted(t, kclient, ic)
err = wait.PollImmediate(1*time.Second, 1*time.Minute, func() (bool, error) {
if err := kclient.Get(context.TODO(), ingressclassName, ingressclass); err != nil {
if errors.IsNotFound(err) {
return true, nil
}
t.Logf("failed to get ingressclass %q: %v", ingressclassName.Name, err)
return false, nil
}
return false, nil
})
if err != nil {
t.Errorf("failed to observe deletion of ingressclass %q: %v", ingressclassName.Name, err)
}
}
func TestUserDefinedIngressController(t *testing.T) {
name := types.NamespacedName{Namespace: operatorNamespace, Name: "test"}
ing := newLoadBalancerController(name, name.Name+"."+dnsConfig.Spec.BaseDomain)
if err := kclient.Create(context.TODO(), ing); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ing)
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Errorf("failed to observe expected conditions: %v", err)
}
}
func TestUniqueDomainRejection(t *testing.T) {
def := &operatorv1.IngressController{}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, defaultName, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
if err := kclient.Get(context.TODO(), defaultName, def); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
conflictName := types.NamespacedName{Namespace: operatorNamespace, Name: "conflict"}
conflict := newLoadBalancerController(conflictName, def.Status.Domain)
if err := kclient.Create(context.TODO(), conflict); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, conflict)
conditions := []operatorv1.OperatorCondition{
{Type: ingresscontroller.IngressControllerAdmittedConditionType, Status: operatorv1.ConditionFalse},
}
err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, conflictName, conditions...)
if err != nil {
t.Errorf("failed to observe expected conditions: %v", err)
}
}
// TestProxyProtocolOnAWS verifies that the default ingresscontroller
// uses PROXY protocol on AWS.
//
// TODO: should this be a test of source IP preservation in the conformance suite?
func TestProxyProtocolOnAWS(t *testing.T) {
if infraConfig.Status.Platform != configv1.AWSPlatformType {
t.Skip("test skipped on non-aws platform")
return
}
ic := &operatorv1.IngressController{}
if err := kclient.Get(context.TODO(), defaultName, ic); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, defaultName, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
deployment := &appsv1.Deployment{}
if err := kclient.Get(context.TODO(), controller.RouterDeploymentName(ic), deployment); err != nil {
t.Fatalf("failed to get default ingresscontroller deployment: %v", err)
}
// Ensure proxy protocol is enabled on the deployment.
proxyProtocolEnabled := false
for _, v := range deployment.Spec.Template.Spec.Containers[0].Env {
if v.Name == "ROUTER_USE_PROXY_PROTOCOL" {
if val, err := strconv.ParseBool(v.Value); err == nil {
proxyProtocolEnabled = val
break
}
}
}
if !proxyProtocolEnabled {
t.Fatalf("expected deployment to enable the PROXY protocol")
}
}
// TestProxyProtocolAPI verifies that the operator configures router pod
// replicas to use PROXY protocol if it is specified on an ingresscontroller.
func TestProxyProtocolAPI(t *testing.T) {
icName := types.NamespacedName{Namespace: operatorNamespace, Name: "proxy-protocol"}
domain := icName.Name + "." + dnsConfig.Spec.BaseDomain
ic := newNodePortController(icName, domain)
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ic)
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, icName, availableConditionsForIngressControllerWithNodePort...); err != nil {
t.Errorf("failed to observe expected conditions: %v", err)
}
deployment := &appsv1.Deployment{}
if err := kclient.Get(context.TODO(), controller.RouterDeploymentName(ic), deployment); err != nil {
t.Fatalf("failed to get ingresscontroller deployment: %v", err)
}
if err := waitForDeploymentEnvVar(t, kclient, deployment, 1*time.Minute, "ROUTER_USE_PROXY_PROTOCOL", ""); err != nil {
t.Fatalf("expected initial deployment not to enable PROXY protocol: %v", err)
}
if err := kclient.Get(context.TODO(), icName, ic); err != nil {
t.Fatalf("failed to get ingresscontroller: %v", err)
}
ic.Spec.EndpointPublishingStrategy.NodePort = &operatorv1.NodePortStrategy{
Protocol: operatorv1.ProxyProtocol,
}
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Fatalf("failed to update ingresscontroller: %v", err)
}
if err := waitForDeploymentEnvVar(t, kclient, deployment, 1*time.Minute, "ROUTER_USE_PROXY_PROTOCOL", "true"); err != nil {
t.Fatalf("expected updated deployment to enable PROXY protocol: %v", err)
}
}
// NOTE: This test will mutate the default ingresscontroller.
//
// TODO: Find a way to do this test without mutating the default ingress?
func TestUpdateDefaultIngressController(t *testing.T) {
ic := &operatorv1.IngressController{}
if err := kclient.Get(context.TODO(), defaultName, ic); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, defaultName, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
defaultIngressCAConfigmap := &corev1.ConfigMap{}
if err := kclient.Get(context.TODO(), controller.DefaultIngressCertConfigMapName(), defaultIngressCAConfigmap); err != nil {
t.Fatalf("failed to get CA certificate configmap: %v", err)
}
// Verify that the deployment uses the secret name specified in the
// ingress controller, or the default if none is set, and store the
// secret name (if any) so we can reset it at the end of the test.
deployment := &appsv1.Deployment{}
if err := kclient.Get(context.TODO(), controller.RouterDeploymentName(ic), deployment); err != nil {
t.Fatalf("failed to get default deployment: %v", err)
}
originalSecret := ic.Spec.DefaultCertificate.DeepCopy()
expectedSecretName := controller.RouterOperatorGeneratedDefaultCertificateSecretName(ic, deployment.Namespace).Name
if originalSecret != nil {
expectedSecretName = originalSecret.Name
}
if deployment.Spec.Template.Spec.Volumes[0].Secret.SecretName != expectedSecretName {
t.Fatalf("expected router deployment certificate secret to be %s, got %s",
expectedSecretName, deployment.Spec.Template.Spec.Volumes[0].Secret.SecretName)
}
// Update the ingress controller and wait for the deployment to match.
secret, err := createDefaultCertTestSecret(kclient, names.SimpleNameGenerator.GenerateName("test-"))
if err != nil {
t.Fatalf("creating default cert test secret: %v", err)
}
defer func() {
if err := kclient.Delete(context.TODO(), secret); err != nil {
t.Errorf("failed to delete test secret: %v", err)
}
}()
ic.Spec.DefaultCertificate = &corev1.LocalObjectReference{Name: secret.Name}
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Fatalf("failed to update default ingresscontroller: %v", err)
}
name := types.NamespacedName{Namespace: deployment.Namespace, Name: deployment.Name}
err = wait.PollImmediate(1*time.Second, 15*time.Second, func() (bool, error) {
if err := kclient.Get(context.TODO(), name, deployment); err != nil {
t.Logf("failed to get deployment %s: %v", name, err)
return false, nil
}
if deployment.Spec.Template.Spec.Volumes[0].Secret.SecretName != secret.Name {
return false, nil
}
return true, nil
})
if err != nil {
t.Fatalf("failed to observe updated deployment: %v", err)
}
// Wait for the default ingress configmap to be updated
previousDefaultIngressCAConfigmap := defaultIngressCAConfigmap.DeepCopy()
err = wait.PollImmediate(1*time.Second, 10*time.Second, func() (bool, error) {
if err := kclient.Get(context.TODO(), controller.DefaultIngressCertConfigMapName(), defaultIngressCAConfigmap); err != nil {
t.Logf("failed to get CA config map %s: %v", controller.DefaultIngressCertConfigMapName(), err)
return false, nil
}
if defaultIngressCAConfigmap.Data["ca-bundle.crt"] == previousDefaultIngressCAConfigmap.Data["ca-bundle.crt"] {
return false, nil
}
return true, nil
})
if err != nil {
t.Fatalf("failed to observe update of default ingress CA certificate configmap: %v", err)
}
// Reset .spec.defaultCertificate to its original value.
if err := kclient.Get(context.TODO(), defaultName, ic); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
ic.Spec.DefaultCertificate = originalSecret
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Errorf("failed to reset default ingresscontroller: %v", err)
}
// Wait for the default ingress configmap to be updated back to the original
previousDefaultIngressCAConfigmap = defaultIngressCAConfigmap.DeepCopy()
err = wait.PollImmediate(1*time.Second, 10*time.Second, func() (bool, error) {
if err := kclient.Get(context.TODO(), controller.DefaultIngressCertConfigMapName(), defaultIngressCAConfigmap); err != nil {
t.Logf("failed to get CA config map %s: %v", controller.DefaultIngressCertConfigMapName(), err)
return false, nil
}
if defaultIngressCAConfigmap.Data["ca-bundle.crt"] == previousDefaultIngressCAConfigmap.Data["ca-bundle.crt"] {
return false, nil
}
return true, nil
})
if err != nil {
t.Logf("secret content=%v", string(secret.Data["tls.crt"]))
t.Fatalf("failed to observe update of default ingress CA certificate configmap: %v\noriginal=%v\ncurrent=%v", err, previousDefaultIngressCAConfigmap.Data["ca-bundle.crt"], defaultIngressCAConfigmap.Data["ca-bundle.crt"])
}
}
// TestIngressControllerScale exercises a simple scale up/down scenario. This
// test creates a private ingresscontroller with 1 replica and then creates a
// scale client and uses it to scale the ingresscontroller up to 2 replicas and
// then back down to 1 replica.
func TestIngressControllerScale(t *testing.T) {
// Create a new ingresscontroller.
name := types.NamespacedName{Namespace: operatorNamespace, Name: "scale"}
domain := name.Name + "." + dnsConfig.Spec.BaseDomain
ic := newPrivateController(name, domain)
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller %s: %v", name, err)
}
defer assertIngressControllerDeleted(t, kclient, ic)
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForPrivateIngressController...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
// Get the ingresscontroller's deployment's selector and replicaset.
deployment := &appsv1.Deployment{}
if err := kclient.Get(context.TODO(), controller.RouterDeploymentName(ic), deployment); err != nil {
t.Fatalf("failed to get deployment for ingresscontroller %s: %v", name, err)
}
selector, err := metav1.LabelSelectorAsSelector(deployment.Spec.Selector)
if err != nil {
t.Fatalf("router deployment has invalid spec.selector: %v", err)
}
oldRsList := &appsv1.ReplicaSetList{}
if err := kclient.List(context.TODO(), oldRsList, client.MatchingLabelsSelector{Selector: selector}); err != nil {
t.Fatalf("failed to list replicasets for ingresscontroller %s: %v", name, err)
}
// Get a scale client.
//
// TODO: Use controller-runtime once it supports the /scale subresource.
scaleClient, err := getScaleClient()
if err != nil {
t.Fatal(err)
}
// Get the ingresscontroller's scale.
resource := schema.GroupResource{
Group: "operator.openshift.io",
Resource: "ingresscontrollers",
}
scale, err := scaleClient.Scales(name.Namespace).Get(context.TODO(), resource, name.Name, metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get initial scale of ingresscontroller %s: %v", name, err)
}
// Make sure the deployment's selector is reflected in the scale status.
if scale.Status.Selector != selector.String() {
t.Fatalf("expected scale status.selector to be %q, got %q", selector.String(), scale.Status.Selector)
}
// Scale the ingresscontroller up.
originalReplicas := scale.Spec.Replicas
newReplicas := originalReplicas + 1
scale.Spec.Replicas = newReplicas
updatedScale, err := scaleClient.Scales(name.Namespace).Update(context.TODO(), resource, scale, metav1.UpdateOptions{})
if err != nil {
t.Fatalf("failed to scale ingresscontroller %s up: %v", name, err)
}
if updatedScale.Spec.Replicas != scale.Spec.Replicas {
t.Fatalf("expected ingresscontroller %s to have spec.replicas equal to %d, got %d", name, scale.Spec.Replicas, updatedScale.Spec.Replicas)
}
// Wait for the deployment scale-up to be observed.
if err := waitForAvailableReplicas(t, kclient, ic, 4*time.Minute, newReplicas); err != nil {
t.Fatalf("failed waiting deployment of ingresscontroller %s to scale to %d: %v", name, newReplicas, err)
}
// Ensure the ingresscontroller remains available
if err := waitForIngressControllerCondition(t, kclient, 2*time.Minute, name, availableConditionsForPrivateIngressController...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
// Scale back down.
scale, err = scaleClient.Scales(name.Namespace).Get(context.TODO(), resource, name.Name, metav1.GetOptions{})
if err != nil {
t.Fatalf("failed to get updated scale of ClusterIngress: %v", err)
}
scale.Spec.Replicas = originalReplicas
updatedScale, err = scaleClient.Scales(name.Namespace).Update(context.TODO(), resource, scale, metav1.UpdateOptions{})
if err != nil {
t.Fatalf("failed to scale ingresscontroller down: %v", err)
}
if updatedScale.Spec.Replicas != scale.Spec.Replicas {
t.Fatalf("expected ingresscontroller %s to have spec.replicas equal to %d, got %d", name, scale.Spec.Replicas, updatedScale.Spec.Replicas)
}
// Wait for the deployment scale down to be observed.
if err := waitForAvailableReplicas(t, kclient, ic, 2*time.Minute, originalReplicas); err != nil {
t.Fatalf("failed waiting deployment of ingresscontroller %s to scale to %d: %v", name, originalReplicas, err)
}
// Ensure the ingresscontroller remains available
// TODO: assert that the conditions hold steady for some amount of time?
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForPrivateIngressController...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
// Ensure the deployment did not create a new replicaset
// (see <https://bugzilla.redhat.com/show_bug.cgi?id=1783007>).
newRsList := &appsv1.ReplicaSetList{}
if err := kclient.List(context.TODO(), newRsList, client.MatchingLabelsSelector{Selector: selector}); err != nil {
t.Fatalf("failed to list replicasets for ingresscontroller %s: %v", name, err)
}
oldRsIds := sets.String{}
for _, rs := range oldRsList.Items {
oldRsIds.Insert(string(rs.UID))
}
newRsIds := sets.String{}
for _, rs := range newRsList.Items {
newRsIds.Insert(string(rs.UID))
}
if !oldRsIds.IsSuperset(newRsIds) {
t.Fatalf("scaling the deployment of ingresscontroller %s created a new replicaset\nold replicaset list:\n%#v\nnew replicaset list:\n%#v)", name, oldRsList.Items, newRsList.Items)
}
}
func getScaleClient() (scale.ScalesGetter, error) {
kubeConfig, err := config.GetConfig()
if err != nil {
return nil, fmt.Errorf("failed to get kube config: %v", err)
}
client, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
return nil, fmt.Errorf("failed to create kube client: %v", err)
}
cachedDiscovery := discocache.NewMemCacheClient(client.Discovery())
cachedDiscovery.Invalidate()
restMapper := restmapper.NewDeferredDiscoveryRESTMapper(cachedDiscovery)
restMapper.Reset()
scaleKindResolver := scale.NewDiscoveryScaleKindResolver(client.Discovery())
return scale.NewForConfig(kubeConfig, restMapper, dynamic.LegacyAPIPathResolverFunc, scaleKindResolver)
}
// TestDefaultIngressCertificate verifies that the "default-ingress-cert"
// configmap is published and can be used to connect to the router.
func TestDefaultIngressCertificate(t *testing.T) {
ic := &operatorv1.IngressController{}
if err := kclient.Get(context.TODO(), defaultName, ic); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
if ic.Status.EndpointPublishingStrategy.Type != operatorv1.LoadBalancerServiceStrategyType {
t.Skip("test only applicable to load balancer controllers")
return
}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, defaultName, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
defaultIngressCAConfigmap := &corev1.ConfigMap{}
if err := kclient.Get(context.TODO(), controller.DefaultIngressCertConfigMapName(), defaultIngressCAConfigmap); err != nil {
t.Fatalf("failed to get CA certificate configmap: %v", err)
}
var certData []byte
if val, ok := defaultIngressCAConfigmap.Data["ca-bundle.crt"]; !ok {
t.Fatalf("%s configmap is missing %q", controller.DefaultIngressCertConfigMapName(), "ca-bundle.crt")
} else {
certData = []byte(val)
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(certData) {
t.Fatalf("failed to parse CA certificate")
}
wildcardRecordName := controller.WildcardDNSRecordName(ic)
wildcardRecord := &iov1.DNSRecord{}
if err := kclient.Get(context.TODO(), wildcardRecordName, wildcardRecord); err != nil {
t.Fatalf("failed to get wildcard dnsrecord %s: %v", wildcardRecordName, err)
}
// TODO: handle >0 targets
host := wildcardRecord.Spec.Targets[0]
// Make sure we can connect without getting a "certificate signed by
// unknown authority" or "x509: certificate is valid for [...], not
// [...]" error.
serverName := "test." + ic.Status.Domain
address := net.JoinHostPort(host, "443")
conn, err := tls.Dial("tcp", address, &tls.Config{
RootCAs: certPool,
ServerName: serverName,
})
if err != nil {
t.Fatalf("failed to connect to router at %s: %v", address, err)
}
defer func() {
if err := conn.Close(); err != nil {
t.Errorf("failed to close connection: %v", err)
}
}()
if _, err := conn.Write([]byte("GET / HTTP/1.1\r\n\r\n")); err != nil {
t.Fatalf("failed to write: %v", err)
}
// We do not care about the response as long as we can read it without
// error.
if _, err := io.Copy(ioutil.Discard, conn); err != nil && err != io.EOF {
t.Fatalf("failed to read response from router at %s: %v", address, err)
}
}
// TestPodDisruptionBudgetExists verifies that a PodDisruptionBudget resource
// exists for the default ingresscontroller.
func TestPodDisruptionBudgetExists(t *testing.T) {
ic := &operatorv1.IngressController{}
if err := kclient.Get(context.TODO(), defaultName, ic); err != nil {
t.Fatalf("failed to get default ingresscontroller: %v", err)
}
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, defaultName, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
pdb := &policyv1.PodDisruptionBudget{}
if err := kclient.Get(context.TODO(), controller.RouterPodDisruptionBudgetName(ic), pdb); err != nil {
t.Fatalf("failed to get default ingresscontroller poddisruptionbudget: %v", err)
}
}
// TestHostNetworkEndpointPublishingStrategy creates an ingresscontroller with
// the "HostNetwork" endpoint publishing strategy type and verifies that the
// operator creates a router and that the router becomes available.
func TestHostNetworkEndpointPublishingStrategy(t *testing.T) {
name := types.NamespacedName{Namespace: operatorNamespace, Name: "host"}
ing := newHostNetworkController(name, name.Name+"."+dnsConfig.Spec.BaseDomain)
if err := kclient.Create(context.TODO(), ing); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ing)
conditions := []operatorv1.OperatorCondition{
{Type: ingresscontroller.IngressControllerAdmittedConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.IngressControllerAvailableConditionType, Status: operatorv1.ConditionTrue},
{Type: operatorv1.LoadBalancerManagedIngressConditionType, Status: operatorv1.ConditionFalse},
{Type: operatorv1.DNSManagedIngressConditionType, Status: operatorv1.ConditionFalse},
}
err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, conditions...)
if err != nil {
t.Errorf("failed to observe expected conditions: %v", err)
}
}
// TestInternalLoadBalancer creates an ingresscontroller with the
// "LoadBalancerService" endpoint publishing strategy type with scope set to
// "Internal" and verifies that the operator creates a load balancer and that
// the load balancer has a private IP address.
func TestInternalLoadBalancer(t *testing.T) {
platform := infraConfig.Status.Platform
supportedPlatforms := map[configv1.PlatformType]struct{}{
configv1.AWSPlatformType: {},
configv1.AzurePlatformType: {},
configv1.GCPPlatformType: {},
configv1.IBMCloudPlatformType: {},
configv1.AlibabaCloudPlatformType: {},
}
if _, supported := supportedPlatforms[platform]; !supported {
t.Skip(fmt.Sprintf("test skipped on platform %q", platform))
}
annotation := ingresscontroller.InternalLBAnnotations[platform]
name := types.NamespacedName{Namespace: operatorNamespace, Name: "test"}
ic := newLoadBalancerController(name, name.Name+"."+dnsConfig.Spec.BaseDomain)
ic.Spec.EndpointPublishingStrategy.LoadBalancer = &operatorv1.LoadBalancerStrategy{
Scope: operatorv1.InternalLoadBalancer,
}
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ic)
// Wait for the load balancer and DNS to be ready.
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
lbService := &corev1.Service{}
if err := kclient.Get(context.TODO(), controller.LoadBalancerServiceName(ic), lbService); err != nil {
t.Fatalf("failed to get LoadBalancer service: %v", err)
}
for name, expected := range annotation {
if actual, ok := lbService.Annotations[name]; !ok {
t.Fatalf("load balancer has no %q annotation: %v", name, lbService.Annotations)
} else if actual != expected {
t.Fatalf("expected %s=%s, found %s=%s", name, expected, name, actual)
}
}
}
// TestInternalLoadBalancerGlobalAccessGCP creates an ingresscontroller
// with internal load balancer on GCP with the GCP Global Access provider
// parameter set to both "Global" and "local" to verify that the
// Load Balancer service is created properly.
func TestInternalLoadBalancerGlobalAccessGCP(t *testing.T) {
platform := infraConfig.Status.Platform
supportedPlatforms := map[configv1.PlatformType]struct{}{
configv1.GCPPlatformType: {},
}
if _, supported := supportedPlatforms[platform]; !supported {
t.Skip(fmt.Sprintf("test skipped on platform %q", platform))
}
name := types.NamespacedName{Namespace: operatorNamespace, Name: "test-gcp"}
ic := newLoadBalancerController(name, name.Name+"."+dnsConfig.Spec.BaseDomain)
ic.Spec.EndpointPublishingStrategy.LoadBalancer = &operatorv1.LoadBalancerStrategy{
Scope: operatorv1.InternalLoadBalancer,
ProviderParameters: &operatorv1.ProviderLoadBalancerParameters{
Type: operatorv1.GCPLoadBalancerProvider,
GCP: &operatorv1.GCPLoadBalancerParameters{
ClientAccess: operatorv1.GCPGlobalAccess,
},
},
}
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ic)
// Wait for the load balancer and DNS to be ready.
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
lbService := &corev1.Service{}
if err := kclient.Get(context.TODO(), controller.LoadBalancerServiceName(ic), lbService); err != nil {
t.Fatalf("failed to get LoadBalancer service: %v", err)
}
// Verify load balancer has desired global access annotation
annotation := ingresscontroller.GCPGlobalAccessAnnotation
// A ClientAccess value of "Global" results in the Global Access Annotation
// being set to "true".
expected := "true"
if actual, ok := lbService.Annotations[annotation]; !ok {
t.Fatalf("load balancer has no %q annotation: %v", annotation, lbService.Annotations)
} else if actual != expected {
t.Fatalf("expected %s=%s, found %s=%s", annotation, expected, annotation, actual)
}
// Update ingress controller to use "Local" Global Access
if err := kclient.Get(context.TODO(), name, ic); err != nil {
t.Fatalf("failed to get ingresscontroller %s: %v", name, err)
}
ic.Spec.EndpointPublishingStrategy.LoadBalancer.ProviderParameters.GCP.ClientAccess = operatorv1.GCPLocalAccess
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Errorf("failed to update ingresscontroller %s: %v", name, err)
}
// A ClientAccess value of "Local" results in the Global Access Annotation
// being set to "false".
expected = "false"
// Verify load balancer has desired global access annotation.
// Use a polling loop since the operator might not switch out the annotation
// immediately.
err := wait.PollImmediate(1*time.Second, 3*time.Minute, func() (bool, error) {
if err := kclient.Get(context.TODO(), controller.LoadBalancerServiceName(ic), lbService); err != nil {
t.Logf("failed to get LoadBalancer service: %v", err)
return false, nil
}
if actual, ok := lbService.Annotations[annotation]; !ok {
t.Logf("load balancer has no %q annotation: %v", annotation, lbService.Annotations)
return false, nil
} else if actual != expected {
t.Logf("expected %s=%s, found %s=%s", annotation, expected, annotation, actual)
return false, nil
}
return true, nil
})
if err != nil {
t.Errorf("failed to observe expected annotations on load balancer service %s: %v", controller.LoadBalancerServiceName(ic), err)
}
}
// TestScopeChange creates an ingresscontroller with the "LoadBalancerService"
// endpoint publishing strategy type and verifies that the operator behaves
// correctly when the ingresscontroller's scope is mutated. The correct
// behavior depends on the platform on which the test is running. On AWS and
// IBM Cloud, the operator should set the Progressing=True status condition to
// prompt the administrator to delete the old LoadBalancer service. On Azure
// and GCP, the operator should update the LoadBalancer service's annotations.
//
// As a special case, if the ingresscontroller's scope has been changed, the
// "ingress.operator.openshift.io/auto-delete-load-balancer" annotation is set
// on the ingresscontroller, and the current platform requires deleting and
// recreating the LoadBalancer service to change its scope, then the operator
// should delete and recreate the service automatically.
func TestScopeChange(t *testing.T) {
platform := infraConfig.Status.Platform
supportedPlatforms := map[configv1.PlatformType]struct{}{
configv1.AlibabaCloudPlatformType: {},
configv1.AWSPlatformType: {},
configv1.AzurePlatformType: {},
configv1.GCPPlatformType: {},
configv1.IBMCloudPlatformType: {},
configv1.PowerVSPlatformType: {},
}
if _, supported := supportedPlatforms[platform]; !supported {
t.Skipf("test skipped on platform %q", platform)
}
name := types.NamespacedName{Namespace: operatorNamespace, Name: "scope"}
ic := newLoadBalancerController(name, name.Name+"."+dnsConfig.Spec.BaseDomain)
ic.Spec.EndpointPublishingStrategy.LoadBalancer = &operatorv1.LoadBalancerStrategy{
Scope: operatorv1.ExternalLoadBalancer,
}
if err := kclient.Create(context.TODO(), ic); err != nil {
t.Fatalf("failed to create ingresscontroller: %v", err)
}
defer assertIngressControllerDeleted(t, kclient, ic)
// Wait for the load balancer and DNS to be ready.
if err := waitForIngressControllerCondition(t, kclient, 5*time.Minute, name, availableConditionsForIngressControllerWithLoadBalancer...); err != nil {
t.Fatalf("failed to observe expected conditions: %v", err)
}
lbService := &corev1.Service{}
if err := kclient.Get(context.TODO(), controller.LoadBalancerServiceName(ic), lbService); err != nil {
t.Fatalf("failed to get LoadBalancer service: %v", err)
}
if ingresscontroller.IsServiceInternal(lbService) {
t.Fatalf("load balancer is internal but should be external")
}
// Change the scope to internal and wait for everything to come back to
// normal.
if err := kclient.Get(context.TODO(), name, ic); err != nil {
t.Fatalf("failed to get ingresscontroller %s: %v", name, err)
}
ic.Spec.EndpointPublishingStrategy.LoadBalancer.Scope = operatorv1.InternalLoadBalancer
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Fatal(err)
}
switch platform {
case configv1.AlibabaCloudPlatformType, configv1.AWSPlatformType, configv1.IBMCloudPlatformType, configv1.PowerVSPlatformType:
progressingTrue := operatorv1.OperatorCondition{
Type: operatorv1.OperatorStatusTypeProgressing,
Status: operatorv1.ConditionTrue,
}
if err := waitForIngressControllerCondition(t, kclient, 1*time.Minute, name, progressingTrue); err != nil {
t.Fatalf("failed to observe the ingresscontroller report Progressing=True: %v", err)
}
case configv1.AzurePlatformType, configv1.GCPPlatformType:
err := wait.PollImmediate(5*time.Second, 5*time.Minute, func() (bool, error) {
service := &corev1.Service{}
if err := kclient.Get(context.TODO(), controller.LoadBalancerServiceName(ic), service); err != nil {
if errors.IsNotFound(err) {
return false, nil
}
t.Logf("failed to get service %s: %v", controller.LoadBalancerServiceName(ic), err)
return false, nil
}
if ingresscontroller.IsServiceInternal(service) {
return true, nil
}
t.Logf("service is still external: %#v\n", service)
return false, nil
})
if err != nil {
t.Fatalf("expected load balancer to become internal: %v", err)
}
}
// Change the scope back to external and wait for everything to come
// back to normal.
if err := kclient.Get(context.TODO(), name, ic); err != nil {
t.Fatalf("failed to get ingresscontroller %s: %v", name, err)
}
ic.Spec.EndpointPublishingStrategy.LoadBalancer.Scope = operatorv1.ExternalLoadBalancer
if err := kclient.Update(context.TODO(), ic); err != nil {
t.Fatal(err)
}