-
Notifications
You must be signed in to change notification settings - Fork 131
/
core_controller.go
1857 lines (1662 loc) · 78.4 KB
/
core_controller.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 (c) 2019-2024 Tigera, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package installation
import (
"context"
"errors"
"fmt"
"math"
"net"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
relasticsearch "github.com/tigera/operator/pkg/render/common/elasticsearch"
"github.com/go-logr/logr"
configv1 "github.com/openshift/api/config/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
v3 "github.com/tigera/api/pkg/apis/projectcalico/v3"
operator "github.com/tigera/operator/api/v1"
v1 "github.com/tigera/operator/api/v1"
"github.com/tigera/operator/pkg/active"
crdv1 "github.com/tigera/operator/pkg/apis/crd.projectcalico.org/v1"
"github.com/tigera/operator/pkg/common"
"github.com/tigera/operator/pkg/components"
"github.com/tigera/operator/pkg/controller/certificatemanager"
"github.com/tigera/operator/pkg/controller/k8sapi"
"github.com/tigera/operator/pkg/controller/migration"
"github.com/tigera/operator/pkg/controller/migration/convert"
"github.com/tigera/operator/pkg/controller/options"
"github.com/tigera/operator/pkg/controller/status"
"github.com/tigera/operator/pkg/controller/utils"
"github.com/tigera/operator/pkg/controller/utils/imageset"
"github.com/tigera/operator/pkg/crds"
"github.com/tigera/operator/pkg/ctrlruntime"
"github.com/tigera/operator/pkg/dns"
"github.com/tigera/operator/pkg/render"
rcertificatemanagement "github.com/tigera/operator/pkg/render/certificatemanagement"
"github.com/tigera/operator/pkg/render/common/networkpolicy"
"github.com/tigera/operator/pkg/render/common/resourcequota"
"github.com/tigera/operator/pkg/render/kubecontrollers"
"github.com/tigera/operator/pkg/render/monitor"
"github.com/tigera/operator/pkg/tls/certificatemanagement"
)
const (
techPreviewFeatureSeccompApparmor = "tech-preview.operator.tigera.io/node-apparmor-profile"
// The default port used by calico/node to report Calico Enterprise internal metrics.
// This is separate from the calico/node prometheus metrics port, which is user configurable.
defaultNodeReporterPort = 9081
)
const InstallationName string = "calico"
//// Use of Finalizers for graceful termination
//
// There is a problem with tearing down the Calico resources where removing the calico-cni RBAC resources
// prevents pod-networked pods (e.g., kube-controllers) from teminating because the CNI plugin no longer has the necessary permissions.
//
// To ensure this problem does not happen we make liberal use of finalizers to ensure a staged teardown of resources created by this operator.
//
// - Each controller (including this one) that requires the CNI plugin for teardown can add its own finalizer to the Installation CR, and is responsible
// for removing this finalizer when its finalization logic is complete.
// - This controller adds a finalizer to the Calico CNI resources to ensure they remain even when the Installation
// is deleted. This finalizer is only removed once all per-controller finalizers on the Installation are removed.
// - This controller adds a finalizer to the Installation that is only removed after the CNI resources have had their finalizers removed.
// This allows the Installation resource to remain while the operator as a whole cleans up.
//
// When the Installation resource is being deleted (has a DeletionTimestamp) the following sequence occurs:
//
// 1. Kubernetes will begin cleaning up any resources owned by the Installation.
// 2. This controller will pass Terminating=true to the kube-controllers render code, ensuring
// the kube-controllers resources are explicitly deleted.
// 3. Once kube-controllers is terminated we will remove this controller's Finalizer from the Installation.
// 4. Once there are no more per-controller finalizers on the Installation, this controller will re-render the calico-cni ClusterRoleBinding,
// ClusterRole, and ServiceAccount resources to remove the finalizers on them.
// 4. Once the calico-cni finalizers are emoved, this controller will remove the tigera.io/operator-cleanup finalizer
// from the Installation, allowing it to be deleted.
// 5. Deletion of the Installation will trigger cleanup of the remaining calico-system resources left in the cluster.
var (
log = logf.Log.WithName("controller_installation")
openshiftNetworkConfig = "cluster"
)
// Add creates a new Installation Controller and adds it to the Manager. The Manager will set fields on the Controller
// and Start it when the Manager is Started.
func Add(mgr manager.Manager, opts options.AddOptions) error {
ri, err := newReconciler(mgr, opts)
if err != nil {
return fmt.Errorf("failed to create Core Reconciler: %w", err)
}
c, err := ctrlruntime.NewController("tigera-installation-controller", mgr, controller.Options{Reconciler: ri})
if err != nil {
return fmt.Errorf("Failed to create tigera-installation-controller: %w", err)
}
// Established deferred watches against the v3 API that should succeed after the Enterprise API Server becomes available.
if opts.EnterpriseCRDExists {
k8sClient, err := kubernetes.NewForConfig(mgr.GetConfig())
if err != nil {
log.Error(err, "Failed to establish a connection to k8s")
return err
}
// Watch for changes to Tier, as its status is used as input to determine whether network policy should be reconciled by this controller.
go utils.WaitToAddTierWatch(networkpolicy.TigeraComponentTierName, c, k8sClient, log, ri.tierWatchReady)
go utils.WaitToAddNetworkPolicyWatches(c, k8sClient, log, []types.NamespacedName{
{Name: kubecontrollers.KubeControllerNetworkPolicyName, Namespace: common.CalicoNamespace},
},
)
}
return add(c, ri)
}
// newReconciler returns a new reconcile.Reconciler
func newReconciler(mgr manager.Manager, opts options.AddOptions) (*ReconcileInstallation, error) {
nm, err := migration.NewCoreNamespaceMigration(mgr.GetConfig())
if err != nil {
return nil, fmt.Errorf("Failed to initialize Namespace migration: %w", err)
}
statusManager := status.New(mgr.GetClient(), "calico", opts.KubernetesVersion)
// The typhaAutoscaler needs a clientset.
cs, err := kubernetes.NewForConfig(mgr.GetConfig())
if err != nil {
return nil, err
}
// Create the SharedIndexInformer used by the typhaAutoscaler
nodeListWatch := cache.NewListWatchFromClient(cs.CoreV1().RESTClient(), "nodes", "", fields.Everything())
nodeIndexInformer := cache.NewSharedIndexInformer(nodeListWatch, &corev1.Node{}, 0, cache.Indexers{})
go nodeIndexInformer.Run(opts.ShutdownContext.Done())
// Create a Typha autoscaler.
typhaListWatch := cache.NewListWatchFromClient(cs.AppsV1().RESTClient(), "deployments", "calico-system", fields.OneTermEqualSelector("metadata.name", "calico-typha"))
typhaScaler := newTyphaAutoscaler(cs, nodeIndexInformer, typhaListWatch, statusManager)
r := &ReconcileInstallation{
config: mgr.GetConfig(),
client: mgr.GetClient(),
scheme: mgr.GetScheme(),
watches: make(map[runtime.Object]struct{}),
autoDetectedProvider: opts.DetectedProvider,
status: statusManager,
typhaAutoscaler: typhaScaler,
namespaceMigration: nm,
enterpriseCRDsExist: opts.EnterpriseCRDExists,
clusterDomain: opts.ClusterDomain,
manageCRDs: opts.ManageCRDs,
usePSP: opts.UsePSP,
tierWatchReady: &utils.ReadyFlag{},
}
r.status.Run(opts.ShutdownContext)
r.typhaAutoscaler.start(opts.ShutdownContext)
return r, nil
}
// add adds watches for resources that are available at startup
func add(c ctrlruntime.Controller, r *ReconcileInstallation) error {
// Watch for changes to primary resource Installation
err := c.WatchObject(&operator.Installation{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch primary resource: %w", err)
}
// Watch for changes to TigeraStatus.
if err = utils.AddTigeraStatusWatch(c, InstallationName); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch calico Tigerastatus: %w", err)
}
if r.autoDetectedProvider == operator.ProviderOpenShift {
// Watch for openshift network configuration as well. If we're running in OpenShift, we need to
// merge this configuration with our own and the write back the status object.
err = c.WatchObject(&configv1.Network{}, &handler.EnqueueRequestForObject{})
if err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("tigera-installation-controller failed to watch openshift network config: %w", err)
}
}
}
// Watch for secrets in the operator namespace. We watch for all secrets, since we care
// about specifically named ones - e.g., manager-tls, as well as image pull secrets that
// may have been provided by the user with arbitrary names.
err = utils.AddSecretsWatch(c, "", common.OperatorNamespace())
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch secrets: %w", err)
}
for _, cm := range []string{render.BirdTemplatesConfigMapName, render.BGPLayoutConfigMapName, render.K8sSvcEndpointConfigMapName, render.TyphaCAConfigMapName} {
if err = utils.AddConfigMapWatch(c, cm, common.OperatorNamespace(), &handler.EnqueueRequestForObject{}); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch ConfigMap %s: %w", cm, err)
}
}
if err = utils.AddConfigMapWatch(c, active.ActiveConfigMapName, common.CalicoNamespace, &handler.EnqueueRequestForObject{}); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch ConfigMap %s: %w", active.ActiveConfigMapName, err)
}
if err = imageset.AddImageSetWatch(c); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch ImageSet: %w", err)
}
for _, obj := range secondaryResources() {
if err = utils.AddNamespacedWatch(c, obj, &handler.EnqueueRequestForObject{}); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch %s: %w", obj, err)
}
}
// Watch for changes to KubeControllersConfiguration.
err = c.WatchObject(&crdv1.KubeControllersConfiguration{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch KubeControllersConfiguration resource: %w", err)
}
// Watch for changes to FelixConfiguration.
err = c.WatchObject(&crdv1.FelixConfiguration{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch FelixConfiguration resource: %w", err)
}
// Watch for changes to BGPConfiguration.
err = c.WatchObject(&crdv1.BGPConfiguration{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch BGPConfiguration resource: %w", err)
}
if r.enterpriseCRDsExist {
// Watch for changes to primary resource ManagementCluster
err = c.WatchObject(&operator.ManagementCluster{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch primary resource: %v", err)
}
// Watch for changes to primary resource ManagementClusterConnection
err = c.WatchObject(&operator.ManagementClusterConnection{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch primary resource: %v", err)
}
// watch for change to primary resource LogCollector
err = c.WatchObject(&operator.LogCollector{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch primary resource: %v", err)
}
// Watch the internal manager TLS secret in the operator namespace, which included in the bundle for es-kube-controllers.
if err = utils.AddSecretsWatch(c, render.ManagerInternalTLSSecretName, common.OperatorNamespace()); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch secret: %v", err)
}
if r.manageCRDs {
if err = addCRDWatches(c, operator.TigeraSecureEnterprise); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch CRD resource: %v", err)
}
}
} else {
if r.manageCRDs {
if err = addCRDWatches(c, operator.Calico); err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch CRD resource: %v", err)
}
}
}
// Watch for changes to IPPool.
err = c.WatchObject(&crdv1.IPPool{}, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to watch IPPool resource: %w", err)
}
// Perform periodic reconciliation. This acts as a backstop to catch reconcile issues,
// and also makes sure we spot when things change that might not trigger a reconciliation.
err = utils.AddPeriodicReconcile(c, utils.PeriodicReconcileTime, &handler.EnqueueRequestForObject{})
if err != nil {
return fmt.Errorf("tigera-installation-controller failed to create periodic reconcile watch: %w", err)
}
return nil
}
// secondaryResources returns a list of the secondary resources that this controller
// monitors for changes. Add resources here which correspond to the resources created by
// this controller.
func secondaryResources() []client.Object {
return []client.Object{
// We care about all of these resource types, so long as they are in the calico-system namespace.
&appsv1.DaemonSet{ObjectMeta: metav1.ObjectMeta{Namespace: common.CalicoNamespace}},
&appsv1.Deployment{ObjectMeta: metav1.ObjectMeta{Namespace: common.CalicoNamespace}},
&corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Namespace: common.CalicoNamespace}},
&corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: common.CalicoNamespace}},
// We care about specific named resources of these types.
&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: render.CalicoNodeObjectName}},
&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: render.CalicoCNIPluginObjectName}},
&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: kubecontrollers.KubeControllerRole}},
&rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: render.CalicoNodeObjectName}},
&rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: render.CalicoCNIPluginObjectName}},
&rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: kubecontrollers.KubeControllerRole}},
&corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: common.CalicoNamespace}},
}
}
var _ reconcile.Reconciler = &ReconcileInstallation{}
// ReconcileInstallation reconciles a Installation object
type ReconcileInstallation struct {
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
config *rest.Config
client client.Client
scheme *runtime.Scheme
watches map[runtime.Object]struct{}
autoDetectedProvider operator.Provider
status status.StatusManager
typhaAutoscaler *typhaAutoscaler
namespaceMigration migration.NamespaceMigration
enterpriseCRDsExist bool
amazonCRDExists bool
migrationChecked bool
clusterDomain string
manageCRDs bool
usePSP bool
tierWatchReady *utils.ReadyFlag
}
// getActivePools returns the full set of enabled IP pools in the cluster.
func getActivePools(ctx context.Context, client client.Client) (*crdv1.IPPoolList, error) {
allPools := crdv1.IPPoolList{}
if err := client.List(ctx, &allPools); err != nil && !apierrors.IsNotFound(err) {
return nil, fmt.Errorf("unable to list IPPools: %s", err.Error())
}
filtered := crdv1.IPPoolList{}
for _, pool := range allPools.Items {
if pool.Spec.Disabled {
continue
}
filtered.Items = append(filtered.Items, pool)
}
return &filtered, nil
}
// updateInstallationWithDefaults returns the default installation instance with defaults populated.
func updateInstallationWithDefaults(ctx context.Context, client client.Client, instance *operator.Installation, provider operator.Provider) error {
// Determine the provider in use by combining any auto-detected value with any value
// specified in the Installation CR. mergeProvider updates the CR with the correct value.
err := mergeProvider(instance, provider)
if err != nil {
return err
}
awsNode := &appsv1.DaemonSet{}
key := types.NamespacedName{Name: "aws-node", Namespace: metav1.NamespaceSystem}
err = client.Get(ctx, key, awsNode)
if err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("Unable to read aws-node daemonset: %s", err.Error())
}
awsNode = nil
}
currentPools, err := getActivePools(ctx, client)
if err != nil {
return fmt.Errorf("unable to list IPPools: %s", err.Error())
}
err = MergeAndFillDefaults(instance, awsNode, currentPools)
if err != nil {
return err
}
return nil
}
// MergeAndFillDefaults merges in configuration from the Kubernetes provider, if applicable, and then
// populates defaults in the Installation instance.
func MergeAndFillDefaults(i *operator.Installation, awsNode *appsv1.DaemonSet, currentPools *crdv1.IPPoolList) error {
if awsNode != nil {
if err := updateInstallationForAWSNode(i, awsNode); err != nil {
return fmt.Errorf("Could not resolve AWS node configuration: %s", err.Error())
}
}
return fillDefaults(i, currentPools)
}
// fillDefaults populates the default values onto an Installation object.
func fillDefaults(instance *operator.Installation, currentPools *crdv1.IPPoolList) error {
// Populate the instance with defaults for any fields not provided by the user.
if len(instance.Spec.Registry) != 0 && instance.Spec.Registry != components.UseDefault && !strings.HasSuffix(instance.Spec.Registry, "/") {
// Make sure registry, except for the special case "UseDefault", always ends with a slash.
instance.Spec.Registry = fmt.Sprintf("%s/", instance.Spec.Registry)
}
if len(instance.Spec.Variant) == 0 {
// Default to installing Calico.
instance.Spec.Variant = operator.Calico
}
// Default to running Calico as privileged.
if instance.Spec.NonPrivileged == nil {
npd := operator.NonPrivilegedDisabled
instance.Spec.NonPrivileged = &npd
}
if instance.Spec.TyphaAffinity == nil {
switch instance.Spec.KubernetesProvider {
// in AKS, there is a feature called 'virtual-nodes' which represent azure's container service as a node in the kubernetes cluster.
// virtual-nodes have many limitations, namely it's unable to run hostNetworked pods. virtual-kubelets are tainted to prevent pods from running on them,
// but typha tolerates all taints and will run there.
// as such, we add a required anti-affinity for virtual-nodes if running on azure
case operator.ProviderAKS:
instance.Spec.TyphaAffinity = &operator.TyphaAffinity{
NodeAffinity: &operator.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: []corev1.NodeSelectorTerm{{
MatchExpressions: []corev1.NodeSelectorRequirement{
{
Key: "type",
Operator: corev1.NodeSelectorOpNotIn,
Values: []string{"virtual-node"},
},
{
Key: "kubernetes.azure.com/cluster",
Operator: corev1.NodeSelectorOpExists,
},
},
}},
},
},
}
default:
instance.Spec.TyphaAffinity = nil
}
}
// Default the CNI plugin based on the Kubernetes provider.
if instance.Spec.CNI == nil {
instance.Spec.CNI = &operator.CNISpec{}
}
if instance.Spec.CNI.Type == "" {
switch instance.Spec.KubernetesProvider {
case operator.ProviderAKS:
instance.Spec.CNI.Type = operator.PluginAzureVNET
case operator.ProviderEKS:
instance.Spec.CNI.Type = operator.PluginAmazonVPC
case operator.ProviderGKE:
instance.Spec.CNI.Type = operator.PluginGKE
default:
instance.Spec.CNI.Type = operator.PluginCalico
}
}
// Default IPAM based on CNI.
if instance.Spec.CNI.IPAM == nil {
instance.Spec.CNI.IPAM = &operator.IPAMSpec{}
}
if instance.Spec.CNI.IPAM.Type == "" {
switch instance.Spec.CNI.Type {
case operator.PluginAzureVNET:
instance.Spec.CNI.IPAM.Type = operator.IPAMPluginAzureVNET
case operator.PluginAmazonVPC:
instance.Spec.CNI.IPAM.Type = operator.IPAMPluginAmazonVPC
case operator.PluginGKE:
instance.Spec.CNI.IPAM.Type = operator.IPAMPluginHostLocal
default:
instance.Spec.CNI.IPAM.Type = operator.IPAMPluginCalico
}
}
// Default any unspecified fields within the CalicoNetworkSpec.
if instance.Spec.CalicoNetwork == nil {
instance.Spec.CalicoNetwork = &operator.CalicoNetworkSpec{}
}
// Default dataplane is iptables.
if instance.Spec.CalicoNetwork.LinuxDataplane == nil {
dpIptables := operator.LinuxDataplaneIptables
instance.Spec.CalicoNetwork.LinuxDataplane = &dpIptables
}
// Default Windows dataplane is disabled
winDataplaneDisabled := operator.WindowsDataplaneDisabled
if instance.Spec.CalicoNetwork.WindowsDataplane == nil {
instance.Spec.CalicoNetwork.WindowsDataplane = &winDataplaneDisabled
}
// If Windows is enabled, populate CNI bin, config and log dirs with defaults
// per provider if not explicitly configured
if *instance.Spec.CalicoNetwork.WindowsDataplane != winDataplaneDisabled {
if instance.Spec.WindowsNodes == nil {
instance.Spec.WindowsNodes = &operator.WindowsNodeSpec{}
}
defaultCNIBinDir, defaultCNIConfigDir, defaultCNILogDir := render.DefaultWindowsCNIDirectories(instance.Spec)
if instance.Spec.WindowsNodes.CNIBinDir == "" {
instance.Spec.WindowsNodes.CNIBinDir = defaultCNIBinDir
}
if instance.Spec.WindowsNodes.CNIConfigDir == "" {
instance.Spec.WindowsNodes.CNIConfigDir = defaultCNIConfigDir
}
if instance.Spec.WindowsNodes.CNILogDir == "" {
instance.Spec.WindowsNodes.CNILogDir = defaultCNILogDir
}
}
// Default BGP enablement based on CNI plugin and provider.
if instance.Spec.CalicoNetwork.BGP == nil {
enabled := operator.BGPEnabled
disabled := operator.BGPDisabled
switch instance.Spec.CNI.Type {
case operator.PluginCalico:
switch instance.Spec.KubernetesProvider {
case operator.ProviderEKS:
// On EKS, we use VXLAN mode with Calico CNI so default BGP off.
instance.Spec.CalicoNetwork.BGP = &disabled
default:
// Other platforms assume BGP is needed.
instance.Spec.CalicoNetwork.BGP = &enabled
}
default:
// For non-Calico CNIs, assume BGP should be off.
instance.Spec.CalicoNetwork.BGP = &disabled
}
}
needIPv4Autodetection := false
if *instance.Spec.CalicoNetwork.LinuxDataplane == operator.LinuxDataplaneBPF {
// BPF dataplane requires IP autodetection even if we're not using Calico IPAM.
needIPv4Autodetection = true
}
if currentPools != nil {
for _, pool := range currentPools.Items {
ip, _, err := net.ParseCIDR(pool.Spec.CIDR)
if err != nil {
return fmt.Errorf("failed to parse CIDR %s: %s", pool.Spec.CIDR, err)
}
if ip.To4() != nil {
// This is an IPv4 pool - we should default IPv4 autodetection if not specified.
needIPv4Autodetection = true
} else if ip.To16() != nil {
// This is an IPv6 pool - we should default IPv6 autodetection if not specified.
if instance.Spec.CalicoNetwork.NodeAddressAutodetectionV6 == nil {
t := true
instance.Spec.CalicoNetwork.NodeAddressAutodetectionV6 = &operator.NodeAddressAutodetection{
FirstFound: &t,
}
}
}
}
}
if needIPv4Autodetection && instance.Spec.CalicoNetwork.NodeAddressAutodetectionV4 == nil {
switch instance.Spec.KubernetesProvider {
case operator.ProviderDockerEE:
// firstFound finds the Docker Enterprise interface prefixed with br-, which is unusable for the
// node address, so instead skip the interface br-.
instance.Spec.CalicoNetwork.NodeAddressAutodetectionV4 = &operator.NodeAddressAutodetection{
SkipInterface: "^br-.*",
}
case operator.ProviderEKS:
// EKS uses multiple interfaces to spread load; we want to pick the main interface with the
// default route.
instance.Spec.CalicoNetwork.NodeAddressAutodetectionV4 = &operator.NodeAddressAutodetection{
CanReach: "8.8.8.8",
}
default:
// Default IPv4 address detection to "first found" if not specified.
t := true
instance.Spec.CalicoNetwork.NodeAddressAutodetectionV4 = &operator.NodeAddressAutodetection{
FirstFound: &t,
}
}
}
if instance.Spec.CNI.Type == operator.PluginCalico &&
*instance.Spec.CalicoNetwork.LinuxDataplane == operator.LinuxDataplaneIptables &&
instance.Spec.CalicoNetwork.LinuxPolicySetupTimeoutSeconds == nil {
var delay int32 = 0
instance.Spec.CalicoNetwork.LinuxPolicySetupTimeoutSeconds = &delay
}
// While a number of the fields in this section are relevant to all CNI plugins,
// there are some settings which are currently only applicable if using Calico CNI.
// Handle those here.
if instance.Spec.CNI.Type == operator.PluginCalico {
if instance.Spec.CalicoNetwork.HostPorts == nil {
hp := operator.HostPortsEnabled
instance.Spec.CalicoNetwork.HostPorts = &hp
}
if instance.Spec.CalicoNetwork.MultiInterfaceMode == nil {
mm := operator.MultiInterfaceModeNone
instance.Spec.CalicoNetwork.MultiInterfaceMode = &mm
}
// setting default values for calico-cni logging configuration when not provided by the user
if instance.Spec.Logging == nil {
instance.Spec.Logging = new(operator.Logging)
}
if instance.Spec.Logging.CNI == nil {
instance.Spec.Logging.CNI = new(operator.CNILogging)
}
// set LofSeverity default to Info
if instance.Spec.Logging.CNI.LogSeverity == nil {
instance.Spec.Logging.CNI.LogSeverity = new(operator.LogLevel)
*instance.Spec.Logging.CNI.LogSeverity = operator.LogLevelInfo
}
// set LogFileMaxCount default to 10
if instance.Spec.Logging.CNI.LogFileMaxCount == nil {
instance.Spec.Logging.CNI.LogFileMaxCount = new(uint32)
*instance.Spec.Logging.CNI.LogFileMaxCount = 10
}
// set LogFileMaxAge default to 30 days
if instance.Spec.Logging.CNI.LogFileMaxAgeDays == nil {
instance.Spec.Logging.CNI.LogFileMaxAgeDays = new(uint32)
*instance.Spec.Logging.CNI.LogFileMaxAgeDays = 30
}
// set LogFileMaxSize default to 100 Mi
if instance.Spec.Logging.CNI.LogFileMaxSize == nil {
instance.Spec.Logging.CNI.LogFileMaxSize = new(resource.Quantity)
*instance.Spec.Logging.CNI.LogFileMaxSize = resource.MustParse("100Mi")
}
}
// If not specified by the user, set the default control plane replicas to 2.
if instance.Spec.ControlPlaneReplicas == nil {
var replicas int32 = 2
instance.Spec.ControlPlaneReplicas = &replicas
}
// If not specified by the user, set the flex volume plugin location based on platform.
if len(instance.Spec.FlexVolumePath) == 0 {
if instance.Spec.KubernetesProvider == operator.ProviderOpenShift {
// In OpenShift 4.x, the location for flexvolume plugins has changed.
// See: https://bugzilla.redhat.com/show_bug.cgi?id=1667606#c5
instance.Spec.FlexVolumePath = "/etc/kubernetes/kubelet-plugins/volume/exec/"
} else if instance.Spec.KubernetesProvider == operator.ProviderGKE {
instance.Spec.FlexVolumePath = "/home/kubernetes/flexvolume/"
} else if instance.Spec.KubernetesProvider == operator.ProviderAKS {
instance.Spec.FlexVolumePath = "/etc/kubernetes/volumeplugins/"
} else if instance.Spec.KubernetesProvider == operator.ProviderRKE2 {
instance.Spec.FlexVolumePath = "/var/lib/kubelet/volumeplugins/"
} else {
instance.Spec.FlexVolumePath = "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/"
}
}
if len(instance.Spec.KubeletVolumePluginPath) == 0 {
instance.Spec.KubeletVolumePluginPath = filepath.Clean("/var/lib/kubelet")
}
// Default rolling update parameters.
one := intstr.FromInt(1)
if instance.Spec.NodeUpdateStrategy.RollingUpdate == nil {
instance.Spec.NodeUpdateStrategy.RollingUpdate = &appsv1.RollingUpdateDaemonSet{}
}
if instance.Spec.NodeUpdateStrategy.RollingUpdate.MaxUnavailable == nil {
instance.Spec.NodeUpdateStrategy.RollingUpdate.MaxUnavailable = &one
}
if instance.Spec.NodeUpdateStrategy.Type == "" {
instance.Spec.NodeUpdateStrategy.Type = appsv1.RollingUpdateDaemonSetStrategyType
}
return nil
}
// mergeProvider determines the correct provider based on the auto-detected value, and the user-provided one,
// and updates the Installation CR accordingly. It returns an error if incompatible values are provided.
func mergeProvider(cr *operator.Installation, provider operator.Provider) error {
// If we detected one provider but user set provider to something else, throw an error
if provider != operator.ProviderNone && cr.Spec.KubernetesProvider != operator.ProviderNone && cr.Spec.KubernetesProvider != provider {
msg := "Installation spec.kubernetesProvider '%s' does not match auto-detected value '%s'"
return fmt.Errorf(msg, cr.Spec.KubernetesProvider, provider)
}
// If we've reached this point, it means only one source of provider is being used - auto-detection or
// user-provided, but not both. Or, it means that both have been specified but are the same.
// If it's the CR provided one, then just use that. Otherwise, use the auto-detected one.
if cr.Spec.KubernetesProvider == operator.ProviderNone {
cr.Spec.KubernetesProvider = provider
}
log.WithValues("provider", cr.Spec.KubernetesProvider).V(1).Info("Determined provider")
return nil
}
func (r *ReconcileInstallation) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) {
reqLogger := log.WithValues("Request.Namespace", request.Namespace, "Request.Name", request.Name)
reqLogger.Info("Reconciling Installation.operator.tigera.io")
newActiveCM, err := r.checkActive(reqLogger)
if err != nil {
return reconcile.Result{}, err
}
// Get the installation object if it exists so that we can save the original
// status before we merge/fill that object with other values.
instance := &operator.Installation{}
if err := r.client.Get(ctx, utils.DefaultInstanceKey, instance); err != nil {
if apierrors.IsNotFound(err) {
reqLogger.Info("Installation config not found")
r.status.OnCRNotFound()
return reconcile.Result{}, nil
}
reqLogger.Error(err, "An error occurred when querying the Installation resource")
return reconcile.Result{}, err
}
installationMarkedForDeletion := (instance.DeletionTimestamp != nil)
if installationMarkedForDeletion {
reqLogger.Info("Installation object is terminating")
}
preDefaultPatchFrom := client.MergeFrom(instance.DeepCopy())
// Mark CR found so we can report converter problems via tigerastatus
r.status.OnCRFound()
// SetMetaData in the TigeraStatus such as observedGenerations.
defer r.status.SetMetaData(&instance.ObjectMeta)
// Changes for updating Installation status conditions.
if request.Name == InstallationName && request.Namespace == "" {
ts := &operator.TigeraStatus{}
err := r.client.Get(ctx, types.NamespacedName{Name: InstallationName}, ts)
if err != nil {
return reconcile.Result{}, err
}
instance.Status.Conditions = status.UpdateStatusCondition(instance.Status.Conditions, ts.Status.Conditions)
if err := r.client.Status().Update(ctx, instance); err != nil {
log.WithValues("reason", err).Info("Failed to create Installation status conditions.")
return reconcile.Result{}, err
}
}
instanceStatus := instance.Status
if !r.migrationChecked {
// update Installation resource with existing install if it exists.
nc, err := convert.NeedsConversion(ctx, r.client)
if err != nil {
r.status.SetDegraded(operator.ResourceValidationError, "Error checking for existing installation", err, reqLogger)
return reconcile.Result{}, err
}
if nc {
install, err := convert.Convert(ctx, r.client)
if err != nil {
if errors.As(err, &convert.ErrIncompatibleCluster{}) {
r.status.SetDegraded(operator.MigrationError, "Existing Calico installation can not be managed by Tigera Operator as it is configured in a way that Operator does not currently support. Please update your existing Calico install config", err, reqLogger)
// We should always requeue a convert problem. Don't return error
// to make sure we never back off retrying.
return reconcile.Result{RequeueAfter: utils.StandardRetry}, nil
}
r.status.SetDegraded(operator.MigrationError, "Error converting existing installation", err, reqLogger)
return reconcile.Result{}, err
}
instance.Spec = utils.OverrideInstallationSpec(install.Spec, instance.Spec)
}
}
// update Installation with defaults
if err := updateInstallationWithDefaults(ctx, r.client, instance, r.autoDetectedProvider); err != nil {
r.status.SetDegraded(operator.ResourceReadError, "Error querying installation", err, reqLogger)
return reconcile.Result{}, err
}
reqLogger.V(2).Info("Loaded config", "installation", instance)
// Validate the configuration.
if err := validateCustomResource(instance); err != nil {
r.status.SetDegraded(operator.InvalidConfigurationError, "Invalid Installation provided", err, reqLogger)
return reconcile.Result{}, err
}
// See the section 'Use of Finalizers for graceful termination' at the top of this file for details.
if installationMarkedForDeletion {
// This controller manages a finalizer to track whether its own pods have been properly torn down. Only remove it
// when all pod-networked Pods managed by this controller have been torn down. For now, this is just calico-kube-controllers.
l := &appsv1.Deployment{}
err = r.client.Get(ctx, types.NamespacedName{Name: "calico-kube-controllers", Namespace: common.CalicoNamespace}, l)
if err != nil && !apierrors.IsNotFound(err) {
r.status.SetDegraded(operator.ResourceReadError, "Unable to read calico-kube-controllers deployment", err, reqLogger)
return reconcile.Result{}, err
} else if apierrors.IsNotFound(err) {
reqLogger.Info("calico-kube-controllers has been deleted, removing finalizer", "finalizer", render.InstallationControllerFinalizer)
utils.RemoveInstallationFinalizer(instance, render.InstallationControllerFinalizer)
} else {
reqLogger.Info("calico-kube-controller is still present, waiting for termination")
}
// Keep an overarching finalizer on the Installation object until ALL necessary dependencies have been cleaned up.
// This ensures we don't delete the CNI plugin and calico-node too early, as they are a pre-requisite for tearing
// down networking for other pods deployed by this operator.
doneTerminating := true
reqLogger.V(1).Info("Checking if we can remove Installation finalizer", "finalizer", render.OperatorCompleteFinalizer)
// Wait until the calico-node cluster role binding has been cleaned up. This ClusterRole will only be removed after all other
// controllers have completed their finalization logic and removed their finalizer from the Installation.
crb := rbacv1.ClusterRoleBinding{}
key := types.NamespacedName{Name: "calico-node"}
err := r.client.Get(ctx, key, &crb)
if err != nil && !apierrors.IsNotFound(err) {
r.status.SetDegraded(operator.ResourceNotFound, "Unable to get ClusterRoleBinding", err, reqLogger)
return reconcile.Result{}, err
}
for _, x := range crb.Finalizers {
if x == render.CNIFinalizer {
reqLogger.V(1).Info("Installation still finalizing: ClusterRoleBinding calico-node still active")
doneTerminating = false
}
}
// If all of the above checks passed, we can clear the finalizer responsible for tracking
// whether all operator cleanup has completed.
if doneTerminating {
reqLogger.Info("Removing Installation finalizer", "finalizer", render.OperatorCompleteFinalizer)
utils.RemoveInstallationFinalizer(instance, render.OperatorCompleteFinalizer)
}
} else {
// Add a finalizer to track whether or not this controller's specific finalization logic has completed.
utils.SetInstallationFinalizer(instance, render.InstallationControllerFinalizer)
// Add a finalizer to ensure the Installation is not deleted until all Operator finalization
// logic has completed.
utils.SetInstallationFinalizer(instance, render.OperatorCompleteFinalizer)
}
// Write the discovered configuration back to the API. This is essentially a poor-man's defaulting, and
// ensures that we don't surprise anyone by changing defaults in a future version of the operator.
// Note that we only write the 'base' installation back. We don't want to write the changes from 'overlay', as those should only
// be stored in the 'overlay' resource.
if err := r.client.Patch(ctx, instance, preDefaultPatchFrom); err != nil {
r.status.SetDegraded(operator.ResourceUpdateError, "Failed to write defaults", err, reqLogger)
return reconcile.Result{}, err
}
// Update Installation with 'overlay'
overlay := operator.Installation{}
if err := r.client.Get(ctx, utils.OverlayInstanceKey, &overlay); err != nil {
if !apierrors.IsNotFound(err) {
reqLogger.Error(err, "An error occurred when querying the 'overlay' Installation resource")
return reconcile.Result{}, err
}
reqLogger.V(5).Info("no 'overlay' installation found")
} else {
instance.Spec = utils.OverrideInstallationSpec(instance.Spec, overlay.Spec)
reqLogger.V(2).Info("loaded final computed config", "config", instance)
// Validate the configuration.
if err := validateCustomResource(instance); err != nil {
r.status.SetDegraded(operator.InvalidConfigurationError, "Invalid computed config", err, reqLogger)
return reconcile.Result{}, err
}
}
if err = r.updateCRDs(ctx, instance.Spec.Variant, reqLogger); err != nil {
return reconcile.Result{}, err
}
// Now that migrated config is stored in the installation resource, we no longer need
// to check if a migration is needed for the lifetime of the operator.
r.migrationChecked = true
// A status is needed at this point for operator scorecard tests.
// status.variant is written later but for some tests the reconciliation
// does not get to that point.
if reflect.DeepEqual(instanceStatus, operator.InstallationStatus{}) {
instance.Status = operator.InstallationStatus{}
if err := r.client.Status().Update(ctx, instance); err != nil {
r.status.SetDegraded(operator.ResourceUpdateError, "Failed to write default status", err, reqLogger)
return reconcile.Result{}, err
}
}
// Wait for IP pools to be programmed. This may be done out-of-band by the user, or by the operator's IP pool controller.
currentPools, err := getActivePools(ctx, r.client)
if err != nil {
r.status.SetDegraded(operator.ResourceReadError, "error querying IP pools", err, reqLogger)
return reconcile.Result{}, err
}
// Make sure CNI is configured before continuing.
if instance.Spec.CNI == nil || instance.Spec.CNI.IPAM == nil {
r.status.SetDegraded(operator.InvalidConfigurationError, "waiting for spec.cni to be filled in", nil, reqLogger)
return reconcile.Result{}, nil
}
// Determine if this cluster needs IP pools in order to operate.
// - If the installation has IP pools specified, then the cluster wants IP pools.
// - If the installation has no IP pools specified, it may still need them if it's using Calico IPAM or networking.
needsIPPools := instance.Spec.CalicoNetwork != nil && len(instance.Spec.CalicoNetwork.IPPools) != 0
if instance.Spec.CNI.Type == operator.PluginCalico || instance.Spec.CNI.IPAM.Type == operator.IPAMPluginCalico {
needsIPPools = true
}
if needsIPPools && len(currentPools.Items) == 0 {
r.status.SetDegraded(operator.ResourceNotFound, "waiting for enabled IP pools to be created", nil, reqLogger)
return reconcile.Result{}, nil
}
// If the autoscalar is degraded then trigger a run and recheck the degraded status. If it is still degraded after the
// the run the reset the degraded status and requeue the request.
if r.typhaAutoscaler.isDegraded() {
if err := r.typhaAutoscaler.triggerRun(); err != nil {
r.status.SetDegraded(operator.ResourceScalingError, "Failed to scale typha", err, reqLogger)
return reconcile.Result{RequeueAfter: utils.StandardRetry}, nil
}
}
// The operator supports running in a "Calico only" mode so that it doesn't need to run TSEE specific controllers.
// If we are switching from this mode to one that enables TSEE, we need to restart the operator to enable the other controllers.
if !r.enterpriseCRDsExist && instance.Spec.Variant == operator.TigeraSecureEnterprise {
// Perform an API discovery to determine if the necessary APIs exist. If they do, we can reboot into TSEE mode.
// if they do not, we need to notify the user that the requested configuration is invalid.
b, err := utils.RequiresTigeraSecure(r.config)
if b {
log.Info("Rebooting to enable TigeraSecure controllers")
os.Exit(0)
} else if err != nil {
r.status.SetDegraded(operator.InternalServerError, "Error discovering Tigera Secure availability", err, reqLogger)
} else {
r.status.SetDegraded(operator.InternalServerError, "Cannot deploy Tigera Secure", fmt.Errorf("Missing Tigera Secure custom resource definitions"), reqLogger)
}
// Queue a retry. We don't want to watch the APIServer API since it might not exist and would cause
// this controller to fail.
reqLogger.Info("Scheduling a retry", "when", utils.StandardRetry)
return reconcile.Result{RequeueAfter: utils.StandardRetry}, nil
}
// Query for pull secrets in operator namespace
pullSecrets, err := utils.GetNetworkingPullSecrets(&instance.Spec, r.client)
if err != nil {
r.status.SetDegraded(operator.ResourceReadError, "Error retrieving pull secrets", err, reqLogger)
return reconcile.Result{}, err
}
var managementCluster *operator.ManagementCluster
var managementClusterConnection *operator.ManagementClusterConnection
var logCollector *operator.LogCollector
includeV3NetworkPolicy := false
if r.enterpriseCRDsExist {
logCollector, err = utils.GetLogCollector(ctx, r.client)
if logCollector != nil {
if err != nil {
r.status.SetDegraded(operator.ResourceReadError, "Error reading LogCollector", err, reqLogger)
return reconcile.Result{}, err
}
}
managementCluster, err = utils.GetManagementCluster(ctx, r.client)
if err != nil {
r.status.SetDegraded(operator.ResourceReadError, "Error reading ManagementCluster", err, reqLogger)
return reconcile.Result{}, err
}
managementClusterConnection, err = utils.GetManagementClusterConnection(ctx, r.client)
if err != nil {