/
main.go
354 lines (288 loc) · 11 KB
/
main.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
/*
Copyright 2022 The Kubermatic Kubernetes Platform contributors.
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 main
import (
"context"
cryptorand "crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"os"
"path"
"time"
"github.com/go-logr/zapr"
"go.uber.org/zap"
"golang.org/x/crypto/ssh"
clusterv1alpha1 "github.com/kubermatic/machine-controller/pkg/apis/cluster/v1alpha1"
"k8c.io/kubermatic/v2/cmd/conformance-tester/pkg/metrics"
"k8c.io/kubermatic/v2/cmd/conformance-tester/pkg/runner"
"k8c.io/kubermatic/v2/cmd/conformance-tester/pkg/scenarios"
"k8c.io/kubermatic/v2/cmd/conformance-tester/pkg/types"
clusterclient "k8c.io/kubermatic/v2/pkg/cluster/client"
kubermaticlog "k8c.io/kubermatic/v2/pkg/log"
kubernetesprovider "k8c.io/kubermatic/v2/pkg/provider/kubernetes"
"k8c.io/kubermatic/v2/pkg/resources/reconciling"
"k8c.io/kubermatic/v2/pkg/test/e2e/utils"
"k8c.io/kubermatic/v2/pkg/util/cli"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
metricsv1beta1 "k8s.io/metrics/pkg/apis/metrics/v1beta1"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
ctrlruntimelog "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)
func main() {
rootCtx := signals.SetupSignalHandler()
// setup flags
opts := types.NewDefaultOptions()
opts.AddFlags()
logOpts := kubermaticlog.NewDefaultOptions()
logOpts.AddFlags(flag.CommandLine)
flag.Parse()
// setup logging
rawLog := kubermaticlog.New(logOpts.Debug, logOpts.Format)
log := rawLog.Sugar()
// set the logger used by sigs.k8s.io/controller-runtime
ctrlruntimelog.SetLogger(zapr.NewLogger(rawLog.WithOptions(zap.AddCallerSkip(1))))
// parse our CLI flags
if err := opts.ParseFlags(log); err != nil {
log.Fatalw("Invalid flags", zap.Error(err))
}
reconciling.Configure(log)
// collect runtime metrics if there is a pushgateway URL configured
// and these variables are set
metrics.Setup(opts.PushgatewayEndpoint, os.Getenv("JOB_NAME"), os.Getenv("PROW_JOB_ID"))
defer metrics.UpdateMetrics(log)
// say hello
cli.Hello(log, "Conformance Tests", true, nil)
log.Infow("Runner configuration",
"providers", sets.List(opts.Providers),
"operatingsystems", sets.List(opts.Distributions),
"versions", opts.Versions,
"tests", sets.List(opts.Tests),
"osm", opts.OperatingSystemManagerEnabled,
"dualstack", opts.DualStackEnabled,
"konnectivity", opts.KonnectivityEnabled,
"updates", opts.TestClusterUpdate,
)
// setup kube client, ctrl-runtime client, clientgetter, seedgetter etc.
if err := setupKubeClients(rootCtx, opts); err != nil {
log.Fatalw("Failed to setup kube clients", zap.Error(err))
}
// create a temporary home directory and a fresh SSH key
homeDir, dynamicSSHPublicKey, err := setupHomeDir(log)
if err != nil {
log.Fatalw("Failed to setup temporary home dir", zap.Error(err))
}
opts.PublicKeys = append(opts.PublicKeys, dynamicSSHPublicKey)
opts.HomeDir = homeDir
// setup runner and KKP clients
log.Info("Preparing project...")
testRunner := runner.NewKubeRunner(opts, log)
if err := testRunner.Setup(rootCtx); err != nil {
log.Fatalw("Failed to setup runner", zap.Error(err))
}
// determine what's to do
scenarios, err := scenarios.NewGenerator().
WithCloudProviders(sets.List(opts.Providers)...).
WithOperatingSystems(sets.List(opts.Distributions)...).
WithOSM(opts.OperatingSystemManagerEnabled).
WithDualstack(opts.DualStackEnabled).
WithVersions(opts.Versions...).
Scenarios(rootCtx, opts, log)
if err != nil {
log.Fatalw("Failed to determine test scenarios", zap.Error(err))
}
if len(scenarios) == 0 {
// Fatalw() because Fatal() trips up the linter because of the previous defer.
log.Fatalw("No scenarios match the given criteria.")
}
// optionally restrict the full set of scenarios to those that previously did not succeed
var previousResults *runner.ResultsFile
if opts.RetryFailedScenarios {
previousResults, err = loadPreviousResults(opts)
if err != nil {
log.Fatalw("Failed to load previous test results", zap.Error(err))
}
scenarios = keepOnlyFailedScenarios(log, scenarios, previousResults, *opts)
}
if err := testRunner.SetupProject(rootCtx); err != nil {
log.Fatalw("Failed to setup project", zap.Error(err))
}
log.Infow("Using project", "project", opts.KubermaticProject)
// let the magic happen!
log.Info("Running E2E tests...")
start := time.Now()
results, err := testRunner.Run(rootCtx, scenarios)
// always print the test results
if results != nil {
results.PrintJUnitDetails()
results.PrintSummary()
if filename := opts.ResultsFile; filename != "" {
log.Infow("Writing results file", "filename", filename)
// Merge the previous tests with the new, current results; otherwise if we'd only
// dump the new results, those would not contain skipped/successful scenarios from
// the previous run, effectively shrinking the results file every time it is used.
if previousResults != nil {
results = runner.MergeResults(previousResults, results)
}
if err := results.WriteToFile(filename); err != nil {
log.Warnw("Failed to write results file", zap.Error(err))
}
}
}
if err != nil {
log.Fatalw("Failed to execute tests", zap.Error(err))
}
if results.HasFailures() {
// Fatalw() because Fatal() trips up the linter because of the previous defer.
log.Fatalw("Not all tests have passed")
}
log.Infow("Test suite has completed successfully", "runtime", time.Since(start))
}
func setupKubeClients(ctx context.Context, opts *types.Options) error {
_, config, err := utils.GetClients()
if err != nil {
return fmt.Errorf("failed to get client config: %w", err)
}
opts.SeedRestConfig = config
if err := clusterv1alpha1.SchemeBuilder.AddToScheme(scheme.Scheme); err != nil {
return fmt.Errorf("failed to add clusterv1alpha1 to scheme: %w", err)
}
if err := metricsv1beta1.SchemeBuilder.AddToScheme(scheme.Scheme); err != nil {
return fmt.Errorf("failed to add metrics v1beta1 to scheme: %w", err)
}
seedClusterClient, err := ctrlruntimeclient.New(config, ctrlruntimeclient.Options{})
if err != nil {
return err
}
opts.SeedClusterClient = seedClusterClient
seedGeneratedClient, err := kubernetes.NewForConfig(config)
if err != nil {
return err
}
opts.SeedGeneratedClient = seedGeneratedClient
seedGetter, err := kubernetesprovider.SeedGetterFactory(ctx, seedClusterClient, opts.KubermaticSeedName, opts.KubermaticNamespace)
if err != nil {
return fmt.Errorf("failed to construct seedGetter: %w", err)
}
opts.Seed, err = seedGetter()
if err != nil {
return fmt.Errorf("failed to get seed: %w", err)
}
configGetter, err := kubernetesprovider.DynamicKubermaticConfigurationGetterFactory(opts.SeedClusterClient, opts.KubermaticNamespace)
if err != nil {
return fmt.Errorf("failed to construct configGetter: %w", err)
}
opts.KubermaticConfiguration, err = configGetter(ctx)
if err != nil {
return fmt.Errorf("failed to get Kubermatic config: %w", err)
}
clusterClientProvider, err := clusterclient.NewExternal(seedClusterClient)
if err != nil {
return fmt.Errorf("failed to get clusterClientProvider: %w", err)
}
opts.ClusterClientProvider = clusterClientProvider
return nil
}
// setupHomeDir set up a temporary home dir (because the e2e tests have some filenames hardcoded,
// which might conflict with the user files).
func setupHomeDir(log *zap.SugaredLogger) (string, []byte, error) {
// We'll set the env-var $HOME to this directory when executing the tests
homeDir, err := os.MkdirTemp("/tmp", "e2e-home-")
if err != nil {
return "", nil, fmt.Errorf("failed to setup temporary home dir: %w", err)
}
log.Infof("Setting up temporary home directory with SSH keys at %s...", homeDir)
if err := os.MkdirAll(path.Join(homeDir, ".ssh"), os.ModePerm); err != nil {
return "", nil, err
}
// Setup temporary home dir with filepath.Join(os.Getenv("HOME"), ".ssh")
// Make sure to create relevant ssh keys (because they are hardcoded in the e2e tests...). They must not be password protected
log.Debug("Generating SSH keys...")
// Private Key generation
privateKey, err := rsa.GenerateKey(cryptorand.Reader, 4096)
if err != nil {
return "", nil, err
}
// Validate Private Key
err = privateKey.Validate()
if err != nil {
return "", nil, err
}
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
privBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privDER,
}
privatePEM := pem.EncodeToMemory(&privBlock)
// Needs to be google_compute_engine as its hardcoded in the kubernetes e2e tests
if err := os.WriteFile(path.Join(homeDir, ".ssh", "google_compute_engine"), privatePEM, 0400); err != nil {
return "", nil, err
}
publicRsaKey, err := ssh.NewPublicKey(privateKey.Public())
if err != nil {
return "", nil, err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
if err := os.WriteFile(path.Join(homeDir, ".ssh", "google_compute_engine.pub"), pubKeyBytes, 0400); err != nil {
return "", nil, err
}
log.Infof("Finished setting up temporary home dir %s", homeDir)
return homeDir, pubKeyBytes, nil
}
func loadPreviousResults(opts *types.Options) (*runner.ResultsFile, error) {
if opts.ResultsFile == "" {
return nil, nil
}
// non-existing or empty files are okay
stat, err := os.Stat(opts.ResultsFile)
if err != nil || stat.Size() == 0 {
return nil, nil
}
return runner.LoadResultsFile(opts.ResultsFile)
}
func keepOnlyFailedScenarios(log *zap.SugaredLogger, allScenarios []scenarios.Scenario, previousResults *runner.ResultsFile, opts types.Options) []scenarios.Scenario {
if optionsChanged(previousResults.Configuration, opts) {
log.Warn("Disregarding previous test results as current options do not match previous options.")
return allScenarios
}
filtered := []scenarios.Scenario{}
for i, scenario := range allScenarios {
hasSuccess := false
for _, previous := range previousResults.Results {
if previous.MatchesScenario(scenario) && previous.Status == runner.ScenarioPassed {
hasSuccess = true
break
}
}
if hasSuccess {
scenario.Log(log).Info("Skipping because scenario succeeded in a previous run.")
continue
}
filtered = append(filtered, allScenarios[i])
}
return filtered
}
func optionsChanged(previous runner.TestConfiguration, current types.Options) bool {
return false ||
previous.OSMEnabled != current.OperatingSystemManagerEnabled ||
previous.KonnectivityEnabled != current.KonnectivityEnabled ||
previous.DualstackEnabled != current.DualStackEnabled ||
previous.TestClusterUpdate != current.TestClusterUpdate ||
!sets.New(previous.Tests...).IsSuperset(current.Tests)
}