-
Notifications
You must be signed in to change notification settings - Fork 359
/
framework.go
1669 lines (1535 loc) · 61.8 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"
"math/rand"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v2"
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/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/component-base/featuregate"
aggregatorclientset "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset"
"github.com/vmware-tanzu/antrea/pkg/agent/config"
crdclientset "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned"
secv1alpha1 "github.com/vmware-tanzu/antrea/pkg/client/clientset/versioned/typed/security/v1alpha1"
"github.com/vmware-tanzu/antrea/pkg/features"
"github.com/vmware-tanzu/antrea/test/e2e/providers"
)
const (
defaultTimeout = 90 * time.Second
defaultInterval = 1 * time.Second
// antreaNamespace is the K8s Namespace in which all Antrea resources are running.
antreaNamespace string = "kube-system"
flowAggregatorNamespace string = "flow-aggregator"
antreaConfigVolume string = "antrea-config"
flowAggregatorConfigVolume string = "flow-aggregator-config"
antreaDaemonSet string = "antrea-agent"
antreaDeployment string = "antrea-controller"
flowAggregatorDeployment string = "flow-aggregator"
antreaDefaultGW string = "antrea-gw0"
testNamespace string = "antrea-test"
busyboxContainerName string = "busybox"
ovsContainerName string = "antrea-ovs"
agentContainerName string = "antrea-agent"
antreaYML string = "antrea.yml"
antreaIPSecYML string = "antrea-ipsec.yml"
antreaCovYML string = "antrea-coverage.yml"
antreaIPSecCovYML string = "antrea-ipsec-coverage.yml"
flowaggregatorYML string = "flow-aggregator.yml"
defaultBridgeName string = "br-int"
monitoringNamespace string = "monitoring"
antreaControllerCovBinary string = "antrea-controller-coverage"
antreaAgentCovBinary string = "antrea-agent-coverage"
antreaControllerCovFile string = "antrea-controller.cov.out"
antreaAgentCovFile string = "antrea-agent.cov.out"
antreaAgentConfName string = "antrea-agent.conf"
antreaControllerConfName string = "antrea-controller.conf"
flowAggregatorConfName string = "flow-aggregator.conf"
nameSuffixLength int = 8
agnhostImage = "gcr.io/kubernetes-e2e-test-images/agnhost:2.8"
busyboxImage = "projects.registry.vmware.com/library/busybox"
nginxImage = "projects.registry.vmware.com/antrea/nginx"
perftoolImage = "projects.registry.vmware.com/antrea/perftool"
ipfixCollectorImage = "projects.registry.vmware.com/antrea/ipfix-collector:v0.4.2"
ipfixCollectorPort = "4739"
nginxLBService = "nginx-loadbalancer"
)
type ClusterNode struct {
idx int // 0 for master Node
name string
}
type ClusterInfo struct {
numWorkerNodes int
numNodes int
podV4NetworkCIDR string
podV6NetworkCIDR string
svcV4NetworkCIDR string
svcV6NetworkCIDR string
masterNodeName string
nodes map[int]ClusterNode
}
var clusterInfo ClusterInfo
type TestOptions struct {
providerName string
providerConfigPath string
logsExportDir string
logsExportOnSuccess bool
withBench bool
enableCoverage bool
coverageDir string
}
var testOptions TestOptions
var provider providers.ProviderInterface
// TestData stores the state required for each test case.
type TestData struct {
kubeConfig *restclient.Config
clientset kubernetes.Interface
aggregatorClient aggregatorclientset.Interface
securityClient secv1alpha1.SecurityV1alpha1Interface
crdClient crdclientset.Interface
logsDirForTestCase string
}
var testData *TestData
type PodIPs struct {
ipv4 *net.IP
ipv6 *net.IP
ipStrings []string
}
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("%sIP strings: %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
}
// 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 master Node)
func workerNodeName(idx int) string {
if idx == 0 { // master Node
return ""
}
if node, ok := clusterInfo.nodes[idx]; !ok {
return ""
} else {
return node.name
}
}
func masterNodeName() string {
return clusterInfo.masterNodeName
}
// nodeName returns an empty string if there is no Node with the provided idx. If idx is 0, the name
// of the master Node will be returned.
func nodeName(idx int) string {
if node, ok := clusterInfo.nodes[idx]; !ok {
return ""
} else {
return node.name
}
}
func initProvider() error {
providerFactory := map[string]func(string) (providers.ProviderInterface, error){
"vagrant": providers.NewVagrantProvider,
"kind": providers.NewKindProvider,
"remote": providers.NewRemoteProvider,
}
if fn, ok := providerFactory[testOptions.providerName]; ok {
if newProvider, err := fn(testOptions.providerConfigPath); err != nil {
return err
} else {
provider = newProvider
}
} else {
return fmt.Errorf("unknown provider '%s'", testOptions.providerName)
}
return nil
}
// RunCommandOnNode is a convenience wrapper around the Provider interface RunCommandOnNode method.
func RunCommandOnNode(nodeName string, cmd string) (code int, stdout string, stderr string, err error) {
return provider.RunCommandOnNode(nodeName, cmd)
}
func collectClusterInfo() error {
// 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)
for _, node := range nodes.Items {
isMaster := func() bool {
_, ok := node.Labels["node-role.kubernetes.io/master"]
return ok
}()
var nodeIdx int
// If multiple master Nodes (HA), we will select the last one in the list
if isMaster {
nodeIdx = 0
clusterInfo.masterNodeName = node.Name
} else {
nodeIdx = workerIdx
workerIdx++
}
clusterInfo.nodes[nodeIdx] = ClusterNode{
idx: nodeIdx,
name: node.Name,
}
}
if clusterInfo.masterNodeName == "" {
return fmt.Errorf("error when listing cluster Nodes: master Node not found")
}
clusterInfo.numNodes = workerIdx
clusterInfo.numWorkerNodes = clusterInfo.numNodes - 1
retrieveCIDRs := func(cmd string, reg string) ([]string, error) {
res := make([]string, 2)
rc, stdout, _, err := RunCommandOnNode(clusterInfo.masterNodeName, cmd)
if err != nil || rc != 0 {
return res, fmt.Errorf("error when running the following command `%s` on master Node: %v, %s", cmd, err, stdout)
}
re := regexp.MustCompile(reg)
if matches := re.FindStringSubmatch(stdout); len(matches) == 0 {
return res, fmt.Errorf("cannot retrieve CIDR, unexpected kubectl output: %s", stdout)
} else {
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 {
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 {
return err
}
clusterInfo.svcV4NetworkCIDR = svcCIDRs[0]
clusterInfo.svcV6NetworkCIDR = svcCIDRs[1]
return nil
}
// createNamespace creates the provided namespace.
func (data *TestData) createNamespace(namespace string) error {
ns := corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: namespace,
},
}
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
}
// createTestNamespace creates the namespace used for tests.
func (data *TestData) createTestNamespace() error {
return data.createNamespace(testNamespace)
}
// deleteNamespace deletes the provided namespace and waits for deletion to actually complete.
func (data *TestData) deleteNamespace(namespace string, timeout time.Duration) error {
var gracePeriodSeconds int64 = 0
var propagationPolicy = metav1.DeletePropagationForeground
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
PropagationPolicy: &propagationPolicy,
}
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)
}
err := wait.Poll(defaultInterval, timeout, func() (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 err
}
// deleteTestNamespace deletes test namespace and waits for deletion to actually complete.
func (data *TestData) deleteTestNamespace(timeout time.Duration) error {
return data.deleteNamespace(testNamespace, timeout)
}
// deployAntreaCommon deploys Antrea using kubectl on the master node.
func (data *TestData) deployAntreaCommon(yamlFile string, extraOptions string) 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 := provider.RunCommandOnNode(masterNodeName(), 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 master Node?", yamlFile)
}
rc, _, _, err = provider.RunCommandOnNode(masterNodeName(), 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, _, _, err = provider.RunCommandOnNode(masterNodeName(), 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")
}
return nil
}
// deployAntrea deploys Antrea with the standard manifest.
func (data *TestData) deployAntrea() error {
if testOptions.enableCoverage {
return data.deployAntreaCommon(antreaCovYML, "")
}
return data.deployAntreaCommon(antreaYML, "")
}
// deployAntreaIPSec deploys Antrea with IPSec tunnel enabled.
func (data *TestData) deployAntreaIPSec() error {
if testOptions.enableCoverage {
return data.deployAntreaCommon(antreaIPSecCovYML, "")
}
return data.deployAntreaCommon(antreaIPSecYML, "")
}
// deployAntreaFlowExporter deploys Antrea with flow exporter config params enabled.
func (data *TestData) deployAntreaFlowExporter(ipfixCollector string) error {
// Enable flow exporter feature and add related config params to antrea agent configmap.
return data.mutateAntreaConfigMap(func(data map[string]string) {
antreaAgentConf, _ := data["antrea-agent.conf"]
antreaAgentConf = strings.Replace(antreaAgentConf, "# FlowExporter: false", " FlowExporter: true", 1)
if ipfixCollector != "" {
antreaAgentConf = strings.Replace(antreaAgentConf, "#flowCollectorAddr: \"flow-aggregator.flow-aggregator.svc:4739:tcp\"", fmt.Sprintf("flowCollectorAddr: \"%s\"", ipfixCollector), 1)
}
antreaAgentConf = strings.Replace(antreaAgentConf, "#flowPollInterval: \"5s\"", "flowPollInterval: \"1s\"", 1)
antreaAgentConf = strings.Replace(antreaAgentConf, "#flowExportFrequency: 12", "flowExportFrequency: 2", 1)
data["antrea-agent.conf"] = antreaAgentConf
}, false, true)
}
// deployFlowAggregator deploys flow aggregator with ipfix collector address.
func (data *TestData) deployFlowAggregator(ipfixCollector string) (string, error) {
rc, _, _, err := provider.RunCommandOnNode(masterNodeName(), fmt.Sprintf("kubectl apply -f %s", flowaggregatorYML))
if err != nil || rc != 0 {
return "", fmt.Errorf("error when deploying flow aggregator; %s not available on the master Node", flowaggregatorYML)
}
if err = data.mutateFlowAggregatorConfigMap(ipfixCollector); err != nil {
return "", err
}
if rc, _, _, err = provider.RunCommandOnNode(masterNodeName(), fmt.Sprintf("kubectl -n %s rollout status deployment/%s --timeout=%v", flowAggregatorNamespace, flowAggregatorDeployment, 2*defaultTimeout)); err != nil || rc != 0 {
_, stdout, _, _ := provider.RunCommandOnNode(masterNodeName(), fmt.Sprintf("kubectl -n %s describe pod", flowAggregatorNamespace))
return stdout, fmt.Errorf("error when waiting for flow aggregator rollout to complete. kubectl describe output: %v", stdout)
}
svc, err := data.clientset.CoreV1().Services(flowAggregatorNamespace).Get(context.TODO(), flowAggregatorDeployment, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("unable to get service %v: %v", flowAggregatorDeployment, err)
}
return svc.Spec.ClusterIP, nil
}
func (data *TestData) mutateFlowAggregatorConfigMap(ipfixCollector string) error {
configMap, err := data.GetFlowAggregatorConfigMap()
if err != nil {
return err
}
flowAggregatorConf, _ := configMap.Data[flowAggregatorConfName]
flowAggregatorConf = strings.Replace(flowAggregatorConf, "#externalFlowCollectorAddr: \"\"", fmt.Sprintf("externalFlowCollectorAddr: \"%s\"", ipfixCollector), 1)
flowAggregatorConf = strings.Replace(flowAggregatorConf, "#flowExportInterval: 60s", "flowExportInterval: 5s", 1)
configMap.Data[flowAggregatorConfName] = flowAggregatorConf
if _, err := data.clientset.CoreV1().ConfigMaps(flowAggregatorNamespace).Update(context.TODO(), configMap, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("failed to update ConfigMap %s: %v", configMap.Name, err)
}
return nil
}
func (data *TestData) GetFlowAggregatorConfigMap() (*corev1.ConfigMap, error) {
deployment, err := data.clientset.AppsV1().Deployments(flowAggregatorNamespace).Get(context.TODO(), flowAggregatorDeployment, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to retrieve Flow aggregator deployment: %v", err)
}
var configMapName string
for _, volume := range deployment.Spec.Template.Spec.Volumes {
if volume.ConfigMap != nil && volume.Name == flowAggregatorConfigVolume {
configMapName = volume.ConfigMap.Name
break
}
}
if len(configMapName) == 0 {
return nil, fmt.Errorf("failed to locate %s ConfigMap volume", flowAggregatorConfigVolume)
}
configMap, err := data.clientset.CoreV1().ConfigMaps(flowAggregatorNamespace).Get(context.TODO(), configMapName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("failed to get ConfigMap %s: %v", configMapName, err)
}
return configMap, nil
}
// getAgentContainersRestartCount reads the restart count for every container across all Antrea
// Agent Pods and returns the sum of all the read values.
func (data *TestData) getAgentContainersRestartCount() (int, error) {
listOptions := metav1.ListOptions{
LabelSelector: "app=antrea,component=antrea-agent",
}
pods, err := data.clientset.CoreV1().Pods(antreaNamespace).List(context.TODO(), listOptions)
if err != nil {
return 0, fmt.Errorf("failed to list antrea-agent Pods: %v", err)
}
containerRestarts := 0
for _, pod := range pods.Items {
for _, containerStatus := range pod.Status.ContainerStatuses {
containerRestarts += int(containerStatus.RestartCount)
}
}
return containerRestarts, nil
}
// waitForAntreaDaemonSetPods waits for the K8s apiserver to report that all the Antrea Pods are
// available, i.e. all the Nodes have one or more of the Antrea daemon Pod running and available.
func (data *TestData) waitForAntreaDaemonSetPods(timeout time.Duration) error {
err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
daemonSet, err := data.clientset.AppsV1().DaemonSets(antreaNamespace).Get(context.TODO(), antreaDaemonSet, metav1.GetOptions{})
if err != nil {
return false, fmt.Errorf("error when getting Antrea daemonset: %v", err)
}
// Make sure that all Daemon Pods are available.
// We use clusterInfo.numNodes instead of DesiredNumberScheduled because
// DesiredNumberScheduled may not be updated right away. If it is still set to 0 the
// first time we get the DaemonSet's Status, we would return immediately instead of
// waiting.
desiredNumber := int32(clusterInfo.numNodes)
if daemonSet.Status.NumberAvailable != desiredNumber ||
daemonSet.Status.UpdatedNumberScheduled != desiredNumber {
return false, nil
}
// Make sure that all antrea-agent Pods are not terminating. This is required because NumberAvailable of
// DaemonSet counts Pods even if they are terminating. Deleting antrea-agent Pods directly does not cause the
// number to decrease if the process doesn't quit immediately, e.g. when the signal is caught by bincover
// program and triggers coverage calculation.
pods, err := data.clientset.CoreV1().Pods(antreaNamespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: "app=antrea,component=antrea-agent",
})
if err != nil {
return false, fmt.Errorf("failed to list antrea-agent Pods: %v", err)
}
if len(pods.Items) != clusterInfo.numNodes {
return false, nil
}
for _, pod := range pods.Items {
if pod.DeletionTimestamp != nil {
return false, nil
}
}
return true, nil
})
if err == wait.ErrWaitTimeout {
return fmt.Errorf("antrea-agent DaemonSet not ready within %v", defaultTimeout)
} else if err != nil {
return err
}
return nil
}
// waitForCoreDNSPods waits for the K8s apiserver to report that all the CoreDNS Pods are available.
func (data *TestData) waitForCoreDNSPods(timeout time.Duration) error {
err := wait.PollImmediate(defaultInterval, timeout, func() (bool, error) {
deployment, err := data.clientset.AppsV1().Deployments("kube-system").Get(context.TODO(), "coredns", metav1.GetOptions{})
if err != nil {
return false, fmt.Errorf("error when retrieving CoreDNS deployment: %v", err)
}
if deployment.Status.UnavailableReplicas == 0 {
return true, nil
}
// Keep trying
return false, nil
})
if err == wait.ErrWaitTimeout {
return fmt.Errorf("some CoreDNS replicas are still unavailable after %v", defaultTimeout)
} else if err != nil {
return err
}
return nil
}
// restartCoreDNSPods deletes all the CoreDNS Pods to force them to be re-scheduled. It then waits
// for all the Pods to become available, by calling waitForCoreDNSPods.
func (data *TestData) restartCoreDNSPods(timeout time.Duration) error {
var gracePeriodSeconds int64 = 1
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
}
listOptions := metav1.ListOptions{
LabelSelector: "k8s-app=kube-dns",
}
if err := data.clientset.CoreV1().Pods(antreaNamespace).DeleteCollection(context.TODO(), deleteOptions, listOptions); err != nil {
return fmt.Errorf("error when deleting all CoreDNS Pods: %v", err)
}
return data.waitForCoreDNSPods(timeout)
}
// checkCoreDNSPods checks that all the Pods for the CoreDNS deployment are ready. If not, it
// deletes all the Pods to force them to restart and waits up to timeout for the Pods to become
// ready.
func (data *TestData) checkCoreDNSPods(timeout time.Duration) error {
if deployment, err := data.clientset.AppsV1().Deployments(antreaNamespace).Get(context.TODO(), "coredns", metav1.GetOptions{}); err != nil {
return fmt.Errorf("error when retrieving CoreDNS deployment: %v", err)
} else if deployment.Status.UnavailableReplicas == 0 {
// deployment ready, nothing to do
return nil
}
return data.restartCoreDNSPods(timeout)
}
// createClient initializes the K8s clientset in the TestData structure.
func (data *TestData) createClient() error {
kubeconfigPath, err := provider.GetKubeconfigPath()
if err != nil {
return fmt.Errorf("error when getting Kubeconfig path: %v", err)
}
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRules.ExplicitPath = kubeconfigPath
configOverrides := &clientcmd.ConfigOverrides{}
kubeConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides).ClientConfig()
if err != nil {
return fmt.Errorf("error when building kube config: %v", err)
}
clientset, err := kubernetes.NewForConfig(kubeConfig)
if err != nil {
return fmt.Errorf("error when creating kubernetes client: %v", err)
}
aggregatorClient, err := aggregatorclientset.NewForConfig(kubeConfig)
if err != nil {
return fmt.Errorf("error when creating kubernetes aggregatorClient: %v", err)
}
securityClient, err := secv1alpha1.NewForConfig(kubeConfig)
if err != nil {
return fmt.Errorf("error when creating Antrea securityClient: %v", err)
}
crdClient, err := crdclientset.NewForConfig(kubeConfig)
if err != nil {
return fmt.Errorf("error when creating CRD client: %v", err)
}
data.kubeConfig = kubeConfig
data.clientset = clientset
data.aggregatorClient = aggregatorClient
data.securityClient = securityClient
data.crdClient = crdClient
return nil
}
// deleteAntrea deletes the Antrea DaemonSet; we use cascading deletion, which means all the Pods created
// by Antrea will be deleted. After issuing the deletion request, we poll the K8s apiserver to ensure
// that the DaemonSet does not exist any more. This function is a no-op if the Antrea DaemonSet does
// not exist at the time the function is called.
func (data *TestData) deleteAntrea(timeout time.Duration) error {
if testOptions.enableCoverage {
data.gracefulExitAntreaAgent(testOptions.coverageDir, "all")
}
var gracePeriodSeconds int64 = 5
// Foreground deletion policy ensures that by the time the DaemonSet is deleted, there are
// no Antrea Pods left.
var propagationPolicy = metav1.DeletePropagationForeground
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
PropagationPolicy: &propagationPolicy,
}
if err := data.clientset.AppsV1().DaemonSets(antreaNamespace).Delete(context.TODO(), antreaDaemonSet, deleteOptions); err != nil {
if errors.IsNotFound(err) {
// no Antrea DaemonSet running, we return right away
return nil
}
return fmt.Errorf("error when trying to delete Antrea DaemonSet: %v", err)
}
err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
if _, err := data.clientset.AppsV1().DaemonSets(antreaNamespace).Get(context.TODO(), antreaDaemonSet, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
// Antrea DaemonSet does not exist any more, success
return true, nil
}
return false, fmt.Errorf("error when trying to get Antrea DaemonSet after deletion: %v", err)
}
// Keep trying
return false, nil
})
return err
}
// getImageName gets the image name from the fully qualified URI.
// For example: "gcr.io/kubernetes-e2e-test-images/agnhost:2.8" gets "agnhost".
func getImageName(uri string) string {
registryAndImage := strings.Split(uri, ":")[0]
paths := strings.Split(registryAndImage, "/")
return paths[len(paths)-1]
}
// createPodOnNode creates a pod in the test namespace with a container whose type is decided by imageName.
// Pod will be scheduled on the specified Node (if nodeName is not empty).
// mutateFunc can be used to customize the Pod if the other parameters don't meet the requirements.
func (data *TestData) createPodOnNode(name string, nodeName string, image string, command []string, args []string, env []corev1.EnvVar, ports []corev1.ContainerPort, hostNetwork bool, mutateFunc func(*corev1.Pod)) error {
// image could be a fully qualified URI which can't be used as container name and label value,
// extract the image name from it.
imageName := getImageName(image)
podSpec := corev1.PodSpec{
Containers: []corev1.Container{
{
Name: imageName,
Image: image,
ImagePullPolicy: corev1.PullIfNotPresent,
Command: command,
Args: args,
Env: env,
Ports: ports,
},
},
RestartPolicy: corev1.RestartPolicyNever,
HostNetwork: hostNetwork,
}
if nodeName != "" {
podSpec.NodeSelector = map[string]string{
"kubernetes.io/hostname": nodeName,
}
}
if nodeName == masterNodeName() {
// tolerate NoSchedule taint if we want Pod to run on master node
noScheduleToleration := corev1.Toleration{
Key: "node-role.kubernetes.io/master",
Operator: corev1.TolerationOpExists,
Effect: corev1.TaintEffectNoSchedule,
}
podSpec.Tolerations = []corev1.Toleration{noScheduleToleration}
}
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Labels: map[string]string{
"antrea-e2e": name,
"app": imageName,
},
},
Spec: podSpec,
}
if mutateFunc != nil {
mutateFunc(pod)
}
if _, err := data.clientset.CoreV1().Pods(testNamespace).Create(context.TODO(), pod, metav1.CreateOptions{}); err != nil {
return err
}
return nil
}
// createBusyboxPodOnNode creates a Pod in the test namespace with a single busybox container. The
// Pod will be scheduled on the specified Node (if nodeName is not empty).
func (data *TestData) createBusyboxPodOnNode(name string, nodeName string) error {
sleepDuration := 3600 // seconds
return data.createPodOnNode(name, nodeName, busyboxImage, []string{"sleep", strconv.Itoa(sleepDuration)}, nil, nil, nil, false, nil)
}
// createBusyboxPod creates a Pod in the test namespace with a single busybox container.
func (data *TestData) createBusyboxPod(name string) error {
return data.createBusyboxPodOnNode(name, "")
}
// createNginxPodOnNode creates a Pod in the test namespace with a single nginx container. The
// Pod will be scheduled on the specified Node (if nodeName is not empty).
func (data *TestData) createNginxPodOnNode(name string, nodeName string) error {
return data.createPodOnNode(name, nodeName, nginxImage, []string{}, nil, nil, []corev1.ContainerPort{
{
Name: "http",
ContainerPort: 80,
Protocol: corev1.ProtocolTCP,
},
}, false, nil)
}
// createNginxPod creates a Pod in the test namespace with a single nginx container.
func (data *TestData) createNginxPod(name, nodeName string) error {
return data.createNginxPodOnNode(name, nodeName)
}
// createServerPod creates a Pod that can listen to specified port and have named port set.
func (data *TestData) createServerPod(name string, portName string, portNum int, setHostPort bool) error {
// See https://github.com/kubernetes/kubernetes/blob/master/test/images/agnhost/porter/porter.go#L17 for the image's detail.
cmd := "porter"
env := corev1.EnvVar{Name: fmt.Sprintf("SERVE_PORT_%d", portNum), Value: "foo"}
port := corev1.ContainerPort{Name: portName, ContainerPort: int32(portNum)}
if setHostPort {
// If hostPort is to be set, it must match the container port number.
port.HostPort = int32(portNum)
}
return data.createPodOnNode(name, "", agnhostImage, nil, []string{cmd}, []corev1.EnvVar{env}, []corev1.ContainerPort{port}, false, nil)
}
// deletePod deletes a Pod in the test namespace.
func (data *TestData) deletePod(name string) error {
var gracePeriodSeconds int64 = 5
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
}
if err := data.clientset.CoreV1().Pods(testNamespace).Delete(context.TODO(), name, deleteOptions); err != nil {
if !errors.IsNotFound(err) {
return err
}
}
return nil
}
// Deletes a Pod in the test namespace then waits us to timeout for the Pod not to be visible to the
// client any more.
func (data *TestData) deletePodAndWait(timeout time.Duration, name string) error {
if err := data.deletePod(name); err != nil {
return err
}
if err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
if _, err := data.clientset.CoreV1().Pods(testNamespace).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
return true, nil
}
return false, fmt.Errorf("error when getting Pod: %v", err)
}
// Keep trying
return false, nil
}); err == wait.ErrWaitTimeout {
return fmt.Errorf("Pod '%s' still visible to client after %v", name, timeout)
} else {
return err
}
}
type PodCondition func(*corev1.Pod) (bool, error)
// podWaitFor polls the K8s apiserver until the specified Pod is found (in the test Namespace) and
// the condition predicate is met (or until the provided timeout expires).
func (data *TestData) podWaitFor(timeout time.Duration, name, namespace string, condition PodCondition) (*corev1.Pod, error) {
err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
if pod, err := data.clientset.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
return false, nil
}
return false, fmt.Errorf("error when getting Pod '%s': %v", name, err)
} else {
return condition(pod)
}
})
if err != nil {
return nil, err
}
return data.clientset.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
}
// podWaitForRunning polls the k8s apiserver until the specified Pod is in the "running" state (or
// until the provided timeout expires).
func (data *TestData) podWaitForRunning(timeout time.Duration, name, namespace string) error {
_, err := data.podWaitFor(timeout, name, namespace, func(pod *corev1.Pod) (bool, error) {
return pod.Status.Phase == corev1.PodRunning, nil
})
return err
}
// podWaitForIPs polls the K8s apiserver until the specified Pod is in the "running" state (or until
// the provided timeout expires). The function then returns the IP addresses assigned to the Pod. If the
// Pod is not using "hostNetwork", the function also checks that an IP address exists in each required
// Address Family in the cluster.
func (data *TestData) podWaitForIPs(timeout time.Duration, name, namespace string) (*PodIPs, error) {
pod, err := data.podWaitFor(timeout, name, namespace, func(pod *corev1.Pod) (bool, error) {
return pod.Status.Phase == corev1.PodRunning, nil
})
if err != nil {
return nil, err
}
// According to the K8s API documentation (https://godoc.org/k8s.io/api/core/v1#PodStatus),
// the PodIP field should only be empty if the Pod has not yet been scheduled, and "running"
// implies scheduled.
if pod.Status.PodIP == "" {
return nil, fmt.Errorf("Pod is running but has no assigned IP, which should never happen")
}
podIPStrings := sets.NewString(pod.Status.PodIP)
for _, podIP := range pod.Status.PodIPs {
ipStr := strings.TrimSpace(podIP.IP)
if ipStr != "" {
podIPStrings.Insert(ipStr)
}
}
ips, err := parsePodIPs(podIPStrings)
if err != nil {
return nil, err
}
if !pod.Spec.HostNetwork {
if clusterInfo.podV4NetworkCIDR != "" && ips.ipv4 == nil {
return nil, fmt.Errorf("no IPv4 address is assigned while cluster was configured with IPv4 Pod CIDR %s", clusterInfo.podV4NetworkCIDR)
}
if clusterInfo.podV6NetworkCIDR != "" && ips.ipv6 == nil {
return nil, fmt.Errorf("no IPv6 address is assigned while cluster was configured with IPv6 Pod CIDR %s", clusterInfo.podV6NetworkCIDR)
}
}
return ips, nil
}
func parsePodIPs(podIPStrings sets.String) (*PodIPs, error) {
ips := new(PodIPs)
for idx := range podIPStrings.List() {
ipStr := podIPStrings.List()[idx]
ip := net.ParseIP(ipStr)
if ip.To4() != nil {
if ips.ipv4 != nil && ipStr != ips.ipv4.String() {
return nil, fmt.Errorf("Pod is assigned multiple IPv4 addresses: %s and %s", ips.ipv4.String(), ipStr)
}
if ips.ipv4 == nil {
ips.ipv4 = &ip
ips.ipStrings = append(ips.ipStrings, ipStr)
}
} else {
if ips.ipv6 != nil && ipStr != ips.ipv6.String() {
return nil, fmt.Errorf("Pod is assigned multiple IPv6 addresses: %s and %s", ips.ipv6.String(), ipStr)
}
if ips.ipv6 == nil {
ips.ipv6 = &ip
ips.ipStrings = append(ips.ipStrings, ipStr)
}
}
}
if len(ips.ipStrings) == 0 {
return nil, fmt.Errorf("pod is running but has no assigned IP, which should never happen")
}
return ips, nil
}
// deleteAntreaAgentOnNode deletes the antrea-agent Pod on a specific Node and measure how long it
// takes for the Pod not to be visible to the client any more. It also waits for a new antrea-agent
// Pod to be running on the Node.
func (data *TestData) deleteAntreaAgentOnNode(nodeName string, gracePeriodSeconds int64, timeout time.Duration) (time.Duration, error) {
if testOptions.enableCoverage {
data.gracefulExitAntreaAgent(testOptions.coverageDir, nodeName)
}
listOptions := metav1.ListOptions{
LabelSelector: "app=antrea,component=antrea-agent",
FieldSelector: fmt.Sprintf("spec.nodeName=%s", nodeName),
}
// we do not use DeleteCollection directly because we want to ensure the resources no longer
// exist by the time we return
pods, err := data.clientset.CoreV1().Pods(antreaNamespace).List(context.TODO(), listOptions)
if err != nil {
return 0, fmt.Errorf("failed to list antrea-agent Pods on Node '%s': %v", nodeName, err)
}
// in the normal case, there should be a single Pod in the list
if len(pods.Items) == 0 {
return 0, fmt.Errorf("no available antrea-agent Pods on Node '%s'", nodeName)
}
deleteOptions := metav1.DeleteOptions{
GracePeriodSeconds: &gracePeriodSeconds,
}
start := time.Now()
if err := data.clientset.CoreV1().Pods(antreaNamespace).DeleteCollection(context.TODO(), deleteOptions, listOptions); err != nil {
return 0, fmt.Errorf("error when deleting antrea-agent Pods on Node '%s': %v", nodeName, err)
}
if err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
for _, pod := range pods.Items {
if _, err := data.clientset.CoreV1().Pods(antreaNamespace).Get(context.TODO(), pod.Name, metav1.GetOptions{}); err != nil {
if errors.IsNotFound(err) {
continue
}
return false, fmt.Errorf("error when getting Pod: %v", err)
}
// Keep trying, at least one Pod left
return false, nil
}
return true, nil
}); err != nil {
return 0, err
}
delay := time.Since(start)
// wait for new antrea-agent Pod
if err := wait.Poll(defaultInterval, timeout, func() (bool, error) {
pods, err := data.clientset.CoreV1().Pods(antreaNamespace).List(context.TODO(), listOptions)
if err != nil {
return false, fmt.Errorf("failed to list antrea-agent Pods on Node '%s': %v", nodeName, err)
}
if len(pods.Items) == 0 {
// keep trying
return false, nil
}
for _, pod := range pods.Items {
if pod.Status.Phase != corev1.PodRunning {
return false, nil
}
}
return true, nil
}); err != nil {
return 0, err
}
return delay, nil
}
// getAntreaPodOnNode retrieves the name of the Antrea Pod (antrea-agent-*) running on a specific Node.
func (data *TestData) getAntreaPodOnNode(nodeName string) (podName string, err error) {
listOptions := metav1.ListOptions{
LabelSelector: "app=antrea,component=antrea-agent",
FieldSelector: fmt.Sprintf("spec.nodeName=%s", nodeName),