/
windows.go
950 lines (835 loc) · 35.4 KB
/
windows.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
// Copyright (c) 2021-2023 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"
"path/filepath"
"strconv"
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/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"
rcomp "github.com/tigera/operator/pkg/render/common/components"
rmeta "github.com/tigera/operator/pkg/render/common/meta"
"github.com/tigera/operator/pkg/render/common/securitycontext"
"github.com/tigera/operator/pkg/tls/certificatemanagement"
)
const (
WindowsNodeObjectName = "calico-node-windows"
WindowsNodeMetricsService = "calico-node-metrics-windows"
)
func Windows(
cfg *WindowsConfiguration,
) Component {
return &windowsComponent{cfg: cfg}
}
type WindowsConfiguration struct {
K8sServiceEp k8sapi.ServiceEndpoint
K8sDNSServers []string
Installation *operatorv1.InstallationSpec
ClusterDomain string
TLS *TyphaNodeTLS
PrometheusServerTLS certificatemanagement.KeyPairInterface
NodeReporterMetricsPort int
AmazonCloudIntegration *operatorv1.AmazonCloudIntegration
VXLANVNI int
}
type windowsComponent struct {
cfg *WindowsConfiguration
cniImage string
nodeImage string
}
func (c *windowsComponent) 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.ComponentTigeraCNIWindows, reg, path, prefix, is))
c.nodeImage = appendIfErr(components.GetReference(components.ComponentTigeraNodeWindows, reg, path, prefix, is))
} else {
c.cniImage = appendIfErr(components.GetReference(components.ComponentCalicoCNIWindows, reg, path, prefix, is))
c.nodeImage = appendIfErr(components.GetReference(components.ComponentCalicoNodeWindows, reg, path, prefix, is))
}
if len(errMsgs) != 0 {
return fmt.Errorf(strings.Join(errMsgs, ","))
}
return nil
}
func (c *windowsComponent) SupportedOSType() rmeta.OSType {
return rmeta.OSTypeWindows
}
func (c *windowsComponent) Objects() ([]client.Object, []client.Object) {
// Clean up old windows upgrader daemonset if present
objsToDelete := []client.Object{
&corev1.ServiceAccount{
TypeMeta: metav1.TypeMeta{Kind: "ServiceAccount", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: common.CalicoWindowsUpgradeResourceName,
Namespace: common.CalicoNamespace,
},
},
&appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{Kind: "DaemonSet", APIVersion: "apps/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: common.CalicoWindowsUpgradeResourceName,
Namespace: "calico-system",
},
},
}
objs := []client.Object{}
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
// Include Service for exposing node metrics.
objs = append(objs, c.nodeMetricsService())
}
cniConfig := c.windowsCNIConfigMap()
if cniConfig != nil {
objs = append(objs, cniConfig)
}
objs = append(objs, c.windowsDaemonset(cniConfig))
return objs, objsToDelete
}
func (c *windowsComponent) Ready() bool {
return true
}
// nodeMetricsService creates a Service which exposes two endpoints on calico/node for
// reporting Prometheus metrics (for policy enforcement activity and BGP stats).
// This service is used internally by Calico Enterprise and is separate from general
// Prometheus metrics which are user-configurable.
func (c *windowsComponent) nodeMetricsService() *corev1.Service {
return &corev1.Service{
TypeMeta: metav1.TypeMeta{Kind: "Service", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: WindowsNodeMetricsService,
Namespace: common.CalicoNamespace,
Labels: map[string]string{"k8s-app": WindowsNodeObjectName},
},
Spec: corev1.ServiceSpec{
Selector: map[string]string{"k8s-app": WindowsNodeObjectName},
// Important: "None" tells Kubernetes that we want a headless service with
// no kube-proxy load balancer. If we omit this then kube-proxy will render
// a huge set of iptables rules for this service since there's an instance
// on every node.
ClusterIP: "None",
Ports: []corev1.ServicePort{
{
Name: "calico-metrics-port",
Port: int32(c.cfg.NodeReporterMetricsPort),
TargetPort: intstr.FromInt(c.cfg.NodeReporterMetricsPort),
Protocol: corev1.ProtocolTCP,
},
{
Name: "calico-bgp-metrics-port",
Port: nodeBGPReporterPort,
TargetPort: intstr.FromInt(int(nodeBGPReporterPort)),
Protocol: corev1.ProtocolTCP,
},
},
},
}
}
// windowsCNIConfigMap returns a config map containing the CNI network config to be installed on each node.
// Returns nil if no configmap is needed.
func (c *windowsComponent) windowsCNIConfigMap() *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())
pluginsArray, _ := json.Marshal(plugins)
config := fmt.Sprintf(`{
"name": "Calico",
"cniVersion": "0.3.1",
"plugins": %s
}`, string(pluginsArray))
return &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{Kind: "ConfigMap", APIVersion: "v1"},
ObjectMeta: metav1.ObjectMeta{
Name: "cni-config-windows",
Namespace: common.CalicoNamespace,
Labels: map[string]string{},
},
Data: map[string]string{
"config": config,
},
}
}
// cniEnvVars creates the CNI container's envvars.
func (c *windowsComponent) cniEnvVars() []corev1.EnvVar {
if c.cfg.Installation.CNI.Type != operatorv1.PluginCalico {
return []corev1.EnvVar{}
}
cniNetDir := c.cfg.Installation.WindowsNodes.CNIConfigDir
// cniNetDir is used in the cni config file, and will have the "c:" prefix added to it.
cniNetDir = strings.TrimPrefix(cniNetDir, "c:")
cniNetDir = strings.TrimPrefix(cniNetDir, "C:")
envVars := []corev1.EnvVar{
{Name: "SLEEP", Value: "false"},
{Name: "CNI_BIN_DIR", Value: "/host/opt/cni/bin"},
{Name: "CNI_CONF_NAME", Value: "10-calico.conflist"},
{Name: "CNI_NET_DIR", Value: cniNetDir},
{Name: "KUBERNETES_DNS_SERVERS", Value: strings.Join(c.cfg.K8sDNSServers, ",")},
{Name: "KUBERNETES_SERVICE_CIDRS", Value: strings.Join(c.cfg.Installation.ServiceCIDRs, ",")},
{Name: "VXLAN_VNI", Value: fmt.Sprintf("%d", c.cfg.VXLANVNI)},
{
Name: "KUBERNETES_NODE_NAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "spec.nodeName"},
},
},
{
Name: "CNI_NETWORK_CONFIG",
ValueFrom: &corev1.EnvVarSource{
ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
Key: "config",
LocalObjectReference: corev1.LocalObjectReference{
Name: "cni-config-windows",
},
},
},
},
}
envVars = append(envVars, c.cfg.K8sServiceEp.EnvVars(true, c.cfg.Installation.KubernetesProvider)...)
return envVars
}
func (c *windowsComponent) 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
}
ipam := map[string]interface{}{
"type": "calico-ipam",
"subnet": "usePodCidr",
}
if c.cfg.Installation.CNI.IPAM.Type == operatorv1.IPAMPluginHostLocal {
ipam["type"] = "host-local"
}
// Determine the networking backend
backend := getWindowsBackend(c.cfg.Installation)
apiRoot := c.cfg.K8sServiceEp.CNIAPIRoot()
vxlanMACPrefix := "0E-2A"
if c.cfg.Installation.WindowsNodes != nil && c.cfg.Installation.WindowsNodes.VXLANMACPrefix != "" {
vxlanMACPrefix = c.cfg.Installation.WindowsNodes.VXLANMACPrefix
}
capabilities := map[string]interface{}{
"dns": true,
}
// calico plugin
calicoPluginConfig := map[string]interface{}{
"type": "calico",
"name": "Calico",
"windows_use_single_network": true,
"mode": backend,
"vxlan_mac_prefix": vxlanMACPrefix,
"vxlan_vni": c.cfg.VXLANVNI,
"mtu": mtu,
"policy": map[string]interface{}{
"type": "k8s",
},
"log_file_path": "c:/var/log/calico/cni/cni.log",
"windows_loopback_DSR": "__DSR_SUPPORT__",
"capabilities": capabilities,
"nodename": "__KUBERNETES_NODE_NAME__",
"nodename_file": "__NODENAME_FILE__",
"nodename_file_optional": true,
"datastore_type": "kubernetes",
"ipam": ipam,
}
// 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
}
}
cniNetDir := c.cfg.Installation.WindowsNodes.CNIConfigDir
cniNetDir = strings.TrimPrefix(cniNetDir, "c:")
cniNetDir = strings.TrimPrefix(cniNetDir, "C:")
kubernetes := map[string]interface{}{
"kubeconfig": filepath.ToSlash(filepath.Join("c:", cniNetDir, "calico-kubeconfig")),
}
if apiRoot != "" {
kubernetes["k8s_api_root"] = apiRoot
}
calicoPluginConfig["kubernetes"] = kubernetes
dns := map[string]interface{}{
"Nameservers": c.cfg.K8sDNSServers,
"Search": []string{
"svc.cluster.local",
},
}
calicoPluginConfig["DNS"] = dns
policies := []map[string]interface{}{
{
"Name": "EndpointPolicy",
"Value": map[string]interface{}{
"Type": "OutBoundNAT",
"ExceptionList": c.cfg.Installation.ServiceCIDRs,
},
},
}
for _, serviceCIDR := range c.cfg.Installation.ServiceCIDRs {
policies = append(policies, map[string]interface{}{
"Name": "EndpointPolicy",
"Value": map[string]interface{}{
"Type": "SDNROUTE",
"DestinationPrefix": serviceCIDR,
"NeedEncap": true,
},
})
}
calicoPluginConfig["policies"] = policies
return calicoPluginConfig
}
// windowsVolumes creates the node's volumes.
func (c *windowsComponent) windowsVolumes() []corev1.Volume {
fileOrCreate := corev1.HostPathFileOrCreate
dirOrCreate := corev1.HostPathDirectoryOrCreate
volumes := []corev1.Volume{
{Name: "lib-modules", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/lib/modules"}}},
{Name: "xtables-lock", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/run/xtables.lock", Type: &fileOrCreate}}},
{Name: "policysync", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/var/run/nodeagent", Type: &dirOrCreate}}},
c.cfg.TLS.TrustedBundle.Volume(),
c.cfg.TLS.NodeSecret.Volume(),
corev1.Volume{Name: "var-run-calico", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/var/run/calico"}}},
corev1.Volume{Name: "var-lib-calico", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/var/lib/calico"}}},
}
// If needed for this configuration, then include the CNI volumes.
if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
// Determine directories to use for CNI artifacts based on the provider.
volumes = append(volumes, corev1.Volume{Name: "cni-bin-dir", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: c.cfg.Installation.WindowsNodes.CNIBinDir}}})
volumes = append(volumes, corev1.Volume{Name: "cni-net-dir", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: c.cfg.Installation.WindowsNodes.CNIConfigDir}}})
volumes = append(volumes, corev1.Volume{Name: "cni-log-dir", VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: c.cfg.Installation.WindowsNodes.CNILogDir, Type: &dirOrCreate}}})
}
// Override with Tigera-specific config.
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
// Add volume for calico logs.
calicoLogVol := corev1.Volume{
Name: "var-log-calico",
VolumeSource: corev1.VolumeSource{HostPath: &corev1.HostPathVolumeSource{Path: "/var/log/calico", Type: &dirOrCreate}},
}
volumes = append(volumes, calicoLogVol)
}
if c.cfg.PrometheusServerTLS != nil {
volumes = append(volumes, c.cfg.PrometheusServerTLS.Volume())
}
return volumes
}
// uninstallEnvVars creates the uninstall-calico initContainer's envvars.
func (c *windowsComponent) uninstallEnvVars() []corev1.EnvVar {
envVars := []corev1.EnvVar{
{Name: "SLEEP", Value: "false"},
{Name: "CNI_BIN_DIR", Value: "/host/opt/cni/bin"},
{Name: "CNI_CONF_NAME", Value: "10-calico.conflist"},
{Name: "CNI_NET_DIR", Value: "/host/etc/cni/net.d"},
}
return envVars
}
// uninstallContainer creates the node's init container that uninstalls non-HPC Calico from the host.
func (c *windowsComponent) uninstallContainer() corev1.Container {
// Determine environment to pass to the uninstall-calico init container.
uninstallEnv := c.uninstallEnvVars()
uninstallVolumeMounts := []corev1.VolumeMount{}
// Only mount CNI volumes if using Calico CNI
if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
uninstallVolumeMounts = append(uninstallVolumeMounts, corev1.VolumeMount{MountPath: "/host/opt/cni/bin", Name: "cni-bin-dir"})
uninstallVolumeMounts = append(uninstallVolumeMounts, corev1.VolumeMount{MountPath: "/host/etc/cni/net.d", Name: "cni-net-dir"})
}
return corev1.Container{
Name: "uninstall-calico",
Image: c.nodeImage,
Args: []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/uninstall-calico.ps1"},
Env: uninstallEnv,
SecurityContext: securitycontext.NewWindowsHostProcessContext(),
VolumeMounts: uninstallVolumeMounts,
}
}
// cniContainer creates the node's init container that installs CNI.
func (c *windowsComponent) cniContainer() corev1.Container {
// Determine environment to pass to the CNI init container.
cniEnv := c.cniEnvVars()
cniVolumeMounts := []corev1.VolumeMount{
{MountPath: "/host/opt/cni/bin", Name: "cni-bin-dir"},
{MountPath: "/host/etc/cni/net.d", Name: "cni-net-dir"},
}
return corev1.Container{
Name: "install-cni",
Image: c.cniImage,
Command: []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/opt/cni/bin/install.exe"},
Env: cniEnv,
SecurityContext: securitycontext.NewWindowsHostProcessContext(),
VolumeMounts: cniVolumeMounts,
}
}
// nodeContainer creates the windows node startup container.
func (c *windowsComponent) nodeContainer() corev1.Container {
return corev1.Container{
Name: "node",
Image: c.nodeImage,
Args: []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/node-service.ps1"},
WorkingDir: "$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/",
Resources: c.nodeWindowsResources(),
SecurityContext: securitycontext.NewWindowsHostProcessContext(),
Env: c.windowsEnvVars(),
VolumeMounts: c.windowsVolumeMounts(),
}
}
// felixContainer creates the windows felix container.
func (c *windowsComponent) felixContainer() corev1.Container {
lp, rp := c.windowsLivenessReadinessProbes()
return corev1.Container{
Name: "felix",
Image: c.nodeImage,
Args: []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/felix-service.ps1"},
WorkingDir: "$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/",
Resources: c.felixWindowsResources(),
SecurityContext: securitycontext.NewWindowsHostProcessContext(),
Env: c.windowsEnvVars(),
VolumeMounts: c.windowsVolumeMounts(),
LivenessProbe: lp,
ReadinessProbe: rp,
Lifecycle: c.windowsLifecycle(),
}
}
// nodeContainer creates the windows confd container (used only for the windows-bgp backend).
func (c *windowsComponent) confdContainer() corev1.Container {
return corev1.Container{
Name: "confd",
Image: c.nodeImage,
Args: []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/confd/confd-service.ps1"},
WorkingDir: "$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/",
Resources: c.confdWindowsResources(),
SecurityContext: securitycontext.NewWindowsHostProcessContext(),
Env: c.windowsEnvVars(),
VolumeMounts: c.windowsVolumeMounts(),
}
}
// windowsEnvVars creates the node's envvars.
func (c *windowsComponent) windowsEnvVars() []corev1.EnvVar {
// Set the clusterType.
clusterType := "k8s,operator"
// Note: Felix now activates certain special-case logic based on the provider in the cluster type; avoid changing
// these unless you also update Felix's parsing logic.
switch c.cfg.Installation.KubernetesProvider {
case operatorv1.ProviderOpenShift:
clusterType = clusterType + ",openshift"
case operatorv1.ProviderEKS:
clusterType = clusterType + ",ecs"
case operatorv1.ProviderGKE:
clusterType = clusterType + ",gke"
case operatorv1.ProviderAKS:
clusterType = clusterType + ",aks"
}
if bgpEnabled(c.cfg.Installation) {
clusterType = clusterType + ",bgp"
}
clusterType = clusterType + ",windows"
vxlanAdapter := ""
if c.cfg.Installation.WindowsNodes != nil && c.cfg.Installation.WindowsNodes.VXLANAdapter != "" {
vxlanAdapter = c.cfg.Installation.WindowsNodes.VXLANAdapter
}
windowsEnv := []corev1.EnvVar{
{Name: "DATASTORE_TYPE", Value: "kubernetes"},
{Name: "WAIT_FOR_DATASTORE", Value: "true"},
{Name: "CLUSTER_TYPE", Value: clusterType},
{Name: "CALICO_DISABLE_FILE_LOGGING", Value: "false"},
{Name: "FELIX_DEFAULTENDPOINTTOHOSTACTION", Value: "ACCEPT"},
{Name: "FELIX_HEALTHENABLED", Value: "true"},
{
Name: "NODENAME",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "spec.nodeName"},
},
},
{
Name: "NAMESPACE",
ValueFrom: &corev1.EnvVarSource{
FieldRef: &corev1.ObjectFieldSelector{FieldPath: "metadata.namespace"},
},
},
{Name: "FELIX_TYPHAK8SNAMESPACE", Value: common.CalicoNamespace},
{Name: "FELIX_TYPHAK8SSERVICENAME", Value: TyphaServiceName},
{Name: "FELIX_TYPHACAFILE", Value: c.cfg.TLS.TrustedBundle.MountPath()},
{Name: "FELIX_TYPHACERTFILE", Value: c.cfg.TLS.NodeSecret.VolumeMountCertificateFilePath()},
{Name: "FELIX_TYPHAKEYFILE", Value: c.cfg.TLS.NodeSecret.VolumeMountKeyFilePath()},
{Name: "FIPS_MODE_ENABLED", Value: operatorv1.IsFIPSModeEnabledString(c.cfg.Installation.FIPSMode)},
{Name: "VXLAN_VNI", Value: fmt.Sprintf("%d", c.cfg.VXLANVNI)},
{Name: "VXLAN_ADAPTER", Value: vxlanAdapter},
}
// We need at least the CN or URISAN set, we depend on the validation
// done by the core_controller that the Secret will have one.
if c.cfg.TLS.TyphaCommonName != "" {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_TYPHACN", Value: c.cfg.TLS.TyphaCommonName})
}
if c.cfg.TLS.TyphaURISAN != "" {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_TYPHAURISAN", Value: c.cfg.TLS.TyphaURISAN})
}
if c.cfg.Installation.CNI != nil && c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
// If using Calico CNI, we need to manage CNI credential rotation on the host.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "CALICO_MANAGE_CNI", Value: "true"})
} else {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "CALICO_MANAGE_CNI", Value: "false"})
}
if c.cfg.Installation.CNI != nil && c.cfg.Installation.CNI.Type == operatorv1.PluginAmazonVPC {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_BPFEXTTOSERVICECONNMARK", Value: "0x80"})
}
// Set the KUBE_NETWORK env var based on the Provider
kubeNetwork := "Calico.*"
switch c.cfg.Installation.KubernetesProvider {
case operatorv1.ProviderAKS:
kubeNetwork = "azure.*"
case operatorv1.ProviderEKS:
kubeNetwork = "vpc.*"
}
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "KUBE_NETWORK", Value: kubeNetwork})
// Determine MTU to use. If specified explicitly, use that. Otherwise, set defaults based on an overall
// MTU of 1460.
mtu := getMTU(c.cfg.Installation)
if mtu != nil {
vxlanMtu := strconv.Itoa(int(*mtu))
wireguardMtu := strconv.Itoa(int(*mtu))
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_VXLANMTU", Value: vxlanMtu})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_WIREGUARDMTU", Value: wireguardMtu})
}
// If host-local IPAM is in use, we need to configure calico/node to use the Kubernetes pod CIDR.
cni := c.cfg.Installation.CNI
if cni != nil && cni.IPAM != nil && cni.IPAM.Type == operatorv1.IPAMPluginHostLocal {
windowsEnv = append(windowsEnv, corev1.EnvVar{
Name: "USE_POD_CIDR",
Value: "true",
})
}
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "CALICO_NETWORKING_BACKEND", Value: getWindowsBackend(c.cfg.Installation)})
// IPv4 auto-detection configuration.
var v4Method string
if c.cfg.Installation.CalicoNetwork != nil {
v4Method = getAutodetectionMethod(c.cfg.Installation.CalicoNetwork.NodeAddressAutodetectionV4)
}
if v4Method != "" {
// IPv4 Auto-detection is enabled.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP", Value: "autodetect"})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP_AUTODETECTION_METHOD", Value: v4Method})
} else {
// IPv4 Auto-detection is disabled.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP", Value: "none"})
}
// IPv6 auto-detection and ippool configuration.
var v6Method string
if c.cfg.Installation.CalicoNetwork != nil {
v6Method = getAutodetectionMethod(c.cfg.Installation.CalicoNetwork.NodeAddressAutodetectionV6)
}
if v6Method != "" {
// IPv6 Auto-detection is enabled.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP6", Value: "autodetect"})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP6_AUTODETECTION_METHOD", Value: v6Method})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_IPV6SUPPORT", Value: "true"})
// Set CALICO_ROUTER_ID to "hash" for IPv6-only with BGP enabled.
if v4Method == "" && bgpEnabled(c.cfg.Installation) {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "CALICO_ROUTER_ID", Value: "hash"})
}
// Set IPv6 VXLAN and Wireguard MTU
if mtu != nil {
vxlanMtuV6 := strconv.Itoa(int(*mtu))
wireguardMtuV6 := strconv.Itoa(int(*mtu))
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_VXLANMTUV6", Value: vxlanMtuV6})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_WIREGUARDMTUV6", Value: wireguardMtuV6})
}
} else {
// IPv6 Auto-detection is disabled.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "IP6", Value: "none"})
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_IPV6SUPPORT", Value: "false"})
}
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
// Add in Calico Enterprise specific configuration.
extraNodeEnv := []corev1.EnvVar{
{Name: "FELIX_PROMETHEUSREPORTERENABLED", Value: "true"},
{Name: "FELIX_PROMETHEUSREPORTERPORT", Value: fmt.Sprintf("%d", c.cfg.NodeReporterMetricsPort)},
{Name: "FELIX_FLOWLOGSFILEENABLED", Value: "true"},
{Name: "FELIX_FLOWLOGSFILEINCLUDELABELS", Value: "true"},
{Name: "FELIX_FLOWLOGSFILEINCLUDEPOLICIES", Value: "true"},
{Name: "FELIX_FLOWLOGSFILEINCLUDESERVICE", Value: "true"},
{Name: "FELIX_FLOWLOGSENABLENETWORKSETS", Value: "true"},
{Name: "FELIX_FLOWLOGSCOLLECTPROCESSINFO", Value: "true"},
{Name: "FELIX_DNSLOGSFILEENABLED", Value: "true"},
{Name: "FELIX_DNSLOGSFILEPERNODELIMIT", Value: "1000"},
}
if c.cfg.PrometheusServerTLS != nil {
extraNodeEnv = append(extraNodeEnv,
corev1.EnvVar{Name: "FELIX_PROMETHEUSREPORTERCERTFILE", Value: c.cfg.PrometheusServerTLS.VolumeMountCertificateFilePath()},
corev1.EnvVar{Name: "FELIX_PROMETHEUSREPORTERKEYFILE", Value: c.cfg.PrometheusServerTLS.VolumeMountKeyFilePath()},
corev1.EnvVar{Name: "FELIX_PROMETHEUSREPORTERCAFILE", Value: c.cfg.TLS.TrustedBundle.MountPath()},
)
}
windowsEnv = append(windowsEnv, extraNodeEnv...)
}
if c.cfg.Installation.NodeMetricsPort != nil {
// If a node metrics port was given, then enable felix prometheus metrics and set the port.
// Note that this takes precedence over any FelixConfiguration resources in the cluster.
extraNodeEnv := []corev1.EnvVar{
{Name: "FELIX_PROMETHEUSMETRICSENABLED", Value: "true"},
{Name: "FELIX_PROMETHEUSMETRICSPORT", Value: fmt.Sprintf("%d", *c.cfg.Installation.NodeMetricsPort)},
}
windowsEnv = append(windowsEnv, extraNodeEnv...)
}
// Configure provider specific environment variables here.
switch c.cfg.Installation.KubernetesProvider {
case operatorv1.ProviderOpenShift:
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
// We need to configure a non-default trusted DNS server, since there's no kube-dns.
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_DNSTRUSTEDSERVERS", Value: "k8s-service:openshift-dns/dns-default"})
}
case operatorv1.ProviderRKE2:
// For RKE2, configure a non-default trusted DNS server, as the DNS service is not named "kube-dns".
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_DNSTRUSTEDSERVERS", Value: "k8s-service:kube-system/rke2-coredns-rke2-coredns"})
}
}
if c.cfg.Installation.CNI.Type != operatorv1.PluginCalico {
windowsEnv = append(windowsEnv, corev1.EnvVar{Name: "FELIX_ROUTESOURCE", Value: "WorkloadIPs"})
}
if c.cfg.AmazonCloudIntegration != nil {
windowsEnv = append(windowsEnv, GetTigeraSecurityGroupEnvVariables(c.cfg.AmazonCloudIntegration)...)
windowsEnv = append(windowsEnv, corev1.EnvVar{
Name: "FELIX_FAILSAFEINBOUNDHOSTPORTS",
Value: "tcp:22,udp:68,tcp:179,tcp:443,tcp:5473,tcp:6443",
})
windowsEnv = append(windowsEnv, corev1.EnvVar{
Name: "FELIX_FAILSAFEOUTBOUNDHOSTPORTS",
Value: "udp:53,udp:67,tcp:179,tcp:443,tcp:5473,tcp:6443",
})
}
windowsEnv = append(windowsEnv, c.cfg.K8sServiceEp.EnvVars(true, c.cfg.Installation.KubernetesProvider)...)
return windowsEnv
}
// windowsVolumeMounts creates the windows node's volume mounts.
func (c *windowsComponent) windowsVolumeMounts() []corev1.VolumeMount {
windowsVolumeMounts := c.cfg.TLS.TrustedBundle.VolumeMounts(c.SupportedOSType())
windowsVolumeMounts = append(windowsVolumeMounts,
c.cfg.TLS.NodeSecret.VolumeMount(c.SupportedOSType()),
corev1.VolumeMount{MountPath: "/var/run/calico", Name: "var-run-calico"},
corev1.VolumeMount{MountPath: "/var/lib/calico", Name: "var-lib-calico"})
if c.cfg.Installation.Variant == operatorv1.TigeraSecureEnterprise {
extraNodeMounts := []corev1.VolumeMount{
{MountPath: "/var/log/calico", Name: "var-log-calico"},
}
windowsVolumeMounts = append(windowsVolumeMounts, extraNodeMounts...)
} else if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
windowsVolumeMounts = append(windowsVolumeMounts, corev1.VolumeMount{MountPath: "/var/log/calico/cni", Name: "cni-log-dir", ReadOnly: false})
}
if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
windowsVolumeMounts = append(windowsVolumeMounts, corev1.VolumeMount{MountPath: "/host/etc/cni/net.d", Name: "cni-net-dir"})
}
if c.cfg.PrometheusServerTLS != nil {
windowsVolumeMounts = append(windowsVolumeMounts, c.cfg.PrometheusServerTLS.VolumeMount(c.SupportedOSType()))
}
return windowsVolumeMounts
}
// windowsLivenessReadinessProbes creates the node's liveness and readiness probes.
func (c *windowsComponent) windowsLivenessReadinessProbes() (*corev1.Probe, *corev1.Probe) {
livenessCmd := []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/calico-node.exe", "-felix-live"}
readinessCmd := []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/calico-node.exe", "-felix-ready"}
lp := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{Exec: &corev1.ExecAction{Command: livenessCmd}},
InitialDelaySeconds: 10,
FailureThreshold: 6,
TimeoutSeconds: 10,
PeriodSeconds: 10,
}
rp := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{Exec: &corev1.ExecAction{Command: readinessCmd}},
TimeoutSeconds: 10,
PeriodSeconds: 10,
}
return lp, rp
}
// windowsLifecycle creates the node's postStart and preStop hooks.
func (c *windowsComponent) windowsLifecycle() *corev1.Lifecycle {
preStopCmd := []string{"$env:CONTAINER_SANDBOX_MOUNT_POINT/CalicoWindows/calico-node.exe", "-shutdown"}
lc := &corev1.Lifecycle{
PreStop: &corev1.LifecycleHandler{Exec: &corev1.ExecAction{Command: preStopCmd}},
}
return lc
}
// nodeWindowsResources creates the windows node's resource requirements.
func (c *windowsComponent) nodeWindowsResources() corev1.ResourceRequirements {
return rmeta.GetResourceRequirements(c.cfg.Installation, operatorv1.ComponentNameNodeWindows)
}
// felixWindowsResources creates the node's resource requirements.
func (c *windowsComponent) felixWindowsResources() corev1.ResourceRequirements {
return rmeta.GetResourceRequirements(c.cfg.Installation, operatorv1.ComponentNameFelixWindows)
}
// confdWindowsResources creates the node's resource requirements.
func (c *windowsComponent) confdWindowsResources() corev1.ResourceRequirements {
return rmeta.GetResourceRequirements(c.cfg.Installation, operatorv1.ComponentNameConfdWindows)
}
// windowsDaemonset creates the windows node daemonset.
func (c *windowsComponent) windowsDaemonset(cniCfgMap *corev1.ConfigMap) *appsv1.DaemonSet {
var terminationGracePeriod int64 = nodeTerminationGracePeriodSeconds
// The uninstall-calico initContainer must be the first initContainer
initContainers := []corev1.Container{c.uninstallContainer()}
annotations := c.cfg.TLS.TrustedBundle.HashAnnotations()
if c.cfg.PrometheusServerTLS != nil {
annotations[c.cfg.PrometheusServerTLS.HashAnnotationKey()] = c.cfg.PrometheusServerTLS.HashAnnotationValue()
}
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)
}
var affinity *corev1.Affinity
if c.cfg.Installation.KubernetesProvider == operatorv1.ProviderAKS {
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 == operatorv1.ProviderEKS {
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"},
}},
}},
},
},
}
}
ds := appsv1.DaemonSet{
TypeMeta: metav1.TypeMeta{Kind: "DaemonSet", APIVersion: "apps/v1"},
ObjectMeta: metav1.ObjectMeta{
Name: common.WindowsDaemonSetName,
Namespace: common.CalicoNamespace,
},
Spec: appsv1.DaemonSetSpec{
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Annotations: annotations,
},
Spec: corev1.PodSpec{
NodeSelector: map[string]string{"kubernetes.io/os": "windows"},
Tolerations: rmeta.TolerateAll,
Affinity: affinity,
ImagePullSecrets: c.cfg.Installation.ImagePullSecrets,
ServiceAccountName: CalicoNodeObjectName,
TerminationGracePeriodSeconds: &terminationGracePeriod,
HostNetwork: true,
InitContainers: initContainers,
Containers: []corev1.Container{
c.felixContainer(),
c.nodeContainer(),
},
Volumes: c.windowsVolumes(),
},
},
UpdateStrategy: c.cfg.Installation.NodeUpdateStrategy,
},
}
// Add confd container if BGP is enabled
if bgpEnabled(c.cfg.Installation) {
ds.Spec.Template.Spec.Containers = append(ds.Spec.Template.Spec.Containers, c.confdContainer())
}
// Only add the CNI initContainer if using Calico CNI
if c.cfg.Installation.CNI.Type == operatorv1.PluginCalico {
ds.Spec.Template.Spec.InitContainers = append(ds.Spec.Template.Spec.InitContainers, c.cniContainer())
}
if overrides := c.cfg.Installation.CalicoNodeWindowsDaemonSet; overrides != nil {
rcomp.ApplyDaemonSetOverrides(&ds, overrides)
}
return &ds
}
func getWindowsBackend(installation *operatorv1.InstallationSpec) string {
if !bgpEnabled(installation) {
if installation.CNI.Type == operatorv1.PluginCalico {
if installation.CNI.IPAM.Type == operatorv1.IPAMPluginHostLocal {
// If BGP is disabled and using HostLocal, then that means routing is done
// by Cloud routing, so networking backend is none. (because we don't support
// vxlan with HostLocal.)
return "none"
} else {
// If BGP is disabled, then set the networking backend to "vxlan". This means that BIRD will be
// disabled, and VXLAN will optionally be configurable via IP pools.
return "vxlan"
}
} else {
// If not using Calico networking at all, set the backend to "none".
return "none"
}
} else {
// BGP is enabled.
return "windows-bgp"
}
}
// DefaultWindowsCNIDirectories returns the CNI binary, network config and log directories and the CNI conf filename for the configured platform.
// FIXME: populate with known default for other providers
func DefaultWindowsCNIDirectories(installation operatorv1.InstallationSpec) (string, string, string) {
var cniBinDir, cniNetDir, cniLogDir string
switch installation.KubernetesProvider {
case operatorv1.ProviderAKS:
cniBinDir = "/k/azurecni/bin"
cniNetDir = "/k/azurecni/netconf"
cniLogDir = "/var/log/calico/cni"
case operatorv1.ProviderEKS:
cniBinDir = "/Program Files/Amazon/EKS/cni"
cniNetDir = "/Program Files/Amazon/EKS/cni/config"
cniLogDir = "/var/log/calico/cni"
default:
// Default locations to match vanilla Kubernetes.
cniBinDir = "/opt/cni/bin"
cniNetDir = "/etc/cni/net.d"
cniLogDir = "/var/log/calico/cni"
}
return cniBinDir, cniNetDir, cniLogDir
}