-
Notifications
You must be signed in to change notification settings - Fork 376
/
Copy pathframework.go
3366 lines (3078 loc) · 120 KB
/
framework.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 2019 Antrea Authors
//
// 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 e2e
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math/rand"
"net"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"testing"
"time"
"github.com/containernetworking/plugins/pkg/ip"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
"golang.org/x/mod/semver"
"gopkg.in/yaml.v2"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
restclient "k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/util/retry"
"k8s.io/component-base/featuregate"
aggregatorclientset "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
"k8s.io/kubectl/pkg/util/podutils"
utilnet "k8s.io/utils/net"
"k8s.io/utils/ptr"
"antrea.io/antrea/pkg/agent/config"
crdclientset "antrea.io/antrea/pkg/client/clientset/versioned"
"antrea.io/antrea/pkg/clusteridentity"
agentconfig "antrea.io/antrea/pkg/config/agent"
controllerconfig "antrea.io/antrea/pkg/config/controller"
flowaggregatorconfig "antrea.io/antrea/pkg/config/flowaggregator"
"antrea.io/antrea/pkg/features"
"antrea.io/antrea/test/e2e/providers"
)
var AntreaConfigMap *corev1.ConfigMap
var (
connectionLostError = fmt.Errorf("http2: client connection lost")
)
const (
defaultTimeout = 90 * time.Second
defaultInterval = 1 * time.Second
// antreaNamespace is the K8s Namespace in which all Antrea resources are running.
antreaNamespace = "kube-system"
kubeNamespace = "kube-system"
flowAggregatorNamespace = "flow-aggregator"
antreaConfigVolume = "antrea-config"
antreaWindowsConfigVolume = "antrea-windows-config"
flowAggregatorConfigVolume = "flow-aggregator-config"
antreaDaemonSet = "antrea-agent"
antreaWindowsDaemonSet = "antrea-agent-windows"
antreaDeployment = "antrea-controller"
flowAggregatorDeployment = "flow-aggregator"
flowAggregatorCHSecret = "clickhouse-ca"
antreaDefaultGW = "antrea-gw0"
testAntreaIPAMNamespace = "antrea-ipam-test"
testAntreaIPAMNamespace11 = "antrea-ipam-test-11"
testAntreaIPAMNamespace12 = "antrea-ipam-test-12"
mcjoinContainerName = "mcjoin"
agnhostContainerName = "agnhost"
toolboxContainerName = "toolbox"
nginxContainerName = "nginx"
controllerContainerName = "antrea-controller"
ovsContainerName = "antrea-ovs"
agentContainerName = "antrea-agent"
flowAggregatorContainerName = "flow-aggregator"
antreaYML = "antrea.yml"
antreaIPSecYML = "antrea-ipsec.yml"
antreaCovYML = "antrea-coverage.yml"
antreaIPSecCovYML = "antrea-ipsec-coverage.yml"
flowAggregatorYML = "flow-aggregator.yml"
flowAggregatorCovYML = "flow-aggregator-coverage.yml"
flowVisibilityYML = "flow-visibility.yml"
flowVisibilityTLSYML = "flow-visibility-tls.yml"
chOperatorYML = "clickhouse-operator-install-bundle.yml"
flowVisibilityCHPodName = "chi-clickhouse-clickhouse-0-0-0"
flowVisibilityNamespace = "flow-visibility"
defaultBridgeName = "br-int"
monitoringNamespace = "monitoring"
cpNodeCoverageDir = "/tmp/antrea-e2e-coverage"
antreaAgentConfName = "antrea-agent.conf"
antreaControllerConfName = "antrea-controller.conf"
flowAggregatorConfName = "flow-aggregator.conf"
agnhostImage = "registry.k8s.io/e2e-test-images/agnhost:2.40"
ToolboxImage = "antrea/toolbox:1.5-1"
mcjoinImage = "antrea/mcjoin:v2.9"
nginxImage = "antrea/nginx:1.21.6-alpine"
iisImage = "mcr.microsoft.com/windows/servercore/iis"
ipfixCollectorImage = "antrea/ipfix-collector:v0.12.0"
nginxLBService = "nginx-loadbalancer"
ipfixCollectorPort = "4739"
exporterFlowPollInterval = 1 * time.Second
exporterActiveFlowExportTimeout = 2 * time.Second
exporterIdleFlowExportTimeout = 1 * time.Second
aggregatorActiveFlowRecordTimeout = 3500 * time.Millisecond
aggregatorInactiveFlowRecordTimeout = 6 * time.Second
aggregatorClickHouseCommitInterval = 1 * time.Second
clickHouseHTTPPort = "8123"
defaultCHDatabaseURL = "tcp://clickhouse-clickhouse.flow-visibility.svc:9000"
statefulSetRestartAnnotationKey = "antrea-e2e/restartedAt"
iperfPort = 5201
iperfSvcPort = 9999
)
type ClusterNode struct {
idx int // 0 for control-plane Node
name string
ipv4Addr string
ipv6Addr string
podV4NetworkCIDR string
podV6NetworkCIDR string
gwV4Addr string
gwV6Addr string
os string
}
func (n ClusterNode) ip() string {
if n.ipv4Addr != "" {
return n.ipv4Addr
}
return n.ipv6Addr
}
type ClusterInfo struct {
numNodes int
podV4NetworkCIDR string
podV6NetworkCIDR string
svcV4NetworkCIDR string
svcV6NetworkCIDR string
controlPlaneNodeName string
controlPlaneNodeIPv4 string
controlPlaneNodeIPv6 string
nodes map[int]*ClusterNode
nodesOS map[string]string
windowsNodes []int
k8sServerVersion string
k8sServiceHost string
k8sServicePort int32
}
type ExternalInfo struct {
externalServerIPv4 string
externalServerIPv6 string
vlanSubnetIPv4 string
vlanGatewayIPv4 string
vlanSubnetIPv6 string
vlanGatewayIPv6 string
vlanID int
externalFRRIPv4 string
externalFRRIPv6 string
externalFRRCID string
}
var clusterInfo ClusterInfo
var externalInfo ExternalInfo
type TestOptions struct {
providerName string
providerConfigPath string
logsExportDir string
logsExportOnSuccess bool
withBench bool
enableCoverage bool
enableAntreaIPAM bool
flowVisibility bool
npEvaluation bool
coverageDir string
skipCases string
linuxVMs string
windowsVMs string
// deployAntrea determines whether to deploy Antrea before running tests. It requires antrea.yml to be present in
// the home directory of the control-plane Node. Note it doesn't affect the tests that redeploy Antrea themselves.
deployAntrea bool
externalAgnhostIPs string
vlanSubnets string
externalFRRIPs string
// FRR cannot currently be configured remotely over networking. As a result, the e2e tests for BGPPolicy can only
// be run in a Kind cluster, where the FRR container can be configured using Docker exec with the container ID.
// TODO: Introduce a BGP router implementation that can be configured remotely over networking to replace FRR.
// This would allow the e2e tests for BGPPolicy to be run in environments other than just a Kind cluster.
externalFRRCID string
}
type flowVisibilityTestOptions struct {
mode flowaggregatorconfig.AggregatorMode
databaseURL string
secureConnection bool
}
var testOptions TestOptions
// PodInfo combines OS info with a Pod name. It is useful when choosing commands and options on Pods of different OS (Windows, Linux).
type PodInfo struct {
Name string
OS string
NodeName string
Namespace string
}
// TestData stores the state required for each test case.
type TestData struct {
ClusterName string
provider providers.ProviderInterface
kubeConfig *restclient.Config
clientset kubernetes.Interface
aggregatorClient aggregatorclientset.Interface
crdClient crdclientset.Interface
logsDirForTestCase string
testNamespace string
}
var testData *TestData
type PodIPs struct {
IPv4 *net.IP
IPv6 *net.IP
IPStrings []string
}
type deployAntreaOptions int
const (
deployAntreaDefault deployAntreaOptions = iota
deployAntreaIPsec
deployAntreaCoverageOffset
)
func (o deployAntreaOptions) WithCoverage() deployAntreaOptions {
return o + deployAntreaCoverageOffset
}
func (o deployAntreaOptions) DeployYML() string {
return deployAntreaOptionsYML[o]
}
func (o deployAntreaOptions) String() string {
return deployAntreaOptionsString[o]
}
var (
deployAntreaOptionsString = [...]string{
"AntreaDefault",
"AntreaWithIPSec",
}
deployAntreaOptionsYML = [...]string{
antreaYML,
antreaIPSecYML,
antreaCovYML,
antreaIPSecCovYML,
}
)
func (p PodIPs) String() string {
res := ""
if p.IPv4 != nil {
res += fmt.Sprintf("IPv4(%s),", p.IPv4.String())
}
if p.IPv6 != nil {
res += fmt.Sprintf("IPv6(%s),", p.IPv6.String())
}
return fmt.Sprintf("%sIPstrings(%s)", res, strings.Join(p.IPStrings, ","))
}
func (p *PodIPs) hasSameIP(p1 *PodIPs) bool {
if len(p.IPStrings) == 0 && len(p1.IPStrings) == 0 {
return true
}
if p.IPv4 != nil && p1.IPv4 != nil && p.IPv4.Equal(*(p1.IPv4)) {
return true
}
if p.IPv6 != nil && p1.IPv6 != nil && p.IPv6.Equal(*(p1.IPv6)) {
return true
}
return false
}
func (p *PodIPs) AsSlice() []*net.IP {
var ips []*net.IP
if p.IPv4 != nil {
ips = append(ips, p.IPv4)
}
if p.IPv6 != nil {
ips = append(ips, p.IPv6)
}
return ips
}
func (p *PodIPs) AsStrings() (ipv4, ipv6 string) {
if p.IPv4 != nil {
ipv4 = p.IPv4.String()
}
if p.IPv6 != nil {
ipv6 = p.IPv6.String()
}
return
}
// workerNodeName returns an empty string if there is no worker Node with the provided idx
// (including if idx is 0, which is reserved for the control-plane Node)
func workerNodeName(idx int) string {
if idx == 0 { // control-plane Node
return ""
}
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.name
}
func workerNodeIPv4(idx int) string {
if idx == 0 { // control-plane Node
return ""
}
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ipv4Addr
}
func workerNodeIPv6(idx int) string {
if idx == 0 { // control-plane Node
return ""
}
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ipv6Addr
}
// workerNodeIP returns an empty string if there is no worker Node with the provided idx
// (including if idx is 0, which is reserved for the control-plane Node)
func workerNodeIP(idx int) string {
if idx == 0 { // control-plane Node
return ""
}
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ip()
}
// nodeGatewayIPs returns the Antrea gateway's IPv4 address and IPv6 address for the provided Node
// (if applicable), in that order.
func nodeGatewayIPs(idx int) (string, string) {
node, ok := clusterInfo.nodes[idx]
if !ok {
return "", ""
}
return node.gwV4Addr, node.gwV6Addr
}
func controlPlaneNodeName() string {
return clusterInfo.controlPlaneNodeName
}
func controlPlaneNodeIPv4() string {
return clusterInfo.controlPlaneNodeIPv4
}
func controlPlaneNodeIPv6() string {
return clusterInfo.controlPlaneNodeIPv6
}
// nodeName returns an empty string if there is no Node with the provided idx. If idx is 0, the name
// of the control-plane Node will be returned.
func nodeName(idx int) string {
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.name
}
// nodeIPv4 returns an empty string if there is no Node with the provided idx. If idx is 0, the IPv4
// Address of the control-plane Node will be returned.
func nodeIPv4(idx int) string {
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ipv4Addr
}
// nodeIPv6 returns an empty string if there is no Node with the provided idx. If idx is 0, the IPv6
// Address of the control-plane Node will be returned.
func nodeIPv6(idx int) string {
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ipv6Addr
}
// nodeIP returns an empty string if there is no Node with the provided idx. If idx is 0, the IP
// of the control-plane Node will be returned.
func nodeIP(idx int) string {
node, ok := clusterInfo.nodes[idx]
if !ok {
return ""
}
return node.ip()
}
// isIPv4Enabled returns true if and only if IPv4 is enabled in the cluster.
func isIPv4Enabled() bool {
return clusterInfo.podV4NetworkCIDR != ""
}
// isIPv6Enabled returns true if and only if IPv6 is enabled in the cluster.
func isIPv6Enabled() bool {
return clusterInfo.podV6NetworkCIDR != ""
}
func labelNodeRoleControlPlane() string {
// TODO: return labelNodeRoleControlPlane unconditionally when the min K8s version
// requirement to run Antrea becomes K8s v1.20
const labelNodeRoleControlPlane = "node-role.kubernetes.io/control-plane"
const labelNodeRoleOldControlPlane = "node-role.kubernetes.io/master"
// If clusterInfo.k8sServerVersion < "v1.20.0"
if semver.Compare(clusterInfo.k8sServerVersion, "v1.20.0") < 0 {
return labelNodeRoleOldControlPlane
}
return labelNodeRoleControlPlane
}
func controlPlaneNoScheduleTolerations() []corev1.Toleration {
// the Node taint still uses "master" in K8s v1.20
return []corev1.Toleration{
{
Key: "node-role.kubernetes.io/master",
Operator: corev1.TolerationOpExists,
Effect: corev1.TaintEffectNoSchedule,
},
{
Key: "node-role.kubernetes.io/control-plane",
Operator: corev1.TolerationOpExists,
Effect: corev1.TaintEffectNoSchedule,
},
}
}
func (data *TestData) InitProvider(providerName, providerConfigPath string) error {
providerFactory := map[string]func(string) (providers.ProviderInterface, error){
"vagrant": providers.NewVagrantProvider,
"kind": providers.NewKindProvider,
"remote": providers.NewRemoteProvider,
}
if fn, ok := providerFactory[providerName]; ok {
newProvider, err := fn(providerConfigPath)
if err != nil {
return err
}
data.provider = newProvider
} else {
return fmt.Errorf("unknown provider '%s'", providerName)
}
return nil
}
// RunCommandOnNode is a convenience wrapper around the Provider interface RunCommandOnNode method.
func (data *TestData) RunCommandOnNode(nodeName string, cmd string) (code int, stdout string, stderr string, err error) {
return data.provider.RunCommandOnNode(nodeName, cmd)
}
func (data *TestData) RunCommandOnNodeExt(nodeName, cmd string, envs map[string]string, stdin string, sudo bool) (
code int, stdout, stderr string, err error) {
return data.provider.RunCommandOnNodeExt(nodeName, cmd, envs, stdin, sudo)
}
func (data *TestData) collectExternalInfo() error {
ips := strings.Split(testOptions.externalAgnhostIPs, ",")
for _, ip := range ips {
if ip == "" {
continue
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return fmt.Errorf("invalid external agnhost IP %s", ip)
}
if parsedIP.To4() != nil {
externalInfo.externalServerIPv4 = ip
} else {
externalInfo.externalServerIPv6 = ip
}
}
vlanSubnetsList := strings.Split(testOptions.vlanSubnets, "=")
vlanIDStr := vlanSubnetsList[0]
if vlanIDStr != "" {
vlanID, err := strconv.Atoi(vlanIDStr)
if err != nil {
return fmt.Errorf("invalid vlan id %s: %w", vlanIDStr, err)
}
externalInfo.vlanID = vlanID
subnets := strings.Split(vlanSubnetsList[1], ",")
for _, subnet := range subnets {
if subnet == "" {
continue
}
gatewayIP, _, err := net.ParseCIDR(subnet)
if err != nil {
return fmt.Errorf("invalid vlan subnet %s: %w", subnet, err)
}
if gatewayIP.To4() != nil {
externalInfo.vlanSubnetIPv4 = subnet
externalInfo.vlanGatewayIPv4 = gatewayIP.String()
} else {
externalInfo.vlanSubnetIPv6 = subnet
externalInfo.vlanGatewayIPv6 = gatewayIP.String()
}
}
}
frrIPs := strings.Split(testOptions.externalFRRIPs, ",")
for _, ip := range frrIPs {
if ip == "" {
continue
}
parsedIP := net.ParseIP(ip)
if parsedIP == nil {
return fmt.Errorf("invalid external FRR IP %s", ip)
}
if parsedIP.To4() != nil {
externalInfo.externalFRRIPv4 = ip
} else {
externalInfo.externalFRRIPv6 = ip
}
}
externalInfo.externalFRRCID = testOptions.externalFRRCID
return nil
}
func (data *TestData) collectClusterInfo() error {
// retrieve K8s server version
// this needs to be done first, as there may be dependencies on the
// version later in this function (e.g., for labelNodeRoleControlPlane()).
serverVersion, err := testData.clientset.Discovery().ServerVersion()
if err != nil {
return err
}
clusterInfo.k8sServerVersion = serverVersion.String()
// retrieve Node information
nodes, err := testData.clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return fmt.Errorf("error when listing cluster Nodes: %v", err)
}
workerIdx := 1
clusterInfo.nodes = make(map[int]*ClusterNode)
clusterInfo.nodesOS = make(map[string]string)
for idx := range nodes.Items {
node := &nodes.Items[idx]
isControlPlaneNode := func() bool {
_, ok := node.Labels[labelNodeRoleControlPlane()]
return ok
}()
var nodeIPv4 string
var nodeIPv6 string
for _, address := range node.Status.Addresses {
if address.Type == corev1.NodeInternalIP {
if utilnet.IsIPv6String(address.Address) {
nodeIPv6 = address.Address
} else if utilnet.IsIPv4String(address.Address) {
nodeIPv4 = address.Address
}
}
}
var nodeIdx int
// If multiple control-plane Nodes (HA), we will select the last one in the list
if isControlPlaneNode {
nodeIdx = 0
clusterInfo.controlPlaneNodeName = node.Name
clusterInfo.controlPlaneNodeIPv4 = nodeIPv4
clusterInfo.controlPlaneNodeIPv6 = nodeIPv6
} else {
nodeIdx = workerIdx
workerIdx++
}
clusterInfo.nodes[nodeIdx] = &ClusterNode{
idx: nodeIdx,
name: node.Name,
ipv4Addr: nodeIPv4,
ipv6Addr: nodeIPv6,
os: node.Status.NodeInfo.OperatingSystem,
}
if node.Status.NodeInfo.OperatingSystem == "windows" {
clusterInfo.windowsNodes = append(clusterInfo.windowsNodes, nodeIdx)
}
clusterInfo.nodesOS[node.Name] = node.Status.NodeInfo.OperatingSystem
}
if clusterInfo.controlPlaneNodeName == "" {
return fmt.Errorf("error when listing cluster Nodes: control-plane Node not found")
}
clusterInfo.numNodes = workerIdx
retrieveCIDRs := func(cmd string, reg string) ([]string, error) {
res := make([]string, 2)
rc, stdout, _, err := data.RunCommandOnNode(controlPlaneNodeName(), cmd)
if err != nil || rc != 0 {
return res, fmt.Errorf("error when running the following command `%s` on control-plane Node: %v, %s", cmd, err, stdout)
}
re := regexp.MustCompile(reg)
matches := re.FindStringSubmatch(stdout)
if len(matches) == 0 {
return res, fmt.Errorf("cannot retrieve CIDR, unexpected kubectl output: %s", stdout)
}
cidrs := strings.Split(matches[1], ",")
if len(cidrs) == 1 {
_, cidr, err := net.ParseCIDR(cidrs[0])
if err != nil {
return res, fmt.Errorf("CIDR cannot be parsed: %s", cidrs[0])
}
if cidr.IP.To4() != nil {
res[0] = cidrs[0]
} else {
res[1] = cidrs[0]
}
} else if len(cidrs) == 2 {
_, cidr, err := net.ParseCIDR(cidrs[0])
if err != nil {
return res, fmt.Errorf("CIDR cannot be parsed: %s", cidrs[0])
}
if cidr.IP.To4() != nil {
res[0] = cidrs[0]
res[1] = cidrs[1]
} else {
res[0] = cidrs[1]
res[1] = cidrs[0]
}
} else {
return res, fmt.Errorf("unexpected cluster CIDR: %s", matches[1])
}
return res, nil
}
// Retrieve cluster CIDRs
podCIDRs, err := retrieveCIDRs("kubectl cluster-info dump | grep cluster-cidr", `cluster-cidr=([^"]+)`)
if err != nil {
// Retrieve cluster CIDRs for Rancher clusters.
podCIDRs, err = retrieveCIDRs("ps aux | grep kube-controller | grep cluster-cidr", `cluster-cidr=([^\s]+)`)
if err != nil {
return err
}
}
clusterInfo.podV4NetworkCIDR = podCIDRs[0]
clusterInfo.podV6NetworkCIDR = podCIDRs[1]
// Retrieve service CIDRs
svcCIDRs, err := retrieveCIDRs("kubectl cluster-info dump | grep service-cluster-ip-range", `service-cluster-ip-range=([^"]+)`)
if err != nil {
// Retrieve service CIDRs for Rancher clusters.
svcCIDRs, err = retrieveCIDRs("ps aux | grep kube-controller | grep service-cluster-ip-range", `service-cluster-ip-range=([^\s]+)`)
if err != nil {
return err
}
}
clusterInfo.svcV4NetworkCIDR = svcCIDRs[0]
clusterInfo.svcV6NetworkCIDR = svcCIDRs[1]
// Retrieve kubernetes Service host and Port
svc, err := testData.clientset.CoreV1().Services("default").Get(context.TODO(), "kubernetes", metav1.GetOptions{})
if err != nil {
return fmt.Errorf("unable to get Service kubernetes: %v", err)
}
clusterInfo.k8sServiceHost = svc.Spec.ClusterIP
clusterInfo.k8sServicePort = svc.Spec.Ports[0].Port
return nil
}
func getNodeByName(name string) *ClusterNode {
for _, node := range clusterInfo.nodes {
if node.name == name {
return node
}
}
return nil
}
func (data *TestData) collectPodCIDRs() error {
nodes, err := testData.clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return fmt.Errorf("error when listing cluster Nodes: %v", err)
}
for _, node := range nodes.Items {
var podV4NetworkCIDR, podV6NetworkCIDR string
var gwV4Addr, gwV6Addr string
processPodCIDR := func(podCIDR string) error {
_, cidr, err := net.ParseCIDR(podCIDR)
if err != nil {
return err
}
if cidr.IP.To4() != nil {
podV4NetworkCIDR = podCIDR
gwV4Addr = ip.NextIP(cidr.IP).String()
} else {
podV6NetworkCIDR = podCIDR
gwV6Addr = ip.NextIP(cidr.IP).String()
}
return nil
}
if len(node.Spec.PodCIDRs) == 0 {
if err := processPodCIDR(node.Spec.PodCIDR); err != nil {
return fmt.Errorf("error when processing PodCIDR field for Node %s: %v", node.Name, err)
}
} else {
for _, podCIDR := range node.Spec.PodCIDRs {
if err := processPodCIDR(podCIDR); err != nil {
return fmt.Errorf("error when processing PodCIDRs field for Node %s: %v", node.Name, err)
}
}
}
clusterNode := getNodeByName(node.Name)
if clusterNode == nil {
return fmt.Errorf("Node %s not found in ClusterInfo", node.Name)
}
clusterNode.podV4NetworkCIDR = podV4NetworkCIDR
clusterNode.podV6NetworkCIDR = podV6NetworkCIDR
clusterNode.gwV4Addr = gwV4Addr
clusterNode.gwV6Addr = gwV6Addr
}
return nil
}
// CreateNamespace creates the provided namespace.
func (data *TestData) CreateNamespace(namespace string, mutateFunc func(*corev1.Namespace)) error {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
if mutateFunc != nil {
mutateFunc(ns)
}
if ns, err := data.clientset.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{}); err != nil {
// Ignore error if the Namespace already exists
if !errors.IsAlreadyExists(err) {
return fmt.Errorf("error when creating '%s' Namespace: %v", namespace, err)
}
// When Namespace already exists, check phase
if ns.Status.Phase == corev1.NamespaceTerminating {
return fmt.Errorf("error when creating '%s' Namespace: namespace exists but is in 'Terminating' phase", namespace)
}
}
return nil
}
func (data *TestData) UpdateNamespace(namespace string, mutateFunc func(*corev1.Namespace)) error {
ns, _ := data.clientset.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
if mutateFunc != nil {
mutateFunc(ns)
}
if ns, err := data.clientset.CoreV1().Namespaces().Update(context.TODO(), ns, metav1.UpdateOptions{}); err != nil {
// Check Namespace phase
if ns.Status.Phase == corev1.NamespaceTerminating {
return fmt.Errorf("error when updating '%s' Namespace: namespace is in 'Terminating' phase", namespace)
}
return fmt.Errorf("error when updating '%s' Namespace: %v", namespace, err)
}
return nil
}
// createNamespaceWithAnnotations creates the Namespace with Annotations.
func (data *TestData) createNamespaceWithAnnotations(namespace string, annotations map[string]string) error {
mutateFunc := data.generateNamespaceAnnotationsMutateFunc(annotations)
return data.CreateNamespace(namespace, mutateFunc)
}
// updateNamespaceWithAnnotations updates the given Namespace with Annotations.
func (data *TestData) updateNamespaceWithAnnotations(namespace string, annotations map[string]string) error {
mutateFunc := data.generateNamespaceAnnotationsMutateFunc(annotations)
return data.UpdateNamespace(namespace, mutateFunc)
}
// generateAnnotationsMutateFunc generates a mutate function to add given Annotations to a Namespace.
func (data *TestData) generateNamespaceAnnotationsMutateFunc(annotations map[string]string) func(*corev1.Namespace) {
var mutateFunc func(*corev1.Namespace)
if annotations != nil {
mutateFunc = func(namespace *corev1.Namespace) {
if namespace.Annotations == nil {
namespace.Annotations = map[string]string{}
}
for k := range annotations {
namespace.Annotations[k] = annotations[k]
}
}
}
return mutateFunc
}
// DeleteNamespace deletes the provided Namespace, and waits for deletion to actually complete if timeout>=0
func (data *TestData) DeleteNamespace(namespace string, timeout time.Duration) error {
var gracePeriodSeconds int64
var propagationPolicy = metav1.DeletePropagationForeground
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
PropagationPolicy: &propagationPolicy,
}
// To log time statistics
startTime := time.Now()
defer func() {
log.Infof("Deleting Namespace %s took %v", namespace, time.Since(startTime))
}()
if err := data.clientset.CoreV1().Namespaces().Delete(context.TODO(), namespace, deleteOptions); err != nil {
if errors.IsNotFound(err) {
// namespace does not exist, we return right away
return nil
}
return fmt.Errorf("error when deleting '%s' Namespace: %v", namespace, err)
}
if timeout >= 0 {
return wait.PollUntilContextTimeout(context.TODO(), defaultInterval, timeout, false, func(ctx context.Context) (bool, error) {
if ns, err := data.clientset.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
// Success
return true, nil
}
return false, fmt.Errorf("error when getting Namespace '%s' after delete: %v", namespace, err)
} else if ns.Status.Phase != corev1.NamespaceTerminating {
return false, fmt.Errorf("deleted Namespace '%s' should be in 'Terminating' phase", namespace)
}
// Keep trying
return false, nil
})
}
return nil
}
// deployAntreaCommon deploys Antrea using kubectl on the control-plane Node.
func (data *TestData) deployAntreaCommon(yamlFile string, extraOptions string, waitForAgentRollout bool) error {
// TODO: use the K8s apiserver when server side apply is available?
// See https://kubernetes.io/docs/reference/using-api/api-concepts/#server-side-apply
rc, _, _, err := data.provider.RunCommandOnNode(controlPlaneNodeName(), fmt.Sprintf("kubectl apply %s -f %s", extraOptions, yamlFile))
if err != nil || rc != 0 {
return fmt.Errorf("error when deploying Antrea; is %s available on the control-plane Node?", yamlFile)
}
rc, stdout, stderr, err := data.provider.RunCommandOnNode(controlPlaneNodeName(), fmt.Sprintf("kubectl -n %s rollout status deploy/%s --timeout=%v", antreaNamespace, antreaDeployment, defaultTimeout))
if err != nil || rc != 0 {
return fmt.Errorf("error when waiting for antrea-controller rollout to complete - rc: %v - stdout: %v - stderr: %v - err: %v", rc, stdout, stderr, err)
}
if waitForAgentRollout {
rc, stdout, stderr, err = data.provider.RunCommandOnNode(controlPlaneNodeName(), fmt.Sprintf("kubectl -n %s rollout status ds/%s --timeout=%v", antreaNamespace, antreaDaemonSet, defaultTimeout))
if err != nil || rc != 0 {
return fmt.Errorf("error when waiting for antrea-agent rollout to complete - rc: %v - stdout: %v - stderr: %v - err: %v", rc, stdout, stderr, err)
}
}
return nil
}
// deployAntrea deploys Antrea with deploy options.
func (data *TestData) deployAntrea(option deployAntreaOptions) error {
if testOptions.enableCoverage {
option = option.WithCoverage()
}
return data.deployAntreaCommon(option.DeployYML(), "", true)
}
// deployFlowVisibilityClickHouse deploys ClickHouse operator and DB.
func (data *TestData) deployFlowVisibilityClickHouse(o flowVisibilityTestOptions) (string, error) {
err := data.CreateNamespace(flowVisibilityNamespace, nil)
if err != nil {
return "", err
}
visibilityYML := flowVisibilityYML
if o.secureConnection {
visibilityYML = flowVisibilityTLSYML
}
rc, _, _, err := data.provider.RunCommandOnNode(controlPlaneNodeName(), fmt.Sprintf("kubectl apply -f %s", chOperatorYML))
if err != nil || rc != 0 {
return "", fmt.Errorf("error when deploying the ClickHouse Operator YML; %s not available on the control-plane Node", chOperatorYML)
}
if err := wait.PollUntilContextTimeout(context.TODO(), 2*time.Second, 10*time.Second, false, func(ctx context.Context) (bool, error) {
rc, stdout, stderr, err := data.provider.RunCommandOnNode(controlPlaneNodeName(), fmt.Sprintf("kubectl apply -f %s", visibilityYML))
if err != nil || rc != 0 {
// ClickHouseInstallation CRD from ClickHouse Operator install bundle applied soon before
// applying CR. Sometimes apiserver validation fails to recognize resource of
// kind: ClickHouseInstallation. Retry in such scenario.
if strings.Contains(stderr, "ClickHouseInstallation") || strings.Contains(stdout, "ClickHouseInstallation") {
return false, nil
}
return false, fmt.Errorf("error when deploying the flow visibility YML %s: %s, %s, %v", visibilityYML, stdout, stderr, err)
}
return true, nil
}); err != nil {
return "", err
}
// check for clickhouse pod Ready. Wait for 2x timeout as ch operator needs to be running first to handle chi
if err := data.podWaitForReady(2*defaultTimeout, flowVisibilityCHPodName, flowVisibilityNamespace); err != nil {
return "", err
}
// check clickhouse service http port for service connectivity
var chSvc *corev1.Service
if err := wait.PollUntilContextTimeout(context.TODO(), defaultInterval, defaultTimeout, true, func(ctx context.Context) (bool, error) {
chSvc, err = data.GetService(flowVisibilityNamespace, "clickhouse-clickhouse")
if err != nil {
return false, nil
} else {
return true, nil
}
}); err != nil {
return "", fmt.Errorf("timeout waiting for ClickHouse Service: %w", err)
}
const probePodName = "ch-svc-probe"
if err := NewPodBuilder(probePodName, flowVisibilityNamespace, agnhostImage).Create(testData); err != nil {
return "", fmt.Errorf("failed to create ClickHouse Service probe Pod: %w", err)
}
defer testData.DeletePod(flowVisibilityNamespace, probePodName)
if err := data.podWaitForReady(defaultTimeout, probePodName, flowVisibilityNamespace); err != nil {
return "", err
}
cmd := []string{"/agnhost", "connect", net.JoinHostPort(chSvc.Spec.ClusterIP, clickHouseHTTPPort), "--timeout=5s"}
if err := wait.PollUntilContextTimeout(context.TODO(), defaultInterval, defaultTimeout, true, func(ctx context.Context) (bool, error) {
_, stderr, err := testData.RunCommandFromPod(flowVisibilityNamespace, probePodName, agnhostContainerName, cmd)
if err != nil {
log.Infof("Failed to connnect to clickhouse Service, err: %v, stderr: %s", err, strings.Trim(stderr, "\n"))
return false, nil
} else {
log.Infof("Successfully connected to clickhouse Service")
return true, nil
}
}); err != nil {
return "", fmt.Errorf("timeout checking http port connectivity of clickhouse service: %w", err)
}
return chSvc.Spec.ClusterIP, nil
}
func (data *TestData) deleteFlowVisibility() error {
startTime := time.Now()
defer func() {