-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
e2e_suite_test.go
294 lines (237 loc) · 11.5 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
//go:build e2e
// +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 (
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"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/cluster-api/test/framework/ginkgoextensions"
)
// 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
// clusterctlConfig is the file which tests will use as a clusterctl config.
// If it is not set, a local clusterctl repository (including a clusterctl config) will be created automatically.
clusterctlConfig string
// alsoLogToFile enables additional logging to the 'ginkgo-log.txt' file in the artifact folder.
// These logs also contain timestamps.
alsoLogToFile bool
// skipCleanup prevents cleanup of test resources e.g. for debug purposes.
skipCleanup bool
)
// Test suite global vars.
var (
ctx = ctrl.SetupSignalHandler()
// 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
)
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(&alsoLogToFile, "e2e.also-log-to-file", true, "if true, ginkgo logs are additionally written to the `ginkgo-log.txt` file in the artifacts folder (including timestamps)")
flag.BoolVar(&skipCleanup, "e2e.skip-resource-cleanup", false, "if true, the resource cleanup after tests will be skipped")
flag.StringVar(&clusterctlConfig, "e2e.clusterctl-config", "", "file which tests will use as a clusterctl config. If it is not set, a local clusterctl repository (including a clusterctl config) will be created automatically.")
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)")
}
func TestE2E(t *testing.T) {
g := NewWithT(t)
// If running in prow, make sure to use the artifacts folder that will be reported in test grid (ignoring the value provided by flag).
if prowArtifactFolder, exists := os.LookupEnv("ARTIFACTS"); exists {
artifactFolder = prowArtifactFolder
}
// ensure the artifacts folder exists
g.Expect(os.MkdirAll(artifactFolder, 0755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder) //nolint:gosec
RegisterFailHandler(Fail)
if alsoLogToFile {
w, err := ginkgoextensions.EnableFileLogging(filepath.Join(artifactFolder, "ginkgo-log.txt"))
g.Expect(err).ToNot(HaveOccurred())
defer w.Close()
}
RunSpecs(t, "capi-e2e")
}
// 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.")
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)
if clusterctlConfig == "" {
Byf("Creating a clusterctl local repository into %q", artifactFolder)
clusterctlConfigPath = createClusterctlLocalRepository(e2eConfig, filepath.Join(artifactFolder, "repository"))
} else {
Byf("Using existing clusterctl config %q", clusterctlConfig)
clusterctlConfigPath = clusterctlConfig
}
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 = framework.NewClusterProxy("bootstrap", kubeconfigPath, initScheme(), framework.WithMachineLogCollector(framework.DockerLogCollector{}))
})
// 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("Dumping logs from the bootstrap cluster")
dumpBootstrapClusterLogs(bootstrapClusterProxy)
By("Tearing down the management cluster")
if !skipCleanup {
tearDown(bootstrapClusterProvider, bootstrapClusterProxy)
}
})
func initScheme() *runtime.Scheme {
sc := runtime.NewScheme()
framework.TryAddDefaultSchemes(sc)
return sc
}
func loadE2EConfig(configPath string) *clusterctl.E2EConfig {
config := clusterctl.LoadE2EConfig(ctx, 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 in place of the CNI_RESOURCES envSubst variable.
Expect(config.Variables).To(HaveKey(CNIPath), "Missing %s variable in the config", CNIPath)
cniPath := config.GetVariable(CNIPath)
Expect(cniPath).To(BeAnExistingFile(), "The %s variable should resolve to an existing file", CNIPath)
createRepositoryInput.RegisterClusterResourceSetConfigMapTransformation(cniPath, CNIResources)
clusterctlConfig := clusterctl.CreateRepository(ctx, 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 {
By("Creating the bootstrap cluster")
clusterProvider = bootstrap.CreateKindBootstrapClusterAndLoadImages(ctx, bootstrap.CreateKindBootstrapClusterAndLoadImagesInput{
Name: config.ManagementClusterName,
KubernetesVersion: config.GetVariable(KubernetesVersionManagement),
RequiresDockerSock: config.HasDockerProvider(),
Images: config.Images,
IPFamily: config.GetVariable(IPFamily),
LogFolder: filepath.Join(artifactFolder, "kind"),
})
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")
} else {
By("Using an existing bootstrap cluster")
}
clusterProxy := framework.NewClusterProxy("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(ctx, clusterctl.InitManagementClusterAndWatchControllerLogsInput{
ClusterProxy: bootstrapClusterProxy,
ClusterctlConfigPath: clusterctlConfig,
InfrastructureProviders: config.InfrastructureProviders(),
LogFolder: filepath.Join(artifactFolder, "clusters", bootstrapClusterProxy.GetName()),
}, config.GetIntervals(bootstrapClusterProxy.GetName(), "wait-controllers")...)
}
func dumpBootstrapClusterLogs(bootstrapClusterProxy framework.ClusterProxy) {
if bootstrapClusterProxy == nil {
return
}
clusterLogCollector := bootstrapClusterProxy.GetLogCollector()
if clusterLogCollector == nil {
return
}
nodes, err := bootstrapClusterProxy.GetClientSet().CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
fmt.Printf("Failed to get nodes for the bootstrap cluster: %v\n", err)
return
}
for i := range nodes.Items {
nodeName := nodes.Items[i].GetName()
err = clusterLogCollector.CollectMachineLog(
ctx,
bootstrapClusterProxy.GetClient(),
// The bootstrap cluster is not expected to be a CAPI cluster, so in order to re-use the logCollector,
// we create a fake machine that wraps the node.
// NOTE: This assumes a naming convention between machines and nodes, which e.g. applies to the bootstrap clusters generated with kind.
// This might not work if you are using an existing bootstrap cluster provided by other means.
&clusterv1.Machine{
Spec: clusterv1.MachineSpec{ClusterName: nodeName},
ObjectMeta: metav1.ObjectMeta{Name: nodeName},
},
filepath.Join(artifactFolder, "clusters", bootstrapClusterProxy.GetName(), "machines", nodeName),
)
if err != nil {
fmt.Printf("Failed to get logs for the bootstrap cluster node %s: %v\n", nodeName, err)
}
}
}
func tearDown(bootstrapClusterProvider bootstrap.ClusterProvider, bootstrapClusterProxy framework.ClusterProxy) {
if bootstrapClusterProxy != nil {
bootstrapClusterProxy.Dispose(ctx)
}
if bootstrapClusterProvider != nil {
bootstrapClusterProvider.Dispose(ctx)
}
}