-
Notifications
You must be signed in to change notification settings - Fork 139
/
node.go
1880 lines (1697 loc) · 64.5 KB
/
node.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 render
import (
"encoding/json"
"fmt"
"net"
"path/filepath"
"sort"
"strconv"
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
operatorv1 "github.com/tigera/operator/api/v1"
"github.com/tigera/operator/pkg/common"
"github.com/tigera/operator/pkg/components"
"github.com/tigera/operator/pkg/controller/k8sapi"
"github.com/tigera/operator/pkg/controller/migration"
"github.com/tigera/operator/pkg/ptr"
rcomp "github.com/tigera/operator/pkg/render/common/components"
"github.com/tigera/operator/pkg/render/common/configmap"
rmeta "github.com/tigera/operator/pkg/render/common/meta"
"github.com/tigera/operator/pkg/render/common/securitycontext"
"github.com/tigera/operator/pkg/render/common/securitycontextconstraints"
"github.com/tigera/operator/pkg/tls/certificatemanagement"
)
const (
BirdTemplatesConfigMapName = "bird-templates"
birdTemplateHashAnnotation = "hash.operator.tigera.io/bird-templates"
BPFOperatorAnnotation = "operator.tigera.io/bpfEnabled"
nodeCniConfigAnnotation = "hash.operator.tigera.io/cni-config"
bgpLayoutHashAnnotation = "hash.operator.tigera.io/bgp-layout"
bgpBindModeHashAnnotation = "hash.operator.tigera.io/bgp-bind-mode"
BGPLayoutConfigMapName = "bgp-layout"
BGPLayoutConfigMapKey = "earlyNetworkConfiguration"
BGPLayoutVolumeName = "bgp-layout"
BGPLayoutPath = "/etc/calico/early-networking.yaml"
K8sSvcEndpointConfigMapName = "kubernetes-services-endpoint"
nodeTerminationGracePeriodSeconds = 5
CNIFinalizer = "tigera.io/cni-protector"
CalicoNodeMetricsService = "calico-node-metrics"
NodePrometheusTLSServerSecret = "calico-node-prometheus-server-tls"
CalicoNodeObjectName = "calico-node"
CalicoCNIPluginObjectName = "calico-cni-plugin"
BPFVolumeName = "bpffs"
)
var (
// The port used by calico/node to report Calico Enterprise BGP metrics.
// This is currently not intended to be user configurable.
nodeBGPReporterPort int32 = 9900
NodeTLSSecretName = "node-certs"
)
// TyphaNodeTLS holds configuration for Node and Typha to establish TLS.
type TyphaNodeTLS struct {
TrustedBundle certificatemanagement.TrustedBundle
TyphaSecret certificatemanagement.KeyPairInterface
TyphaCommonName string
TyphaURISAN string
NodeSecret certificatemanagement.KeyPairInterface
NodeCommonName string
NodeURISAN string
}
// NodeConfiguration is the public API used to provide information to the render code to
// generate Kubernetes objects for installing calico/node on a cluster.
type NodeConfiguration struct {
K8sServiceEp k8sapi.ServiceEndpoint
Installation *operatorv1.InstallationSpec
IPPools []operatorv1.IPPool
TLS *TyphaNodeTLS
ClusterDomain string
// Optional fields.
LogCollector *operatorv1.LogCollector
MigrateNamespaces bool
NodeAppArmorProfile string
BirdTemplates map[string]string
NodeReporterMetricsPort int
// CanRemoveCNIFinalizer specifies whether CNI plugin is still needed during uninstall since the CNI plugin and
// associated RBAC resources are required for pod teardown to succeed. Setting this to true removes
// the finalizer from the CNI plugin and associated RBAC resources, allowing them to be deleted.
// For details on why this is needed see 'Node and Installation finalizer' in the core_controller.
CanRemoveCNIFinalizer bool
PrometheusServerTLS certificatemanagement.KeyPairInterface
// BGPLayouts is returned by the rendering code after modifying its namespace
// so that it can be deployed into the cluster.
// TODO: The controller should pass the contents, the renderer should build its own
// configmap, rather than this "copy" semantic.
BGPLayouts *corev1.ConfigMap
// The health port that Felix should bind to. The controller reads FelixConfiguration
// and sets this.
FelixHealthPort int
// The bindMode read from the default BGPConfiguration. Used to trigger rolling updates
// should this value change.
BindMode string
FelixPrometheusMetricsEnabled bool
FelixPrometheusMetricsPort int
}
// Node creates the node daemonset and other resources for the daemonset to operate normally.
func Node(cfg *NodeConfiguration) Component {
return &nodeComponent{cfg: cfg}
}
type nodeComponent struct {
// Input configuration from the controller.
cfg *NodeConfiguration
// Calculated internal fields based on the given information.
cniImage string
flexvolImage string
nodeImage string
}
func (c *nodeComponent) ResolveImages(is *operatorv1.ImageSet) error {
reg := c.cfg.Installation.Registry
path := c.cfg.Installation.ImagePath
prefix := c.cfg.Installation.ImagePrefix
var errMsgs []string
appendIfErr := func(imageName string, err error) string {
if err != nil {
errMsgs = append(errMsgs, err.Error())
}
return imageName
}
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
c.cniImage = appendIfErr(components.GetReference(components.ComponentTigeraCNI, reg, path, prefix, is))
c.nodeImage = appendIfErr(components.GetReference(components.ComponentTigeraNode, reg, path, prefix, is))
c.flexvolImage = appendIfErr(components.GetReference(components.ComponentTigeraFlexVolume, reg, path, prefix, is))
} else {
c.flexvolImage = appendIfErr(components.GetReference(components.ComponentCalicoFlexVolume, reg, path, prefix, is))
if operatorv1.IsFIPSModeEnabled(c.cfg.Installation.FIPSMode) {
c.cniImage = appendIfErr(components.GetReference(components.ComponentCalicoCNIFIPS, reg, path, prefix, is))
c.nodeImage = appendIfErr(components.GetReference(components.ComponentCalicoNodeFIPS, reg, path, prefix, is))
} else {
c.cniImage = appendIfErr(components.GetReference(components.ComponentCalicoCNI, reg, path, prefix, is))
c.nodeImage = appendIfErr(components.GetReference(components.ComponentCalicoNode, reg, path, prefix, is))
}
}
if len(errMsgs) != 0 {
return fmt.Errorf("%s", strings.Join(errMsgs, ","))
}
return nil
}
func (c *nodeComponent) SupportedOSType() rmeta.OSType {
return rmeta.OSTypeLinux
}
func (c *nodeComponent) Objects() ([]client.Object, []client.Object) {
objs := []client.Object{
c.nodeServiceAccount(),
c.nodeRole(),
c.nodeRoleBinding(),
c.cniPluginServiceAccount(),
c.cniPluginRole(),
c.cniPluginRoleBinding(),
}
// These are objects to keep even when we're terminating. They will be deleted by the Kubernetes
// garbage collector when the Installation is finally deleted.
objsToKeep := []client.Object{}
if c.cfg.CanRemoveCNIFinalizer {
objsToKeep = objs
objs = []client.Object{}
}
if c.cfg.BGPLayouts != nil {
objs = append(objs, configmap.ToRuntimeObjects(configmap.CopyToNamespace(common.CalicoNamespace, c.cfg.BGPLayouts)...)...)
}
var objsToDelete []client.Object
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
// Include Service for exposing node metrics.
objs = append(objs, c.nodeMetricsService())
}
cniConfig := c.nodeCNIConfigMap()
if cniConfig != nil {
objs = append(objs, cniConfig)
}
if btcm := c.birdTemplateConfigMap(); btcm != nil {
objs = append(objs, btcm)
}
if c.cfg.Installation.KubernetesProvider.IsDockerEE() {
objs = append(objs, c.clusterAdminClusterRoleBinding())
}
objs = append(objs, c.nodeDaemonset(cniConfig))
if c.cfg.MigrateNamespaces {
objs = append(objs, migration.ClusterRoleForKubeSystemNode())
objs = append(objs, migration.ClusterRoleBindingForKubeSystemNode())
} else {
objsToDelete = append(objsToDelete, migration.ClusterRoleForKubeSystemNode())
objsToDelete = append(objsToDelete, migration.ClusterRoleBindingForKubeSystemNode())
}
if c.cfg.CanRemoveCNIFinalizer {
return objsToKeep, append(objs, objsToDelete...)
}
return objs, objsToDelete
}
func (c *nodeComponent) Ready() bool {
return true
}
// CNIPluginFinalizedObjects returns a list of objects that use the CNIFinalizer that should be
// removed only after the CNI plugin is removed.
func CNIPluginFinalizedObjects() []client.Object {
return []client.Object{
&corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: CalicoNodeObjectName, Namespace: common.CalicoNamespace}},
&corev1.ServiceAccount{ObjectMeta: metav1.ObjectMeta{Name: CalicoCNIPluginObjectName, Namespace: common.CalicoNamespace}},
&rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: CalicoNodeObjectName}},
&rbacv1.ClusterRoleBinding{ObjectMeta: metav1.ObjectMeta{Name: CalicoCNIPluginObjectName}},
&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: CalicoNodeObjectName}},
&rbacv1.ClusterRole{ObjectMeta: metav1.ObjectMeta{Name: CalicoCNIPluginObjectName}},
}
}
// nodeServiceAccount creates the node's service account.
func (c *nodeComponent) nodeServiceAccount() *corev1.ServiceAccount {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
return &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{Kind: "ServiceAccount", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoNodeObjectName,
Namespace: common.CalicoNamespace,
Finalizers: finalizer,
},
}
}
// cniPluginServiceAccount creates the Calico CNI plugin's service account.
func (c *nodeComponent) cniPluginServiceAccount() *corev1.ServiceAccount {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
return &corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{Kind: "ServiceAccount", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoCNIPluginObjectName,
Namespace: common.CalicoNamespace,
Finalizers: finalizer,
},
}
}
// nodeRoleBinding creates a clusterrolebinding giving the node service account the required permissions to operate.
func (c *nodeComponent) nodeRoleBinding() *rbacv1.ClusterRoleBinding {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
crb := &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoNodeObjectName,
Labels: map[string]string{},
Finalizers: finalizer,
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: CalicoNodeObjectName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: CalicoNodeObjectName,
Namespace: common.CalicoNamespace,
},
},
}
if c.cfg.MigrateNamespaces {
migration.AddBindingForKubeSystemNode(crb)
}
return crb
}
// cniPluginRoleBinding creates a rolebinding giving the Calico CNI plugin service account the required permissions to operate.
func (c *nodeComponent) cniPluginRoleBinding() *rbacv1.ClusterRoleBinding {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
crb := &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoCNIPluginObjectName,
Finalizers: finalizer,
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: CalicoCNIPluginObjectName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: CalicoCNIPluginObjectName,
Namespace: common.CalicoNamespace,
},
},
}
return crb
}
// nodeRole creates the clusterrole containing policy rules that allow the node daemonset to operate normally.
func (c *nodeComponent) nodeRole() *rbacv1.ClusterRole {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
role := &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRole", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoNodeObjectName,
Labels: map[string]string{},
Finalizers: finalizer,
},
Rules: []rbacv1.PolicyRule{
{
// Calico uses endpoint slices for service-based network policy rules.
APIGroups: []string{"discovery.k8s.io"},
Resources: []string{"endpointslices"},
Verbs: []string{"list", "watch"},
},
{
// The CNI plugin needs to get pods, nodes, namespaces.
APIGroups: []string{""},
Resources: []string{"pods", "nodes", "namespaces"},
Verbs: []string{"get"},
},
{
// Used to discover Typha endpoints and service IPs for advertisement.
APIGroups: []string{""},
Resources: []string{"endpoints", "services"},
Verbs: []string{"watch", "list", "get"},
},
{
// Some information is stored on the node status.
APIGroups: []string{""},
Resources: []string{"nodes/status"},
Verbs: []string{"patch", "update"},
},
{
// For enforcing network policies.
APIGroups: []string{"networking.k8s.io"},
Resources: []string{"networkpolicies"},
Verbs: []string{"watch", "list"},
},
{
// For enforcing admin network policies.
APIGroups: []string{"policy.networking.k8s.io"},
Resources: []string{"adminnetworkpolicies", "baselineadminnetworkpolicies"},
Verbs: []string{"watch", "list"},
},
{
// Metadata from these are used in conjunction with network policy.
APIGroups: []string{""},
Resources: []string{"pods", "namespaces", "serviceaccounts"},
Verbs: []string{"watch", "list"},
},
{
// Calico patches the allocated IP onto the pod.
APIGroups: []string{""},
Resources: []string{"pods/status"},
Verbs: []string{"patch"},
},
{
// Used for creating service account tokens to be used by the CNI plugin.
APIGroups: []string{""},
Resources: []string{"serviceaccounts/token"},
ResourceNames: []string{CalicoCNIPluginObjectName},
Verbs: []string{"create"},
},
{
// Calico needs to query configmaps for pool auto-detection on kubeadm.
APIGroups: []string{""},
Resources: []string{"configmaps"},
Verbs: []string{"get"},
},
{
// For monitoring Calico-specific configuration.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"bgpconfigurations",
"bgpfilters",
"bgpfilters",
"bgppeers",
"blockaffinities",
"clusterinformations",
"felixconfigurations",
"globalnetworkpolicies",
"globalnetworksets",
"hostendpoints",
"ipamblocks",
"ippools",
"ipreservations",
"networkpolicies",
"networksets",
"stagedglobalnetworkpolicies",
"stagedkubernetesnetworkpolicies",
"stagednetworkpolicies",
"tiers",
},
Verbs: []string{"get", "list", "watch"},
},
{
// calico/node monitors for caliconodestatus objects and writes its status back into the object.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"caliconodestatuses",
},
Verbs: []string{"get", "list", "watch", "update"},
},
{
// For migration code in calico/node startup only. Remove when the migration
// code is removed from node.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"globalbgpconfigs",
"globalfelixconfigs",
},
Verbs: []string{"get", "list", "watch"},
},
{
// Calico creates some configuration on startup.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"clusterinformations",
"felixconfigurations",
"ippools",
},
Verbs: []string{"create", "update"},
},
{
// Calico creates some tiers on startup.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"tiers",
},
Verbs: []string{"create"},
},
{
// Calico monitors nodes for some networking configuration.
APIGroups: []string{""},
Resources: []string{"nodes"},
Verbs: []string{"get", "list", "watch"},
},
{
// Most IPAM resources need full CRUD permissions so we can allocate and
// release IP addresses for pods.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"blockaffinities",
"ipamblocks",
"ipamconfigs",
"ipamhandles",
},
Verbs: []string{"get", "list", "create", "update", "delete"},
},
{
// But, we only need to be able to query for IPAM config.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{"ipamconfigs"},
Verbs: []string{"get"},
},
{
// confd (and in some cases, felix) watches block affinities for route aggregation.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{"blockaffinities"},
Verbs: []string{"watch"},
},
},
}
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
extraRules := []rbacv1.PolicyRule{
{
// Calico Enterprise needs to be able to read additional resources.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"bfdconfigurations",
"egressgatewaypolicies",
"externalnetworks",
"licensekeys",
"packetcaptures",
"remoteclusterconfigurations",
"stagedglobalnetworkpolicies",
"stagedkubernetesnetworkpolicies",
"stagednetworkpolicies",
},
Verbs: []string{"get", "list", "watch"},
},
{
// Tigera Secure updates status for packet captures.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"packetcaptures",
},
Verbs: []string{"update"},
},
}
role.Rules = append(role.Rules, extraRules...)
}
if c.cfg.Installation.KubernetesProvider.IsOpenShift() {
role.Rules = append(role.Rules, rbacv1.PolicyRule{
APIGroups: []string{"security.openshift.io"},
Resources: []string{"securitycontextconstraints"},
Verbs: []string{"use"},
ResourceNames: []string{securitycontextconstraints.Privileged},
})
}
return role
}
// cniPluginRole creates the role containing policy rules that allow the Calico CNI plugin to operate normally.
func (c *nodeComponent) cniPluginRole() *rbacv1.ClusterRole {
finalizer := []string{}
if !c.cfg.CanRemoveCNIFinalizer {
finalizer = []string{CNIFinalizer}
}
role := &rbacv1.ClusterRole{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRole", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: CalicoCNIPluginObjectName,
Finalizers: finalizer,
},
Rules: []rbacv1.PolicyRule{
{
// The CNI plugin needs to get pods, nodes, namespaces.
APIGroups: []string{""},
Resources: []string{"pods", "nodes", "namespaces"},
Verbs: []string{"get"},
},
{
// Calico patches the allocated IP onto the pod.
APIGroups: []string{""},
Resources: []string{"pods/status"},
Verbs: []string{"patch"},
},
{
// Most IPAM resources need full CRUD permissions so we can allocate and
// release IP addresses for pods.
APIGroups: []string{"crd.projectcalico.org"},
Resources: []string{
"blockaffinities",
"ipamblocks",
"ipamhandles",
"ipamconfigs",
"clusterinformations",
"ippools",
"ipreservations",
},
Verbs: []string{"get", "list", "create", "update", "delete"},
},
},
}
return role
}
func (c *nodeComponent) createCalicoPluginConfig() map[string]interface{} {
// Determine MTU to use for veth interfaces.
// Zero means to use auto-detection.
var mtu int32 = 0
if m := getMTU(c.cfg.Installation); m != nil {
mtu = *m
}
// Determine per-provider settings.
nodenameFileOptional := false
switch c.cfg.Installation.KubernetesProvider {
case operatorv1.ProviderDockerEE:
nodenameFileOptional = true
}
// Pull out other settings.
ipForward := false
if c.cfg.Installation.CalicoNetwork.ContainerIPForwarding != nil {
ipForward = (*c.cfg.Installation.CalicoNetwork.ContainerIPForwarding == operatorv1.ContainerIPForwardingEnabled)
}
ipam := c.getCalicoIPAM()
if c.cfg.Installation.CNI.IPAM.Type == operatorv1.IPAMPluginHostLocal {
ipam = buildHostLocalIPAM(c.cfg.IPPools)
}
apiRoot := c.cfg.K8sServiceEp.CNIAPIRoot()
linuxPolicySetupTimeoutSeconds := int32(0)
if c.cfg.Installation.CalicoNetwork.LinuxPolicySetupTimeoutSeconds != nil {
linuxPolicySetupTimeoutSeconds = *c.cfg.Installation.CalicoNetwork.LinuxPolicySetupTimeoutSeconds
}
// calico plugin
calicoPluginConfig := map[string]interface{}{
"type": "calico",
"datastore_type": "kubernetes",
"mtu": mtu,
"nodename_file_optional": nodenameFileOptional,
"log_file_path": "/var/log/calico/cni/cni.log",
"ipam": ipam,
"container_settings": map[string]interface{}{
"allow_ip_forwarding": ipForward,
},
"policy": map[string]interface{}{
"type": "k8s",
},
"policy_setup_timeout_seconds": linuxPolicySetupTimeoutSeconds,
"endpoint_status_dir": filepath.Join(c.varRunCalicoVolume().VolumeSource.HostPath.Path, "endpoint-status"),
}
// Determine logging configuration
if c.cfg.Installation.Logging != nil && c.cfg.Installation.Logging.CNI != nil {
if c.cfg.Installation.Logging.CNI.LogSeverity != nil {
logSeverity := string(*c.cfg.Installation.Logging.CNI.LogSeverity)
calicoPluginConfig["log_level"] = logSeverity
}
if c.cfg.Installation.Logging.CNI.LogFileMaxSize != nil {
logFileMaxSize := c.cfg.Installation.Logging.CNI.LogFileMaxSize.Value() / (1024 * 1024)
calicoPluginConfig["log_file_max_size"] = logFileMaxSize
}
if c.cfg.Installation.Logging.CNI.LogFileMaxCount != nil {
logFileMaxCount := *c.cfg.Installation.Logging.CNI.LogFileMaxCount
calicoPluginConfig["log_file_max_count"] = logFileMaxCount
}
if c.cfg.Installation.Logging.CNI.LogFileMaxAgeDays != nil {
logFileMaxAgeDays := *c.cfg.Installation.Logging.CNI.LogFileMaxAgeDays
calicoPluginConfig["log_file_max_age"] = logFileMaxAgeDays
}
}
// optional properties
kubernetes := map[string]interface{}{
"kubeconfig": "__KUBECONFIG_FILEPATH__",
}
if apiRoot != "" {
kubernetes["k8s_api_root"] = apiRoot
}
calicoPluginConfig["kubernetes"] = kubernetes
if c.vppDataplaneEnabled() {
calicoPluginConfig["dataplane_options"] = map[string]interface{}{
"type": "grpc",
"socket": "unix:///var/run/calico/cni-server.sock",
}
}
return calicoPluginConfig
}
func (c *nodeComponent) createBandwidthPlugin() map[string]interface{} {
// bandwidth plugin
bandwidthPlugin := map[string]interface{}{
"type": "bandwidth",
"capabilities": map[string]bool{"bandwidth": true},
}
return bandwidthPlugin
}
func (c *nodeComponent) createPortmapPlugin() map[string]interface{} {
// Determine portmap configuration to use.
portmapPlugin := map[string]interface{}{
"type": "portmap",
"snat": true,
"capabilities": map[string]bool{
"portMappings": true,
},
}
return portmapPlugin
}
func (c *nodeComponent) createTuningPlugin() map[string]interface{} {
// tuning plugin (sysctl)
sysctl := map[string]string{}
tuningPlugin := map[string]interface{}{
"type": "tuning",
"sysctl": sysctl,
}
// convert []operatorv1.Sysctl{} to map[string]string for CNI definition
// details: https://www.cni.dev/plugins/current/meta/tuning/#system-controls-operation
for _, v := range c.cfg.Installation.CalicoNetwork.Sysctl {
sysctl[v.Key] = v.Value
}
tuningPlugin["sysctl"] = sysctl
return tuningPlugin
}
// nodeCNIConfigMap returns a config map containing the CNI network config to be installed on each node.
// Returns nil if no configmap is needed.
func (c *nodeComponent) nodeCNIConfigMap() *corev1.ConfigMap {
if c.cfg.Installation.CNI.Type != operatorv1.PluginCalico {
// If calico cni is not being used, then no cni configmap is needed.
return nil
}
plugins := make([]interface{}, 0)
plugins = append(plugins, c.createCalicoPluginConfig())
plugins = append(plugins, c.createBandwidthPlugin())
// optional portmap plugin
if c.cfg.Installation.CalicoNetwork.HostPorts != nil &&
*c.cfg.Installation.CalicoNetwork.HostPorts == operatorv1.HostPortsEnabled {
plugins = append(plugins, c.createPortmapPlugin())
}
// optional tuning plugin
if c.cfg.Installation.CalicoNetwork.Sysctl != nil {
plugins = append(plugins, c.createTuningPlugin())
}
pluginsArray, _ := json.Marshal(plugins)
config := fmt.Sprintf(`{
"name": "k8s-pod-network",
"cniVersion": "0.3.1",
"plugins": %s
}`, string(pluginsArray))
return &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: "cni-config",
Namespace: common.CalicoNamespace,
Labels: map[string]string{},
},
Data: map[string]string{
"config": config,
},
}
}
func (c *nodeComponent) getCalicoIPAM() map[string]interface{} {
// Determine what address families to enable.
var assign_ipv4 string
var assign_ipv6 string
if v4pool := GetIPv4Pool(c.cfg.IPPools); v4pool != nil {
assign_ipv4 = "true"
} else {
assign_ipv4 = "false"
}
if v6pool := GetIPv6Pool(c.cfg.IPPools); v6pool != nil {
assign_ipv6 = "true"
} else {
assign_ipv6 = "false"
}
return map[string]interface{}{
"type": "calico-ipam",
"assign_ipv4": assign_ipv4,
"assign_ipv6": assign_ipv6,
}
}
func buildHostLocalIPAM(pools []operatorv1.IPPool) map[string]interface{} {
v6 := GetIPv6Pool(pools) != nil
v4 := GetIPv4Pool(pools) != nil
if v4 && v6 {
// Dual-stack
return map[string]interface{}{
"type": "host-local",
"ranges": [][]map[string]string{{{"subnet": "usePodCidr"}}, {{"subnet": "usePodCidrIPv6"}}},
}
} else if v6 {
// Single-stack v6
return map[string]interface{}{
"type": "host-local",
"subnet": "usePodCidrIPv6",
}
} else {
// Single-stack v4
return map[string]interface{}{
"type": "host-local",
"subnet": "usePodCidr",
}
}
}
func (c *nodeComponent) birdTemplateConfigMap() *corev1.ConfigMap {
if len(c.cfg.BirdTemplates) == 0 {
return nil
}
cm := corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: BirdTemplatesConfigMapName,
Namespace: common.CalicoNamespace,
},
Data: map[string]string{},
}
for k, v := range c.cfg.BirdTemplates {
cm.Data[k] = v
}
return &cm
}
// clusterAdminClusterRoleBinding returns a ClusterRoleBinding for DockerEE to give
// the cluster-admin role to calico-node and calico-cni-plugin, this is needed for calico-node/calico-cni-plugin to be
// able to use hostNetwork in Docker Enterprise.
func (c *nodeComponent) clusterAdminClusterRoleBinding() *rbacv1.ClusterRoleBinding {
crb := &rbacv1.ClusterRoleBinding{
TypeMeta: metav1.TypeMeta{Kind: "ClusterRoleBinding", APIVersion: "rbac.authorization.k8s.io/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: "calico-cluster-admin",
Labels: map[string]string{},
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "ClusterRole",
Name: "cluster-admin",
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: CalicoNodeObjectName,
Namespace: common.CalicoNamespace,
},
{
Kind: "ServiceAccount",
Name: CalicoCNIPluginObjectName,
Namespace: common.CalicoNamespace,
},
},
}
return crb
}
// nodeDaemonset creates the node daemonset.
func (c *nodeComponent) nodeDaemonset(cniCfgMap *corev1.ConfigMap) *appsv1.DaemonSet {
var terminationGracePeriod int64 = nodeTerminationGracePeriodSeconds
var initContainers []corev1.Container
annotations := c.cfg.TLS.TrustedBundle.HashAnnotations()
if len(c.cfg.BirdTemplates) != 0 {
annotations[birdTemplateHashAnnotation] = rmeta.AnnotationHash(c.cfg.BirdTemplates)
}
if c.cfg.PrometheusServerTLS != nil {
annotations[c.cfg.PrometheusServerTLS.HashAnnotationKey()] = c.cfg.PrometheusServerTLS.HashAnnotationValue()
}
if c.cfg.TLS.NodeSecret.UseCertificateManagement() {
initContainers = append(initContainers, c.cfg.TLS.NodeSecret.InitContainer(common.CalicoNamespace))
}
if c.cfg.PrometheusServerTLS != nil && c.cfg.PrometheusServerTLS.UseCertificateManagement() {
initContainers = append(initContainers, c.cfg.PrometheusServerTLS.InitContainer(common.CalicoNamespace))
}
if cniCfgMap != nil {
annotations[nodeCniConfigAnnotation] = rmeta.AnnotationHash(cniCfgMap.Data)
}
// Include annotation for prometheus scraping configuration.
if c.cfg.Installation.NodeMetricsPort != nil {
annotations["prometheus.io/scrape"] = "true"
annotations["prometheus.io/port"] = fmt.Sprintf("%d", *c.cfg.Installation.NodeMetricsPort)
}
// check tech preview annotation for calico-node apparmor profile
if c.cfg.NodeAppArmorProfile != "" {
annotations["container.apparmor.security.beta.kubernetes.io/calico-node"] = c.cfg.NodeAppArmorProfile
}
if c.cfg.BGPLayouts != nil {
annotations[bgpLayoutHashAnnotation] = rmeta.AnnotationHash(c.cfg.BGPLayouts.Data)
}
if c.cfg.Installation.FlexVolumePath != "None" {
initContainers = append(initContainers, c.flexVolumeContainer())
}
if c.cfg.Installation.BPFEnabled() {
initContainers = append(initContainers, c.bpffsInitContainer())
}
if c.runAsNonPrivileged() {
initContainers = append(initContainers, c.hostPathInitContainer())
}
var affinity *corev1.Affinity
if c.cfg.Installation.KubernetesProvider.IsAKS() {
affinity = &corev1.Affinity{
NodeAffinity: &corev1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: []corev1.NodeSelectorTerm{{
MatchExpressions: []corev1.NodeSelectorRequirement{{
Key: "type",
Operator: corev1.NodeSelectorOpNotIn,
Values: []string{"virtual-kubelet"},
}},
}},
},
},
}
} else if c.cfg.Installation.KubernetesProvider.IsEKS() {
affinity = &corev1.Affinity{
NodeAffinity: &corev1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: []corev1.NodeSelectorTerm{{
MatchExpressions: []corev1.NodeSelectorRequirement{{
Key: "eks.amazonaws.com/compute-type",
Operator: corev1.NodeSelectorOpNotIn,
Values: []string{"fargate"},
}},
}},
},
},
}
}
// Include the annotation of BindMode
if c.cfg.BindMode != "" {
annotations[bgpBindModeHashAnnotation] = rmeta.AnnotationHash(c.cfg.BindMode)
}
// Determine the name to use for the calico/node daemonset. For mixed-mode, we run the enterprise DaemonSet
// with its own name so as to not conflict.
ds := appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{Kind: "DaemonSet", APIVersion: "apps/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: common.NodeDaemonSetName,
Namespace: common.CalicoNamespace,
},
Spec: appsv1.DaemonSetSpec{
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: annotations,
},
Spec: corev1.PodSpec{
Tolerations: rmeta.TolerateAll,
Affinity: affinity,
ImagePullSecrets: c.cfg.Installation.ImagePullSecrets,
ServiceAccountName: CalicoNodeObjectName,
TerminationGracePeriodSeconds: &terminationGracePeriod,
HostNetwork: true,
InitContainers: initContainers,
Containers: []corev1.Container{c.nodeContainer()},
Volumes: c.nodeVolumes(),
},
},
UpdateStrategy: c.cfg.Installation.NodeUpdateStrategy,
},
}
if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {