-
Notifications
You must be signed in to change notification settings - Fork 431
/
e2e_suite_test.go
405 lines (337 loc) · 16.4 KB
/
e2e_suite_test.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
// +build e2e
/*
Copyright 2020 The Kubernetes 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 (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Azure/go-autorest/autorest/to"
aadpodv1 "github.com/Azure/aad-pod-identity/pkg/apis/aadpodidentity/v1"
"github.com/Azure/azure-sdk-for-go/services/preview/monitor/mgmt/2019-06-01/insights"
"github.com/Azure/go-autorest/autorest/azure/auth"
. "github.com/onsi/ginkgo"
"github.com/onsi/ginkgo/config"
"github.com/onsi/ginkgo/reporters"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
infrav1 "sigs.k8s.io/cluster-api-provider-azure/api/v1alpha4"
capi_e2e "sigs.k8s.io/cluster-api/test/e2e"
"sigs.k8s.io/cluster-api/test/framework"
"sigs.k8s.io/cluster-api/test/framework/bootstrap"
"sigs.k8s.io/cluster-api/test/framework/clusterctl"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
kubesystem = "kube-system"
activitylog = "azure-activity-logs"
)
// Test suite flags
var (
// configPath is the path to the e2e config file.
configPath string
// useExistingCluster instructs the test to use the current cluster instead of creating a new one (default discovery rules apply).
useExistingCluster bool
// artifactFolder is the folder to store e2e test artifacts.
artifactFolder string
// skipCleanup prevents cleanup of test resources e.g. for debug purposes.
skipCleanup bool
)
// Test suite global vars
var (
// e2eConfig to be used for this test, read from configPath.
e2eConfig *clusterctl.E2EConfig
// clusterctlConfigPath to be used for this test, created by generating a clusterctl local repository
// with the providers specified in the configPath.
clusterctlConfigPath string
// bootstrapClusterProvider manages provisioning of the the bootstrap cluster to be used for the e2e tests.
// Please note that provisioning will be skipped if e2e.use-existing-cluster is provided.
bootstrapClusterProvider bootstrap.ClusterProvider
// bootstrapClusterProxy allows to interact with the bootstrap cluster to be used for the e2e tests.
bootstrapClusterProxy framework.ClusterProxy
// kubetestConfigFilePath is the path to the kubetest configuration file
kubetestConfigFilePath string
// useCIArtifacts specifies whether or not to use the latest build from the main branch of the Kubernetes repository
useCIArtifacts bool
)
type (
AzureClusterProxy struct {
framework.ClusterProxy
}
// myEventData is used to be able to Marshal insights.EventData into JSON
// see https://github.com/Azure/azure-sdk-for-go/issues/8224#issuecomment-614777550
myEventData insights.EventData
)
func NewAzureClusterProxy(name string, kubeconfigPath string, scheme *runtime.Scheme, options ...framework.Option) *AzureClusterProxy {
proxy, ok := framework.NewClusterProxy(name, kubeconfigPath, scheme, options...).(framework.ClusterProxy)
Expect(ok).To(BeTrue(), "framework.NewClusterProxy must implement capi_e2e.ClusterProxy")
return &AzureClusterProxy{
ClusterProxy: proxy,
}
}
func (acp *AzureClusterProxy) CollectWorkloadClusterLogs(ctx context.Context, namespace, name, outputPath string) {
Byf("Dumping workload cluster %s/%s logs", namespace, name)
acp.ClusterProxy.CollectWorkloadClusterLogs(ctx, namespace, name, outputPath)
aboveMachinesPath := strings.Replace(outputPath, "/machines", "", 1)
Byf("Dumping workload cluster %s/%s kube-system pod logs", namespace, name)
start := time.Now()
acp.collectPodLogs(ctx, namespace, name, aboveMachinesPath)
Byf("Fetching kube-system pod logs took %s", time.Since(start).String())
Byf("Dumping workload cluster %s/%s Azure activity log", namespace, name)
start = time.Now()
acp.collectActivityLogs(ctx, aboveMachinesPath)
Byf("Fetching activity logs took %s", time.Since(start).String())
}
func (acp *AzureClusterProxy) collectPodLogs(ctx context.Context, namespace string, name string, aboveMachinesPath string) {
workload := acp.GetWorkloadCluster(ctx, namespace, name)
pods := &corev1.PodList{}
Expect(workload.GetClient().List(ctx, pods, client.InNamespace(kubesystem))).To(Succeed())
for _, pod := range pods.Items {
for _, container := range pod.Spec.Containers {
// Watch each container's logs in a goroutine so we can stream them all concurrently.
go func(pod corev1.Pod, container corev1.Container) {
defer GinkgoRecover()
Byf("Creating log watcher for controller %s/%s, container %s", kubesystem, pod.Name, container.Name)
logFile := path.Join(aboveMachinesPath, kubesystem, pod.Name, container.Name+".log")
Expect(os.MkdirAll(filepath.Dir(logFile), 0755)).To(Succeed())
f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
// Failing to fetch logs should not cause the test to fail
Byf("Error opening file to write pod logs: %v", err)
return
}
defer f.Close()
opts := &corev1.PodLogOptions{
Container: container.Name,
Follow: true,
}
podLogs, err := workload.GetClientSet().CoreV1().Pods(kubesystem).GetLogs(pod.Name, opts).Stream(ctx)
if err != nil {
// Failing to stream logs should not cause the test to fail
Byf("Error starting logs stream for pod %s/%s, container %s: %v", kubesystem, pod.Name, container.Name, err)
return
}
defer podLogs.Close()
out := bufio.NewWriter(f)
defer out.Flush()
_, err = out.ReadFrom(podLogs)
if err != nil && err != io.ErrUnexpectedEOF {
// Failing to stream logs should not cause the test to fail
Byf("Got error while streaming logs for pod %s/%s, container %s: %v", kubesystem, pod.Name, container.Name, err)
}
}(pod, container)
}
}
}
func (acp *AzureClusterProxy) collectActivityLogs(ctx context.Context, aboveMachinesPath string) {
timeoutctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
settings, err := auth.GetSettingsFromEnvironment()
Expect(err).NotTo(HaveOccurred())
subscriptionID := settings.GetSubscriptionID()
authorizer, err := settings.GetAuthorizer()
Expect(err).NotTo(HaveOccurred())
activityLogsClient := insights.NewActivityLogsClient(subscriptionID)
activityLogsClient.Authorizer = authorizer
groupName := os.Getenv(AzureResourceGroup)
start := time.Now().Add(-2 * time.Hour).UTC().Format(time.RFC3339)
end := time.Now().UTC().Format(time.RFC3339)
itr, err := activityLogsClient.ListComplete(timeoutctx, fmt.Sprintf("eventTimestamp ge '%s' and eventTimestamp le '%s' and resourceGroupName eq '%s'", start, end, groupName), "")
if err != nil {
// Failing to fetch logs should not cause the test to fail
Byf("Error fetching activity logs for resource group %s: %v", groupName, err)
return
}
logFile := path.Join(aboveMachinesPath, activitylog, groupName+".log")
Expect(os.MkdirAll(filepath.Dir(logFile), 0755)).To(Succeed())
f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
// Failing to fetch logs should not cause the test to fail
Byf("Error opening file to write activity logs: %v", err)
return
}
defer f.Close()
out := bufio.NewWriter(f)
defer out.Flush()
for ; itr.NotDone(); err = itr.NextWithContext(timeoutctx) {
if err != nil {
Byf("Got error while iterating over activity logs for resource group %s: %v", groupName, err)
return
}
event := itr.Value()
if to.String(event.Category.Value) != "Policy" {
b, err := json.MarshalIndent(myEventData(event), "", " ")
if err != nil {
Byf("Got error converting activity logs data to json: %v", err)
}
if _, err = out.WriteString(string(b) + "\n"); err != nil {
Byf("Got error while writing activity logs for resource group %s: %v", groupName, err)
}
}
}
}
func init() {
flag.StringVar(&configPath, "e2e.config", "", "path to the e2e config file")
flag.StringVar(&artifactFolder, "e2e.artifacts-folder", "", "folder where e2e test artifact should be stored")
flag.BoolVar(&useCIArtifacts, "kubetest.use-ci-artifacts", false, "use the latest build from the main branch of the Kubernetes repository. Set KUBERNETES_VERSION environment variable to latest-1.xx to use the build from 1.xx release branch.")
flag.BoolVar(&skipCleanup, "e2e.skip-resource-cleanup", false, "if true, the resource cleanup after tests will be skipped")
flag.BoolVar(&useExistingCluster, "e2e.use-existing-cluster", false, "if true, the test uses the current cluster instead of creating a new one (default discovery rules apply)")
flag.StringVar(&kubetestConfigFilePath, "kubetest.config-file", "", "path to the kubetest configuration file")
}
func TestE2E(t *testing.T) {
RegisterFailHandler(Fail)
junitPath := filepath.Join(artifactFolder, fmt.Sprintf("junit.e2e_suite.%d.xml", config.GinkgoConfig.ParallelNode))
junitReporter := reporters.NewJUnitReporter(junitPath)
RunSpecsWithDefaultAndCustomReporters(t, "capz-e2e", []Reporter{junitReporter})
}
// Using a SynchronizedBeforeSuite for controlling how to create resources shared across ParallelNodes (~ginkgo threads).
// The local clusterctl repository & the bootstrap cluster are created once and shared across all the tests.
var _ = SynchronizedBeforeSuite(func() []byte {
// Before all ParallelNodes.
Expect(configPath).To(BeAnExistingFile(), "Invalid test suite argument. e2e.config should be an existing file.")
Expect(os.MkdirAll(artifactFolder, 0755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder)
By("Initializing a runtime.Scheme with all the GVK relevant for this test")
scheme := initScheme()
Byf("Loading the e2e test configuration from %q", configPath)
e2eConfig = loadE2EConfig(configPath)
Byf("Creating a clusterctl local repository into %q", artifactFolder)
clusterctlConfigPath = createClusterctlLocalRepository(e2eConfig, filepath.Join(artifactFolder, "repository"))
By("Setting up the bootstrap cluster")
bootstrapClusterProvider, bootstrapClusterProxy = setupBootstrapCluster(e2eConfig, scheme, useExistingCluster)
By("Initializing the bootstrap cluster")
initBootstrapCluster(bootstrapClusterProxy, e2eConfig, clusterctlConfigPath, artifactFolder)
return []byte(
strings.Join([]string{
artifactFolder,
configPath,
clusterctlConfigPath,
bootstrapClusterProxy.GetKubeconfigPath(),
}, ","),
)
}, func(data []byte) {
// Before each ParallelNode.
parts := strings.Split(string(data), ",")
Expect(parts).To(HaveLen(4))
artifactFolder = parts[0]
configPath = parts[1]
clusterctlConfigPath = parts[2]
kubeconfigPath := parts[3]
e2eConfig = loadE2EConfig(configPath)
bootstrapClusterProxy = NewAzureClusterProxy("bootstrap", kubeconfigPath, initScheme(),
framework.WithMachineLogCollector(AzureLogCollector{}))
})
// Using a SynchronizedAfterSuite for controlling how to delete resources shared across ParallelNodes (~ginkgo threads).
// The bootstrap cluster is shared across all the tests, so it should be deleted only after all ParallelNodes completes.
// The local clusterctl repository is preserved like everything else created into the artifact folder.
var _ = SynchronizedAfterSuite(func() {
// After each ParallelNode.
}, func() {
// After all ParallelNodes.
By("Tearing down the management cluster")
if !skipCleanup {
tearDown(bootstrapClusterProvider, bootstrapClusterProxy)
}
})
func initScheme() *runtime.Scheme {
scheme := runtime.NewScheme()
framework.TryAddDefaultSchemes(scheme)
Expect(infrav1.AddToScheme(scheme)).To(Succeed())
// Add aadpodidentity v1 to the scheme.
aadPodIdentityGroupVersion := schema.GroupVersion{Group: aadpodv1.CRDGroup, Version: aadpodv1.CRDVersion}
scheme.AddKnownTypes(aadPodIdentityGroupVersion,
&aadpodv1.AzureIdentity{},
&aadpodv1.AzureIdentityList{},
&aadpodv1.AzureIdentityBinding{},
&aadpodv1.AzureIdentityBindingList{},
&aadpodv1.AzureAssignedIdentity{},
&aadpodv1.AzureAssignedIdentityList{},
&aadpodv1.AzurePodIdentityException{},
&aadpodv1.AzurePodIdentityExceptionList{},
)
metav1.AddToGroupVersion(scheme, aadPodIdentityGroupVersion)
return scheme
}
func loadE2EConfig(configPath string) *clusterctl.E2EConfig {
config := clusterctl.LoadE2EConfig(context.TODO(), clusterctl.LoadE2EConfigInput{ConfigPath: configPath})
Expect(config).ToNot(BeNil(), "Failed to load E2E config from %s", configPath)
return config
}
func createClusterctlLocalRepository(config *clusterctl.E2EConfig, repositoryFolder string) string {
createRepositoryInput := clusterctl.CreateRepositoryInput{
E2EConfig: config,
RepositoryFolder: repositoryFolder,
}
// Ensuring a CNI file is defined in the config and register a FileTransformation to inject the referenced file as in place of the CNI_RESOURCES envSubst variable.
Expect(config.Variables).To(HaveKey(capi_e2e.CNIPath), "Missing %s variable in the config", capi_e2e.CNIPath)
cniPath := config.GetVariable(capi_e2e.CNIPath)
Expect(cniPath).To(BeAnExistingFile(), "The %s variable should resolve to an existing file", capi_e2e.CNIPath)
createRepositoryInput.RegisterClusterResourceSetConfigMapTransformation(cniPath, capi_e2e.CNIResources)
// Do the same for CNI_RESOURCES_IPV6.
Expect(config.Variables).To(HaveKey(CNIPathIPv6), "Missing %s variable in the config", CNIPathIPv6)
cniPathIPv6 := config.GetVariable(CNIPathIPv6)
Expect(cniPathIPv6).To(BeAnExistingFile(), "The %s variable should resolve to an existing file", CNIPathIPv6)
createRepositoryInput.RegisterClusterResourceSetConfigMapTransformation(cniPathIPv6, CNIResourcesIPv6)
// Read CNI_WINDOWS file and set CNI_RESOURCES_WINDOWS environmental variable
Expect(config.Variables).To(HaveKey(CNIPathWindows), "Missing %s variable in the config", CNIPathWindows)
cniPathWindows := config.GetVariable(CNIPathWindows)
Expect(cniPathWindows).To(BeAnExistingFile(), "The %s variable should resolve to an existing file", CNIPathWindows)
createRepositoryInput.RegisterClusterResourceSetConfigMapTransformation(cniPathWindows, CNIResourcesWindows)
clusterctlConfig := clusterctl.CreateRepository(context.TODO(), createRepositoryInput)
Expect(clusterctlConfig).To(BeAnExistingFile(), "The clusterctl config file does not exists in the local repository %s", repositoryFolder)
return clusterctlConfig
}
func setupBootstrapCluster(config *clusterctl.E2EConfig, scheme *runtime.Scheme, useExistingCluster bool) (bootstrap.ClusterProvider, framework.ClusterProxy) {
var clusterProvider bootstrap.ClusterProvider
kubeconfigPath := ""
if !useExistingCluster {
clusterProvider = bootstrap.CreateKindBootstrapClusterAndLoadImages(context.TODO(), bootstrap.CreateKindBootstrapClusterAndLoadImagesInput{
Name: config.ManagementClusterName,
RequiresDockerSock: config.HasDockerProvider(),
Images: config.Images,
})
Expect(clusterProvider).ToNot(BeNil(), "Failed to create a bootstrap cluster")
kubeconfigPath = clusterProvider.GetKubeconfigPath()
Expect(kubeconfigPath).To(BeAnExistingFile(), "Failed to get the kubeconfig file for the bootstrap cluster")
}
clusterProxy := NewAzureClusterProxy("bootstrap", kubeconfigPath, scheme)
Expect(clusterProxy).ToNot(BeNil(), "Failed to get a bootstrap cluster proxy")
return clusterProvider, clusterProxy
}
func initBootstrapCluster(bootstrapClusterProxy framework.ClusterProxy, config *clusterctl.E2EConfig, clusterctlConfig, artifactFolder string) {
clusterctl.InitManagementClusterAndWatchControllerLogs(context.TODO(), clusterctl.InitManagementClusterAndWatchControllerLogsInput{
ClusterProxy: bootstrapClusterProxy,
ClusterctlConfigPath: clusterctlConfig,
InfrastructureProviders: config.InfrastructureProviders(),
LogFolder: filepath.Join(artifactFolder, "clusters", bootstrapClusterProxy.GetName()),
}, config.GetIntervals(bootstrapClusterProxy.GetName(), "wait-controllers")...)
}
func tearDown(bootstrapClusterProvider bootstrap.ClusterProvider, bootstrapClusterProxy framework.ClusterProxy) {
if bootstrapClusterProxy != nil {
bootstrapClusterProxy.Dispose(context.TODO())
}
if bootstrapClusterProvider != nil {
bootstrapClusterProvider.Dispose(context.TODO())
}
}