/
e2e_config.go
410 lines (360 loc) · 14.9 KB
/
e2e_config.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
/*
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 clusterctl
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strconv"
"time"
. "github.com/onsi/gomega"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/util/version"
"k8s.io/utils/pointer"
clusterctlv1 "sigs.k8s.io/cluster-api/cmd/clusterctl/api/v1alpha3"
clusterctlconfig "sigs.k8s.io/cluster-api/cmd/clusterctl/client/config"
"sigs.k8s.io/cluster-api/test/framework"
"sigs.k8s.io/cluster-api/util"
"sigs.k8s.io/yaml"
)
// Provides access to the configuration for an e2e test.
// LoadE2EConfigInput is the input for LoadE2EConfig.
type LoadE2EConfigInput struct {
// ConfigPath for the e2e test.
ConfigPath string
}
// LoadE2EConfig loads the configuration for the e2e test environment.
func LoadE2EConfig(ctx context.Context, input LoadE2EConfigInput) *E2EConfig {
configData, err := ioutil.ReadFile(input.ConfigPath)
Expect(err).ToNot(HaveOccurred(), "Failed to read the e2e test config file")
Expect(configData).ToNot(BeEmpty(), "The e2e test config file should not be empty")
config := &E2EConfig{}
Expect(yaml.Unmarshal(configData, config)).To(Succeed(), "Failed to convert the e2e test config file to yaml")
config.Defaults()
config.AbsPaths(filepath.Dir(input.ConfigPath))
Expect(config.Validate()).To(Succeed(), "The e2e test config file is not valid")
return config
}
// SetCNIEnvVar read CNI from cniManifestPath and sets an environmental variable that keeps CNI resources.
// A ClusterResourceSet can be used to apply CNI using this environmental variable.
//
// Deprecated: Use FileTransformations in the CreateRepositoryInput to embedded CNI into cluster templates during create repository.
// The new approach does not uses env variables so we can avoid https://github.com/kubernetes-sigs/cluster-api/issues/3797;
// This func is preserved for avoiding to break users in the v0.3 series, but it is now a no-op.
func SetCNIEnvVar(cniManifestPath string, cniEnvVar string) {
}
// E2EConfig defines the configuration of an e2e test environment.
type E2EConfig struct {
// Name is the name of the Kind management cluster.
// Defaults to test-[random generated suffix].
ManagementClusterName string `json:"managementClusterName,omitempty"`
// Images is a list of container images to load into the Kind cluster.
Images []framework.ContainerImage `json:"images,omitempty"`
// Providers is a list of providers to be configured in the local repository that will be created for the e2e test.
// It is required to provide following providers
// - cluster-api
// - bootstrap kubeadm
// - control-plane kubeadm
// - one infrastructure provider
// The test will adapt to the selected infrastructure provider
Providers []ProviderConfig `json:"providers,omitempty"`
// Variables to be added to the clusterctl config file
// Please note that clusterctl read variables from OS environment variables as well, so you can avoid to hard code
// sensitive data in the config file.
Variables map[string]string `json:"variables,omitempty"`
// Intervals to be used for long operations during tests
Intervals map[string][]string `json:"intervals,omitempty"`
}
// ProviderConfig describes a provider to be configured in the local repository that will be created for the e2e test.
type ProviderConfig struct {
// Name is the name of the provider.
Name string `json:"name"`
// Type is the type of the provider.
Type string `json:"type"`
// Versions is a list of component YAML to be added to the local repository, one for each release.
// Please note that the first source will be used a a default release for this provider.
Versions []framework.ComponentSource `json:"versions,omitempty"`
// Files is a list of test files to be copied into the local repository for the default release of this provider.
Files []Files `json:"files,omitempty"`
}
// Files contains information about files to be copied into the local repository
type Files struct {
// SourcePath path of the file.
SourcePath string `json:"sourcePath"`
// TargetName name of the file copied into the local repository. if empty, the source name
// Will be preserved
TargetName string `json:"targetName,omitempty"`
}
// Defaults assigns default values to the object. More specifically:
// - ManagementClusterName gets a default name if empty.
// - Providers version gets type KustomizeSource if not otherwise specified.
// - Providers file gets targetName = sourceName if not otherwise specified.
// - Images gets LoadBehavior = MustLoadImage if not otherwise specified.
func (c *E2EConfig) Defaults() {
if c.ManagementClusterName == "" {
c.ManagementClusterName = fmt.Sprintf("test-%s", util.RandomString(6))
}
for i := range c.Providers {
provider := &c.Providers[i]
for j := range provider.Versions {
version := &provider.Versions[j]
if version.Type == "" {
version.Type = framework.KustomizeSource
}
}
for j := range provider.Files {
file := &provider.Files[j]
if file.SourcePath != "" && file.TargetName == "" {
file.TargetName = filepath.Base(file.SourcePath)
}
}
}
for i := range c.Images {
containerImage := &c.Images[i]
if containerImage.LoadBehavior == "" {
containerImage.LoadBehavior = framework.MustLoadImage
}
}
}
// AbsPaths makes relative paths absolute using the give base path.
func (c *E2EConfig) AbsPaths(basePath string) {
for i := range c.Providers {
provider := &c.Providers[i]
for j := range provider.Versions {
version := &provider.Versions[j]
if version.Type != framework.URLSource && version.Value != "" {
if !filepath.IsAbs(version.Value) {
version.Value = filepath.Join(basePath, version.Value)
}
}
}
for j := range provider.Files {
file := &provider.Files[j]
if file.SourcePath != "" {
if !filepath.IsAbs(file.SourcePath) {
file.SourcePath = filepath.Join(basePath, file.SourcePath)
}
}
}
}
}
func errInvalidArg(format string, args ...interface{}) error {
msg := fmt.Sprintf(format, args...)
return errors.Errorf("invalid argument: %s", msg)
}
func errEmptyArg(argName string) error {
return errInvalidArg("%s is empty", argName)
}
// Validate validates the configuration. More specifically:
// - ManagementClusterName should not be empty.
// - There should be one CoreProvider (cluster-api), one BootstrapProvider (kubeadm), one ControlPlaneProvider (kubeadm).
// - There should be one InfraProvider (pick your own).
// - Image should have name and loadBehavior be one of [mustload, tryload].
// - Intervals should be valid ginkgo intervals.
func (c *E2EConfig) Validate() error {
// ManagementClusterName should not be empty.
if c.ManagementClusterName == "" {
return errEmptyArg("ManagementClusterName")
}
if err := c.validateProviders(); err != nil {
return err
}
// Image should have name and loadBehavior be one of [mustload, tryload].
for i, containerImage := range c.Images {
if containerImage.Name == "" {
return errEmptyArg(fmt.Sprintf("Images[%d].Name=%q", i, containerImage.Name))
}
switch containerImage.LoadBehavior {
case framework.MustLoadImage, framework.TryLoadImage:
// Valid
default:
return errInvalidArg("Images[%d].LoadBehavior=%q", i, containerImage.LoadBehavior)
}
}
// Intervals should be valid ginkgo intervals.
for k, intervals := range c.Intervals {
switch len(intervals) {
case 0:
return errInvalidArg("Intervals[%s]=%q", k, intervals)
case 1, 2:
default:
return errInvalidArg("Intervals[%s]=%q", k, intervals)
}
for _, i := range intervals {
if _, err := time.ParseDuration(i); err != nil {
return errInvalidArg("Intervals[%s]=%q", k, intervals)
}
}
}
return nil
}
// validateProviders validates the provider configuration. More specifically:
// - Providers name should not be empty.
// - Providers type should be one of [CoreProvider, BootstrapProvider, ControlPlaneProvider, InfrastructureProvider].
// - Providers version should have a name.
// - Providers version.type should be one of [url, kustomize].
// - Providers version.replacements.old should be a valid regex.
// - Providers files should be an existing file and have a target name.
func (c *E2EConfig) validateProviders() error {
providersByType := map[clusterctlv1.ProviderType][]string{
clusterctlv1.CoreProviderType: nil,
clusterctlv1.BootstrapProviderType: nil,
clusterctlv1.ControlPlaneProviderType: nil,
clusterctlv1.InfrastructureProviderType: nil,
}
for i, providerConfig := range c.Providers {
// Providers name should not be empty.
if providerConfig.Name == "" {
return errEmptyArg(fmt.Sprintf("Providers[%d].Name", i))
}
// Providers type should be one of [CoreProvider, BootstrapProvider, ControlPlaneProvider, InfrastructureProvider].
providerType := clusterctlv1.ProviderType(providerConfig.Type)
switch providerType {
case clusterctlv1.CoreProviderType, clusterctlv1.BootstrapProviderType, clusterctlv1.ControlPlaneProviderType, clusterctlv1.InfrastructureProviderType:
providersByType[providerType] = append(providersByType[providerType], providerConfig.Name)
default:
return errInvalidArg("Providers[%d].Type=%q", i, providerConfig.Type)
}
// Providers providerVersion should have a name.
// Providers providerVersion.type should be one of [url, kustomize].
// Providers providerVersion.replacements.old should be a valid regex.
for j, providerVersion := range providerConfig.Versions {
if providerVersion.Name == "" {
return errEmptyArg(fmt.Sprintf("Providers[%d].Sources[%d].Name", i, j))
}
if _, err := version.ParseSemantic(providerVersion.Name); err != nil {
return errInvalidArg("Providers[%d].Sources[%d].Name=%q", i, j, providerVersion.Name)
}
switch providerVersion.Type {
case framework.URLSource, framework.KustomizeSource:
if providerVersion.Value == "" {
return errEmptyArg(fmt.Sprintf("Providers[%d].Sources[%d].Value", i, j))
}
default:
return errInvalidArg("Providers[%d].Sources[%d].Type=%q", i, j, providerVersion.Type)
}
for k, replacement := range providerVersion.Replacements {
if _, err := regexp.Compile(replacement.Old); err != nil {
return errInvalidArg("Providers[%d].Sources[%d].Replacements[%d].Old=%q: %v", i, j, k, replacement.Old, err)
}
}
}
// Providers files should be an existing file and have a target name.
for j, file := range providerConfig.Files {
if file.SourcePath == "" {
return errInvalidArg("Providers[%d].Files[%d].SourcePath=%q", i, j, file.SourcePath)
}
if !fileExists(file.SourcePath) {
return errInvalidArg("Providers[%d].Files[%d].SourcePath=%q", i, j, file.SourcePath)
}
if file.TargetName == "" {
return errInvalidArg("Providers[%d].Files[%d].TargetName=%q", i, j, file.TargetName)
}
}
}
// There should be one CoreProvider (cluster-api), one BootstrapProvider (kubeadm), one ControlPlaneProvider (kubeadm).
if len(providersByType[clusterctlv1.CoreProviderType]) != 1 {
return errInvalidArg("invalid config: it is required to have exactly one core-provider")
}
if providersByType[clusterctlv1.CoreProviderType][0] != clusterctlconfig.ClusterAPIProviderName {
return errInvalidArg("invalid config: core-provider should be named %s", clusterctlconfig.ClusterAPIProviderName)
}
if len(providersByType[clusterctlv1.BootstrapProviderType]) != 1 {
return errInvalidArg("invalid config: it is required to have exactly one bootstrap-provider")
}
if providersByType[clusterctlv1.BootstrapProviderType][0] != clusterctlconfig.KubeadmBootstrapProviderName {
return errInvalidArg("invalid config: bootstrap-provider should be named %s", clusterctlconfig.KubeadmBootstrapProviderName)
}
if len(providersByType[clusterctlv1.ControlPlaneProviderType]) != 1 {
return errInvalidArg("invalid config: it is required to have exactly one control-plane-provider")
}
if providersByType[clusterctlv1.ControlPlaneProviderType][0] != clusterctlconfig.KubeadmControlPlaneProviderName {
return errInvalidArg("invalid config: control-plane-provider should be named %s", clusterctlconfig.KubeadmControlPlaneProviderName)
}
// There should be one InfraProvider (pick your own).
if len(providersByType[clusterctlv1.InfrastructureProviderType]) != 1 {
return errInvalidArg("invalid config: it is required to have exactly one infrastructure-provider")
}
return nil
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// InfraProvider returns the infrastructure provider selected for running this E2E test.
func (c *E2EConfig) InfrastructureProviders() []string {
InfraProviders := []string{}
for _, provider := range c.Providers {
if provider.Type == string(clusterctlv1.InfrastructureProviderType) {
InfraProviders = append(InfraProviders, provider.Name)
}
}
return InfraProviders
}
func (c *E2EConfig) HasDockerProvider() bool {
for _, i := range c.InfrastructureProviders() {
if i == "docker" {
return true
}
}
return false
}
// GetIntervals returns the intervals to be applied to a Eventually operation.
// It searches for [spec]/[key] intervals first, and if it is not found, it searches
// for default/[key]. If also the default/[key] intervals are not found,
// ginkgo DefaultEventuallyTimeout and DefaultEventuallyPollingInterval are used.
func (c *E2EConfig) GetIntervals(spec, key string) []interface{} {
intervals, ok := c.Intervals[fmt.Sprintf("%s/%s", spec, key)]
if !ok {
if intervals, ok = c.Intervals[fmt.Sprintf("default/%s", key)]; !ok {
return nil
}
}
intervalsInterfaces := make([]interface{}, len(intervals))
for i := range intervals {
intervalsInterfaces[i] = intervals[i]
}
return intervalsInterfaces
}
// GetVariable returns a variable from the e2e config file.
func (c *E2EConfig) GetVariable(varName string) string {
version, ok := c.Variables[varName]
Expect(ok).NotTo(BeFalse())
return version
}
// GetInt64PtrVariable returns an Int64Ptr variable from the e2e config file.
func (c *E2EConfig) GetInt64PtrVariable(varName string) *int64 {
wCountStr := c.GetVariable(varName)
if wCountStr == "" {
return nil
}
wCount, err := strconv.ParseInt(wCountStr, 10, 64)
Expect(err).NotTo(HaveOccurred())
return pointer.Int64Ptr(wCount)
}
// GetInt32PtrVariable returns an Int32Ptr variable from the e2e config file.
func (c *E2EConfig) GetInt32PtrVariable(varName string) *int32 {
wCountStr := c.GetVariable(varName)
if wCountStr == "" {
return nil
}
wCount, err := strconv.ParseUint(wCountStr, 10, 32)
Expect(err).NotTo(HaveOccurred())
return pointer.Int32Ptr(int32(wCount))
}