-
Notifications
You must be signed in to change notification settings - Fork 287
/
cluster.go
2226 lines (1913 loc) Β· 79.8 KB
/
cluster.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
package framework
import (
"bufio"
"bytes"
"context"
"crypto/sha1"
_ "embed"
"encoding/json"
"fmt"
"io"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
rapi "github.com/tinkerbell/rufio/api/v1alpha1"
rctrl "github.com/tinkerbell/rufio/controllers"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/yaml"
packagesv1 "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere/internal/pkg/api"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/clients/kubernetes"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/pkg/executables"
"github.com/aws/eks-anywhere/pkg/filewriter"
"github.com/aws/eks-anywhere/pkg/git"
"github.com/aws/eks-anywhere/pkg/providers/cloudstack/decoder"
"github.com/aws/eks-anywhere/pkg/retrier"
"github.com/aws/eks-anywhere/pkg/semver"
"github.com/aws/eks-anywhere/pkg/templater"
"github.com/aws/eks-anywhere/pkg/types"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
const (
defaultClusterConfigFile = "cluster.yaml"
defaultBundleReleaseManifestFile = "bin/local-bundle-release.yaml"
defaultEksaBinaryLocation = "eksctl anywhere"
defaultClusterName = "eksa-test"
defaultDownloadArtifactsOutputLocation = "eks-anywhere-downloads.tar.gz"
defaultDownloadImagesOutputLocation = "images.tar"
eksctlVersionEnvVar = "EKSCTL_VERSION"
eksctlVersionEnvVarDummyVal = "ham sandwich"
ClusterPrefixVar = "T_CLUSTER_PREFIX"
JobIdVar = "T_JOB_ID"
BundlesOverrideVar = "T_BUNDLES_OVERRIDE"
ClusterIPPoolEnvVar = "T_CLUSTER_IP_POOL"
CleanupVmsVar = "T_CLEANUP_VMS"
hardwareYamlPath = "hardware.yaml"
hardwareCsvPath = "hardware.csv"
EksaPackagesInstallation = "eks-anywhere-packages"
)
//go:embed testdata/oidc-roles.yaml
var oidcRoles []byte
//go:embed testdata/hpa_busybox.yaml
var hpaBusybox []byte
type ClusterE2ETest struct {
T T
ClusterConfigLocation string
ClusterConfigFolder string
HardwareConfigLocation string
HardwareCsvLocation string
TestHardware map[string]*api.Hardware
HardwarePool map[string]*api.Hardware
WithNoPowerActions bool
ClusterName string
ClusterConfig *cluster.Config
clusterStateValidationConfig *clusterf.StateValidationConfig
Provider Provider
clusterFillers []api.ClusterFiller
KubectlClient *executables.Kubectl
GitProvider git.ProviderClient
GitClient git.Client
HelmInstallConfig *HelmInstallConfig
PackageConfig *PackageConfig
GitWriter filewriter.FileWriter
eksaBinaryLocation string
ExpectFailure bool
// PersistentCluster avoids creating the clusters if it finds a kubeconfig
// in the corresponding cluster folder. Useful for local development of tests.
// When generating a new base cluster config, it will read from disk instead of
// using the CLI generate command and will preserve the previous CP endpoint.
PersistentCluster bool
}
type ClusterE2ETestOpt func(e *ClusterE2ETest)
// NewClusterE2ETest is a support structure for defining an end-to-end test.
func NewClusterE2ETest(t T, provider Provider, opts ...ClusterE2ETestOpt) *ClusterE2ETest {
e := &ClusterE2ETest{
T: t,
Provider: provider,
ClusterConfig: &cluster.Config{},
ClusterConfigLocation: defaultClusterConfigFile,
ClusterName: getClusterName(t),
clusterFillers: make([]api.ClusterFiller, 0),
KubectlClient: buildKubectl(t),
eksaBinaryLocation: defaultEksaBinaryLocation,
}
for _, opt := range opts {
opt(e)
}
if e.ClusterConfigFolder == "" {
e.ClusterConfigFolder = e.ClusterName
}
if e.HardwareConfigLocation == "" {
e.HardwareConfigLocation = filepath.Join(e.ClusterConfigFolder, hardwareYamlPath)
}
if e.HardwareCsvLocation == "" {
e.HardwareCsvLocation = filepath.Join(e.ClusterConfigFolder, hardwareCsvPath)
}
e.ClusterConfigLocation = filepath.Join(e.ClusterConfigFolder, e.ClusterName+"-eks-a.yaml")
if err := os.MkdirAll(e.ClusterConfigFolder, os.ModePerm); err != nil {
t.Fatalf("Failed creating cluster config folder for test: %s", err)
}
provider.Setup()
e.T.Cleanup(func() {
e.CleanupVms()
tinkerbellCIEnvironment := os.Getenv(TinkerbellCIEnvironment)
if e.Provider.Name() == TinkerbellProviderName && tinkerbellCIEnvironment == "true" {
e.CleanupDockerEnvironment()
}
})
return e
}
func withHardware(requiredCount int, hardareType string, labels map[string]string) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
hardwarePool := e.GetHardwarePool()
if e.TestHardware == nil {
e.TestHardware = make(map[string]*api.Hardware)
}
var count int
for id, h := range hardwarePool {
if _, exists := e.TestHardware[id]; !exists {
count++
h.Labels = labels
e.TestHardware[id] = h
}
if count == requiredCount {
break
}
}
if count < requiredCount {
e.T.Errorf("this test requires at least %d piece(s) of %s hardware", requiredCount, hardareType)
}
}
}
func WithNoPowerActions() ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.WithNoPowerActions = true
}
}
func ExpectFailure(expected bool) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.ExpectFailure = expected
}
}
func WithControlPlaneHardware(requiredCount int) ClusterE2ETestOpt {
return withHardware(
requiredCount,
api.ControlPlane,
map[string]string{api.HardwareLabelTypeKeyName: api.ControlPlane},
)
}
func WithWorkerHardware(requiredCount int) ClusterE2ETestOpt {
return withHardware(requiredCount, api.Worker, map[string]string{api.HardwareLabelTypeKeyName: api.Worker})
}
func WithCustomLabelHardware(requiredCount int, label string) ClusterE2ETestOpt {
return withHardware(requiredCount, api.Worker, map[string]string{api.HardwareLabelTypeKeyName: label})
}
func WithExternalEtcdHardware(requiredCount int) ClusterE2ETestOpt {
return withHardware(
requiredCount,
api.ExternalEtcd,
map[string]string{api.HardwareLabelTypeKeyName: api.ExternalEtcd},
)
}
// WithClusterName sets the name that will be used for the cluster. This will drive both the name of the eks-a
// cluster config objects as well as the cluster config file name.
func WithClusterName(name string) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.ClusterName = name
}
}
// PersistentCluster avoids creating the clusters if it finds a kubeconfig
// in the corresponding cluster folder. Useful for local development of tests.
func PersistentCluster() ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.PersistentCluster = true
}
}
func (e *ClusterE2ETest) GetHardwarePool() map[string]*api.Hardware {
if e.HardwarePool == nil {
csvFilePath := os.Getenv(tinkerbellInventoryCsvFilePathEnvVar)
var err error
e.HardwarePool, err = api.NewHardwareMapFromFile(csvFilePath)
if err != nil {
e.T.Fatalf("failed to create hardware map from test hardware pool: %v", err)
}
}
return e.HardwarePool
}
func (e *ClusterE2ETest) RunClusterFlowWithGitOps(clusterOpts ...ClusterE2ETestOpt) {
e.GenerateClusterConfig()
e.createCluster()
e.UpgradeWithGitOps(clusterOpts...)
time.Sleep(5 * time.Minute)
e.deleteCluster()
}
func WithClusterFiller(f ...api.ClusterFiller) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.clusterFillers = append(e.clusterFillers, f...)
}
}
// WithClusterSingleNode helps to create an e2e test option for a single node cluster.
func WithClusterSingleNode(v v1alpha1.KubernetesVersion) ClusterE2ETestOpt {
return WithClusterFiller(
api.WithKubernetesVersion(v),
api.WithControlPlaneCount(1),
api.WithEtcdCountIfExternal(0),
api.RemoveAllWorkerNodeGroups(),
)
}
func WithClusterConfigLocationOverride(path string) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.ClusterConfigLocation = path
}
}
func WithEksaVersion(version *semver.Version) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
eksaBinaryLocation, err := GetReleaseBinaryFromVersion(version)
if err != nil {
e.T.Fatal(err)
}
e.eksaBinaryLocation = eksaBinaryLocation
err = setEksctlVersionEnvVar()
if err != nil {
e.T.Fatal(err)
}
}
}
func WithLatestMinorReleaseFromMain() ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
eksaBinaryLocation, err := GetLatestMinorReleaseBinaryFromMain()
if err != nil {
e.T.Fatal(err)
}
e.eksaBinaryLocation = eksaBinaryLocation
err = setEksctlVersionEnvVar()
if err != nil {
e.T.Fatal(err)
}
}
}
func WithEnvVar(key, val string) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
err := os.Setenv(key, val)
if err != nil {
e.T.Fatalf("couldn't set env var %s to value %s due to: %v", key, val, err)
}
}
}
type Provider interface {
Name() string
// ClusterConfigUpdates allows a provider to modify the default cluster config
// after this one is generated for the first time. This is not reapplied on every CLI operation.
// Prefer to call UpdateClusterConfig directly from the tests to make it more explicit.
ClusterConfigUpdates() []api.ClusterConfigFiller
Setup()
CleanupVMs(clusterName string) error
UpdateKubeConfig(content *[]byte, clusterName string) error
ClusterStateValidations() []clusterf.StateValidation
}
func (e *ClusterE2ETest) GenerateClusterConfig(opts ...CommandOpt) {
e.GenerateClusterConfigForVersion("", opts...)
}
func (e *ClusterE2ETest) PowerOffHardware() {
// Initializing BMC Client
ctx := context.Background()
bmcClientFactory := rctrl.NewBMCClientFactoryFunc(ctx)
for _, h := range e.TestHardware {
bmcClient, err := bmcClientFactory(ctx, h.BMCIPAddress, "623", h.BMCUsername, h.BMCPassword)
if err != nil {
e.T.Fatalf("failed to create bmc client: %v", err)
}
defer func() {
// Close BMC connection after reconcilation
err = bmcClient.Close(ctx)
if err != nil {
e.T.Fatalf("BMC close connection failed: %v", err)
}
}()
_, err = bmcClient.SetPowerState(ctx, string(rapi.Off))
if err != nil {
e.T.Fatalf("failed to power off hardware: %v", err)
}
}
}
func (e *ClusterE2ETest) PXEBootHardware() {
// Initializing BMC Client
ctx := context.Background()
bmcClientFactory := rctrl.NewBMCClientFactoryFunc(ctx)
for _, h := range e.TestHardware {
bmcClient, err := bmcClientFactory(ctx, h.BMCIPAddress, "623", h.BMCUsername, h.BMCPassword)
if err != nil {
e.T.Fatalf("failed to create bmc client: %v", err)
}
defer func() {
// Close BMC connection after reconcilation
err = bmcClient.Close(ctx)
if err != nil {
e.T.Fatalf("BMC close connection failed: %v", err)
}
}()
_, err = bmcClient.SetBootDevice(ctx, string(rapi.PXE), false, true)
if err != nil {
e.T.Fatalf("failed to pxe boot hardware: %v", err)
}
}
}
func (e *ClusterE2ETest) PowerOnHardware() {
// Initializing BMC Client
ctx := context.Background()
bmcClientFactory := rctrl.NewBMCClientFactoryFunc(ctx)
for _, h := range e.TestHardware {
bmcClient, err := bmcClientFactory(ctx, h.BMCIPAddress, "623", h.BMCUsername, h.BMCPassword)
if err != nil {
e.T.Fatalf("failed to create bmc client: %v", err)
}
defer func() {
// Close BMC connection after reconcilation
err = bmcClient.Close(ctx)
if err != nil {
e.T.Fatalf("BMC close connection failed: %v", err)
}
}()
_, err = bmcClient.SetPowerState(ctx, string(rapi.On))
if err != nil {
e.T.Fatalf("failed to power on hardware: %v", err)
}
}
}
func (e *ClusterE2ETest) ValidateHardwareDecommissioned() {
// Initializing BMC Client
ctx := context.Background()
bmcClientFactory := rctrl.NewBMCClientFactoryFunc(ctx)
var failedToDecomm []*api.Hardware
for _, h := range e.TestHardware {
bmcClient, err := bmcClientFactory(ctx, h.BMCIPAddress, "443", h.BMCUsername, h.BMCPassword)
if err != nil {
e.T.Fatalf("failed to create bmc client: %v", err)
}
defer func() {
// Close BMC connection after reconcilation
err = bmcClient.Close(ctx)
if err != nil {
e.T.Fatalf("BMC close connection failed: %v", err)
}
}()
powerState, err := bmcClient.GetPowerState(ctx)
// add sleep retries to give the machine time to power off
timeout := 15
for !strings.EqualFold(powerState, string(rapi.Off)) && timeout > 0 {
if err != nil {
e.T.Logf("failed to get power state for hardware (%v): %v", h, err)
}
time.Sleep(5 * time.Second)
timeout = timeout - 5
powerState, err = bmcClient.GetPowerState(ctx)
e.T.Logf(
"hardware power state (id=%s, hostname=%s, bmc_ip=%s): power_state=%s",
h.MACAddress,
h.Hostname,
h.BMCIPAddress,
powerState,
)
}
if !strings.EqualFold(powerState, string(rapi.Off)) {
e.T.Logf(
"failed to decommission hardware: id=%s, hostname=%s, bmc_ip=%s",
h.MACAddress,
h.Hostname,
h.BMCIPAddress,
)
failedToDecomm = append(failedToDecomm, h)
} else {
e.T.Logf("successfully decommissioned hardware: id=%s, hostname=%s, bmc_ip=%s", h.MACAddress, h.Hostname, h.BMCIPAddress)
}
}
if len(failedToDecomm) > 0 {
e.T.Fatalf("failed to decommision hardware during cluster deletion")
}
}
func (e *ClusterE2ETest) GenerateHardwareConfig(opts ...CommandOpt) {
e.generateHardwareConfig(opts...)
}
func (e *ClusterE2ETest) generateHardwareConfig(opts ...CommandOpt) {
if len(e.TestHardware) == 0 {
e.T.Fatal("you must provide the ClusterE2ETest the hardware to use for the test run")
}
if _, err := os.Stat(e.HardwareCsvLocation); err == nil {
os.Remove(e.HardwareCsvLocation)
}
testHardware := e.TestHardware
if e.WithNoPowerActions {
hardwareWithNoBMC := make(map[string]*api.Hardware)
for k, h := range testHardware {
lessBmc := *h
lessBmc.BMCIPAddress = ""
lessBmc.BMCUsername = ""
lessBmc.BMCPassword = ""
hardwareWithNoBMC[k] = &lessBmc
}
testHardware = hardwareWithNoBMC
}
err := api.WriteHardwareMapToCSV(testHardware, e.HardwareCsvLocation)
if err != nil {
e.T.Fatalf("failed to create hardware csv for the test run: %v", err)
}
generateHardwareConfigArgs := []string{
"generate", "hardware",
"-z", e.HardwareCsvLocation,
"-o", e.HardwareConfigLocation,
}
e.RunEKSA(generateHardwareConfigArgs, opts...)
}
func (e *ClusterE2ETest) GenerateClusterConfigForVersion(eksaVersion string, opts ...CommandOpt) {
e.generateClusterConfigObjects(opts...)
if eksaVersion != "" {
err := cleanUpClusterForVersion(e.ClusterConfig, eksaVersion)
if err != nil {
e.T.Fatal(err)
}
}
e.buildClusterConfigFile()
}
func (e *ClusterE2ETest) generateClusterConfigObjects(opts ...CommandOpt) {
e.generateClusterConfigWithCLI(opts...)
config, err := cluster.ParseConfigFromFile(e.ClusterConfigLocation)
if err != nil {
e.T.Fatalf("Failed parsing generated cluster config: %s", err)
}
// Copy all objects that might be generated by the CLI.
// Don't replace the whole ClusterConfig since some ClusterE2ETestOpt might
// have already set some data in it.
e.ClusterConfig.Cluster = config.Cluster
e.ClusterConfig.CloudStackDatacenter = config.CloudStackDatacenter
e.ClusterConfig.VSphereDatacenter = config.VSphereDatacenter
e.ClusterConfig.DockerDatacenter = config.DockerDatacenter
e.ClusterConfig.SnowDatacenter = config.SnowDatacenter
e.ClusterConfig.NutanixDatacenter = config.NutanixDatacenter
e.ClusterConfig.TinkerbellDatacenter = config.TinkerbellDatacenter
e.ClusterConfig.VSphereMachineConfigs = config.VSphereMachineConfigs
e.ClusterConfig.CloudStackMachineConfigs = config.CloudStackMachineConfigs
e.ClusterConfig.SnowMachineConfigs = config.SnowMachineConfigs
e.ClusterConfig.SnowIPPools = config.SnowIPPools
e.ClusterConfig.NutanixMachineConfigs = config.NutanixMachineConfigs
e.ClusterConfig.TinkerbellMachineConfigs = config.TinkerbellMachineConfigs
e.ClusterConfig.TinkerbellTemplateConfigs = config.TinkerbellTemplateConfigs
e.UpdateClusterConfig(e.baseClusterConfigUpdates()...)
}
// UpdateClusterConfig applies the cluster Config provided updates to e.ClusterConfig, marshalls its content
// to yaml and writes it to a file on disk configured by e.ClusterConfigLocation. Call this method when you want
// make changes to the eks-a cluster definition before running a CLI command or API operation.
func (e *ClusterE2ETest) UpdateClusterConfig(fillers ...api.ClusterConfigFiller) {
e.T.Log("Updating cluster config")
api.UpdateClusterConfig(e.ClusterConfig, fillers...)
e.T.Logf("Writing cluster config to file: %s", e.ClusterConfigLocation)
e.buildClusterConfigFile()
}
func (e *ClusterE2ETest) baseClusterConfigUpdates(opts ...CommandOpt) []api.ClusterConfigFiller {
clusterFillers := make([]api.ClusterFiller, 0, len(e.clusterFillers)+3)
// This defaults all tests to a 1:1:1 configuration. Since all the fillers defined on each test are run
// after these 3, if the tests is explicit about any of these, the defaults will be overwritten
clusterFillers = append(clusterFillers,
api.WithControlPlaneCount(1), api.WithWorkerNodeCount(1), api.WithEtcdCountIfExternal(1),
)
clusterFillers = append(clusterFillers, e.clusterFillers...)
configFillers := []api.ClusterConfigFiller{api.ClusterToConfigFiller(clusterFillers...)}
configFillers = append(configFillers, e.Provider.ClusterConfigUpdates()...)
// If we are persisting an existing cluster, set the control plane endpoint back to the original, since
// it is immutable
if e.PersistentCluster && e.ClusterConfig.Cluster.Spec.ControlPlaneConfiguration.Endpoint.Host != "" {
endpoint := e.ClusterConfig.Cluster.Spec.ControlPlaneConfiguration.Endpoint.Host
e.T.Logf("Resseting CP endpoint for persistent cluster to %s", endpoint)
configFillers = append(configFillers,
api.ClusterToConfigFiller(api.WithControlPlaneEndpointIP(endpoint)),
)
}
return configFillers
}
func (e *ClusterE2ETest) generateClusterConfigWithCLI(opts ...CommandOpt) {
if e.PersistentCluster && fileExists(e.ClusterConfigLocation) {
e.T.Log("Skipping CLI cluster generation since this is a persistent cluster that already had one cluster config generated")
return
}
generateClusterConfigArgs := []string{"generate", "clusterconfig", e.ClusterName, "-p", e.Provider.Name(), ">", e.ClusterConfigLocation}
e.RunEKSA(generateClusterConfigArgs, opts...)
e.T.Log("Cluster config generated with CLI")
}
func (e *ClusterE2ETest) parseClusterConfigFromDisk(file string) {
e.T.Logf("Parsing cluster config from disk: %s", file)
config, err := cluster.ParseConfigFromFile(file)
if err != nil {
e.T.Fatalf("Failed parsing generated cluster config: %s", err)
}
e.ClusterConfig = config
}
// WithClusterConfig generates a base cluster config using the CLI `generate clusterconfig` command
// and updates them with the provided fillers. Helpful for defining the initial Cluster config
// before running a create operation.
func (e *ClusterE2ETest) WithClusterConfig(fillers ...api.ClusterConfigFiller) *ClusterE2ETest {
e.T.Logf("Generating base config for cluster %s", e.ClusterName)
e.generateClusterConfigWithCLI()
e.parseClusterConfigFromDisk(e.ClusterConfigLocation)
base := e.baseClusterConfigUpdates()
allUpdates := make([]api.ClusterConfigFiller, 0, len(base)+len(fillers))
allUpdates = append(allUpdates, base...)
allUpdates = append(allUpdates, fillers...)
e.UpdateClusterConfig(allUpdates...)
return e
}
// DownloadArtifacts runs the EKS-A `download artifacts` command with appropriate args.
func (e *ClusterE2ETest) DownloadArtifacts(opts ...CommandOpt) {
downloadArtifactsArgs := []string{"download", "artifacts", "-f", e.ClusterConfigLocation}
if getBundlesOverride() == "true" {
downloadArtifactsArgs = append(downloadArtifactsArgs, "--bundles-override", defaultBundleReleaseManifestFile)
}
e.RunEKSA(downloadArtifactsArgs, opts...)
if _, err := os.Stat(defaultDownloadArtifactsOutputLocation); err != nil {
e.T.Fatal(err)
} else {
e.T.Logf("Downloaded artifacts tarball saved at %s", defaultDownloadArtifactsOutputLocation)
}
}
// ExtractDownloadedArtifacts extracts the downloaded artifacts.
func (e *ClusterE2ETest) ExtractDownloadedArtifacts(opts ...CommandOpt) {
e.T.Log("Extracting downloaded artifacts")
e.Run("tar", "-xf", defaultDownloadArtifactsOutputLocation)
}
// CleanupDownloadedArtifactsAndImages cleans up the downloaded artifacts and images.
func (e *ClusterE2ETest) CleanupDownloadedArtifactsAndImages(opts ...CommandOpt) {
e.T.Log("Cleaning up downloaded artifacts and images")
e.Run("rm", "-rf", defaultDownloadArtifactsOutputLocation, defaultDownloadImagesOutputLocation)
}
// DownloadImages runs the EKS-A `download images` command with appropriate args.
func (e *ClusterE2ETest) DownloadImages(opts ...CommandOpt) {
downloadImagesArgs := []string{"download", "images", "-o", defaultDownloadImagesOutputLocation}
if getBundlesOverride() == "true" {
var bundleManifestLocation string
if _, err := os.Stat(defaultDownloadArtifactsOutputLocation); err == nil {
bundleManifestLocation = "eks-anywhere-downloads/bundle-release.yaml"
} else {
bundleManifestLocation = defaultBundleReleaseManifestFile
}
downloadImagesArgs = append(downloadImagesArgs, "--bundles-override", bundleManifestLocation)
}
e.RunEKSA(downloadImagesArgs, opts...)
if _, err := os.Stat(defaultDownloadImagesOutputLocation); err != nil {
e.T.Fatal(err)
} else {
e.T.Logf("Downloaded images archive saved at %s", defaultDownloadImagesOutputLocation)
}
}
// ImportImages runs the EKS-A `import images` command with appropriate args.
func (e *ClusterE2ETest) ImportImages(opts ...CommandOpt) {
clusterConfig := e.ClusterConfig.Cluster
registyMirrorEndpoint, registryMirrorPort := clusterConfig.Spec.RegistryMirrorConfiguration.Endpoint, clusterConfig.Spec.RegistryMirrorConfiguration.Port
registryMirrorHost := net.JoinHostPort(registyMirrorEndpoint, registryMirrorPort)
var bundleManifestLocation string
if _, err := os.Stat(defaultDownloadArtifactsOutputLocation); err == nil {
bundleManifestLocation = "eks-anywhere-downloads/bundle-release.yaml"
} else {
bundleManifestLocation = defaultBundleReleaseManifestFile
}
importImagesArgs := []string{"import images", "--input", defaultDownloadImagesOutputLocation, "--bundles", bundleManifestLocation, "--registry", registryMirrorHost, "--insecure"}
e.RunEKSA(importImagesArgs, opts...)
}
// ChangeInstanceSecurityGroup modifies the security group of the instance to the provided value.
func (e *ClusterE2ETest) ChangeInstanceSecurityGroup(securityGroup string) {
e.T.Logf("Changing instance security group to %s", securityGroup)
e.Run(fmt.Sprintf("INSTANCE_ID=$(ec2-metadata -i | awk '{print $2}') && aws ec2 modify-instance-attribute --instance-id $INSTANCE_ID --groups %s", securityGroup))
}
func (e *ClusterE2ETest) CreateCluster(opts ...CommandOpt) {
e.setFeatureFlagForUnreleasedKubernetesVersion(e.ClusterConfig.Cluster.Spec.KubernetesVersion)
e.createCluster(opts...)
}
func (e *ClusterE2ETest) createCluster(opts ...CommandOpt) {
if e.PersistentCluster {
if fileExists(e.KubeconfigFilePath()) {
e.T.Logf("Persisent cluster: kubeconfig found for cluster %s, skipping cluster creation", e.ClusterName)
return
}
}
e.T.Logf("Creating cluster %s", e.ClusterName)
createClusterArgs := []string{"create", "cluster", "-f", e.ClusterConfigLocation, "-v", "12", "--force-cleanup"}
dumpFile("Create cluster from file:", e.ClusterConfigLocation, e.T)
if getBundlesOverride() == "true" {
createClusterArgs = append(createClusterArgs, "--bundles-override", defaultBundleReleaseManifestFile)
}
if e.Provider.Name() == TinkerbellProviderName {
createClusterArgs = append(createClusterArgs, "-z", e.HardwareCsvLocation)
dumpFile("Hardware csv file:", e.HardwareCsvLocation, e.T)
tinkBootstrapIP := os.Getenv(tinkerbellBootstrapIPEnvVar)
e.T.Logf("tinkBootstrapIP: %s", tinkBootstrapIP)
if tinkBootstrapIP != "" {
createClusterArgs = append(createClusterArgs, "--tinkerbell-bootstrap-ip", tinkBootstrapIP)
}
}
e.RunEKSA(createClusterArgs, opts...)
}
func (e *ClusterE2ETest) ValidateCluster(kubeVersion v1alpha1.KubernetesVersion) {
ctx := context.Background()
e.T.Log("Validating cluster node status")
r := retrier.New(10 * time.Minute)
err := r.Retry(func() error {
err := e.KubectlClient.ValidateNodes(ctx, e.Cluster().KubeconfigFile)
if err != nil {
return fmt.Errorf("validating nodes status: %v", err)
}
return nil
})
if err != nil {
e.T.Fatal(err)
}
e.T.Log("Validating cluster node version")
err = retrier.Retry(180, 1*time.Second, func() error {
if err = e.KubectlClient.ValidateNodesVersion(ctx, e.Cluster().KubeconfigFile, kubeVersion); err != nil {
return fmt.Errorf("validating nodes version: %v", err)
}
return nil
})
if err != nil {
e.T.Fatal(err)
}
}
func (e *ClusterE2ETest) WaitForMachineDeploymentReady(machineDeploymentName string) {
ctx := context.Background()
e.T.Logf("Waiting for machine deployment %s to be ready for cluster %s", machineDeploymentName, e.ClusterName)
err := e.KubectlClient.WaitForMachineDeploymentReady(ctx, e.Cluster(), "5m", machineDeploymentName)
if err != nil {
e.T.Fatal(err)
}
}
// GetEKSACluster retrieves the EKSA cluster from the runtime environment using kubectl.
func (e *ClusterE2ETest) GetEKSACluster() *v1alpha1.Cluster {
ctx := context.Background()
clus, err := e.KubectlClient.GetEksaCluster(ctx, e.Cluster(), e.ClusterName)
if err != nil {
e.T.Fatal(err)
}
return clus
}
func (e *ClusterE2ETest) GetCapiMachinesForCluster(clusterName string) map[string]types.Machine {
machines, err := e.CapiMachinesForCluster(clusterName)
if err != nil {
e.T.Fatal(err)
}
return machines
}
// CapiMachinesForCluster reads all the CAPI Machines for a particular cluster and returns them
// index by their name.
func (e *ClusterE2ETest) CapiMachinesForCluster(clusterName string) (map[string]types.Machine, error) {
ctx := context.Background()
capiMachines, err := e.KubectlClient.GetMachines(ctx, e.Cluster(), clusterName)
if err != nil {
return nil, err
}
machinesMap := make(map[string]types.Machine, 0)
for _, machine := range capiMachines {
machinesMap[machine.Metadata.Name] = machine
}
return machinesMap, nil
}
// ApplyClusterManifest uses client-side logic to create/update objects defined in a cluster yaml manifest.
func (e *ClusterE2ETest) ApplyClusterManifest() {
ctx := context.Background()
e.T.Logf("Applying cluster %s spec located at %s", e.ClusterName, e.ClusterConfigLocation)
e.applyClusterManifest(ctx)
}
func (e *ClusterE2ETest) applyClusterManifest(ctx context.Context) {
if err := e.KubectlClient.ApplyManifest(ctx, e.KubeconfigFilePath(), e.ClusterConfigLocation); err != nil {
e.T.Fatalf("Failed to apply cluster config: %s", err)
}
}
// WithClusterUpgrade adds a cluster upgrade.
func WithClusterUpgrade(fillers ...api.ClusterFiller) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.UpdateClusterConfig(api.ClusterToConfigFiller(fillers...))
}
}
// UpgradeClusterWithKubectl uses client-side logic to upgrade a cluster that was created using the CLI.
func (e *ClusterE2ETest) UpgradeClusterWithKubectl(fillers ...api.ClusterConfigFiller) {
// The CLI adds the BundlesRef field to the config and writes it to disk.
// We want to grab the existing BundlesRef, and update our test ClusterConfig
// because updating it with a nil value after previously being set will throw a webhook error.
if e.ClusterConfig.Cluster.Spec.BundlesRef == nil {
fullClusterConfigLocation := filepath.Join(e.ClusterConfigFolder, e.ClusterName+"-eks-a-cluster.yaml")
e.T.Logf("Parsing cluster config from disk: %s", fullClusterConfigLocation)
config, err := cluster.ParseConfigFromFile(fullClusterConfigLocation)
if err != nil {
e.T.Fatalf("Failed parsing generated cluster config: %s", err)
}
e.ClusterConfig.Cluster.Spec.BundlesRef = config.Cluster.Spec.BundlesRef
}
e.UpdateClusterConfig(fillers...)
e.ApplyClusterManifest()
}
// UpgradeClusterWithNewConfig applies the test options, re-generates the cluster config file and runs the CLI upgrade command.
func (e *ClusterE2ETest) UpgradeClusterWithNewConfig(clusterOpts []ClusterE2ETestOpt, commandOpts ...CommandOpt) {
e.upgradeCluster(clusterOpts, commandOpts...)
}
func (e *ClusterE2ETest) upgradeCluster(clusterOpts []ClusterE2ETestOpt, commandOpts ...CommandOpt) {
for _, opt := range clusterOpts {
opt(e)
}
e.buildClusterConfigFile()
e.setFeatureFlagForUnreleasedKubernetesVersion(e.ClusterConfig.Cluster.Spec.KubernetesVersion)
e.UpgradeCluster(commandOpts...)
}
// UpgradeCluster runs the CLI upgrade command.
func (e *ClusterE2ETest) UpgradeCluster(commandOpts ...CommandOpt) {
upgradeClusterArgs := []string{"upgrade", "cluster", "-f", e.ClusterConfigLocation, "-v", "4"}
if getBundlesOverride() == "true" {
upgradeClusterArgs = append(upgradeClusterArgs, "--bundles-override", defaultBundleReleaseManifestFile)
}
e.RunEKSA(upgradeClusterArgs, commandOpts...)
}
func (e *ClusterE2ETest) generateClusterConfigYaml() []byte {
childObjs := e.ClusterConfig.ChildObjects()
yamlB := make([][]byte, 0, len(childObjs)+1)
if e.PackageConfig != nil {
e.ClusterConfig.Cluster.Spec.Packages = e.PackageConfig.packageConfiguration
}
// This is required because Flux requires a namespace be specified for objects
// to be able to reconcile right.
if e.ClusterConfig.Cluster.Namespace == "" {
e.ClusterConfig.Cluster.Namespace = "default"
}
clusterConfigB, err := yaml.Marshal(e.ClusterConfig.Cluster)
if err != nil {
e.T.Fatal(err)
}
yamlB = append(yamlB, clusterConfigB)
for _, o := range childObjs {
// This is required because Flux requires a namespace be specified for objects
// to be able to reconcile right.
if o.GetNamespace() == "" {
o.SetNamespace("default")
}
objB, err := yaml.Marshal(o)
if err != nil {
e.T.Fatalf("Failed marshalling %s config: %v", o.GetName(), err)
}
yamlB = append(yamlB, objB)
}
return templater.AppendYamlResources(yamlB...)
}
func (e *ClusterE2ETest) buildClusterConfigFile() {
yaml := e.generateClusterConfigYaml()
writer, err := filewriter.NewWriter(e.ClusterConfigFolder)
if err != nil {
e.T.Fatalf("Error creating writer: %v", err)
}
writtenFile, err := writer.Write(filepath.Base(e.ClusterConfigLocation), yaml, filewriter.PersistentFile)
if err != nil {
e.T.Fatalf("Error writing cluster config to file %s: %v", e.ClusterConfigLocation, err)
}
e.T.Logf("Written cluster config to %v", writtenFile)
e.ClusterConfigLocation = writtenFile
}
func (e *ClusterE2ETest) DeleteCluster(opts ...CommandOpt) {
e.deleteCluster(opts...)
}
// CleanupVms is a helper to clean up VMs. It is a noop if the T_CLEANUP_VMS environment variable
// is false or unset.
func (e *ClusterE2ETest) CleanupVms() {
if !shouldCleanUpVms() {
e.T.Logf("Skipping VM cleanup")
return
}
if err := e.Provider.CleanupVMs(e.ClusterName); err != nil {
e.T.Logf("failed to clean up VMs: %v", err)
}
}
func (e *ClusterE2ETest) CleanupDockerEnvironment() {
e.T.Logf("cleanup kind enviornment...")
e.Run("kind", "delete", "clusters", "--all", "||", "true")
e.T.Logf("cleanup docker enviornment...")
e.Run("docker", "rm", "-vf", "$(docker ps -a -q)", "||", "true")
}
func shouldCleanUpVms() bool {
shouldCleanupVms, err := getCleanupVmsVar()
return err == nil && shouldCleanupVms
}
func (e *ClusterE2ETest) deleteCluster(opts ...CommandOpt) {
deleteClusterArgs := []string{"delete", "cluster", e.ClusterName, "-v", "4"}
if getBundlesOverride() == "true" {
deleteClusterArgs = append(deleteClusterArgs, "--bundles-override", defaultBundleReleaseManifestFile)
}
e.RunEKSA(deleteClusterArgs, opts...)
}
// GenerateSupportBundleOnCleanupIfTestFailed does what it says on the tin.
//
// It uses testing.T.Cleanup to register a handler that checks if the test
// failed, and generates a support bundle only in the event of a failure.
func (e *ClusterE2ETest) GenerateSupportBundleOnCleanupIfTestFailed(opts ...CommandOpt) {
e.T.Cleanup(func() {
if e.T.Failed() {
e.T.Log("Generating support bundle for failed test")
generateSupportBundleArgs := []string{"generate", "support-bundle", "-f", e.ClusterConfigLocation}
e.RunEKSA(generateSupportBundleArgs, opts...)
}
})
}
func (e *ClusterE2ETest) Run(name string, args ...string) {
command := strings.Join(append([]string{name}, args...), " ")
shArgs := []string{"-c", command}
e.T.Log("Running shell command", "[", command, "]")
cmd := exec.CommandContext(context.Background(), "sh", shArgs...)
envPath := os.Getenv("PATH")
binDir, err := DefaultLocalEKSABinDir()
if err != nil {
e.T.Fatalf("Error finding current directory: %v", err)
}
var stdoutAndErr bytes.Buffer
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("PATH=%s:%s", binDir, envPath))
cmd.Stderr = io.MultiWriter(os.Stderr, &stdoutAndErr)
cmd.Stdout = io.MultiWriter(os.Stdout, &stdoutAndErr)
if err = cmd.Run(); err != nil {
e.T.Log("Command failed, scanning output for error")
scanner := bufio.NewScanner(&stdoutAndErr)
var errorMessage string
// Look for the last line of the out put that starts with 'Error:'
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "Error:") {
errorMessage = line
}
}
if err := scanner.Err(); err != nil {
e.T.Fatalf("Failed reading command output looking for error message: %v", err)
}
if errorMessage != "" {
if e.ExpectFailure {
e.T.Logf("This error was expected. Continuing...")
return
}
e.T.Fatalf("Command %s %v failed with error: %v: %s", name, args, err, errorMessage)
}
e.T.Fatalf("Error running command %s %v: %v", name, args, err)
}
}
func (e *ClusterE2ETest) RunEKSA(args []string, opts ...CommandOpt) {
binaryPath := e.eksaBinaryLocation
for _, o := range opts {
err := o(&binaryPath, &args)
if err != nil {
e.T.Fatalf("Error executing EKS-A at path %s with args %s: %v", binaryPath, args, err)
}