forked from kubermatic/kubermatic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.go
1604 lines (1418 loc) · 49.5 KB
/
runner.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 2020 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 (
"bufio"
"bytes"
"context"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/go-openapi/runtime"
"github.com/onsi/ginkgo/reporters"
"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
kubermaticapiv1 "github.com/kubermatic/kubermatic/api/pkg/api/v1"
clusterclient "github.com/kubermatic/kubermatic/api/pkg/cluster/client"
kubermaticv1 "github.com/kubermatic/kubermatic/api/pkg/crd/kubermatic/v1"
kubermaticv1helper "github.com/kubermatic/kubermatic/api/pkg/crd/kubermatic/v1/helper"
"github.com/kubermatic/kubermatic/api/pkg/provider"
"github.com/kubermatic/kubermatic/api/pkg/resources"
apiclient "github.com/kubermatic/kubermatic/api/pkg/test/e2e/api/utils/apiclient/client"
projectclient "github.com/kubermatic/kubermatic/api/pkg/test/e2e/api/utils/apiclient/client/project"
apimodels "github.com/kubermatic/kubermatic/api/pkg/test/e2e/api/utils/apiclient/models"
clusterv1alpha1 "github.com/kubermatic/machine-controller/pkg/apis/cluster/v1alpha1"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
utilerror "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/util/retry"
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
)
func podIsReady(p *corev1.Pod) bool {
for _, c := range p.Status.Conditions {
if c.Type == corev1.PodReady {
return c.Status == corev1.ConditionTrue
}
}
return false
}
type testScenario interface {
Name() string
Cluster(secrets secrets) *apimodels.CreateClusterSpec
NodeDeployments(num int, secrets secrets) ([]apimodels.NodeDeployment, error)
OS() apimodels.OperatingSystemSpec
}
func newRunner(scenarios []testScenario, opts *Opts, log *zap.SugaredLogger) *testRunner {
return &testRunner{
scenarios: scenarios,
controlPlaneReadyWaitTimeout: opts.controlPlaneReadyWaitTimeout,
deleteClusterAfterTests: opts.deleteClusterAfterTests,
secrets: opts.secrets,
namePrefix: opts.namePrefix,
clusterClientProvider: opts.clusterClientProvider,
seed: opts.seed,
seedRestConfig: opts.seedRestConfig,
nodeCount: opts.nodeCount,
repoRoot: opts.repoRoot,
reportsRoot: opts.reportsRoot,
clusterParallelCount: opts.clusterParallelCount,
PublicKeys: opts.publicKeys,
workerName: opts.workerName,
homeDir: opts.homeDir,
seedClusterClient: opts.seedClusterClient,
seedGeneratedClient: opts.seedGeneratedClient,
log: log,
existingClusterLabel: opts.existingClusterLabel,
openshift: opts.openshift,
openshiftPullSecret: opts.openshiftPullSecret,
printGinkoLogs: opts.printGinkoLogs,
onlyTestCreation: opts.onlyTestCreation,
pspEnabled: opts.pspEnabled,
kubermatcProjectID: opts.kubermatcProjectID,
kubermaticClient: opts.kubermaticClient,
kubermaticAuthenticator: opts.kubermaticAuthenticator,
}
}
type testRunner struct {
ctx context.Context
scenarios []testScenario
secrets secrets
namePrefix string
repoRoot string
reportsRoot string
PublicKeys [][]byte
workerName string
homeDir string
log *zap.SugaredLogger
openshift bool
openshiftPullSecret string
printGinkoLogs bool
onlyTestCreation bool
pspEnabled bool
controlPlaneReadyWaitTimeout time.Duration
deleteClusterAfterTests bool
nodeCount int
clusterParallelCount int
seedClusterClient ctrlruntimeclient.Client
seedGeneratedClient kubernetes.Interface
clusterClientProvider *clusterclient.Provider
seed *kubermaticv1.Seed
seedRestConfig *rest.Config
// The label to use to select an existing cluster to test against instead of
// creating a new one
existingClusterLabel string
kubermatcProjectID string
kubermaticClient *apiclient.Kubermatic
kubermaticAuthenticator runtime.ClientAuthInfoWriter
}
type testResult struct {
report *reporters.JUnitTestSuite
err error
scenario testScenario
}
func (t *testResult) Passed() bool {
if t.err != nil {
return false
}
if t.report == nil {
return false
}
if len(t.report.TestCases) == 0 {
return false
}
if t.report.Errors > 0 || t.report.Failures > 0 {
return false
}
return true
}
func (r *testRunner) worker(scenarios <-chan testScenario, results chan<- testResult) {
for s := range scenarios {
var report *reporters.JUnitTestSuite
scenarioLog := r.log.With("scenario", s.Name())
scenarioLog.Info("Starting to test scenario...")
err := measureTime(scenarioRuntimeMetric.With(prometheus.Labels{"scenario": s.Name()}), scenarioLog, func() error {
var err error
report, err = r.executeScenario(scenarioLog, s)
return err
})
if err != nil {
scenarioLog.Warnw("Finished with error", zap.Error(err))
} else {
scenarioLog.Info("Finished")
}
results <- testResult{
report: report,
scenario: s,
err: err,
}
}
}
func (r *testRunner) Run() error {
scenariosCh := make(chan testScenario, len(r.scenarios))
resultsCh := make(chan testResult, len(r.scenarios))
r.log.Info("Test suite:")
for _, scenario := range r.scenarios {
r.log.Info(scenario.Name())
scenariosCh <- scenario
}
r.log.Infof("Total: %d tests", len(r.scenarios))
for i := 1; i <= r.clusterParallelCount; i++ {
go r.worker(scenariosCh, resultsCh)
}
close(scenariosCh)
var results []testResult
for range r.scenarios {
results = append(results, <-resultsCh)
r.log.Infof("Finished %d/%d test cases", len(results), len(r.scenarios))
}
overallResultBuf := &bytes.Buffer{}
hadFailure := false
for _, result := range results {
prefix := "PASS"
if !result.Passed() {
prefix = "FAIL"
hadFailure = true
}
scenarioResultMsg := fmt.Sprintf("[%s] - %s", prefix, result.scenario.Name())
if result.err != nil {
scenarioResultMsg = fmt.Sprintf("%s : %v", scenarioResultMsg, result.err)
}
fmt.Fprintln(overallResultBuf, scenarioResultMsg)
if result.report != nil {
printDetailedReport(result.report)
}
}
fmt.Println("========================== RESULT ===========================")
fmt.Println(overallResultBuf.String())
if hadFailure {
return errors.New("some tests failed")
}
return nil
}
func (r *testRunner) executeScenario(log *zap.SugaredLogger, scenario testScenario) (*reporters.JUnitTestSuite, error) {
var err error
var cluster *kubermaticv1.Cluster
report := &reporters.JUnitTestSuite{
Name: scenario.Name(),
}
totalStart := time.Now()
// We'll store the report there and all kinds of logs
scenarioFolder := path.Join(r.reportsRoot, scenario.Name())
if err := os.MkdirAll(scenarioFolder, os.ModePerm); err != nil {
return nil, fmt.Errorf("failed to create the scenario folder '%s': %v", scenarioFolder, err)
}
// We need the closure to defer the evaluation of the time.Since(totalStart) call
defer func() {
log.Infof("Finished testing cluster after %s", time.Since(totalStart))
}()
// Always write junit to disk
defer func() {
report.Time = time.Since(totalStart).Seconds()
b, err := xml.Marshal(report)
if err != nil {
log.Errorw("failed to marshal junit", zap.Error(err))
return
}
if err := ioutil.WriteFile(path.Join(r.reportsRoot, fmt.Sprintf("junit.%s.xml", scenario.Name())), b, 0644); err != nil {
log.Errorw("Failed to write junit", zap.Error(err))
}
}()
ctx := context.Background()
if r.existingClusterLabel == "" && os.Getenv("KUBERMATIC_USE_EXISTING_CLUSTER") == "" {
if err := junitReporterWrapper(
"[Kubermatic] Create cluster",
report,
func() error {
cluster, err = r.createCluster(log, scenario)
return err
}); err != nil {
return report, fmt.Errorf("failed to create cluster: %v", err)
}
} else {
log.Info("Using existing cluster")
selector, err := labels.Parse(r.existingClusterLabel)
if err != nil {
return nil, fmt.Errorf("failed to parse labelselector %q: %v", r.existingClusterLabel, err)
}
clusterList := &kubermaticv1.ClusterList{}
listOptions := &ctrlruntimeclient.ListOptions{LabelSelector: selector}
if err := r.seedClusterClient.List(ctx, clusterList, listOptions); err != nil {
return nil, fmt.Errorf("failed to list clusters: %v", err)
}
if foundClusterNum := len(clusterList.Items); foundClusterNum != 1 {
return nil, fmt.Errorf("expected to find exactly one existing cluster, but got %d", foundClusterNum)
}
cluster = &clusterList.Items[0]
}
clusterName := cluster.Name
log = log.With("cluster", cluster.Name)
if err := junitReporterWrapper(
"[Kubermatic] Wait for successful reconciliation",
report,
timeMeasurementWrapper(
kubermaticReconciliationDurationMetric.With(prometheus.Labels{"scenario": scenario.Name()}),
log,
func() error {
return wait.Poll(5*time.Second, 5*time.Minute, func() (bool, error) {
if err := r.seedClusterClient.Get(ctx, types.NamespacedName{Name: clusterName}, cluster); err != nil {
log.Errorw("Failed to get cluster when waiting for successful reconciliation", zap.Error(err))
return false, nil
}
missingConditions, success := kubermaticv1helper.ClusterReconciliationSuccessful(cluster)
if len(missingConditions) > 0 {
log.Infof("Waiting for the following conditions: %v", missingConditions)
}
return success, nil
})
},
),
); err != nil {
return report, fmt.Errorf("failed to wait for successful reconciliation: %v", err)
}
if err := r.executeTests(log, cluster, report, scenario); err != nil {
return report, err
}
if !r.deleteClusterAfterTests {
return report, nil
}
return report, r.deleteCluster(report, cluster, log)
}
func (r *testRunner) executeTests(
log *zap.SugaredLogger,
cluster *kubermaticv1.Cluster,
report *reporters.JUnitTestSuite,
scenario testScenario,
) error {
// We must store the name here because the cluster object may be nil on error
clusterName := cluster.Name
// Print all controlplane logs to both make debugging easier and show issues
// that didn't result in test failures.
defer r.printAllControlPlaneLogs(log, clusterName)
var err error
if err := junitReporterWrapper(
"[Kubermatic] Wait for control plane",
report,
timeMeasurementWrapper(
seedControlplaneDurationMetric.With(prometheus.Labels{"scenario": scenario.Name()}),
log,
func() error {
cluster, err = r.waitForControlPlane(log, clusterName)
return err
},
),
); err != nil {
return fmt.Errorf("failed waiting for control plane to become ready: %v", err)
}
if err := junitReporterWrapper(
"[Kubermatic] Add LB and PV Finalizers",
report,
func() error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() error {
if err := r.seedClusterClient.Get(context.Background(), types.NamespacedName{Name: clusterName}, cluster); err != nil {
return err
}
cluster.Finalizers = append(cluster.Finalizers,
kubermaticapiv1.InClusterPVCleanupFinalizer,
kubermaticapiv1.InClusterLBCleanupFinalizer,
)
return r.seedClusterClient.Update(context.Background(), cluster)
})
},
); err != nil {
return fmt.Errorf("failed to add PV and LB cleanup finalizers: %v", err)
}
providerName, err := provider.ClusterCloudProviderName(cluster.Spec.Cloud)
if err != nil {
return fmt.Errorf("failed to get cloud provider name from cluster: %v", err)
}
log = log.With("cloud-provider", providerName)
_, exists := r.seed.Spec.Datacenters[cluster.Spec.Cloud.DatacenterName]
if !exists {
return fmt.Errorf("datacenter %q doesn't exist", cluster.Spec.Cloud.DatacenterName)
}
kubeconfigFilename, err := r.getKubeconfig(log, cluster)
if err != nil {
return fmt.Errorf("failed to get kubeconfig: %v", err)
}
cloudConfigFilename, err := r.getCloudConfig(log, cluster)
if err != nil {
return fmt.Errorf("failed to get cloud config: %v", err)
}
userClusterClient, err := r.clusterClientProvider.GetClient(cluster)
if err != nil {
return fmt.Errorf("failed to get the client for the cluster: %v", err)
}
if err := junitReporterWrapper(
"[Kubermatic] Create NodeDeployments",
report,
func() error {
return r.createNodeDeployments(log, scenario, clusterName)
},
); err != nil {
return fmt.Errorf("failed to setup nodes: %v", err)
}
defer logEventsForAllMachines(context.Background(), log, userClusterClient)
defer logUserClusterPodEventsAndLogs(
log,
r.clusterClientProvider,
cluster.DeepCopy(),
)
var overallTimeout = 10 * time.Minute
var timeoutLeft time.Duration
if cluster.IsOpenshift() {
// Openshift installs a lot more during node provisioning, hence this may take longer
overallTimeout += 5 * time.Minute
}
// The initialization of the external CCM is super slow
if cluster.Spec.Features[kubermaticv1.ClusterFeatureExternalCloudProvider] {
overallTimeout += 5 * time.Minute
}
// Packet is slower at provisioning the instances, presumably because those are actual
// physical hosts.
if cluster.Spec.Cloud.Packet != nil {
overallTimeout += 5 * time.Minute
}
if err := junitReporterWrapper(
"[Kubermatic] Wait for machines to get a node",
report,
timeMeasurementWrapper(
nodeCreationDuration.With(prometheus.Labels{"scenario": scenario.Name()}),
log,
func() error {
var err error
timeoutLeft, err = waitForMachinesToJoinCluster(log, userClusterClient, overallTimeout)
return err
},
),
); err != nil {
return fmt.Errorf("failed to wait for machines to get a node: %v", err)
}
if err := junitReporterWrapper(
"[Kubermatic] Wait for nodes to be ready",
report,
timeMeasurementWrapper(
nodeRadinessDuration.With(prometheus.Labels{"scenario": scenario.Name()}),
log,
func() error {
// Getting ready just implies starting the CNI deamonset, so that should
// be quick.
var err error
timeoutLeft, err = waitForNodesToBeReady(log, userClusterClient, timeoutLeft)
return err
},
),
); err != nil {
return fmt.Errorf("failed to wait for all nodes to be ready: %v", err)
}
if err := junitReporterWrapper(
"[Kubermatic] Wait for Pods inside usercluster to be ready",
report,
timeMeasurementWrapper(
seedControlplaneDurationMetric.With(prometheus.Labels{"scenario": scenario.Name()}),
log,
func() error {
return r.waitUntilAllPodsAreReady(log, userClusterClient, timeoutLeft)
},
),
); err != nil {
return fmt.Errorf("failed to wait for all pods to get ready: %v", err)
}
if r.onlyTestCreation {
return nil
}
if err := r.testCluster(
log,
scenario,
cluster,
userClusterClient,
kubeconfigFilename,
cloudConfigFilename,
report,
); err != nil {
return fmt.Errorf("failed to test cluster: %v", err)
}
return nil
}
func (r *testRunner) deleteCluster(report *reporters.JUnitTestSuite, cluster *kubermaticv1.Cluster, log *zap.SugaredLogger) error {
deleteParms := &projectclient.DeleteClusterParams{
ProjectID: r.kubermatcProjectID,
DC: r.seed.Name,
}
deleteTimeout := 15 * time.Minute
if cluster.Spec.Cloud.Azure != nil {
// 15 Minutes are not enough for Azure
deleteTimeout = 30 * time.Minute
}
deleteParms.SetTimeout(15 * time.Second)
if err := junitReporterWrapper(
"[Kubermatic] Delete cluster",
report,
func() error {
var selector labels.Selector
var err error
if r.workerName != "" {
selector, err = labels.Parse(fmt.Sprintf("worker-name=%s", r.workerName))
if err != nil {
return fmt.Errorf("failed to parse selector: %v", err)
}
}
return wait.PollImmediate(5*time.Second, deleteTimeout, func() (bool, error) {
clusterList := &kubermaticv1.ClusterList{}
listOpts := &ctrlruntimeclient.ListOptions{LabelSelector: selector}
if err := r.seedClusterClient.List(r.ctx, clusterList, listOpts); err != nil {
log.Errorw("Listing clusters failed", zap.Error(err))
return false, nil
}
// Success!
if len(clusterList.Items) == 0 {
return true, nil
}
// Should never happen
if len(clusterList.Items) > 1 {
return false, fmt.Errorf("expected to find zero or one cluster, got %d", len(clusterList.Items))
}
// Cluster is currently being deleted
if clusterList.Items[0].DeletionTimestamp != nil {
return false, nil
}
// Issue Delete call
log.With("cluster", clusterList.Items[0].Name).Info("Deleting user cluster now...")
deleteParms.ClusterID = clusterList.Items[0].Name
_, err := r.kubermaticClient.Project.DeleteCluster(deleteParms, r.kubermaticAuthenticator)
log.Infow("Cluster deleted.", zap.Error(errors.New(fmtSwaggerError(err))))
return false, nil
})
},
); err != nil {
log.Errorw("Failed to delete cluster", zap.Error(err))
return err
}
return nil
}
func retryNAttempts(maxAttempts int, f func(attempt int) error) error {
var err error
for attempt := 1; attempt <= maxAttempts; attempt++ {
err = f(attempt)
if err != nil {
continue
}
return nil
}
return fmt.Errorf("function did not succeed after %d attempts: %v", maxAttempts, err)
}
// measuredRetryNAttempts wraps retryNAttempts with code that counts
// the executed number of attempts and the runtimes for each
// attempt.
func measuredRetryNAttempts(
runtimeMetric *prometheus.GaugeVec,
attemptsMetric prometheus.Gauge,
log *zap.SugaredLogger,
maxAttempts int,
f func(attempt int) error,
) func() error {
return func() error {
attempts := 0
err := retryNAttempts(maxAttempts, func(attempt int) error {
attempts++
metric := runtimeMetric.With(prometheus.Labels{"attempt": strconv.Itoa(attempt)})
return measureTime(metric, log, func() error {
return f(attempt)
})
})
attemptsMetric.Set(float64(attempts))
updateMetrics(log)
return err
}
}
func (r *testRunner) testCluster(
log *zap.SugaredLogger,
scenario testScenario,
cluster *kubermaticv1.Cluster,
userClusterClient ctrlruntimeclient.Client,
kubeconfigFilename string,
cloudConfigFilename string,
report *reporters.JUnitTestSuite,
) error {
const maxTestAttempts = 3
// var err error
log.Info("Starting to test cluster...")
if r.openshift {
// Openshift supports neither the conformance tests nor PVs/LBs yet :/
return nil
}
ginkgoRuns, err := r.getGinkgoRuns(log, scenario, kubeconfigFilename, cloudConfigFilename, cluster)
if err != nil {
return fmt.Errorf("failed to get Ginkgo runs: %v", err)
}
for _, run := range ginkgoRuns {
if err := junitReporterWrapper(
fmt.Sprintf("[Ginkgo] Run ginkgo tests %q", run.name),
report,
func() error {
ginkgoRes, err := r.executeGinkgoRunWithRetries(log, scenario, run, userClusterClient)
if ginkgoRes != nil {
// We append the report from Ginkgo to our scenario wide report
appendReport(report, ginkgoRes.report)
}
return err
},
); err != nil {
log.Errorf("Ginkgo scenario '%s' failed, giving up retrying: %v", err)
// We still wan't to run potential next runs
continue
}
}
defaultLabels := prometheus.Labels{
"scenario": scenario.Name(),
}
// Do a simple PVC test - with retries
if supportsStorage(cluster) {
if err := junitReporterWrapper(
"[Kubermatic] [CloudProvider] Test PersistentVolumes",
report,
measuredRetryNAttempts(
pvctestRuntimeMetric.MustCurryWith(defaultLabels),
pvctestAttemptsMetric.With(defaultLabels),
log,
maxTestAttempts,
func(attempt int) error {
return r.testPVC(log, userClusterClient, attempt)
},
),
); err != nil {
log.Errorf("Failed to verify that PVC's work: %v", err)
}
}
// Do a simple LB test - with retries
if supportsLBs(cluster) {
if err := junitReporterWrapper(
"[Kubermatic] [CloudProvider] Test LoadBalancers",
report,
measuredRetryNAttempts(
lbtestRuntimeMetric.MustCurryWith(defaultLabels),
lbtestAttemptsMetric.With(defaultLabels),
log,
maxTestAttempts,
func(attempt int) error {
return r.testLB(log, userClusterClient, attempt)
},
),
); err != nil {
log.Errorf("Failed to verify that LB's work: %v", err)
}
}
// Do user cluster RBAC controller test - with retries
if err := junitReporterWrapper(
"[Kubermatic] Test user cluster RBAC controller",
report,
func() error {
return retryNAttempts(maxTestAttempts, func(attempt int) error {
return r.testUserclusterControllerRBAC(log, cluster, userClusterClient, r.seedClusterClient)
})
}); err != nil {
log.Errorf("Failed to verify that user cluster RBAC controller work: %v", err)
}
// Do prometheus metrics available test - with retries
if err := junitReporterWrapper(
"[Kubermatic] Test prometheus metrics availability", report, func() error {
return retryNAttempts(maxTestAttempts, func(attempt int) error {
return r.testUserClusterMetrics(log, cluster, r.seedClusterClient)
})
}); err != nil {
log.Errorf("Failed to verify that prometheus metrics are available: %v", err)
}
return nil
}
// executeGinkgoRunWithRetries executes the passed GinkgoRun and retries if it failed hard(Failed to execute the Ginkgo binary for example)
// Or if the JUnit report from Ginkgo contains failed tests.
// Only if Ginkgo failed hard, an error will be returned. If some tests still failed after retrying the run, the report will reflect that.
func (r *testRunner) executeGinkgoRunWithRetries(log *zap.SugaredLogger, scenario testScenario, run *ginkgoRun, client ctrlruntimeclient.Client) (ginkgoRes *ginkgoResult, err error) {
const maxAttempts = 3
attempts := 1
defer func() {
ginkgoAttemptsMetric.With(prometheus.Labels{
"scenario": scenario.Name(),
"run": run.name,
}).Set(float64(attempts))
updateMetrics(log)
}()
for attempts = 1; attempts <= maxAttempts; attempts++ {
ginkgoRes, err = executeGinkgoRun(log, run, client)
if ginkgoRes != nil {
ginkgoRuntimeMetric.With(prometheus.Labels{
"scenario": scenario.Name(),
"run": run.name,
"attempt": strconv.Itoa(attempts),
}).Set(ginkgoRes.duration.Seconds())
updateMetrics(log)
}
if err != nil {
// Something critical happened and we don't have a valid result
log.Errorf("Failed to execute the Ginkgo run '%s': %v", run.name, err)
continue
}
if ginkgoRes.report.Errors > 0 || ginkgoRes.report.Failures > 0 {
msg := fmt.Sprintf("Ginkgo run '%s' had failed tests.", run.name)
if attempts < maxAttempts {
msg = fmt.Sprintf("%s. Retrying...", msg)
}
log.Info(msg)
if r.printGinkoLogs {
if err := printFileUnbuffered(ginkgoRes.logfile); err != nil {
log.Infof("Error printing ginkgo logfile: %v", err)
}
log.Info("Successfully printed logfile")
}
continue
}
// Ginkgo run successfully and no test failed
return ginkgoRes, err
}
return ginkgoRes, err
}
func (r *testRunner) createNodeDeployments(log *zap.SugaredLogger, scenario testScenario, clusterName string) error {
var existingReplicas int
nodeDeploymentGetParams := &projectclient.ListNodeDeploymentsParams{
ProjectID: r.kubermatcProjectID,
ClusterID: clusterName,
DC: r.seed.Name,
}
nodeDeploymentGetParams.SetTimeout(15 * time.Second)
log.Info("Getting existing NodeDeployments")
if err := wait.PollImmediate(10*time.Second, time.Minute, func() (bool, error) {
resp, err := r.kubermaticClient.Project.ListNodeDeployments(nodeDeploymentGetParams, r.kubermaticAuthenticator)
if err != nil {
log.Errorw("Failed to get existing NodeDeployments", zap.Error(errors.New(fmtSwaggerError(err))))
return false, nil
}
for _, nodeDeployment := range resp.Payload {
existingReplicas += int(*nodeDeployment.Spec.Replicas)
}
return true, nil
}); err != nil {
return fmt.Errorf("failed to get existing NodeDeployments: %v", err)
}
log.Infof("Found %d pre-existing node replicas", existingReplicas)
nodeCount := r.nodeCount - existingReplicas
if nodeCount < 0 {
return fmt.Errorf("found %d existing replicas and want %d, scaledown not supported", existingReplicas, r.nodeCount)
}
if nodeCount == 0 {
return nil
}
log.Info("Creating NodeDeployments via Kubermatic API")
var nodeDeployments []apimodels.NodeDeployment
var err error
if err := wait.PollImmediate(10*time.Second, time.Minute, func() (bool, error) {
nodeDeployments, err = scenario.NodeDeployments(nodeCount, r.secrets)
if err != nil {
log.Infow("Getting NodeDeployments from scenario failed", zap.Error(err))
return false, nil
}
return true, nil
}); err != nil {
return fmt.Errorf("didn't get NodeDeployments from scenario within a minute: %v", err)
}
for _, nd := range nodeDeployments {
params := &projectclient.CreateNodeDeploymentParams{
ProjectID: r.kubermatcProjectID,
ClusterID: clusterName,
DC: r.seed.Name,
Body: &nd,
}
params.SetTimeout(15 * time.Second)
if err := retryNAttempts(defaultAPIRetries, func(attempt int) error {
if _, err := r.kubermaticClient.Project.CreateNodeDeployment(params, r.kubermaticAuthenticator); err != nil {
log.Warnf("[Attempt %d/%d] Failed to create NodeDeployment %s: %v. Retrying", attempt, defaultAPIRetries, nd.Name, fmtSwaggerError(err))
return err
}
return nil
}); err != nil {
return fmt.Errorf("failed to create NodeDeployment %s via kubermatic api after %d attempts: %q", nd.Name, defaultAPIRetries, fmtSwaggerError(err))
}
}
log.Infof("Successfully created %d NodeDeployments via Kubermatic API", nodeCount)
return nil
}
func (r *testRunner) getKubeconfig(log *zap.SugaredLogger, cluster *kubermaticv1.Cluster) (string, error) {
log.Debug("Getting kubeconfig...")
var kubeconfig []byte
// Needed for Openshift where we have to create a SA and bindings inside the cluster
// which can only be done after the APIServer is up and ready
if err := wait.PollImmediate(time.Second, time.Minute, func() (bool, error) {
var err error
kubeconfig, err = r.clusterClientProvider.GetAdminKubeconfig(cluster)
if err != nil {
log.Debugw("Failed to get Kubeconfig", zap.Error(err))
return false, nil
}
return true, nil
}); err != nil {
return "", fmt.Errorf("failed to wait for kubeconfig: %v", err)
}
filename := path.Join(r.homeDir, fmt.Sprintf("%s-kubeconfig", cluster.Name))
if err := ioutil.WriteFile(filename, kubeconfig, 0644); err != nil {
return "", fmt.Errorf("failed to write kubeconfig to %s: %v", filename, err)
}
log.Infof("Successfully wrote kubeconfig to %s", filename)
return filename, nil
}
func (r *testRunner) getCloudConfig(log *zap.SugaredLogger, cluster *kubermaticv1.Cluster) (string, error) {
log.Debug("Getting cloud-config...")
var cmData string
err := retryNAttempts(defaultAPIRetries, func(attempt int) error {
cm := &corev1.ConfigMap{}
name := types.NamespacedName{Namespace: cluster.Status.NamespaceName, Name: resources.CloudConfigConfigMapName}
if err := r.seedClusterClient.Get(context.Background(), name, cm); err != nil {
return fmt.Errorf("failed to load cloud-config: %v", err)
}
cmData = cm.Data["config"]
return nil
})
if err != nil {
return "", fmt.Errorf("failed to get cloud config ConfigMap: %v", err)
}
filename := path.Join(r.homeDir, fmt.Sprintf("%s-cloud-config", cluster.Name))
if err := ioutil.WriteFile(filename, []byte(cmData), 0644); err != nil {
return "", fmt.Errorf("failed to write cloud config: %v", err)
}
log.Infof("Successfully wrote cloud-config to %s", filename)
return filename, nil
}
func (r *testRunner) createCluster(log *zap.SugaredLogger, scenario testScenario) (*kubermaticv1.Cluster, error) {
log.Info("Creating cluster via Kubermatic API")
cluster := scenario.Cluster(r.secrets)
if r.openshift {
cluster.Cluster.Type = "openshift"
cluster.Cluster.Spec.Openshift = &apimodels.Openshift{
ImagePullSecret: r.openshiftPullSecret,
}
}
// The cluster name must be unique per project.
// We build up a understandable name with the various cli parameters & add a random string in the end to ensure
// we really have a unique name
if r.namePrefix != "" {
cluster.Cluster.Name = r.namePrefix + "-"
}
if r.workerName != "" {
cluster.Cluster.Name += r.workerName + "-"
}
cluster.Cluster.Name += scenario.Name() + "-"
cluster.Cluster.Name += rand.String(8)
cluster.Cluster.Spec.UsePodSecurityPolicyAdmissionPlugin = r.pspEnabled
params := &projectclient.CreateClusterParams{
ProjectID: r.kubermatcProjectID,
DC: r.seed.Name,
Body: cluster,
}
params.SetTimeout(15 * time.Second)
crCluster := &kubermaticv1.Cluster{}
var selector labels.Selector
var err error
if r.workerName != "" {
selector, err = labels.Parse(fmt.Sprintf("worker-name=%s", r.workerName))
if err != nil {
return nil, fmt.Errorf("failed to parse selector: %v", err)
}
}
var errs []error
if err := wait.PollImmediate(5*time.Second, 45*time.Second, func() (bool, error) {
// For some reason the cluster doesn't have the name we set via ID on creation
clusterList := &kubermaticv1.ClusterList{}
opts := &ctrlruntimeclient.ListOptions{LabelSelector: selector}
if err := r.seedClusterClient.List(r.ctx, clusterList, opts); err != nil {
return false, err
}
numFoundClusters := len(clusterList.Items)
switch {
case numFoundClusters < 1:
if _, err := r.kubermaticClient.Project.CreateCluster(params, r.kubermaticAuthenticator); err != nil {
// Log the error but don't return it, we want to retry
err = errors.New(fmtSwaggerError(err))
errs = append(errs, err)
log.Errorw("Failed to create cluster via Kubermatic API", zap.Error(err))
}
// Always return here, our clusterList is not up to date anymore
return false, nil
case numFoundClusters > 1:
return false, fmt.Errorf("had more than one cluster (%d) with our worker-name, how is this possible?! ", numFoundClusters)
default:
crCluster = &clusterList.Items[0]
return true, err
}
}); err != nil {
errs = append(errs, err)
return nil, fmt.Errorf("cluster creation failed: %v", utilerror.NewAggregate(errs))
}
log.Info("Successfully created cluster via Kubermatic API")
return crCluster, nil
}
func (r *testRunner) waitForControlPlane(log *zap.SugaredLogger, clusterName string) (*kubermaticv1.Cluster, error) {
log.Debug("Waiting for control plane to become ready...")
started := time.Now()
namespacedClusterName := types.NamespacedName{Name: clusterName}
err := wait.Poll(controlPlaneReadyPollPeriod, r.controlPlaneReadyWaitTimeout, func() (done bool, err error) {
newCluster := &kubermaticv1.Cluster{}
if err := r.seedClusterClient.Get(context.Background(), namespacedClusterName, newCluster); err != nil {