repo_name
stringlengths
1
52
repo_creator
stringclasses
6 values
programming_language
stringclasses
4 values
code
stringlengths
0
9.68M
num_lines
int64
1
234k
eks-anywhere
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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 v1alpha1 import ( "fmt" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" ) // log is for logging in this package. var tinkerbelldatacenterconfiglog = logf.Log.WithName("tinkerbelldatacenterconfig-resource") // SetupWebhookWithManager sets up TinkerbellDatacenterConfig webhook to controller manager. func (r *TinkerbellDatacenterConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! // TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-anywhere-eks-amazonaws-com-v1alpha1-tinkerbelldatacenterconfig,mutating=false,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=tinkerbelldatacenterconfigs,verbs=create;update,versions=v1alpha1,name=validation.tinkerbelldatacenterconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Validator = &TinkerbellDatacenterConfig{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellDatacenterConfig) ValidateCreate() error { tinkerbelldatacenterconfiglog.Info("validate create", "name", r.Name) if err := r.Validate(); err != nil { return apierrors.NewInvalid( GroupVersion.WithKind(TinkerbellDatacenterKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec"), r.Spec, err.Error()), }, ) } if r.IsReconcilePaused() { tinkerbelldatacenterconfiglog.Info("TinkerbellDatacenterConfig is paused, so allowing create", "name", r.Name) return nil } return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellDatacenterConfig) ValidateUpdate(old runtime.Object) error { tinkerbelldatacenterconfiglog.Info("validate update", "name", r.Name) oldTinkerbellDatacenterConfig, ok := old.(*TinkerbellDatacenterConfig) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a TinkerbellDatacenterConfig but got a %T", old)) } var allErrs field.ErrorList allErrs = append(allErrs, validateImmutableFieldsTinkerbellDatacenterConfig(r, oldTinkerbellDatacenterConfig)...) if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(TinkerbellDatacenterKind).GroupKind(), r.Name, allErrs) } if err := r.Validate(); err != nil { allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), r.Spec, err.Error())) } if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(TinkerbellDatacenterKind).GroupKind(), r.Name, allErrs) } return nil } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellDatacenterConfig) ValidateDelete() error { tinkerbelldatacenterconfiglog.Info("validate delete", "name", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil } func validateImmutableFieldsTinkerbellDatacenterConfig(new, old *TinkerbellDatacenterConfig) field.ErrorList { var allErrs field.ErrorList specPath := field.NewPath("spec") if new.Spec.TinkerbellIP != old.Spec.TinkerbellIP { allErrs = append( allErrs, field.Forbidden(specPath.Child("tinkerbellIP"), "field is immutable"), ) } return allErrs }
116
eks-anywhere
aws
Go
package v1alpha1_test import ( "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func TestTinkerbellDatacenterValidateCreate(t *testing.T) { dataCenterConfig := tinkerbellDatacenterConfig() g := NewWithT(t) g.Expect(dataCenterConfig.ValidateCreate()).To(Succeed()) } func TestTinkerbellDatacenterValidateCreateFail(t *testing.T) { dataCenterConfig := tinkerbellDatacenterConfig() dataCenterConfig.Spec.TinkerbellIP = "" g := NewWithT(t) g.Expect(dataCenterConfig.ValidateCreate()).NotTo(Succeed()) } func TestTinkerbellDatacenterValidateUpdateSucceed(t *testing.T) { tOld := tinkerbellDatacenterConfig() tOld.Spec.TinkerbellIP = "1.1.1.1" tNew := tOld.DeepCopy() tNew.Spec.TinkerbellIP = "1.1.1.1" g := NewWithT(t) g.Expect(tNew.ValidateUpdate(&tOld)).To(Succeed()) } func TestTinkerbellDatacenterValidateUpdateFailOSImageURL(t *testing.T) { tOld := tinkerbellDatacenterConfig() tNew := tOld.DeepCopy() tNew.Spec.OSImageURL = "test" g := NewWithT(t) g.Expect(tNew.ValidateUpdate(&tOld)).ToNot(Succeed()) } func TestTinkerbellDatacenterValidateUpdateFailBadReq(t *testing.T) { cOld := &v1alpha1.Cluster{} c := &v1alpha1.TinkerbellDatacenterConfig{} g := NewWithT(t) g.Expect(c.ValidateUpdate(cOld)).To(MatchError(ContainSubstring("expected a TinkerbellDatacenterConfig but got a *v1alpha1.Cluster"))) } func TestTinkerbellDatacenterValidateUpdateImmutableTinkIP(t *testing.T) { tOld := tinkerbellDatacenterConfig() tOld.Spec.TinkerbellIP = "1.1.1.1" tNew := tOld.DeepCopy() tNew.Spec.TinkerbellIP = "1.1.1.2" g := NewWithT(t) g.Expect(tNew.ValidateUpdate(&tOld)).To(MatchError(ContainSubstring("spec.tinkerbellIP: Forbidden: field is immutable"))) } func TestTinkerbellDatacenterValidateDelete(t *testing.T) { tOld := tinkerbellDatacenterConfig() g := NewWithT(t) g.Expect(tOld.ValidateDelete()).To(Succeed()) } func tinkerbellDatacenterConfig() v1alpha1.TinkerbellDatacenterConfig { return v1alpha1.TinkerbellDatacenterConfig{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{ Annotations: make(map[string]string, 1), Name: "tinkerbelldatacenterconfig", }, Spec: v1alpha1.TinkerbellDatacenterConfigSpec{ TinkerbellIP: "1.1.1.1", }, Status: v1alpha1.TinkerbellDatacenterConfigStatus{}, } }
84
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "os" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" ) const TinkerbellMachineConfigKind = "TinkerbellMachineConfig" // +kubebuilder:object:generate=false type TinkerbellMachineConfigGenerateOpt func(config *TinkerbellMachineConfigGenerate) // Used for generating yaml for generate clusterconfig command. func NewTinkerbellMachineConfigGenerate(name string, opts ...TinkerbellMachineConfigGenerateOpt) *TinkerbellMachineConfigGenerate { machineConfig := &TinkerbellMachineConfigGenerate{ TypeMeta: metav1.TypeMeta{ Kind: TinkerbellMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: ObjectMeta{ Name: name, }, Spec: TinkerbellMachineConfigSpec{ HardwareSelector: HardwareSelector{}, OSFamily: Bottlerocket, Users: []UserConfiguration{ { Name: "ec2-user", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }, }, }, } for _, opt := range opts { opt(machineConfig) } return machineConfig } func (c *TinkerbellMachineConfigGenerate) APIVersion() string { return c.TypeMeta.APIVersion } func (c *TinkerbellMachineConfigGenerate) Kind() string { return c.TypeMeta.Kind } func (c *TinkerbellMachineConfigGenerate) Name() string { return c.ObjectMeta.Name } func GetTinkerbellMachineConfigs(fileName string) (map[string]*TinkerbellMachineConfig, error) { configs := make(map[string]*TinkerbellMachineConfig) content, err := os.ReadFile(fileName) if err != nil { return nil, fmt.Errorf("unable to read file due to: %v", err) } for _, c := range strings.Split(string(content), YamlSeparator) { var config TinkerbellMachineConfig if err = yaml.UnmarshalStrict([]byte(c), &config); err == nil { if config.Kind == TinkerbellMachineConfigKind { configs[config.Name] = &config continue } } _ = yaml.Unmarshal([]byte(c), &config) // this is to check if there is a bad spec in the file if config.Kind == TinkerbellMachineConfigKind { return nil, fmt.Errorf("unable to unmarshall content from file due to: %v", err) } } if len(configs) == 0 { return nil, fmt.Errorf("unable to find kind %v in file", TinkerbellMachineConfigKind) } return configs, nil } func WithTemplateRef(ref ProviderRefAccessor) TinkerbellMachineConfigGenerateOpt { return func(c *TinkerbellMachineConfigGenerate) { c.Spec.TemplateRef = Ref{ Kind: ref.Kind(), Name: ref.Name(), } } } func validateTinkerbellMachineConfig(config *TinkerbellMachineConfig) error { if err := validateObjectMeta(config.ObjectMeta); err != nil { return fmt.Errorf("TinkerbellMachineConfig: %v", err) } if len(config.Spec.HardwareSelector) == 0 { return fmt.Errorf("TinkerbellMachineConfig: missing spec.hardwareSelector: %s", config.Name) } if len(config.Spec.HardwareSelector) != 1 { return fmt.Errorf( "TinkerbellMachineConfig: spec.hardwareSelector must contain only 1 key-value pair: %s", config.Name, ) } if config.Spec.OSFamily == "" { return fmt.Errorf("TinkerbellMachineConfig: missing spec.osFamily: %s", config.Name) } if config.Spec.OSFamily != Ubuntu && config.Spec.OSFamily != Bottlerocket && config.Spec.OSFamily != RedHat { return fmt.Errorf( "TinkerbellMachineConfig: unsupported spec.osFamily (%v); Please use one of the following: %s, %s, %s", config.Spec.OSFamily, Ubuntu, RedHat, Bottlerocket, ) } if len(config.Spec.Users) == 0 { return fmt.Errorf("TinkerbellMachineConfig: missing spec.Users: %s", config.Name) } if err := validateHostOSConfig(config.Spec.HostOSConfiguration, config.Spec.OSFamily); err != nil { return fmt.Errorf("HostOSConfiguration is invalid for TinkerbellMachineConfig %s: %v", config.Name, err) } return nil } func setTinkerbellMachineConfigDefaults(machineConfig *TinkerbellMachineConfig) { if machineConfig.Spec.OSFamily == "" { machineConfig.Spec.OSFamily = Bottlerocket } }
138
eks-anywhere
aws
Go
package v1alpha1 import ( "encoding/json" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // TinkerbellMachineConfigSpec defines the desired state of TinkerbellMachineConfig. type TinkerbellMachineConfigSpec struct { HardwareSelector HardwareSelector `json:"hardwareSelector"` TemplateRef Ref `json:"templateRef,omitempty"` OSFamily OSFamily `json:"osFamily"` Users []UserConfiguration `json:"users,omitempty"` HostOSConfiguration *HostOSConfiguration `json:"hostOSConfiguration,omitempty"` } // HardwareSelector models a simple key-value selector used in Tinkerbell provisioning. type HardwareSelector map[string]string // IsEmpty returns true if s has no key-value pairs. func (s HardwareSelector) IsEmpty() bool { return len(s) == 0 } func (s HardwareSelector) ToString() (string, error) { encoded, err := json.Marshal(s) if err != nil { return "", err } return string(encoded), nil } func (c *TinkerbellMachineConfig) PauseReconcile() { c.Annotations[pausedAnnotation] = "true" } func (c *TinkerbellMachineConfig) IsReconcilePaused() bool { if s, ok := c.Annotations[pausedAnnotation]; ok { return s == "true" } return false } func (c *TinkerbellMachineConfig) SetControlPlane() { c.Annotations[controlPlaneAnnotation] = "true" } func (c *TinkerbellMachineConfig) IsControlPlane() bool { if s, ok := c.Annotations[controlPlaneAnnotation]; ok { return s == "true" } return false } func (c *TinkerbellMachineConfig) SetEtcd() { c.Annotations[etcdAnnotation] = "true" } func (c *TinkerbellMachineConfig) IsEtcd() bool { if s, ok := c.Annotations[etcdAnnotation]; ok { return s == "true" } return false } func (c *TinkerbellMachineConfig) SetManagedBy(clusterName string) { if c.Annotations == nil { c.Annotations = map[string]string{} } c.Annotations[managementAnnotation] = clusterName } func (c *TinkerbellMachineConfig) IsManaged() bool { if s, ok := c.Annotations[managementAnnotation]; ok { return s != "" } return false } func (c *TinkerbellMachineConfig) OSFamily() OSFamily { return c.Spec.OSFamily } func (c *TinkerbellMachineConfig) GetNamespace() string { return c.Namespace } func (c *TinkerbellMachineConfig) GetName() string { return c.Name } // TinkerbellMachineConfigStatus defines the observed state of TinkerbellMachineConfig. type TinkerbellMachineConfigStatus struct{} //+kubebuilder:object:root=true //+kubebuilder:subresource:status // TinkerbellMachineConfig is the Schema for the tinkerbellmachineconfigs API. type TinkerbellMachineConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec TinkerbellMachineConfigSpec `json:"spec,omitempty"` Status TinkerbellMachineConfigStatus `json:"status,omitempty"` } func (c *TinkerbellMachineConfig) ConvertConfigToConfigGenerateStruct() *TinkerbellMachineConfigGenerate { namespace := defaultEksaNamespace if c.Namespace != "" { namespace = c.Namespace } config := &TinkerbellMachineConfigGenerate{ TypeMeta: c.TypeMeta, ObjectMeta: ObjectMeta{ Name: c.Name, Annotations: c.Annotations, Namespace: namespace, }, Spec: c.Spec, } return config } func (c *TinkerbellMachineConfig) Marshallable() Marshallable { return c.ConvertConfigToConfigGenerateStruct() } // Validate performs light and fast Tinkerbell machine config validation. func (c *TinkerbellMachineConfig) Validate() error { return validateTinkerbellMachineConfig(c) } // SetDefaults sets defaults for Tinkerbell machine config. func (c *TinkerbellMachineConfig) SetDefaults() { setTinkerbellMachineConfigDefaults(c) } // +kubebuilder:object:generate=false // Same as TinkerbellMachineConfig except stripped down for generation of yaml file during generate clusterconfig. type TinkerbellMachineConfigGenerate struct { metav1.TypeMeta `json:",inline"` ObjectMeta `json:"metadata,omitempty"` Spec TinkerbellMachineConfigSpec `json:"spec,omitempty"` } //+kubebuilder:object:root=true // TinkerbellMachineConfigList contains a list of TinkerbellMachineConfig. type TinkerbellMachineConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []TinkerbellMachineConfig `json:"items"` } func init() { SchemeBuilder.Register(&TinkerbellMachineConfig{}, &TinkerbellMachineConfigList{}) }
164
eks-anywhere
aws
Go
package v1alpha1 import ( "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestTinkerbellMachineConfigValidateSucceed(t *testing.T) { machineConfig := CreateTinkerbellMachineConfig() g := NewWithT(t) g.Expect(machineConfig.Validate()).To(Succeed()) } func TestTinkerbellMachineConfigValidateFail(t *testing.T) { tests := []struct { name string machineConfig *TinkerbellMachineConfig expectedErr string }{ { name: "Invalid object meta", machineConfig: CreateTinkerbellMachineConfig(func(mc *TinkerbellMachineConfig) { mc.ObjectMeta.Name = "" }), expectedErr: "TinkerbellMachineConfig: missing name", }, { name: "Empty hardware selector", machineConfig: CreateTinkerbellMachineConfig(func(mc *TinkerbellMachineConfig) { mc.Spec.HardwareSelector = nil }), expectedErr: "TinkerbellMachineConfig: missing spec.hardwareSelector", }, { name: "Multiple hardware selectors", machineConfig: CreateTinkerbellMachineConfig(func(mc *TinkerbellMachineConfig) { mc.Spec.HardwareSelector["type2"] = "cp2" }), expectedErr: "TinkerbellMachineConfig: spec.hardwareSelector must contain only 1 key-value pair", }, { name: "Empty OS family", machineConfig: CreateTinkerbellMachineConfig(func(mc *TinkerbellMachineConfig) { mc.Spec.OSFamily = "" }), expectedErr: "TinkerbellMachineConfig: missing spec.osFamily", }, { name: "Invalid OS family", machineConfig: CreateTinkerbellMachineConfig(func(mc *TinkerbellMachineConfig) { mc.Spec.OSFamily = "invalid OS" }), expectedErr: "unsupported spec.osFamily (invalid OS); Please use one of the following", }, { name: "Invalid hostOSConfiguration", machineConfig: CreateTinkerbellMachineConfig( withHostOSConfiguration( &HostOSConfiguration{ NTPConfiguration: &NTPConfiguration{}, }, ), ), expectedErr: "HostOSConfiguration is invalid for TinkerbellMachineConfig tinkerbellmachineconfig: NTPConfiguration.Servers can not be empty", }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { g := NewWithT(t) g.Expect(tc.machineConfig.Validate()).To(MatchError(ContainSubstring(tc.expectedErr))) }) } } type tinkerbellMachineConfigOpt func(mc *TinkerbellMachineConfig) func withHostOSConfiguration(config *HostOSConfiguration) tinkerbellMachineConfigOpt { return func(mc *TinkerbellMachineConfig) { mc.Spec.HostOSConfiguration = config } } func CreateTinkerbellMachineConfig(options ...tinkerbellMachineConfigOpt) *TinkerbellMachineConfig { defaultMachineConfig := &TinkerbellMachineConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "tinkerbellmachineconfig", }, Spec: TinkerbellMachineConfigSpec{ HardwareSelector: map[string]string{ "type1": "cp1", }, OSFamily: Ubuntu, Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, }, } for _, opt := range options { opt(defaultMachineConfig) } return defaultMachineConfig }
110
eks-anywhere
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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 v1alpha1 import ( "fmt" "reflect" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/klog/v2" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" ) // log is for logging in this package. var tinkerbellmachineconfiglog = logf.Log.WithName("tinkerbellmachineconfig-resource") // SetupWebhookWithManager sets up TinkerbellMachineConfig webhook to controller manager. func (r *TinkerbellMachineConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } //+kubebuilder:webhook:path=/mutate-anywhere-eks-amazonaws-com-v1alpha1-tinkerbellmachineconfig,mutating=true,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=tinkerbellmachineconfigs,verbs=create;update,versions=v1alpha1,name=mutation.tinkerbellmachineconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Defaulter = &TinkerbellMachineConfig{} // Default implements webhook.Defaulter so a webhook will be registered for the type. func (r *TinkerbellMachineConfig) Default() { tinkerbellmachineconfiglog.Info("Setting up Tinkerbell Machine Config defaults", klog.KObj(r)) r.SetDefaults() } // TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-anywhere-eks-amazonaws-com-v1alpha1-tinkerbellmachineconfig,mutating=false,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=tinkerbellmachineconfigs,verbs=create;update,versions=v1alpha1,name=validation.tinkerbellmachineconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Validator = &TinkerbellMachineConfig{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellMachineConfig) ValidateCreate() error { tinkerbellmachineconfiglog.Info("validate create", "name", r.Name) var allErrs field.ErrorList if err := r.Validate(); err != nil { allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), r.Spec, err.Error())) } if len(r.Spec.Users) > 0 { if len(r.Spec.Users[0].SshAuthorizedKeys) == 0 || r.Spec.Users[0].SshAuthorizedKeys[0] == "" { allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), r.Spec, fmt.Sprintf("TinkerbellMachineConfig: missing spec.Users[0].SshAuthorizedKeys: %s for user %s. Please specify a ssh authorized key", r.Name, r.Spec.Users[0]))) } } if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(ClusterKind).GroupKind(), r.Name, allErrs) } if r.IsReconcilePaused() { tinkerbellmachineconfiglog.Info("TinkerbellMachineConfig is paused, so allowing create", "name", r.Name) return nil } return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellMachineConfig) ValidateUpdate(old runtime.Object) error { tinkerbellmachineconfiglog.Info("validate update", "name", r.Name) oldTinkerbellMachineConfig, ok := old.(*TinkerbellMachineConfig) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a TinkerbellMachineConfig but got a %T", old)) } var allErrs field.ErrorList allErrs = append(allErrs, validateImmutableFieldsTinkerbellMachineConfig(r, oldTinkerbellMachineConfig)...) if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(TinkerbellMachineConfigKind).GroupKind(), r.Name, allErrs) } if err := r.Validate(); err != nil { allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), r.Spec, err.Error())) } if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(TinkerbellMachineConfigKind).GroupKind(), r.Name, allErrs) } return nil } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *TinkerbellMachineConfig) ValidateDelete() error { tinkerbellmachineconfiglog.Info("validate delete", "name", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil } func validateImmutableFieldsTinkerbellMachineConfig(new, old *TinkerbellMachineConfig) field.ErrorList { var allErrs field.ErrorList specPath := field.NewPath("spec") if new.Spec.OSFamily != old.Spec.OSFamily { allErrs = append(allErrs, field.Forbidden(specPath.Child("OSFamily"), "field is immutable")) } if len(new.Spec.Users) != len(old.Spec.Users) { allErrs = append(allErrs, field.Forbidden(specPath.Child("Users"), "field is immutable")) } if new.Spec.Users[0].Name != old.Spec.Users[0].Name { allErrs = append(allErrs, field.Forbidden(specPath.Child("Users[0].Name"), "field is immutable")) } if len(new.Spec.Users[0].SshAuthorizedKeys) != len(old.Spec.Users[0].SshAuthorizedKeys) { allErrs = append(allErrs, field.Forbidden(specPath.Child("Users[0].SshAuthorizedKeys"), "field is immutable")) } if len(new.Spec.Users[0].SshAuthorizedKeys) > 0 && (new.Spec.Users[0].SshAuthorizedKeys[0] != old.Spec.Users[0].SshAuthorizedKeys[0]) { allErrs = append(allErrs, field.Forbidden(specPath.Child("Users[0].SshAuthorizedKeys[0]"), "field is immutable")) } if !reflect.DeepEqual(new.Spec.HardwareSelector, old.Spec.HardwareSelector) { allErrs = append(allErrs, field.Forbidden(specPath.Child("HardwareSelector"), "field is immutable")) } return allErrs }
148
eks-anywhere
aws
Go
package v1alpha1_test import ( "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func TestTinkerbellMachineConfigValidateCreateSuccess(t *testing.T) { machineConfig := v1alpha1.CreateTinkerbellMachineConfig() g := NewWithT(t) g.Expect(machineConfig.ValidateCreate()).To(Succeed()) } func TestTinkerbellMachineConfigValidateCreateFail(t *testing.T) { machineConfig := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.HardwareSelector = nil }) g := NewWithT(t) g.Expect(machineConfig.ValidateCreate()).To(MatchError(ContainSubstring("TinkerbellMachineConfig: missing spec.hardwareSelector: tinkerbellmachineconfig"))) } func TestTinkerbellMachineConfigValidateCreateFailNoUsers(t *testing.T) { machineConfig := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{} }) g := NewWithT(t) g.Expect(machineConfig.ValidateCreate()).To(MatchError(ContainSubstring("TinkerbellMachineConfig: missing spec.Users: tinkerbellmachineconfig"))) } func TestTinkerbellMachineConfigValidateCreateFailNoSSHkeys(t *testing.T) { machineConfig := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{ { Name: "test", }, } }) g := NewWithT(t) g.Expect(machineConfig.ValidateCreate()).To(MatchError(ContainSubstring("Please specify a ssh authorized key"))) } func TestTinkerbellMachineConfigValidateCreateFailEmptySSHkeys(t *testing.T) { machineConfig := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{}, }, } }) g := NewWithT(t) g.Expect(machineConfig.ValidateCreate()).To(MatchError(ContainSubstring("Please specify a ssh authorized key"))) } func TestTinkerbellMachineConfigValidateUpdateSucceed(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := machineConfigOld.DeepCopy() g := NewWithT(t) g.Expect(machineConfigNew.ValidateUpdate(machineConfigOld)).To(Succeed()) } func TestTinkerbellMachineConfigValidateUpdateFailOldMachineConfig(t *testing.T) { machineConfigOld := &v1alpha1.TinkerbellDatacenterConfig{} machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig() g := NewWithT(t) g.Expect(machineConfigNew.ValidateUpdate(machineConfigOld)).To(MatchError(ContainSubstring("expected a TinkerbellMachineConfig but got a *v1alpha1.TinkerbellDatacenterConfig"))) } func TestTinkerbellMachineConfigValidateUpdateFailOSFamily(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.OSFamily = v1alpha1.Bottlerocket }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("spec.OSFamily", err)) } func TestTinkerbellMachineConfigValidateUpdateFailLenSshAuthorizedKeys(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{}, }} }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("Users[0].SshAuthorizedKeys", err)) } func TestTinkerbellMachineConfigValidateUpdateFailSshAuthorizedKeys(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey1"}, }} }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("Users[0].SshAuthorizedKeys[0]", err)) } func TestTinkerbellMachineConfigValidateUpdateFailUsersLen(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{ { Name: "mySshUsername1", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }, { Name: "mySshUsername2", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }, } }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("Users", err)) } func TestTinkerbellMachineConfigDefaultOSFamily(t *testing.T) { mOld := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.OSFamily = "" }) mOld.Default() g := NewWithT(t) g.Expect(mOld.Spec.OSFamily).To(Equal(v1alpha1.Bottlerocket)) } func TestTinkerbellMachineConfigValidateUpdateFailUsers(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.Users = []v1alpha1.UserConfiguration{{ Name: "mySshUsername1", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }} }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("Users[0].Name", err)) } func TestTinkerbellMachineConfigValidateUpdateFailHardwareSelector(t *testing.T) { machineConfigOld := v1alpha1.CreateTinkerbellMachineConfig() machineConfigNew := v1alpha1.CreateTinkerbellMachineConfig(func(mc *v1alpha1.TinkerbellMachineConfig) { mc.Spec.HardwareSelector = map[string]string{ "type2": "cp2", } }) g := NewWithT(t) err := machineConfigNew.ValidateUpdate(machineConfigOld) g.Expect(err).NotTo(BeNil()) g.Expect(HaveField("HardwareSelector", err)) }
180
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "os" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" "github.com/aws/eks-anywhere/pkg/api/v1alpha1/thirdparty/tinkerbell" "github.com/aws/eks-anywhere/release/api/v1alpha1" ) const TinkerbellTemplateConfigKind = "TinkerbellTemplateConfig" // +kubebuilder:object:generate=false type ActionOpt func(action *[]tinkerbell.Action) // NewDefaultTinkerbellTemplateConfigCreate returns a default TinkerbellTemplateConfig with the // required Tasks and Actions. func NewDefaultTinkerbellTemplateConfigCreate(clusterSpec *Cluster, versionBundle v1alpha1.VersionsBundle, osImageOverride, tinkerbellLocalIP, tinkerbellLBIP string, osFamily OSFamily) *TinkerbellTemplateConfig { config := &TinkerbellTemplateConfig{ TypeMeta: metav1.TypeMeta{ Kind: TinkerbellTemplateConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: clusterSpec.Name, }, Spec: TinkerbellTemplateConfigSpec{ Template: tinkerbell.Workflow{ Version: "0.1", Name: clusterSpec.Name, GlobalTimeout: 6000, Tasks: []tinkerbell.Task{{ Name: clusterSpec.Name, WorkerAddr: "{{.device_1}}", Volumes: []string{ "/dev:/dev", "/dev/console:/dev/console", "/lib/firmware:/lib/firmware:ro", }, }}, }, }, } defaultActions := GetDefaultActionsFromBundle(clusterSpec, versionBundle, osImageOverride, tinkerbellLocalIP, tinkerbellLBIP, osFamily) for _, action := range defaultActions { action(&config.Spec.Template.Tasks[0].Actions) } return config } func (c *TinkerbellTemplateConfigGenerate) APIVersion() string { return c.TypeMeta.APIVersion } func (c *TinkerbellTemplateConfigGenerate) Kind() string { return c.TypeMeta.Kind } func (c *TinkerbellTemplateConfigGenerate) Name() string { return c.ObjectMeta.Name } func GetTinkerbellTemplateConfig(fileName string) (map[string]*TinkerbellTemplateConfig, error) { templates := make(map[string]*TinkerbellTemplateConfig) content, err := os.ReadFile(fileName) if err != nil { return nil, fmt.Errorf("unable to read file due to: %v", err) } for _, c := range strings.Split(string(content), YamlSeparator) { var template TinkerbellTemplateConfig if err := yaml.Unmarshal([]byte(c), &template); err != nil { return nil, fmt.Errorf("unable to unmarshall content from file due to: %v", err) } if template.Kind() == template.ExpectedKind() { if err = yaml.UnmarshalStrict([]byte(c), &template); err != nil { return nil, fmt.Errorf("invalid template config content: %v", err) } templates[template.Name] = &template } } return templates, nil }
90
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "strings" "github.com/aws/eks-anywhere/pkg/api/v1alpha1/thirdparty/tinkerbell" "github.com/aws/eks-anywhere/release/api/v1alpha1" ) const ( bottlerocketBootconfig = `kernel {}` cloudInit = `datasource: Ec2: metadata_urls: [%s] strict_id: false manage_etc_hosts: localhost warnings: dsid_missing_source: off ` ) // GetDefaultActionsFromBundle constructs a set of default actions for the given osFamily using the // bundle as the source of action images. func GetDefaultActionsFromBundle(clusterSpec *Cluster, b v1alpha1.VersionsBundle, osImageOverride, tinkerbellLocalIP, tinkerbellLBIP string, osFamily OSFamily) []ActionOpt { // The metadata string will have two URLs: // 1. one that will be used initially for bootstrap and will point to hegel running on kind. // 2. one that will be used when the workload cluster is up and will point to hegel running on // the workload cluster. metadataURLs := []string{ fmt.Sprintf("http://%s:50061", tinkerbellLocalIP), fmt.Sprintf("http://%s:50061", tinkerbellLBIP), } additionalEnvVar := make(map[string]string) if clusterSpec.Spec.ProxyConfiguration != nil { proxyConfig := clusterSpec.ProxyConfiguration() additionalEnvVar["HTTP_PROXY"] = proxyConfig["HTTP_PROXY"] additionalEnvVar["HTTPS_PROXY"] = proxyConfig["HTTPS_PROXY"] noProxy := fmt.Sprintf("%s,%s", tinkerbellLocalIP, tinkerbellLBIP) if proxyConfig["NO_PROXY"] != "" { noProxy = fmt.Sprintf("%s,%s", proxyConfig["NO_PROXY"], noProxy) } additionalEnvVar["NO_PROXY"] = noProxy } // During workflow reconciliation when the Tinkerbell template is rendered, the Workflow // Controller injects a subset of data from the Hardware resource. This lets us use Go template // language to render the disks enabling mix'n'match disk types for templates that represent // the same kind of machine such as control plane nodes. // // The devicePath disk index and the storagePartitionPath disk index should match. devicePath := "{{ index .Hardware.Disks 0 }}" paritionPathFmt := "{{ formatPartition ( index .Hardware.Disks 0 ) %s }}" actions := []ActionOpt{withStreamImageAction(b, devicePath, osImageOverride, additionalEnvVar)} switch osFamily { case Bottlerocket: partitionPath := fmt.Sprintf(paritionPathFmt, "12") actions = append(actions, withBottlerocketBootconfigAction(b, partitionPath), withBottlerocketUserDataAction(b, partitionPath, strings.Join(metadataURLs, ",")), // Order matters. This action needs to append to an existing user-data.toml file so // must be after withBottlerocketUserDataAction(). withNetplanAction(b, partitionPath, osFamily), withRebootAction(b), ) case RedHat: var mu []string for _, u := range metadataURLs { mu = append(mu, fmt.Sprintf("'%s'", u)) } partitionPath := fmt.Sprintf(paritionPathFmt, "1") actions = append(actions, withNetplanAction(b, partitionPath, osFamily), withDisableCloudInitNetworkCapabilities(b, partitionPath), withTinkCloudInitAction(b, partitionPath, strings.Join(mu, ",")), withDsCloudInitAction(b, partitionPath), withRebootAction(b), ) default: partitionPath := fmt.Sprintf(paritionPathFmt, "2") actions = append(actions, withNetplanAction(b, partitionPath, osFamily), withDisableCloudInitNetworkCapabilities(b, partitionPath), withTinkCloudInitAction(b, partitionPath, strings.Join(metadataURLs, ",")), withDsCloudInitAction(b, partitionPath), withRebootAction(b), ) } return actions } func withStreamImageAction(b v1alpha1.VersionsBundle, disk, osImageOverride string, additionalEnvVar map[string]string) ActionOpt { return func(a *[]tinkerbell.Action) { var imageURL string switch { case osImageOverride != "": imageURL = osImageOverride default: imageURL = b.EksD.Raw.Bottlerocket.URI } env := map[string]string{ "DEST_DISK": disk, "IMG_URL": imageURL, "COMPRESSED": "true", } for k, v := range additionalEnvVar { env[k] = v } *a = append(*a, tinkerbell.Action{ Name: "stream-image", Image: b.Tinkerbell.TinkerbellStack.Actions.ImageToDisk.URI, Timeout: 600, Environment: env, }) } } func withNetplanAction(b v1alpha1.VersionsBundle, disk string, osFamily OSFamily) ActionOpt { return func(a *[]tinkerbell.Action) { netplanAction := tinkerbell.Action{ Name: "write-netplan", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Environment: map[string]string{ "DEST_DISK": disk, "DEST_PATH": "/etc/netplan/config.yaml", "DIRMODE": "0755", "FS_TYPE": "ext4", "GID": "0", "MODE": "0644", "UID": "0", }, Pid: "host", } if osFamily == Bottlerocket { // Bottlerocket needs to write onto the 12th partition as opposed to 2nd for non-Bottlerocket OS netplanAction.Environment["DEST_PATH"] = "/net.toml" netplanAction.Environment["STATIC_BOTTLEROCKET"] = "true" netplanAction.Environment["IFNAME"] = "eno1" } else { netplanAction.Environment["STATIC_NETPLAN"] = "true" } *a = append(*a, netplanAction) } } func withDisableCloudInitNetworkCapabilities(b v1alpha1.VersionsBundle, disk string) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "disable-cloud-init-network-capabilities", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Environment: map[string]string{ "CONTENTS": "network: {config: disabled}", "DEST_DISK": disk, "DEST_PATH": "/etc/cloud/cloud.cfg.d/99-disable-network-config.cfg", "DIRMODE": "0700", "FS_TYPE": "ext4", "GID": "0", "MODE": "0600", "UID": "0", }, }) } } func withTinkCloudInitAction(b v1alpha1.VersionsBundle, disk string, metadataURLs string) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "add-tink-cloud-init-config", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Environment: map[string]string{ "DEST_DISK": disk, "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/cloud.cfg.d/10_tinkerbell.cfg", "CONTENTS": fmt.Sprintf(cloudInit, metadataURLs), "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }) } } func withDsCloudInitAction(b v1alpha1.VersionsBundle, disk string) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "add-tink-cloud-init-ds-config", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Environment: map[string]string{ "DEST_DISK": disk, "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/ds-identify.cfg", "CONTENTS": "datasource: Ec2\n", "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }) } } func withRebootAction(b v1alpha1.VersionsBundle) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "reboot-image", Image: b.Tinkerbell.TinkerbellStack.Actions.Reboot.URI, Timeout: 90, Pid: "host", Volumes: []string{"/worker:/worker"}, }) } } func withBottlerocketBootconfigAction(b v1alpha1.VersionsBundle, disk string) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "write-bootconfig", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": disk, "FS_TYPE": "ext4", "DEST_PATH": "/bootconfig.data", "BOOTCONFIG_CONTENTS": bottlerocketBootconfig, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }) } } func withBottlerocketUserDataAction(b v1alpha1.VersionsBundle, disk string, metadataURLs string) ActionOpt { return func(a *[]tinkerbell.Action) { *a = append(*a, tinkerbell.Action{ Name: "write-user-data", Image: b.Tinkerbell.TinkerbellStack.Actions.WriteFile.URI, Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": disk, "FS_TYPE": "ext4", "DEST_PATH": "/user-data.toml", "HEGEL_URLS": metadataURLs, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }) } }
276
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "testing" "github.com/google/go-cmp/cmp" "github.com/aws/eks-anywhere/pkg/api/v1alpha1/thirdparty/tinkerbell" "github.com/aws/eks-anywhere/release/api/v1alpha1" ) func TestWithDefaultActionsFromBundle(t *testing.T) { vBundle := givenVersionBundle() tinkerbellLocalIp := "127.0.0.1" tinkerbellLBIP := "1.2.3.4" metadataString := fmt.Sprintf("http://%s:50061,http://%s:50061", tinkerbellLocalIp, tinkerbellLBIP) rhelMetadataString := fmt.Sprintf("'http://%s:50061','http://%s:50061'", tinkerbellLocalIp, tinkerbellLBIP) cloudInit := `datasource: Ec2: metadata_urls: [%s] strict_id: false manage_etc_hosts: localhost warnings: dsid_missing_source: off ` tests := []struct { testName string osFamily OSFamily osImageOverride string clusterSpec *Cluster wantActions []tinkerbell.Action }{ { testName: "Bottlerocket-sda", osFamily: Bottlerocket, clusterSpec: &Cluster{}, wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/bottlerocket-2004-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", }, }, { Name: "write-bootconfig", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/bootconfig.data", "BOOTCONFIG_CONTENTS": bottlerocketBootconfig, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }, { Name: "write-user-data", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/user-data.toml", "HEGEL_URLS": metadataString, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/net.toml", "STATIC_BOTTLEROCKET": "true", "IFNAME": "eno1", "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0755", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Volumes: []string{"/worker:/worker"}, Pid: "host", }, }, }, { testName: "Bottlerocket-nvme", osFamily: Bottlerocket, clusterSpec: &Cluster{}, wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/bottlerocket-2004-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", }, }, { Name: "write-bootconfig", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/bootconfig.data", "BOOTCONFIG_CONTENTS": bottlerocketBootconfig, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }, { Name: "write-user-data", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/user-data.toml", "HEGEL_URLS": metadataString, "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0700", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Pid: "host", Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 12 }}", "FS_TYPE": "ext4", "DEST_PATH": "/net.toml", "STATIC_BOTTLEROCKET": "true", "IFNAME": "eno1", "UID": "0", "GID": "0", "MODE": "0644", "DIRMODE": "0755", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Volumes: []string{"/worker:/worker"}, Pid: "host", }, }, }, { testName: "RedHat-sda", osFamily: RedHat, clusterSpec: &Cluster{}, osImageOverride: "http://tinkerbell-example:8080/redhat-8.4-kube-v1.21.5.gz", wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/redhat-8.4-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 1 }}", "DEST_PATH": "/etc/netplan/config.yaml", "DIRMODE": "0755", "FS_TYPE": "ext4", "GID": "0", "MODE": "0644", "UID": "0", "STATIC_NETPLAN": "true", }, Pid: "host", }, { Name: "disable-cloud-init-network-capabilities", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "CONTENTS": "network: {config: disabled}", "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 1 }}", "DEST_PATH": "/etc/cloud/cloud.cfg.d/99-disable-network-config.cfg", "DIRMODE": "0700", "FS_TYPE": "ext4", "GID": "0", "MODE": "0600", "UID": "0", }, }, { Name: "add-tink-cloud-init-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 1 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/cloud.cfg.d/10_tinkerbell.cfg", "CONTENTS": fmt.Sprintf(cloudInit, rhelMetadataString), "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "add-tink-cloud-init-ds-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 1 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/ds-identify.cfg", "CONTENTS": "datasource: Ec2\n", "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Pid: "host", Volumes: []string{"/worker:/worker"}, }, }, }, { testName: "Ubuntu-sda", osFamily: Ubuntu, clusterSpec: &Cluster{}, osImageOverride: "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/netplan/config.yaml", "DIRMODE": "0755", "FS_TYPE": "ext4", "GID": "0", "MODE": "0644", "UID": "0", "STATIC_NETPLAN": "true", }, Pid: "host", }, { Name: "disable-cloud-init-network-capabilities", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "CONTENTS": "network: {config: disabled}", "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/cloud/cloud.cfg.d/99-disable-network-config.cfg", "DIRMODE": "0700", "FS_TYPE": "ext4", "GID": "0", "MODE": "0600", "UID": "0", }, }, { Name: "add-tink-cloud-init-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/cloud.cfg.d/10_tinkerbell.cfg", "CONTENTS": fmt.Sprintf(cloudInit, metadataString), "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "add-tink-cloud-init-ds-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/ds-identify.cfg", "CONTENTS": "datasource: Ec2\n", "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Pid: "host", Volumes: []string{"/worker:/worker"}, }, }, }, { testName: "Ubuntu-nvme", osFamily: Ubuntu, clusterSpec: &Cluster{}, osImageOverride: "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/netplan/config.yaml", "DIRMODE": "0755", "FS_TYPE": "ext4", "GID": "0", "MODE": "0644", "UID": "0", "STATIC_NETPLAN": "true", }, Pid: "host", }, { Name: "disable-cloud-init-network-capabilities", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "CONTENTS": "network: {config: disabled}", "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/cloud/cloud.cfg.d/99-disable-network-config.cfg", "DIRMODE": "0700", "FS_TYPE": "ext4", "GID": "0", "MODE": "0600", "UID": "0", }, }, { Name: "add-tink-cloud-init-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/cloud.cfg.d/10_tinkerbell.cfg", "CONTENTS": fmt.Sprintf(cloudInit, metadataString), "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "add-tink-cloud-init-ds-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/ds-identify.cfg", "CONTENTS": "datasource: Ec2\n", "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Pid: "host", Volumes: []string{"/worker:/worker"}, }, }, }, { testName: "Ubuntu-sda-with-proxy", osFamily: Ubuntu, clusterSpec: &Cluster{ Spec: ClusterSpec{ ControlPlaneConfiguration: ControlPlaneConfiguration{ Endpoint: &Endpoint{ Host: "1.2.3.4", }, }, ProxyConfiguration: &ProxyConfiguration{ HttpProxy: "2.3.4.5:3128", HttpsProxy: "2.3.4.5:3128", }, }, }, osImageOverride: "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", wantActions: []tinkerbell.Action{ { Name: "stream-image", Image: "public.ecr.aws/eks-anywhere/image2disk:latest", Timeout: 600, Environment: map[string]string{ "IMG_URL": "http://tinkerbell-example:8080/ubuntu-kube-v1.21.5.gz", "DEST_DISK": "{{ index .Hardware.Disks 0 }}", "COMPRESSED": "true", "HTTPS_PROXY": "2.3.4.5:3128", "HTTP_PROXY": "2.3.4.5:3128", "NO_PROXY": "1.2.3.4,127.0.0.1,1.2.3.4", }, }, { Name: "write-netplan", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/netplan/config.yaml", "DIRMODE": "0755", "FS_TYPE": "ext4", "GID": "0", "MODE": "0644", "UID": "0", "STATIC_NETPLAN": "true", }, Pid: "host", }, { Name: "disable-cloud-init-network-capabilities", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "CONTENTS": "network: {config: disabled}", "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "DEST_PATH": "/etc/cloud/cloud.cfg.d/99-disable-network-config.cfg", "DIRMODE": "0700", "FS_TYPE": "ext4", "GID": "0", "MODE": "0600", "UID": "0", }, }, { Name: "add-tink-cloud-init-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/cloud.cfg.d/10_tinkerbell.cfg", "CONTENTS": fmt.Sprintf(cloudInit, metadataString), "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "add-tink-cloud-init-ds-config", Image: "public.ecr.aws/eks-anywhere/writefile:latest", Timeout: 90, Environment: map[string]string{ "DEST_DISK": "{{ formatPartition ( index .Hardware.Disks 0 ) 2 }}", "FS_TYPE": "ext4", "DEST_PATH": "/etc/cloud/ds-identify.cfg", "CONTENTS": "datasource: Ec2\n", "UID": "0", "GID": "0", "MODE": "0600", "DIRMODE": "0700", }, }, { Name: "reboot-image", Image: "public.ecr.aws/eks-anywhere/reboot:latest", Timeout: 90, Pid: "host", Volumes: []string{"/worker:/worker"}, }, }, }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { givenActions := []tinkerbell.Action{} opts := GetDefaultActionsFromBundle(tt.clusterSpec, vBundle, tt.osImageOverride, tinkerbellLocalIp, tinkerbellLBIP, tt.osFamily) for _, opt := range opts { opt(&givenActions) } if diff := cmp.Diff(givenActions, tt.wantActions); diff != "" { t.Fatalf("Expected file mismatch (-want +got):\n%s", diff) } }) } } func givenVersionBundle() v1alpha1.VersionsBundle { return v1alpha1.VersionsBundle{ EksD: v1alpha1.EksDRelease{ Raw: v1alpha1.OSImageBundle{ Bottlerocket: v1alpha1.Archive{ URI: "http://tinkerbell-example:8080/bottlerocket-2004-kube-v1.21.5.gz", }, }, }, Tinkerbell: v1alpha1.TinkerbellBundle{ TinkerbellStack: v1alpha1.TinkerbellStackBundle{ Actions: v1alpha1.ActionsBundle{ ImageToDisk: v1alpha1.Image{ URI: "public.ecr.aws/eks-anywhere/image2disk:latest", }, WriteFile: v1alpha1.Image{ URI: "public.ecr.aws/eks-anywhere/writefile:latest", }, Kexec: v1alpha1.Image{ URI: "public.ecr.aws/eks-anywhere/kexec:latest", }, Reboot: v1alpha1.Image{ URI: "public.ecr.aws/eks-anywhere/reboot:latest", }, }, }, }, } }
584
eks-anywhere
aws
Go
package v1alpha1 import ( "testing" "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/api/v1alpha1/thirdparty/tinkerbell" ) func TestGetTinkerbellTemplateConfig(t *testing.T) { tests := []struct { testName string fileName string wantConfigs map[string]*TinkerbellTemplateConfig wantErr bool }{ { testName: "file doesn't exist", fileName: "testdata/fake_file.yaml", wantConfigs: nil, wantErr: true, }, { testName: "not parseable file", fileName: "testdata/not_parseable_cluster_tinkerbell.yaml", wantConfigs: nil, wantErr: true, }, { testName: "valid tinkerbell template config", fileName: "testdata/cluster_1_21_valid_tinkerbell.yaml", wantConfigs: map[string]*TinkerbellTemplateConfig{ "tink-test": { TypeMeta: metav1.TypeMeta{ Kind: TinkerbellTemplateConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "tink-test", }, Spec: TinkerbellTemplateConfigSpec{ Template: tinkerbell.Workflow{ Version: "0.1", Name: "tink-test", GlobalTimeout: 6000, ID: "", Tasks: []tinkerbell.Task{ { Name: "tink-test", WorkerAddr: "{{.device_1}}", Volumes: []string{ "/dev:/dev", "/dev/console:/dev/console", "/lib/firmware:/lib/firmware:ro", }, Actions: []tinkerbell.Action{ { Name: "stream-image", Image: "image2disk:v1.0.0", Timeout: 600, Environment: map[string]string{ "IMG_URL": "", "DEST_DISK": "/dev/sda", "COMPRESSED": "true", }, }, }, }, }, }, }, }, }, wantErr: false, }, { testName: "multiple tinkerbell template configs", fileName: "testdata/cluster_1_21_valid_multiple_tinkerbell_templates.yaml", wantConfigs: map[string]*TinkerbellTemplateConfig{ "tink-test-1": { TypeMeta: metav1.TypeMeta{ Kind: TinkerbellTemplateConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "tink-test-1", }, Spec: TinkerbellTemplateConfigSpec{ Template: tinkerbell.Workflow{ Version: "0.1", Name: "tink-test-1", GlobalTimeout: 6000, ID: "", Tasks: []tinkerbell.Task{ { Name: "tink-test-1", WorkerAddr: "{{.device_1}}", Volumes: []string{ "/dev:/dev", "/dev/console:/dev/console", "/lib/firmware:/lib/firmware:ro", }, Actions: []tinkerbell.Action{ { Name: "stream-image", Image: "image2disk:v1.0.0", Timeout: 600, Environment: map[string]string{ "IMG_URL": "", "DEST_DISK": "/dev/sda", "COMPRESSED": "true", }, }, }, }, }, }, }, }, "tink-test-2": { TypeMeta: metav1.TypeMeta{ Kind: TinkerbellTemplateConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "tink-test-2", }, Spec: TinkerbellTemplateConfigSpec{ Template: tinkerbell.Workflow{ Version: "0.1", Name: "tink-test-2", GlobalTimeout: 6000, ID: "", Tasks: []tinkerbell.Task{ { Name: "tink-test-2", WorkerAddr: "{{.device_1}}", Volumes: []string{ "/dev:/dev", "/dev/console:/dev/console", "/lib/firmware:/lib/firmware:ro", }, Actions: []tinkerbell.Action{ { Name: "stream-image", Image: "image2disk:v1.0.0", Timeout: 600, Environment: map[string]string{ "IMG_URL": "", "DEST_DISK": "/dev/sda", "COMPRESSED": "true", }, }, }, }, }, }, }, }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { g := gomega.NewWithT(t) got, err := GetTinkerbellTemplateConfig(tt.fileName) g.Expect((err != nil)).To(gomega.BeEquivalentTo(tt.wantErr)) g.Expect(got).To(gomega.BeEquivalentTo(tt.wantConfigs)) }) } }
175
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" "github.com/aws/eks-anywhere/pkg/api/v1alpha1/thirdparty/tinkerbell" ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // Important: Run "make generate" to regenerate code after modifying this file // TinkerbellTemplateConfigSpec defines the desired state of TinkerbellTemplateConfig. type TinkerbellTemplateConfigSpec struct { // Template defines a Tinkerbell workflow template with specific tasks and actions. Template tinkerbell.Workflow `json:"template"` } // TinkerbellTemplateConfigStatus defines the observed state of TinkerbellTemplateConfig. type TinkerbellTemplateConfigStatus struct{} //+kubebuilder:object:root=true //+kubebuilder:subresource:status // TinkerbellTemplateConfig is the Schema for the TinkerbellTemplateConfigs API. type TinkerbellTemplateConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec TinkerbellTemplateConfigSpec `json:"spec,omitempty"` Status TinkerbellTemplateConfigStatus `json:"status,omitempty"` } func (t *TinkerbellTemplateConfig) Kind() string { return t.TypeMeta.Kind } func (t *TinkerbellTemplateConfig) ExpectedKind() string { return TinkerbellTemplateConfigKind } func (t *TinkerbellTemplateConfig) ToTemplateString() (string, error) { b, err := yaml.Marshal(&t.Spec.Template) if err != nil { return "", fmt.Errorf("failed to convert TinkerbellTemplateConfig.Spec.Template to string: %v", err) } return string(b), nil } func (c *TinkerbellTemplateConfig) ConvertConfigToConfigGenerateStruct() *TinkerbellTemplateConfigGenerate { namespace := defaultEksaNamespace if c.Namespace != "" { namespace = c.Namespace } config := &TinkerbellTemplateConfigGenerate{ TypeMeta: c.TypeMeta, ObjectMeta: ObjectMeta{ Name: c.Name, Annotations: c.Annotations, Namespace: namespace, }, Spec: c.Spec, } return config } // +kubebuilder:object:generate=false // Same as TinkerbellTemplateConfig except stripped down for generation of yaml file during generate clusterconfig. type TinkerbellTemplateConfigGenerate struct { metav1.TypeMeta `json:",inline"` ObjectMeta `json:"metadata,omitempty"` Spec TinkerbellTemplateConfigSpec `json:"spec,omitempty"` } //+kubebuilder:object:root=true // TinkerbellTemplateConfigList contains a list of TinkerbellTemplateConfig. type TinkerbellTemplateConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []TinkerbellTemplateConfig `json:"items"` } func init() { SchemeBuilder.Register(&TinkerbellTemplateConfig{}, &TinkerbellTemplateConfigList{}) }
92
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "k8s.io/apimachinery/pkg/util/version" ) // SupportedMinorVersionIncrement represents the minor version skew for kubernetes version upgrades. const SupportedMinorVersionIncrement = 1 // ValidateVersionSkew validates Kubernetes version skew between valid non-nil versions. func ValidateVersionSkew(oldVersion, newVersion *version.Version) error { if newVersion.LessThan(oldVersion) { return fmt.Errorf("kubernetes version downgrade is not supported (%s) -> (%s)", oldVersion, newVersion) } newVersionMinor := newVersion.Minor() oldVersionMinor := oldVersion.Minor() minorVersionDifference := int(newVersionMinor) - int(oldVersionMinor) if minorVersionDifference < 0 || minorVersionDifference > SupportedMinorVersionIncrement { return fmt.Errorf("only +%d minor version skew is supported, minor version skew detected %v", SupportedMinorVersionIncrement, minorVersionDifference) } return nil }
29
eks-anywhere
aws
Go
package v1alpha1_test import ( "fmt" "reflect" "testing" "k8s.io/apimachinery/pkg/util/version" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func TestValidateVersionSkew(t *testing.T) { v122, _ := version.ParseGeneric(string(v1alpha1.Kube122)) v123, _ := version.ParseGeneric(string(v1alpha1.Kube123)) v124, _ := version.ParseGeneric(string(v1alpha1.Kube124)) tests := []struct { name string oldVersion *version.Version newVersion *version.Version wantErr error }{ { name: "No upgrade", oldVersion: v122, newVersion: v122, wantErr: nil, }, { name: "Minor version increment success", oldVersion: v122, newVersion: v123, wantErr: nil, }, { name: "Minor version invalid, failure", oldVersion: v122, newVersion: v124, wantErr: fmt.Errorf("only +%d minor version skew is supported, minor version skew detected 2", v1alpha1.SupportedMinorVersionIncrement), }, { name: "Minor version downgrade, failure", oldVersion: v124, newVersion: v123, wantErr: fmt.Errorf("kubernetes version downgrade is not supported (%s) -> (%s)", v124, v123), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := v1alpha1.ValidateVersionSkew(tt.oldVersion, tt.newVersion) if err != nil && !reflect.DeepEqual(err.Error(), tt.wantErr.Error()) { t.Errorf("ValidateVersionSkew() error = %v, wantErr = %v", err, tt.wantErr) } }) } }
58
eks-anywhere
aws
Go
package v1alpha1 // +kubebuilder:validation:Enum=fullClone;linkedClone // CloneMode describes the clone mode to be used when cloning vSphere VMs. type CloneMode string const ( // FullClone indicates a VM will have no relationship to the source of the // clone operation once the operation is complete. This is the safest clone // mode, but it is not the fastest. FullClone CloneMode = "fullClone" // LinkedClone means resulting VMs will be dependent upon the snapshot of // the source VM/template from which the VM was cloned. This is the fastest // clone mode, but it also prevents expanding a VMs disk beyond the size of // the source VM/template. LinkedClone CloneMode = "linkedClone" )
20
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "path/filepath" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/logger" ) const VSphereDatacenterKind = "VSphereDatacenterConfig" type folderType string const ( networkFolderType folderType = "network" ) // Used for generating yaml for generate clusterconfig command. func NewVSphereDatacenterConfigGenerate(clusterName string) *VSphereDatacenterConfigGenerate { return &VSphereDatacenterConfigGenerate{ TypeMeta: metav1.TypeMeta{ Kind: VSphereDatacenterKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: ObjectMeta{ Name: clusterName, }, Spec: VSphereDatacenterConfigSpec{}, } } func (c *VSphereDatacenterConfigGenerate) APIVersion() string { return c.TypeMeta.APIVersion } func (c *VSphereDatacenterConfigGenerate) Kind() string { return c.TypeMeta.Kind } func (c *VSphereDatacenterConfigGenerate) Name() string { return c.ObjectMeta.Name } func GetVSphereDatacenterConfig(fileName string) (*VSphereDatacenterConfig, error) { var clusterConfig VSphereDatacenterConfig err := ParseClusterConfig(fileName, &clusterConfig) if err != nil { return nil, err } return &clusterConfig, nil } func generateFullVCenterPath(foldType folderType, folderPath string, datacenter string) string { if folderPath == "" { return folderPath } prefix := fmt.Sprintf("/%s", datacenter) modPath := folderPath if !strings.HasPrefix(folderPath, prefix) { modPath = fmt.Sprintf("%s/%s/%s", prefix, foldType, folderPath) logger.V(4).Info(fmt.Sprintf("Relative %s path specified, using path %s", foldType, modPath)) return modPath } return modPath } func validatePath(foldType folderType, folderPath string, datacenter string) error { prefix := filepath.Join(fmt.Sprintf("/%s", datacenter), string(foldType)) if !strings.HasPrefix(folderPath, prefix) { return fmt.Errorf("invalid path, expected path [%s] to be under [%s]", folderPath, prefix) } return nil }
80
eks-anywhere
aws
Go
package v1alpha1 import ( "reflect" "testing" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestGetVSphereDatacenterConfig(t *testing.T) { tests := []struct { testName string fileName string wantVSphereDatacenter *VSphereDatacenterConfig wantErr bool }{ { testName: "file doesn't exist", fileName: "testdata/fake_file.yaml", wantVSphereDatacenter: nil, wantErr: true, }, { testName: "not parseable file", fileName: "testdata/not_parseable_cluster.yaml", wantVSphereDatacenter: nil, wantErr: true, }, { testName: "valid 1.18", fileName: "testdata/cluster_1_18.yaml", wantVSphereDatacenter: &VSphereDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: VSphereDatacenterKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereDatacenterConfigSpec{ Datacenter: "myDatacenter", Network: "myNetwork", Server: "myServer", Thumbprint: "myTlsThumbprint", Insecure: false, }, }, wantErr: false, }, { testName: "valid 1.19", fileName: "testdata/cluster_1_19.yaml", wantVSphereDatacenter: &VSphereDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: VSphereDatacenterKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereDatacenterConfigSpec{ Datacenter: "myDatacenter", Network: "myNetwork", Server: "myServer", Thumbprint: "myTlsThumbprint", Insecure: false, }, }, wantErr: false, }, { testName: "valid with extra delimiters", fileName: "testdata/cluster_extra_delimiters.yaml", wantVSphereDatacenter: &VSphereDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: VSphereDatacenterKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereDatacenterConfigSpec{ Datacenter: "myDatacenter", Network: "myNetwork", Server: "myServer", Thumbprint: "myTlsThumbprint", Insecure: false, }, }, wantErr: false, }, { testName: "valid 1.20", fileName: "testdata/cluster_1_20.yaml", wantVSphereDatacenter: &VSphereDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: VSphereDatacenterKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereDatacenterConfigSpec{ Datacenter: "myDatacenter", Network: "myNetwork", Server: "myServer", Thumbprint: "myTlsThumbprint", Insecure: false, }, }, wantErr: false, }, { testName: "invalid kind", fileName: "testdata/cluster_invalid_kinds.yaml", wantVSphereDatacenter: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { got, err := GetVSphereDatacenterConfig(tt.fileName) if (err != nil) != tt.wantErr { t.Fatalf("GetVSphereDatacenterConfig() error = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.wantVSphereDatacenter) { t.Fatalf("GetVSphereDatacenterConfig() = %#v, want %#v", got, tt.wantVSphereDatacenter) } }) } }
132
eks-anywhere
aws
Go
package v1alpha1 import ( "errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/logger" ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // VSphereDatacenterConfigSpec defines the desired state of VSphereDatacenterConfig. type VSphereDatacenterConfigSpec struct { // Important: Run "make generate" to regenerate code after modifying this file Datacenter string `json:"datacenter"` Network string `json:"network"` Server string `json:"server"` Thumbprint string `json:"thumbprint"` Insecure bool `json:"insecure"` } // VSphereDatacenterConfigStatus defines the observed state of VSphereDatacenterConfig. type VSphereDatacenterConfigStatus struct { // Important: Run "make generate" to regenerate code after modifying this file // SpecValid is set to true if vspheredatacenterconfig is validated. SpecValid bool `json:"specValid,omitempty"` // ObservedGeneration is the latest generation observed by the controller. ObservedGeneration int64 `json:"observedGeneration,omitempty"` // FailureMessage indicates that there is a fatal problem reconciling the // state, and will be set to a descriptive error message. FailureMessage *string `json:"failureMessage,omitempty"` } //+kubebuilder:object:root=true //+kubebuilder:subresource:status // VSphereDatacenterConfig is the Schema for the VSphereDatacenterConfigs API. type VSphereDatacenterConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec VSphereDatacenterConfigSpec `json:"spec,omitempty"` Status VSphereDatacenterConfigStatus `json:"status,omitempty"` } func (v *VSphereDatacenterConfig) Kind() string { return v.TypeMeta.Kind } func (v *VSphereDatacenterConfig) ExpectedKind() string { return VSphereDatacenterKind } func (v *VSphereDatacenterConfig) PauseReconcile() { if v.Annotations == nil { v.Annotations = map[string]string{} } v.Annotations[pausedAnnotation] = "true" } func (v *VSphereDatacenterConfig) IsReconcilePaused() bool { if s, ok := v.Annotations[pausedAnnotation]; ok { return s == "true" } return false } func (v *VSphereDatacenterConfig) ClearPauseAnnotation() { if v.Annotations != nil { delete(v.Annotations, pausedAnnotation) } } func (v *VSphereDatacenterConfig) SetDefaults() { v.Spec.Network = generateFullVCenterPath(networkFolderType, v.Spec.Network, v.Spec.Datacenter) if v.Spec.Insecure { logger.Info("Warning: VSphereDatacenterConfig configured in insecure mode") v.Spec.Thumbprint = "" } } func (v *VSphereDatacenterConfig) Validate() error { if len(v.Spec.Server) <= 0 { return errors.New("VSphereDatacenterConfig server is not set or is empty") } if len(v.Spec.Datacenter) <= 0 { return errors.New("VSphereDatacenterConfig datacenter is not set or is empty") } if len(v.Spec.Network) <= 0 { return errors.New("VSphereDatacenterConfig VM network is not set or is empty") } if err := validatePath(networkFolderType, v.Spec.Network, v.Spec.Datacenter); err != nil { return err } return nil } func (v *VSphereDatacenterConfig) ConvertConfigToConfigGenerateStruct() *VSphereDatacenterConfigGenerate { namespace := defaultEksaNamespace if v.Namespace != "" { namespace = v.Namespace } config := &VSphereDatacenterConfigGenerate{ TypeMeta: v.TypeMeta, ObjectMeta: ObjectMeta{ Name: v.Name, Annotations: v.Annotations, Namespace: namespace, }, Spec: v.Spec, } return config } func (v *VSphereDatacenterConfig) Marshallable() Marshallable { return v.ConvertConfigToConfigGenerateStruct() } // +kubebuilder:object:generate=false // Same as VSphereDatacenterConfig except stripped down for generation of yaml file during generate clusterconfig. type VSphereDatacenterConfigGenerate struct { metav1.TypeMeta `json:",inline"` ObjectMeta `json:"metadata,omitempty"` Spec VSphereDatacenterConfigSpec `json:"spec,omitempty"` } //+kubebuilder:object:root=true // VSphereDatacenterConfigList contains a list of VSphereDatacenterConfig. type VSphereDatacenterConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []VSphereDatacenterConfig `json:"items"` } func init() { SchemeBuilder.Register(&VSphereDatacenterConfig{}, &VSphereDatacenterConfigList{}) }
150
eks-anywhere
aws
Go
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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 v1alpha1 import ( "fmt" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" ) // log is for logging in this package. var vspheredatacenterconfiglog = logf.Log.WithName("vspheredatacenterconfig-resource") func (r *VSphereDatacenterConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! //+kubebuilder:webhook:path=/mutate-anywhere-eks-amazonaws-com-v1alpha1-vspheredatacenterconfig,mutating=true,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=vspheredatacenterconfigs,verbs=create;update,versions=v1alpha1,name=mutation.vspheredatacenterconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Defaulter = &VSphereDatacenterConfig{} // Default implements webhook.Defaulter so a webhook will be registered for the type. func (r *VSphereDatacenterConfig) Default() { vspheredatacenterconfiglog.Info("Setting up VSphere Datacenter Config defaults for", "name", r.Name) r.SetDefaults() } // change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-anywhere-eks-amazonaws-com-v1alpha1-vspheredatacenterconfig,mutating=false,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=vspheredatacenterconfigs,verbs=create;update,versions=v1alpha1,name=validation.vspheredatacenterconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Validator = &VSphereDatacenterConfig{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereDatacenterConfig) ValidateCreate() error { vspheredatacenterconfiglog.Info("validate create", "name", r.Name) if err := r.Validate(); err != nil { return apierrors.NewInvalid( GroupVersion.WithKind(VSphereDatacenterKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec"), r.Spec, err.Error()), }, ) } if r.IsReconcilePaused() { vspheredatacenterconfiglog.Info("VSphereDatacenterConfig is paused, so allowing create", "name", r.Name) return nil } return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereDatacenterConfig) ValidateUpdate(old runtime.Object) error { vspheredatacenterconfiglog.Info("validate update", "name", r.Name) oldDatacenterConfig, ok := old.(*VSphereDatacenterConfig) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a VSphereDataCenterConfig but got a %T", old)) } if err := r.Validate(); err != nil { return apierrors.NewInvalid( GroupVersion.WithKind(VSphereDatacenterKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec"), r.Spec, err.Error()), }, ) } if oldDatacenterConfig.IsReconcilePaused() { vspheredatacenterconfiglog.Info("Reconciliation is paused") return nil } r.SetDefaults() if allErrs := validateImmutableFieldsVSphereCluster(r, oldDatacenterConfig); len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereDatacenterKind).GroupKind(), r.Name, allErrs) } return nil } func validateImmutableFieldsVSphereCluster(new, old *VSphereDatacenterConfig) field.ErrorList { var allErrs field.ErrorList specPath := field.NewPath("spec") if old.Spec.Server != new.Spec.Server { allErrs = append( allErrs, field.Forbidden(specPath.Child("server"), "field is immutable"), ) } if old.Spec.Datacenter != new.Spec.Datacenter { allErrs = append( allErrs, field.Forbidden(specPath.Child("datacenter"), "field is immutable"), ) } if old.Spec.Network != new.Spec.Network { allErrs = append( allErrs, field.Forbidden(specPath.Child("network"), "field is immutable"), ) } if old.Spec.Insecure != new.Spec.Insecure { allErrs = append( allErrs, field.Forbidden(specPath.Child("insecure"), "field is immutable"), ) } if old.Spec.Thumbprint != new.Spec.Thumbprint { allErrs = append( allErrs, field.Forbidden(specPath.Child("thumbprint"), "field is immutable"), ) } return allErrs } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereDatacenterConfig) ValidateDelete() error { vspheredatacenterconfiglog.Info("validate delete", "name", r.Name) // TODO(user): fill in your validation logic upon object deletion. return nil }
158
eks-anywhere
aws
Go
package v1alpha1_test import ( "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func TestVSphereDatacenterValidateUpdateServerImmutable(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Server = "https://realOldServer.realOldDatacenter.com" c := vOld.DeepCopy() c.Spec.Server = "https://newFancyServer.newFancyCloud.io" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.server: Forbidden: field is immutable"))) } func TestVSphereDatacenterValidateUpdateDataCenterImmutable(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Datacenter = "oldCruftyDatacenter" c := vOld.DeepCopy() c.Spec.Datacenter = "/shinyNewDatacenter" c.Spec.Network = "/shinyNewDatacenter/network" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.datacenter: Forbidden: field is immutable"))) } func TestVSphereDatacenterValidateUpdateNetworkImmutable(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Network = "OldNet" c := vOld.DeepCopy() c.Spec.Network = "/datacenter/network" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.network: Forbidden: field is immutable"))) } func TestVSphereDatacenterValidateUpdateTLSInsecureImmutable(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Insecure = true c := vOld.DeepCopy() c.Spec.Insecure = false g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.insecure: Forbidden: field is immutable"))) } func TestVSphereDatacenterValidateUpdateTlsThumbprintImmutable(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Thumbprint = "5334E1D85B267B78F99BAF553FEB2F94E72EFDFD" c := vOld.DeepCopy() c.Spec.Thumbprint = "B3D1C464976E725E599D3548180CB56311818F224E701F9D56F22E8079A7B396" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.thumbprint: Forbidden: field is immutable"))) } func TestVSphereDatacenterValidateUpdateWithPausedAnnotation(t *testing.T) { vOld := vsphereDatacenterConfig() vOld.Spec.Network = "/datacenter/oldNetwork" c := vOld.DeepCopy() c.Spec.Network = "/datacenter/network/newNetwork" vOld.PauseReconcile() g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereDatacenterValidateUpdateInvalidType(t *testing.T) { vOld := &v1alpha1.Cluster{} c := &v1alpha1.VSphereDatacenterConfig{} g := NewWithT(t) g.Expect(c.ValidateUpdate(vOld)).To(MatchError(ContainSubstring("expected a VSphereDataCenterConfig but got a *v1alpha1.Cluster"))) } func TestVSphereDatacenterValidateUpdateInvalidServer(t *testing.T) { vOld := vsphereDatacenterConfig() c := vOld.DeepCopy() vOld.Spec.Server = "" c.Spec.Server = "" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("VSphereDatacenterConfig server is not set or is empty"))) } func TestVSphereDatacenterValidateUpdateInvalidDatacenter(t *testing.T) { vOld := vsphereDatacenterConfig() c := vOld.DeepCopy() vOld.Spec.Datacenter = "" c.Spec.Datacenter = "" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("VSphereDatacenterConfig datacenter is not set or is empty"))) } func TestVSphereDatacenterValidateUpdateInvalidNetwork(t *testing.T) { vOld := vsphereDatacenterConfig() c := vOld.DeepCopy() vOld.Spec.Network = "" c.Spec.Network = "" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("VSphereDatacenterConfig VM network is not set or is empty"))) } func TestVSphereDatacenterConfigSetDefaults(t *testing.T) { g := NewWithT(t) sOld := vsphereDatacenterConfig() sOld.Spec.Network = "network-1" sOld.Default() g.Expect(sOld.Spec.Network).To(Equal("/datacenter/network/network-1")) } func vsphereDatacenterConfig() v1alpha1.VSphereDatacenterConfig { return v1alpha1.VSphereDatacenterConfig{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{Annotations: make(map[string]string, 1)}, Spec: v1alpha1.VSphereDatacenterConfigSpec{ Datacenter: "datacenter", Network: "/datacenter/network-1", Server: "vcenter.com", Insecure: false, Thumbprint: "abc", }, Status: v1alpha1.VSphereDatacenterConfigStatus{}, } } func TestVSphereDatacenterValidateCreateFullManagementCycleOn(t *testing.T) { t.Setenv("FULL_LIFECYCLE_API", "true") dataCenterConfig := vsphereDatacenterConfig() g := NewWithT(t) g.Expect(dataCenterConfig.ValidateCreate()).To(Succeed()) } func TestVSphereDatacenterValidateCreate(t *testing.T) { dataCenterConfig := vsphereDatacenterConfig() g := NewWithT(t) g.Expect(dataCenterConfig.ValidateCreate()).To(Succeed()) } func TestVSphereDatacenterValidateCreateFail(t *testing.T) { dataCenterConfig := vsphereDatacenterConfig() dataCenterConfig.Spec.Datacenter = "" g := NewWithT(t) g.Expect(dataCenterConfig.ValidateCreate()).To(MatchError(ContainSubstring("VSphereDatacenterConfig datacenter is not set or is empty"))) }
162
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "os" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" "github.com/aws/eks-anywhere/pkg/logger" ) const ( VSphereMachineConfigKind = "VSphereMachineConfig" DefaultVSphereDiskGiB = 25 DefaultVSphereNumCPUs = 2 DefaultVSphereMemoryMiB = 8192 DefaultVSphereOSFamily = Bottlerocket ) // Used for generating yaml for generate clusterconfig command. func NewVSphereMachineConfigGenerate(name string) *VSphereMachineConfigGenerate { return &VSphereMachineConfigGenerate{ TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: ObjectMeta{ Name: name, }, Spec: VSphereMachineConfigSpec{ DiskGiB: DefaultVSphereDiskGiB, NumCPUs: DefaultVSphereNumCPUs, MemoryMiB: DefaultVSphereMemoryMiB, OSFamily: DefaultVSphereOSFamily, Users: []UserConfiguration{{ Name: "ec2-user", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }}, }, } } func (c *VSphereMachineConfigGenerate) APIVersion() string { return c.TypeMeta.APIVersion } func (c *VSphereMachineConfigGenerate) Kind() string { return c.TypeMeta.Kind } func (c *VSphereMachineConfigGenerate) Name() string { return c.ObjectMeta.Name } func GetVSphereMachineConfigs(fileName string) (map[string]*VSphereMachineConfig, error) { configs := make(map[string]*VSphereMachineConfig) content, err := os.ReadFile(fileName) if err != nil { return nil, fmt.Errorf("unable to read file due to: %v", err) } for _, c := range strings.Split(string(content), YamlSeparator) { var config VSphereMachineConfig if err = yaml.UnmarshalStrict([]byte(c), &config); err == nil { if config.Kind == VSphereMachineConfigKind { configs[config.Name] = &config continue } } _ = yaml.Unmarshal([]byte(c), &config) // this is to check if there is a bad spec in the file if config.Kind == VSphereMachineConfigKind { return nil, fmt.Errorf("unable to unmarshall content from file due to: %v", err) } } if len(configs) == 0 { return nil, fmt.Errorf("unable to find kind %v in file", VSphereMachineConfigKind) } return configs, nil } func setVSphereMachineConfigDefaults(machineConfig *VSphereMachineConfig) { if len(machineConfig.Spec.Folder) <= 0 { logger.Info("VSphereMachineConfig Folder is not set or is empty. Defaulting to root vSphere folder.") } if machineConfig.Spec.MemoryMiB <= 0 { logger.V(1).Info("VSphereMachineConfig MemoryMiB is not set or is empty. Defaulting to 8192.", "machineConfig", machineConfig.Name) machineConfig.Spec.MemoryMiB = 8192 } if machineConfig.Spec.MemoryMiB < 2048 { logger.Info("Warning: VSphereMachineConfig MemoryMiB should not be less than 2048. Defaulting to 2048. Recommended memory is 8192.", "machineConfig", machineConfig.Name) machineConfig.Spec.MemoryMiB = 2048 } if machineConfig.Spec.NumCPUs <= 0 { logger.V(1).Info("VSphereMachineConfig NumCPUs is not set or is empty. Defaulting to 2.", "machineConfig", machineConfig.Name) machineConfig.Spec.NumCPUs = 2 } if machineConfig.Spec.OSFamily == "" { logger.Info("Warning: OS family not specified in machine config specification. Defaulting to Bottlerocket.") machineConfig.Spec.OSFamily = Bottlerocket } } func validateVSphereMachineConfig(config *VSphereMachineConfig) error { if len(config.Spec.Datastore) <= 0 { return fmt.Errorf("VSphereMachineConfig %s datastore is not set or is empty", config.Name) } if len(config.Spec.ResourcePool) <= 0 { return fmt.Errorf("VSphereMachineConfig %s VM resourcePool is not set or is empty", config.Name) } if config.Spec.OSFamily != Bottlerocket && config.Spec.OSFamily != Ubuntu && config.Spec.OSFamily != RedHat { return fmt.Errorf("VSphereMachineConfig %s osFamily: %s is not supported, please use one of the following: %s, %s, %s", config.Name, config.Spec.OSFamily, Bottlerocket, Ubuntu, RedHat) } if err := validateVSphereMachineConfigOSFamilyUser(config); err != nil { return err } if err := validateHostOSConfig(config.Spec.HostOSConfiguration, config.Spec.OSFamily); err != nil { return fmt.Errorf("HostOSConfiguration is invalid for VSphereMachineConfig %s: %v", config.Name, err) } return nil } func validateVSphereMachineConfigHasTemplate(config *VSphereMachineConfig) error { if config.Spec.Template == "" { return fmt.Errorf("template field is required") } return nil }
135
eks-anywhere
aws
Go
package v1alpha1 import ( "reflect" "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) func TestGetVSphereMachineConfigs(t *testing.T) { tests := []struct { testName string fileName string wantVSphereMachineConfigs map[string]*VSphereMachineConfig wantErr bool }{ { testName: "file doesn't exist", fileName: "testdata/fake_file.yaml", wantVSphereMachineConfigs: nil, wantErr: true, }, { testName: "not parseable file", fileName: "testdata/not_parseable_cluster.yaml", wantVSphereMachineConfigs: nil, wantErr: true, }, { testName: "valid 1.18", fileName: "testdata/cluster_1_18.yaml", wantVSphereMachineConfigs: map[string]*VSphereMachineConfig{ "eksa-unit-test": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 25, MemoryMiB: 8192, NumCPUs: 2, OSFamily: Ubuntu, Template: "myTemplate", Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, Datastore: "myDatastore", Folder: "myFolder", ResourcePool: "myResourcePool", StoragePolicyName: "myStoragePolicyName", }, }, }, wantErr: false, }, { testName: "valid 1.19", fileName: "testdata/cluster_1_19.yaml", wantVSphereMachineConfigs: map[string]*VSphereMachineConfig{ "eksa-unit-test": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 25, MemoryMiB: 8192, NumCPUs: 2, OSFamily: Ubuntu, Template: "myTemplate", Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, Datastore: "myDatastore", Folder: "myFolder", ResourcePool: "myResourcePool", StoragePolicyName: "myStoragePolicyName", }, }, }, wantErr: false, }, { testName: "valid with extra delimiters", fileName: "testdata/cluster_extra_delimiters.yaml", wantVSphereMachineConfigs: map[string]*VSphereMachineConfig{ "eksa-unit-test": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 25, MemoryMiB: 8192, NumCPUs: 2, OSFamily: Ubuntu, Template: "myTemplate", Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, Datastore: "myDatastore", Folder: "myFolder", ResourcePool: "myResourcePool", StoragePolicyName: "myStoragePolicyName", }, }, }, wantErr: false, }, { testName: "valid 1.20", fileName: "testdata/cluster_1_20.yaml", wantVSphereMachineConfigs: map[string]*VSphereMachineConfig{ "eksa-unit-test": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 25, MemoryMiB: 8192, NumCPUs: 2, OSFamily: Ubuntu, Template: "myTemplate", Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, Datastore: "myDatastore", Folder: "myFolder", ResourcePool: "myResourcePool", StoragePolicyName: "myStoragePolicyName", }, }, }, wantErr: false, }, { testName: "valid different machine configs", fileName: "testdata/cluster_different_machine_configs.yaml", wantVSphereMachineConfigs: map[string]*VSphereMachineConfig{ "eksa-unit-test": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 25, MemoryMiB: 8192, NumCPUs: 2, OSFamily: Ubuntu, Template: "myTemplate", Users: []UserConfiguration{{ Name: "mySshUsername", SshAuthorizedKeys: []string{"mySshAuthorizedKey"}, }}, Datastore: "myDatastore", Folder: "myFolder", ResourcePool: "myResourcePool", StoragePolicyName: "myStoragePolicyName", }, }, "eksa-unit-test-2": { TypeMeta: metav1.TypeMeta{ Kind: VSphereMachineConfigKind, APIVersion: SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test-2", }, Spec: VSphereMachineConfigSpec{ DiskGiB: 20, MemoryMiB: 2048, NumCPUs: 4, OSFamily: Bottlerocket, Template: "myTemplate2", Users: []UserConfiguration{{ Name: "mySshUsername2", SshAuthorizedKeys: []string{"mySshAuthorizedKey2"}, }}, Datastore: "myDatastore2", Folder: "myFolder2", ResourcePool: "myResourcePool2", StoragePolicyName: "myStoragePolicyName2", }, }, }, wantErr: false, }, { testName: "invalid kind", fileName: "testdata/cluster_invalid_kinds.yaml", wantVSphereMachineConfigs: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { got, err := GetVSphereMachineConfigs(tt.fileName) if (err != nil) != tt.wantErr { t.Fatalf("GetVSphereMachineConfigs() error = %v, wantErr %v", err, tt.wantErr) } if !reflect.DeepEqual(got, tt.wantVSphereMachineConfigs) { t.Fatalf("GetVSphereMachineConfigs() = %#v, want %#v", got, tt.wantVSphereMachineConfigs) } }) } } func TestVSphereMachineConfigValidate(t *testing.T) { tests := []struct { name string obj *VSphereMachineConfig wantErr string }{ { name: "valid config", obj: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Datastore: "ds-aaa", Folder: "folder/A", OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "", }, { name: "valid without folder", obj: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Datastore: "ds-aaa", OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "", }, { name: "invalid - datastore not set", obj: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Folder: "folder/A", OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "VSphereMachineConfig test datastore is not set or is empty", }, { name: "invalid - resource pool not set", obj: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", Datastore: "ds-aaa", Folder: "folder/A", OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "VSphereMachineConfig test VM resourcePool is not set or is empty", }, { name: "unsupported os family", obj: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Datastore: "ds-aaa", Folder: "folder/A", OSFamily: "suse", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "VSphereMachineConfig test osFamily: suse is not supported, please use one of the following: bottlerocket, ubuntu", }, { name: "invalid ssh username", obj: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Datastore: "ds-aaa", Folder: "folder/A", OSFamily: "bottlerocket", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, }, }, wantErr: "users[0].name test is invalid. Please use 'ec2-user' for Bottlerocket", }, { name: "invalid hostOSConfiguration", obj: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, Spec: VSphereMachineConfigSpec{ MemoryMiB: 64, DiskGiB: 100, NumCPUs: 3, Template: "templateA", ResourcePool: "poolA", Datastore: "ds-aaa", Folder: "folder/A", OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "test", SshAuthorizedKeys: []string{ "ssh_rsa", }, }, }, HostOSConfiguration: &HostOSConfiguration{ NTPConfiguration: &NTPConfiguration{}, }, }, }, wantErr: "HostOSConfiguration is invalid for VSphereMachineConfig test: NTPConfiguration.Servers can not be empty", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) err := tt.obj.Validate() if tt.wantErr == "" { g.Expect(err).To(BeNil()) } else { g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) } }) } } func TestVSphereMachineConfigValidateUsers(t *testing.T) { g := NewWithT(t) tests := []struct { name string machineConfig *VSphereMachineConfig wantErr string }{ { name: "machineconfig with bottlerocket user valid", machineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "bottlerocket", Users: []UserConfiguration{{ Name: "ec2-user", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }}, }, }, }, { name: "machineconfig with bottlerocket user valid", machineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "ubuntu", Users: []UserConfiguration{{ Name: "capv", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }}, }, }, }, { name: "machineconfig users not set", machineConfig: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cp", }, Spec: VSphereMachineConfigSpec{}, }, wantErr: "users is not set for VSphereMachineConfig test-cp, please provide a user", }, { name: "machineconfig with bottlerocket user name invalid", machineConfig: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cp", }, Spec: VSphereMachineConfigSpec{ OSFamily: "bottlerocket", Users: []UserConfiguration{ { Name: "capv", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }, }, }, }, wantErr: "users[0].name capv is invalid. Please use 'ec2-user' for Bottlerocket", }, { name: "machineconfig user name empty", machineConfig: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cp", }, Spec: VSphereMachineConfigSpec{ Users: []UserConfiguration{ { Name: "", SshAuthorizedKeys: []string{"ssh-rsa AAAA..."}, }, }, }, }, wantErr: "users[0].name is not set or is empty for VSphereMachineConfig test-cp, please provide a username", }, { name: "user ssh authorized key empty or not set", machineConfig: &VSphereMachineConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cp", }, Spec: VSphereMachineConfigSpec{ Users: []UserConfiguration{{ Name: "Jeff", SshAuthorizedKeys: []string{""}, }}, }, }, wantErr: "users[0].SshAuthorizedKeys is not set or is empty for VSphereMachineConfig test-cp, please provide a valid ssh authorized key", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { err := tt.machineConfig.ValidateUsers() if tt.wantErr == "" { g.Expect(err).To(BeNil()) } else { g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) } }) } } func TestVSphereMachineConfigSetDefaultUsers(t *testing.T) { g := NewWithT(t) tests := []struct { name string machineConfig *VSphereMachineConfig expectedMachineConfig *VSphereMachineConfig }{ { name: "machine config with bottlerocket", machineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "bottlerocket", }, }, expectedMachineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "bottlerocket", Users: []UserConfiguration{ { Name: "ec2-user", SshAuthorizedKeys: []string{""}, }, }, }, }, }, { name: "machine config with ubuntu", machineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "ubuntu", }, }, expectedMachineConfig: &VSphereMachineConfig{ Spec: VSphereMachineConfigSpec{ OSFamily: "ubuntu", Users: []UserConfiguration{ { Name: "capv", SshAuthorizedKeys: []string{""}, }, }, }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tt.machineConfig.SetUserDefaults() g.Expect(tt.machineConfig).To(Equal(tt.expectedMachineConfig)) }) } }
581
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/logger" ) // NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized. // VSphereMachineConfigSpec defines the desired state of VSphereMachineConfig. type VSphereMachineConfigSpec struct { DiskGiB int `json:"diskGiB,omitempty"` Datastore string `json:"datastore"` Folder string `json:"folder"` NumCPUs int `json:"numCPUs"` MemoryMiB int `json:"memoryMiB"` OSFamily OSFamily `json:"osFamily"` ResourcePool string `json:"resourcePool"` StoragePolicyName string `json:"storagePolicyName,omitempty"` Template string `json:"template,omitempty"` Users []UserConfiguration `json:"users,omitempty"` TagIDs []string `json:"tags,omitempty"` CloneMode CloneMode `json:"cloneMode,omitempty"` HostOSConfiguration *HostOSConfiguration `json:"hostOSConfiguration,omitempty"` } func (c *VSphereMachineConfig) PauseReconcile() { c.Annotations[pausedAnnotation] = "true" } func (c *VSphereMachineConfig) IsReconcilePaused() bool { if s, ok := c.Annotations[pausedAnnotation]; ok { return s == "true" } return false } func (c *VSphereMachineConfig) SetControlPlane() { c.Annotations[controlPlaneAnnotation] = "true" } func (c *VSphereMachineConfig) IsControlPlane() bool { if s, ok := c.Annotations[controlPlaneAnnotation]; ok { return s == "true" } return false } func (c *VSphereMachineConfig) SetEtcd() { c.Annotations[etcdAnnotation] = "true" } func (c *VSphereMachineConfig) IsEtcd() bool { if s, ok := c.Annotations[etcdAnnotation]; ok { return s == "true" } return false } func (c *VSphereMachineConfig) SetManagedBy(clusterName string) { if c.Annotations == nil { c.Annotations = map[string]string{} } c.Annotations[managementAnnotation] = clusterName } // IsManaged returns true if the vspheremachineconfig is associated with a workload cluster. func (c *VSphereMachineConfig) IsManaged() bool { if s, ok := c.Annotations[managementAnnotation]; ok { return s != "" } return false } func (c *VSphereMachineConfig) OSFamily() OSFamily { return c.Spec.OSFamily } func (c *VSphereMachineConfig) GetNamespace() string { return c.Namespace } func (c *VSphereMachineConfig) GetName() string { return c.Name } // VSphereMachineConfigStatus defines the observed state of VSphereMachineConfig. type VSphereMachineConfigStatus struct{} //+kubebuilder:object:root=true //+kubebuilder:subresource:status // VSphereMachineConfig is the Schema for the vspheremachineconfigs API. type VSphereMachineConfig struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec VSphereMachineConfigSpec `json:"spec,omitempty"` Status VSphereMachineConfigStatus `json:"status,omitempty"` } func (c *VSphereMachineConfig) ConvertConfigToConfigGenerateStruct() *VSphereMachineConfigGenerate { namespace := defaultEksaNamespace if c.Namespace != "" { namespace = c.Namespace } config := &VSphereMachineConfigGenerate{ TypeMeta: c.TypeMeta, ObjectMeta: ObjectMeta{ Name: c.Name, Annotations: c.Annotations, Namespace: namespace, }, Spec: c.Spec, } return config } func (c *VSphereMachineConfig) Marshallable() Marshallable { return c.ConvertConfigToConfigGenerateStruct() } func (c *VSphereMachineConfig) SetDefaults() { setVSphereMachineConfigDefaults(c) } // SetUserDefaults initializes Spec.Users for the VSphereMachineConfig with default values. // This only runs in the CLI, as we support do support user defaults through the webhook. func (c *VSphereMachineConfig) SetUserDefaults() { var defaultUsername string if len(c.Spec.Users) == 0 || c.Spec.Users[0].Name == "" { if c.Spec.OSFamily == Bottlerocket { defaultUsername = constants.BottlerocketDefaultUser } else { defaultUsername = constants.UbuntuDefaultUser } logger.V(1).Info("SSHUsername is not set or is empty for VSphereMachineConfig, using default", "c", c.Name, "user", defaultUsername) } c.Spec.Users = defaultMachineConfigUsers(defaultUsername, c.Spec.Users) } func (c *VSphereMachineConfig) Validate() error { return validateVSphereMachineConfig(c) } // ValidateUsers verifies a VSphereMachineConfig object must have a users with ssh authorized keys. // This validation only runs in VSphereMachineConfig validation webhook, as we support // auto-generate and import ssh key when creating a cluster via CLI. func (c *VSphereMachineConfig) ValidateUsers() error { if err := validateMachineConfigUsers(c.Name, VSphereMachineConfigKind, c.Spec.Users); err != nil { return err } if err := validateVSphereMachineConfigOSFamilyUser(c); err != nil { return err } return nil } func validateVSphereMachineConfigOSFamilyUser(machineConfig *VSphereMachineConfig) error { if machineConfig.Spec.OSFamily != Bottlerocket { return nil } if machineConfig.Spec.Users[0].Name != constants.BottlerocketDefaultUser { return fmt.Errorf("users[0].name %s is invalid. Please use 'ec2-user' for Bottlerocket", machineConfig.Spec.Users[0].Name) } return nil } // ValidateHasTemplate verifies that a VSphereMachineConfig object has a template. // Specifying a template is required when submitting an object via webhook, // as we only support auto-importing templates when creating a cluster via CLI. func (c *VSphereMachineConfig) ValidateHasTemplate() error { return validateVSphereMachineConfigHasTemplate(c) } // +kubebuilder:object:generate=false // VSphereMachineConfigGenerate Same as VSphereMachineConfig except stripped down for generation of yaml file during generate clusterconfig. type VSphereMachineConfigGenerate struct { metav1.TypeMeta `json:",inline"` ObjectMeta `json:"metadata,omitempty"` Spec VSphereMachineConfigSpec `json:"spec,omitempty"` } //+kubebuilder:object:root=true // VSphereMachineConfigList contains a list of VSphereMachineConfig. type VSphereMachineConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []VSphereMachineConfig `json:"items"` } func init() { SchemeBuilder.Register(&VSphereMachineConfig{}, &VSphereMachineConfigList{}) }
203
eks-anywhere
aws
Go
package v1alpha1 import ( "fmt" "reflect" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/webhook" ) // log is for logging in this package. var vspheremachineconfiglog = logf.Log.WithName("vspheremachineconfig-resource") func (r *VSphereMachineConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). Complete() } // EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN! //+kubebuilder:webhook:path=/mutate-anywhere-eks-amazonaws-com-v1alpha1-vspheremachineconfig,mutating=true,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=vspheremachineconfigs,verbs=create;update,versions=v1alpha1,name=mutation.vspheremachineconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Defaulter = &VSphereMachineConfig{} // Default implements webhook.Defaulter so a webhook will be registered for the type. func (r *VSphereMachineConfig) Default() { vspheremachineconfiglog.Info("Setting up VSphere Machine Config defaults for", "name", r.Name) r.SetDefaults() } // TODO(user): change verbs to "verbs=create;update;delete" if you want to enable deletion validation. //+kubebuilder:webhook:path=/validate-anywhere-eks-amazonaws-com-v1alpha1-vspheremachineconfig,mutating=false,failurePolicy=fail,sideEffects=None,groups=anywhere.eks.amazonaws.com,resources=vspheremachineconfigs,verbs=create;update,versions=v1alpha1,name=validation.vspheremachineconfig.anywhere.amazonaws.com,admissionReviewVersions={v1,v1beta1} var _ webhook.Validator = &VSphereMachineConfig{} // ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereMachineConfig) ValidateCreate() error { vspheremachineconfiglog.Info("validate create", "name", r.Name) if err := r.ValidateHasTemplate(); err != nil { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec", "template"), r.Spec, err.Error()), }) } if err := r.ValidateUsers(); err != nil { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec", "users"), r.Spec.Users, err.Error()), }) } if err := r.Validate(); err != nil { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec", "users"), r.Spec.Users, err.Error()), }) } return nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereMachineConfig) ValidateUpdate(old runtime.Object) error { vspheremachineconfiglog.Info("validate update", "name", r.Name) oldVSphereMachineConfig, ok := old.(*VSphereMachineConfig) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a VSphereMachineConfig but got a %T", old)) } if err := r.ValidateUsers(); err != nil { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, field.ErrorList{ field.Invalid(field.NewPath("spec", "users"), r.Spec.Users, err.Error()), }) } var allErrs field.ErrorList allErrs = append(allErrs, validateImmutableFieldsVSphereMachineConfig(r, oldVSphereMachineConfig)...) if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, allErrs) } if err := r.Validate(); err != nil { allErrs = append(allErrs, field.Invalid(field.NewPath("spec"), r.Spec, err.Error())) } if len(allErrs) != 0 { return apierrors.NewInvalid(GroupVersion.WithKind(VSphereMachineConfigKind).GroupKind(), r.Name, allErrs) } return nil } func validateImmutableFieldsVSphereMachineConfig(new, old *VSphereMachineConfig) field.ErrorList { if old.IsReconcilePaused() { vspheremachineconfiglog.Info("Reconciliation is paused") return nil } var allErrs field.ErrorList specPath := field.NewPath("spec") if old.Spec.OSFamily != new.Spec.OSFamily { allErrs = append( allErrs, field.Forbidden(specPath.Child("osFamily"), "field is immutable"), ) } if old.Spec.StoragePolicyName != new.Spec.StoragePolicyName { allErrs = append( allErrs, field.Forbidden(specPath.Child("storagePolicyName"), "field is immutable"), ) } if old.IsManaged() { vspheremachineconfiglog.Info("Machine config is associated with workload cluster", "name", old.Name) return allErrs } if !old.IsEtcd() && !old.IsControlPlane() { vspheremachineconfiglog.Info("Machine config is associated with management cluster's worker nodes", "name", old.Name) return allErrs } vspheremachineconfiglog.Info("Machine config is associated with management cluster's control plane or etcd", "name", old.Name) if !reflect.DeepEqual(old.Spec.Users, new.Spec.Users) { allErrs = append( allErrs, field.Forbidden(specPath.Child("users"), "field is immutable"), ) } if old.Spec.Template != new.Spec.Template { allErrs = append( allErrs, field.Forbidden(specPath.Child("template"), "field is immutable"), ) } if old.Spec.Datastore != new.Spec.Datastore { allErrs = append( allErrs, field.Forbidden(specPath.Child("datastore"), "field is immutable"), ) } if old.Spec.Folder != new.Spec.Folder { allErrs = append( allErrs, field.Forbidden(specPath.Child("folder"), "field is immutable"), ) } if old.Spec.ResourcePool != new.Spec.ResourcePool { allErrs = append( allErrs, field.Forbidden(specPath.Child("resourcePool"), "field is immutable"), ) } if old.Spec.MemoryMiB != new.Spec.MemoryMiB { allErrs = append( allErrs, field.Forbidden(specPath.Child("memoryMiB"), "field is immutable"), ) } if old.Spec.NumCPUs != new.Spec.NumCPUs { allErrs = append( allErrs, field.Forbidden(specPath.Child("numCPUs"), "field is immutable"), ) } if old.Spec.DiskGiB != new.Spec.DiskGiB { allErrs = append( allErrs, field.Forbidden(specPath.Child("diskGiB"), "field is immutable"), ) } return allErrs } // ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *VSphereMachineConfig) ValidateDelete() error { vspheremachineconfiglog.Info("validate delete", "name", r.Name) return nil }
199
eks-anywhere
aws
Go
package v1alpha1_test import ( "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func TestManagementCPVSphereMachineValidateUpdateTemplateImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.template: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateTemplateSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateTemplateSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateTemplateSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateTemplateImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.template: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateTemplateSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.Template = "newTemplate" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereMachineValidateUpdateOSFamilyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.OSFamily = v1alpha1.Ubuntu c := vOld.DeepCopy() c.Spec.OSFamily = v1alpha1.Bottlerocket c.Spec.Users[0].Name = "ec2-user" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.osFamily: Forbidden: field is immutable"))) } func TestManagementCPVSphereMachineValidateUpdateMemoryMiBImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.memoryMiB: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateMemoryMiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateMemoryMiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateMemoryMiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateMemoryMiBImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.memoryMiB: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateMemoryMiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.MemoryMiB = 2 c := vOld.DeepCopy() c.Spec.MemoryMiB = 2000000 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementCPVSphereMachineValidateUpdateNumCPUsImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.numCPUs: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateNumCPUsSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateNumCPUsSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateNumCPUsSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateNumCPUsImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.numCPUs: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateNumCPUsSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.NumCPUs = 1 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementCPVSphereMachineValidateUpdateDiskGiBImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.diskGiB: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateDiskGiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateDiskGiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateDiskGiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateDiskGiBImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.diskGiB: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateDiskGiBSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.DiskGiB = 1 c := vOld.DeepCopy() c.Spec.DiskGiB = 160 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementControlPlaneSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.users: Forbidden: field is immutable"))) } func TestWorkloadControlPlaneVSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementControlPlaneVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.users: Forbidden: field is immutable"))) } func TestWorkloadControlPlaneVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereMachineValidateUpdateWithPausedAnnotation(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.DiskGiB = 1 vOld.Spec.Template = "oldTemplate" c := vOld.DeepCopy() c.Spec.DiskGiB = 160 c.Spec.Template = "newTemplate" vOld.PauseReconcile() g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.users: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.users: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkerNodeSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkerNodeVSphereMachineValidateUpdateSshAuthorizedKeyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.Users = []v1alpha1.UserConfiguration{{Name: "Jeff"}} vOld.Spec.Users[0].SshAuthorizedKeys = []string{"rsa-blahdeblahbalh"} c := vOld.DeepCopy() c.Spec.Users[0].SshAuthorizedKeys[0] = "rsa-laDeLala" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkerNodeVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkerNodeVSphereMachineValidateUpdateSshUsernameImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.Users[0].Name = "Jeff" c := vOld.DeepCopy() c.Spec.Users[0].Name = "Andy" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereMachineValidateUpdateInvalidType(t *testing.T) { vOld := &v1alpha1.Cluster{} c := &v1alpha1.VSphereMachineConfig{} g := NewWithT(t) g.Expect(c.ValidateUpdate(vOld)).To(MatchError(ContainSubstring("expected a VSphereMachineConfig but got a *v1alpha1.Cluster"))) } func TestVSphereMachineValidateUpdateSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.NumCPUs = 4 c := vOld.DeepCopy() c.Spec.NumCPUs = 16 g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereMachineValidateUpdateBottleRocketInvalidUserName(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.OSFamily = "bottlerocket" c := vOld.DeepCopy() c.Spec.Users = []v1alpha1.UserConfiguration{ { Name: "jeff", SshAuthorizedKeys: []string{"ssh AAA..."}, }, } g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).ToNot(Succeed()) } func TestManagementCPVSphereMachineValidateUpdateDatastoreImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.datastore: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateDatastoreSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateDatastoreImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.datastore: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateDatastoreSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateDatastoreSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateDatastoreSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.Datastore = "OldDataStore" c := vOld.DeepCopy() c.Spec.Datastore = "NewDataStore" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementCPVSphereMachineValidateUpdateFolderImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.folder: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateFolderSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateFolderImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.folder: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateFolderSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateFolderSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateFolderSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.Folder = "/dev/null" c := vOld.DeepCopy() c.Spec.Folder = "/tmp" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementCPVSphereMachineValidateUpdateResourcePoolImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.resourcePool: Forbidden: field is immutable"))) } func TestWorkloadCPVSphereMachineValidateUpdateResourcePoolSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetControlPlane() vOld.SetManagedBy("test-cluster") vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementEtcdVSphereMachineValidateUpdateResourcePoolImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.resourcePool: Forbidden: field is immutable"))) } func TestWorkloadEtcdVSphereMachineValidateUpdateResourcePoolSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetEtcd() vOld.SetManagedBy("test-cluster") vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestManagementWorkersVSphereMachineValidateUpdateResourcePoolSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestWorkloadWorkersVSphereMachineValidateUpdateResourcePoolSuccess(t *testing.T) { vOld := vsphereMachineConfig() vOld.SetManagedBy("test-cluster") vOld.Spec.ResourcePool = "AbovegroundPool" c := vOld.DeepCopy() c.Spec.ResourcePool = "IngroundPool" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(Succeed()) } func TestVSphereMachineValidateUpdateStoragePolicyImmutable(t *testing.T) { vOld := vsphereMachineConfig() vOld.Spec.StoragePolicyName = "Space-Inefficient" c := vOld.DeepCopy() c.Spec.StoragePolicyName = "Space-Efficient" g := NewWithT(t) g.Expect(c.ValidateUpdate(&vOld)).To(MatchError(ContainSubstring("spec.storagePolicyName: Forbidden: field is immutable"))) } func TestVSphereMachineConfigValidateCreateSuccess(t *testing.T) { config := vsphereMachineConfig() g := NewWithT(t) g.Expect(config.ValidateCreate()).To(Succeed()) } func TestVSphereMachineConfigValidateInvalidUserSSHAuthorizedKeys(t *testing.T) { config := vsphereMachineConfig() config.Spec.Users = []v1alpha1.UserConfiguration{ { Name: "capv", SshAuthorizedKeys: []string{""}, }, } g := NewWithT(t) g.Expect(config.ValidateCreate()).ToNot(Succeed()) } func TestVSphereMachineConfigValidateCreateResourcePoolNotSet(t *testing.T) { config := vsphereMachineConfig() config.Spec.ResourcePool = "" g := NewWithT(t) g.Expect(config.ValidateCreate()).To(MatchError(ContainSubstring("resourcePool is not set or is empty"))) } func TestVSphereMachineConfigValidateCreateTemplateNotSet(t *testing.T) { config := vsphereMachineConfig() config.Spec.Template = "" g := NewWithT(t) g.Expect(config.ValidateCreate()).To(MatchError(ContainSubstring("template field is required"))) } func TestVSphereMachineConfigSetDefaults(t *testing.T) { g := NewWithT(t) sOld := vsphereMachineConfig() sOld.Spec.OSFamily = "" sOld.Default() g.Expect(sOld.Spec.MemoryMiB).To(Equal(8192)) g.Expect(sOld.Spec.NumCPUs).To(Equal(2)) g.Expect(sOld.Spec.OSFamily).To(Equal(v1alpha1.Bottlerocket)) } func vsphereMachineConfig() v1alpha1.VSphereMachineConfig { return v1alpha1.VSphereMachineConfig{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{Annotations: make(map[string]string, 2)}, Spec: v1alpha1.VSphereMachineConfigSpec{ ResourcePool: "my-resourcePool", Datastore: "my-datastore", OSFamily: "ubuntu", Template: "/Datacenter/vm/Templates/bottlerocket-v1.23.12-kubernetes-1-23-eks-7-amd64-d44065e", Users: []v1alpha1.UserConfiguration{ { Name: "capv", SshAuthorizedKeys: []string{"ssh AAA..."}, }, }, }, Status: v1alpha1.VSphereMachineConfigStatus{}, } }
760
eks-anywhere
aws
Go
//go:build !ignore_autogenerated // +build !ignore_autogenerated // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. // Code generated by controller-gen. DO NOT EDIT. package v1alpha1 import ( snowapiv1beta1 "github.com/aws/eks-anywhere/pkg/providers/snow/api/v1beta1" "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/cluster-api/api/v1beta1" apiv1beta1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1beta1" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSDatacenterConfig) DeepCopyInto(out *AWSDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSDatacenterConfig. func (in *AWSDatacenterConfig) DeepCopy() *AWSDatacenterConfig { if in == nil { return nil } out := new(AWSDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *AWSDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSDatacenterConfigList) DeepCopyInto(out *AWSDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]AWSDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSDatacenterConfigList. func (in *AWSDatacenterConfigList) DeepCopy() *AWSDatacenterConfigList { if in == nil { return nil } out := new(AWSDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *AWSDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSDatacenterConfigSpec) DeepCopyInto(out *AWSDatacenterConfigSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSDatacenterConfigSpec. func (in *AWSDatacenterConfigSpec) DeepCopy() *AWSDatacenterConfigSpec { if in == nil { return nil } out := new(AWSDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSDatacenterConfigStatus) DeepCopyInto(out *AWSDatacenterConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSDatacenterConfigStatus. func (in *AWSDatacenterConfigStatus) DeepCopy() *AWSDatacenterConfigStatus { if in == nil { return nil } out := new(AWSDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSIamConfig) DeepCopyInto(out *AWSIamConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSIamConfig. func (in *AWSIamConfig) DeepCopy() *AWSIamConfig { if in == nil { return nil } out := new(AWSIamConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *AWSIamConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSIamConfigList) DeepCopyInto(out *AWSIamConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]AWSIamConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSIamConfigList. func (in *AWSIamConfigList) DeepCopy() *AWSIamConfigList { if in == nil { return nil } out := new(AWSIamConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *AWSIamConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSIamConfigSpec) DeepCopyInto(out *AWSIamConfigSpec) { *out = *in if in.BackendMode != nil { in, out := &in.BackendMode, &out.BackendMode *out = make([]string, len(*in)) copy(*out, *in) } if in.MapRoles != nil { in, out := &in.MapRoles, &out.MapRoles *out = make([]MapRoles, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.MapUsers != nil { in, out := &in.MapUsers, &out.MapUsers *out = make([]MapUsers, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSIamConfigSpec. func (in *AWSIamConfigSpec) DeepCopy() *AWSIamConfigSpec { if in == nil { return nil } out := new(AWSIamConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AWSIamConfigStatus) DeepCopyInto(out *AWSIamConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AWSIamConfigStatus. func (in *AWSIamConfigStatus) DeepCopy() *AWSIamConfigStatus { if in == nil { return nil } out := new(AWSIamConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *AutoScalingConfiguration) DeepCopyInto(out *AutoScalingConfiguration) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new AutoScalingConfiguration. func (in *AutoScalingConfiguration) DeepCopy() *AutoScalingConfiguration { if in == nil { return nil } out := new(AutoScalingConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BottlerocketConfiguration) DeepCopyInto(out *BottlerocketConfiguration) { *out = *in if in.Kubernetes != nil { in, out := &in.Kubernetes, &out.Kubernetes *out = new(apiv1beta1.BottlerocketKubernetesSettings) (*in).DeepCopyInto(*out) } if in.Kernel != nil { in, out := &in.Kernel, &out.Kernel *out = new(apiv1beta1.BottlerocketKernelSettings) (*in).DeepCopyInto(*out) } if in.Boot != nil { in, out := &in.Boot, &out.Boot *out = new(apiv1beta1.BottlerocketBootSettings) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BottlerocketConfiguration. func (in *BottlerocketConfiguration) DeepCopy() *BottlerocketConfiguration { if in == nil { return nil } out := new(BottlerocketConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *BundlesRef) DeepCopyInto(out *BundlesRef) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundlesRef. func (in *BundlesRef) DeepCopy() *BundlesRef { if in == nil { return nil } out := new(BundlesRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CNIConfig) DeepCopyInto(out *CNIConfig) { *out = *in if in.Cilium != nil { in, out := &in.Cilium, &out.Cilium *out = new(CiliumConfig) (*in).DeepCopyInto(*out) } if in.Kindnetd != nil { in, out := &in.Kindnetd, &out.Kindnetd *out = new(KindnetdConfig) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CNIConfig. func (in *CNIConfig) DeepCopy() *CNIConfig { if in == nil { return nil } out := new(CNIConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CiliumConfig) DeepCopyInto(out *CiliumConfig) { *out = *in if in.SkipUpgrade != nil { in, out := &in.SkipUpgrade, &out.SkipUpgrade *out = new(bool) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CiliumConfig. func (in *CiliumConfig) DeepCopy() *CiliumConfig { if in == nil { return nil } out := new(CiliumConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackAvailabilityZone) DeepCopyInto(out *CloudStackAvailabilityZone) { *out = *in out.Zone = in.Zone } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackAvailabilityZone. func (in *CloudStackAvailabilityZone) DeepCopy() *CloudStackAvailabilityZone { if in == nil { return nil } out := new(CloudStackAvailabilityZone) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackDatacenterConfig) DeepCopyInto(out *CloudStackDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackDatacenterConfig. func (in *CloudStackDatacenterConfig) DeepCopy() *CloudStackDatacenterConfig { if in == nil { return nil } out := new(CloudStackDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CloudStackDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackDatacenterConfigList) DeepCopyInto(out *CloudStackDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CloudStackDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackDatacenterConfigList. func (in *CloudStackDatacenterConfigList) DeepCopy() *CloudStackDatacenterConfigList { if in == nil { return nil } out := new(CloudStackDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CloudStackDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackDatacenterConfigSpec) DeepCopyInto(out *CloudStackDatacenterConfigSpec) { *out = *in if in.Zones != nil { in, out := &in.Zones, &out.Zones *out = make([]CloudStackZone, len(*in)) copy(*out, *in) } if in.AvailabilityZones != nil { in, out := &in.AvailabilityZones, &out.AvailabilityZones *out = make([]CloudStackAvailabilityZone, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackDatacenterConfigSpec. func (in *CloudStackDatacenterConfigSpec) DeepCopy() *CloudStackDatacenterConfigSpec { if in == nil { return nil } out := new(CloudStackDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackDatacenterConfigStatus) DeepCopyInto(out *CloudStackDatacenterConfigStatus) { *out = *in if in.FailureMessage != nil { in, out := &in.FailureMessage, &out.FailureMessage *out = new(string) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackDatacenterConfigStatus. func (in *CloudStackDatacenterConfigStatus) DeepCopy() *CloudStackDatacenterConfigStatus { if in == nil { return nil } out := new(CloudStackDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackMachineConfig) DeepCopyInto(out *CloudStackMachineConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackMachineConfig. func (in *CloudStackMachineConfig) DeepCopy() *CloudStackMachineConfig { if in == nil { return nil } out := new(CloudStackMachineConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CloudStackMachineConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackMachineConfigList) DeepCopyInto(out *CloudStackMachineConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]CloudStackMachineConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackMachineConfigList. func (in *CloudStackMachineConfigList) DeepCopy() *CloudStackMachineConfigList { if in == nil { return nil } out := new(CloudStackMachineConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *CloudStackMachineConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackMachineConfigSpec) DeepCopyInto(out *CloudStackMachineConfigSpec) { *out = *in out.Template = in.Template out.ComputeOffering = in.ComputeOffering if in.DiskOffering != nil { in, out := &in.DiskOffering, &out.DiskOffering *out = new(CloudStackResourceDiskOffering) **out = **in } if in.Users != nil { in, out := &in.Users, &out.Users *out = make([]UserConfiguration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.AffinityGroupIds != nil { in, out := &in.AffinityGroupIds, &out.AffinityGroupIds *out = make([]string, len(*in)) copy(*out, *in) } if in.UserCustomDetails != nil { in, out := &in.UserCustomDetails, &out.UserCustomDetails *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.Symlinks != nil { in, out := &in.Symlinks, &out.Symlinks *out = make(SymlinkMaps, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackMachineConfigSpec. func (in *CloudStackMachineConfigSpec) DeepCopy() *CloudStackMachineConfigSpec { if in == nil { return nil } out := new(CloudStackMachineConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackMachineConfigStatus) DeepCopyInto(out *CloudStackMachineConfigStatus) { *out = *in if in.FailureMessage != nil { in, out := &in.FailureMessage, &out.FailureMessage *out = new(string) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackMachineConfigStatus. func (in *CloudStackMachineConfigStatus) DeepCopy() *CloudStackMachineConfigStatus { if in == nil { return nil } out := new(CloudStackMachineConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackResourceDiskOffering) DeepCopyInto(out *CloudStackResourceDiskOffering) { *out = *in out.CloudStackResourceIdentifier = in.CloudStackResourceIdentifier } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackResourceDiskOffering. func (in *CloudStackResourceDiskOffering) DeepCopy() *CloudStackResourceDiskOffering { if in == nil { return nil } out := new(CloudStackResourceDiskOffering) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackResourceIdentifier) DeepCopyInto(out *CloudStackResourceIdentifier) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackResourceIdentifier. func (in *CloudStackResourceIdentifier) DeepCopy() *CloudStackResourceIdentifier { if in == nil { return nil } out := new(CloudStackResourceIdentifier) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CloudStackZone) DeepCopyInto(out *CloudStackZone) { *out = *in out.Network = in.Network } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CloudStackZone. func (in *CloudStackZone) DeepCopy() *CloudStackZone { if in == nil { return nil } out := new(CloudStackZone) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Cluster) DeepCopyInto(out *Cluster) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cluster. func (in *Cluster) DeepCopy() *Cluster { if in == nil { return nil } out := new(Cluster) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *Cluster) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterList) DeepCopyInto(out *ClusterList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]Cluster, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterList. func (in *ClusterList) DeepCopy() *ClusterList { if in == nil { return nil } out := new(ClusterList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *ClusterList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterNetwork) DeepCopyInto(out *ClusterNetwork) { *out = *in in.Pods.DeepCopyInto(&out.Pods) in.Services.DeepCopyInto(&out.Services) if in.CNIConfig != nil { in, out := &in.CNIConfig, &out.CNIConfig *out = new(CNIConfig) (*in).DeepCopyInto(*out) } in.DNS.DeepCopyInto(&out.DNS) if in.Nodes != nil { in, out := &in.Nodes, &out.Nodes *out = new(Nodes) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterNetwork. func (in *ClusterNetwork) DeepCopy() *ClusterNetwork { if in == nil { return nil } out := new(ClusterNetwork) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterSpec) DeepCopyInto(out *ClusterSpec) { *out = *in in.ControlPlaneConfiguration.DeepCopyInto(&out.ControlPlaneConfiguration) if in.WorkerNodeGroupConfigurations != nil { in, out := &in.WorkerNodeGroupConfigurations, &out.WorkerNodeGroupConfigurations *out = make([]WorkerNodeGroupConfiguration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } out.DatacenterRef = in.DatacenterRef if in.IdentityProviderRefs != nil { in, out := &in.IdentityProviderRefs, &out.IdentityProviderRefs *out = make([]Ref, len(*in)) copy(*out, *in) } if in.GitOpsRef != nil { in, out := &in.GitOpsRef, &out.GitOpsRef *out = new(Ref) **out = **in } in.ClusterNetwork.DeepCopyInto(&out.ClusterNetwork) if in.ExternalEtcdConfiguration != nil { in, out := &in.ExternalEtcdConfiguration, &out.ExternalEtcdConfiguration *out = new(ExternalEtcdConfiguration) (*in).DeepCopyInto(*out) } if in.ProxyConfiguration != nil { in, out := &in.ProxyConfiguration, &out.ProxyConfiguration *out = new(ProxyConfiguration) (*in).DeepCopyInto(*out) } if in.RegistryMirrorConfiguration != nil { in, out := &in.RegistryMirrorConfiguration, &out.RegistryMirrorConfiguration *out = new(RegistryMirrorConfiguration) (*in).DeepCopyInto(*out) } out.ManagementCluster = in.ManagementCluster if in.PodIAMConfig != nil { in, out := &in.PodIAMConfig, &out.PodIAMConfig *out = new(PodIAMConfig) **out = **in } if in.Packages != nil { in, out := &in.Packages, &out.Packages *out = new(PackageConfiguration) (*in).DeepCopyInto(*out) } if in.BundlesRef != nil { in, out := &in.BundlesRef, &out.BundlesRef *out = new(BundlesRef) **out = **in } if in.EksaVersion != nil { in, out := &in.EksaVersion, &out.EksaVersion *out = new(EksaVersion) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSpec. func (in *ClusterSpec) DeepCopy() *ClusterSpec { if in == nil { return nil } out := new(ClusterSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClusterStatus) DeepCopyInto(out *ClusterStatus) { *out = *in if in.FailureMessage != nil { in, out := &in.FailureMessage, &out.FailureMessage *out = new(string) **out = **in } if in.EksdReleaseRef != nil { in, out := &in.EksdReleaseRef, &out.EksdReleaseRef *out = new(EksdReleaseRef) **out = **in } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]v1beta1.Condition, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterStatus. func (in *ClusterStatus) DeepCopy() *ClusterStatus { if in == nil { return nil } out := new(ClusterStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ControlPlaneConfiguration) DeepCopyInto(out *ControlPlaneConfiguration) { *out = *in if in.Endpoint != nil { in, out := &in.Endpoint, &out.Endpoint *out = new(Endpoint) **out = **in } if in.MachineGroupRef != nil { in, out := &in.MachineGroupRef, &out.MachineGroupRef *out = new(Ref) **out = **in } if in.Taints != nil { in, out := &in.Taints, &out.Taints *out = make([]v1.Taint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Labels != nil { in, out := &in.Labels, &out.Labels *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.UpgradeRolloutStrategy != nil { in, out := &in.UpgradeRolloutStrategy, &out.UpgradeRolloutStrategy *out = new(ControlPlaneUpgradeRolloutStrategy) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneConfiguration. func (in *ControlPlaneConfiguration) DeepCopy() *ControlPlaneConfiguration { if in == nil { return nil } out := new(ControlPlaneConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ControlPlaneRollingUpdateParams) DeepCopyInto(out *ControlPlaneRollingUpdateParams) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneRollingUpdateParams. func (in *ControlPlaneRollingUpdateParams) DeepCopy() *ControlPlaneRollingUpdateParams { if in == nil { return nil } out := new(ControlPlaneRollingUpdateParams) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ControlPlaneUpgradeRolloutStrategy) DeepCopyInto(out *ControlPlaneUpgradeRolloutStrategy) { *out = *in out.RollingUpdate = in.RollingUpdate } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ControlPlaneUpgradeRolloutStrategy. func (in *ControlPlaneUpgradeRolloutStrategy) DeepCopy() *ControlPlaneUpgradeRolloutStrategy { if in == nil { return nil } out := new(ControlPlaneUpgradeRolloutStrategy) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DNS) DeepCopyInto(out *DNS) { *out = *in if in.ResolvConf != nil { in, out := &in.ResolvConf, &out.ResolvConf *out = new(ResolvConf) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DNS. func (in *DNS) DeepCopy() *DNS { if in == nil { return nil } out := new(DNS) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerDatacenterConfig) DeepCopyInto(out *DockerDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerDatacenterConfig. func (in *DockerDatacenterConfig) DeepCopy() *DockerDatacenterConfig { if in == nil { return nil } out := new(DockerDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *DockerDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerDatacenterConfigList) DeepCopyInto(out *DockerDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]DockerDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerDatacenterConfigList. func (in *DockerDatacenterConfigList) DeepCopy() *DockerDatacenterConfigList { if in == nil { return nil } out := new(DockerDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *DockerDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerDatacenterConfigSpec) DeepCopyInto(out *DockerDatacenterConfigSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerDatacenterConfigSpec. func (in *DockerDatacenterConfigSpec) DeepCopy() *DockerDatacenterConfigSpec { if in == nil { return nil } out := new(DockerDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DockerDatacenterConfigStatus) DeepCopyInto(out *DockerDatacenterConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new DockerDatacenterConfigStatus. func (in *DockerDatacenterConfigStatus) DeepCopy() *DockerDatacenterConfigStatus { if in == nil { return nil } out := new(DockerDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EksdReleaseRef) DeepCopyInto(out *EksdReleaseRef) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new EksdReleaseRef. func (in *EksdReleaseRef) DeepCopy() *EksdReleaseRef { if in == nil { return nil } out := new(EksdReleaseRef) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Endpoint) DeepCopyInto(out *Endpoint) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Endpoint. func (in *Endpoint) DeepCopy() *Endpoint { if in == nil { return nil } out := new(Endpoint) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ExternalEtcdConfiguration) DeepCopyInto(out *ExternalEtcdConfiguration) { *out = *in if in.MachineGroupRef != nil { in, out := &in.MachineGroupRef, &out.MachineGroupRef *out = new(Ref) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ExternalEtcdConfiguration. func (in *ExternalEtcdConfiguration) DeepCopy() *ExternalEtcdConfiguration { if in == nil { return nil } out := new(ExternalEtcdConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Flux) DeepCopyInto(out *Flux) { *out = *in out.Github = in.Github } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Flux. func (in *Flux) DeepCopy() *Flux { if in == nil { return nil } out := new(Flux) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FluxConfig) DeepCopyInto(out *FluxConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FluxConfig. func (in *FluxConfig) DeepCopy() *FluxConfig { if in == nil { return nil } out := new(FluxConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *FluxConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FluxConfigList) DeepCopyInto(out *FluxConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]FluxConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FluxConfigList. func (in *FluxConfigList) DeepCopy() *FluxConfigList { if in == nil { return nil } out := new(FluxConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *FluxConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FluxConfigSpec) DeepCopyInto(out *FluxConfigSpec) { *out = *in if in.Github != nil { in, out := &in.Github, &out.Github *out = new(GithubProviderConfig) **out = **in } if in.Git != nil { in, out := &in.Git, &out.Git *out = new(GitProviderConfig) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FluxConfigSpec. func (in *FluxConfigSpec) DeepCopy() *FluxConfigSpec { if in == nil { return nil } out := new(FluxConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *FluxConfigStatus) DeepCopyInto(out *FluxConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new FluxConfigStatus. func (in *FluxConfigStatus) DeepCopy() *FluxConfigStatus { if in == nil { return nil } out := new(FluxConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitOpsConfig) DeepCopyInto(out *GitOpsConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitOpsConfig. func (in *GitOpsConfig) DeepCopy() *GitOpsConfig { if in == nil { return nil } out := new(GitOpsConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *GitOpsConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitOpsConfigList) DeepCopyInto(out *GitOpsConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]GitOpsConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitOpsConfigList. func (in *GitOpsConfigList) DeepCopy() *GitOpsConfigList { if in == nil { return nil } out := new(GitOpsConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *GitOpsConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitOpsConfigSpec) DeepCopyInto(out *GitOpsConfigSpec) { *out = *in out.Flux = in.Flux } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitOpsConfigSpec. func (in *GitOpsConfigSpec) DeepCopy() *GitOpsConfigSpec { if in == nil { return nil } out := new(GitOpsConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitOpsConfigStatus) DeepCopyInto(out *GitOpsConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitOpsConfigStatus. func (in *GitOpsConfigStatus) DeepCopy() *GitOpsConfigStatus { if in == nil { return nil } out := new(GitOpsConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GitProviderConfig) DeepCopyInto(out *GitProviderConfig) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GitProviderConfig. func (in *GitProviderConfig) DeepCopy() *GitProviderConfig { if in == nil { return nil } out := new(GitProviderConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Github) DeepCopyInto(out *Github) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Github. func (in *Github) DeepCopy() *Github { if in == nil { return nil } out := new(Github) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GithubProviderConfig) DeepCopyInto(out *GithubProviderConfig) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GithubProviderConfig. func (in *GithubProviderConfig) DeepCopy() *GithubProviderConfig { if in == nil { return nil } out := new(GithubProviderConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in HardwareSelector) DeepCopyInto(out *HardwareSelector) { { in := &in *out = make(HardwareSelector, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HardwareSelector. func (in HardwareSelector) DeepCopy() HardwareSelector { if in == nil { return nil } out := new(HardwareSelector) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *HostOSConfiguration) DeepCopyInto(out *HostOSConfiguration) { *out = *in if in.NTPConfiguration != nil { in, out := &in.NTPConfiguration, &out.NTPConfiguration *out = new(NTPConfiguration) (*in).DeepCopyInto(*out) } if in.BottlerocketConfiguration != nil { in, out := &in.BottlerocketConfiguration, &out.BottlerocketConfiguration *out = new(BottlerocketConfiguration) (*in).DeepCopyInto(*out) } if in.CertBundles != nil { in, out := &in.CertBundles, &out.CertBundles *out = make([]certBundle, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new HostOSConfiguration. func (in *HostOSConfiguration) DeepCopy() *HostOSConfiguration { if in == nil { return nil } out := new(HostOSConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *IPPool) DeepCopyInto(out *IPPool) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new IPPool. func (in *IPPool) DeepCopy() *IPPool { if in == nil { return nil } out := new(IPPool) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ImageResource) DeepCopyInto(out *ImageResource) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImageResource. func (in *ImageResource) DeepCopy() *ImageResource { if in == nil { return nil } out := new(ImageResource) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *KindnetdConfig) DeepCopyInto(out *KindnetdConfig) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KindnetdConfig. func (in *KindnetdConfig) DeepCopy() *KindnetdConfig { if in == nil { return nil } out := new(KindnetdConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ManagementCluster) DeepCopyInto(out *ManagementCluster) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ManagementCluster. func (in *ManagementCluster) DeepCopy() *ManagementCluster { if in == nil { return nil } out := new(ManagementCluster) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MapRoles) DeepCopyInto(out *MapRoles) { *out = *in if in.Groups != nil { in, out := &in.Groups, &out.Groups *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapRoles. func (in *MapRoles) DeepCopy() *MapRoles { if in == nil { return nil } out := new(MapRoles) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *MapUsers) DeepCopyInto(out *MapUsers) { *out = *in if in.Groups != nil { in, out := &in.Groups, &out.Groups *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MapUsers. func (in *MapUsers) DeepCopy() *MapUsers { if in == nil { return nil } out := new(MapUsers) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NTPConfiguration) DeepCopyInto(out *NTPConfiguration) { *out = *in if in.Servers != nil { in, out := &in.Servers, &out.Servers *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NTPConfiguration. func (in *NTPConfiguration) DeepCopy() *NTPConfiguration { if in == nil { return nil } out := new(NTPConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Nodes) DeepCopyInto(out *Nodes) { *out = *in if in.CIDRMaskSize != nil { in, out := &in.CIDRMaskSize, &out.CIDRMaskSize *out = new(int) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Nodes. func (in *Nodes) DeepCopy() *Nodes { if in == nil { return nil } out := new(Nodes) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixCategoryIdentifier) DeepCopyInto(out *NutanixCategoryIdentifier) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixCategoryIdentifier. func (in *NutanixCategoryIdentifier) DeepCopy() *NutanixCategoryIdentifier { if in == nil { return nil } out := new(NutanixCategoryIdentifier) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixDatacenterConfig) DeepCopyInto(out *NutanixDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixDatacenterConfig. func (in *NutanixDatacenterConfig) DeepCopy() *NutanixDatacenterConfig { if in == nil { return nil } out := new(NutanixDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *NutanixDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixDatacenterConfigList) DeepCopyInto(out *NutanixDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]NutanixDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixDatacenterConfigList. func (in *NutanixDatacenterConfigList) DeepCopy() *NutanixDatacenterConfigList { if in == nil { return nil } out := new(NutanixDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *NutanixDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixDatacenterConfigSpec) DeepCopyInto(out *NutanixDatacenterConfigSpec) { *out = *in if in.CredentialRef != nil { in, out := &in.CredentialRef, &out.CredentialRef *out = new(Ref) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixDatacenterConfigSpec. func (in *NutanixDatacenterConfigSpec) DeepCopy() *NutanixDatacenterConfigSpec { if in == nil { return nil } out := new(NutanixDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixDatacenterConfigStatus) DeepCopyInto(out *NutanixDatacenterConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixDatacenterConfigStatus. func (in *NutanixDatacenterConfigStatus) DeepCopy() *NutanixDatacenterConfigStatus { if in == nil { return nil } out := new(NutanixDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixMachineConfig) DeepCopyInto(out *NutanixMachineConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixMachineConfig. func (in *NutanixMachineConfig) DeepCopy() *NutanixMachineConfig { if in == nil { return nil } out := new(NutanixMachineConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *NutanixMachineConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixMachineConfigList) DeepCopyInto(out *NutanixMachineConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]NutanixMachineConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixMachineConfigList. func (in *NutanixMachineConfigList) DeepCopy() *NutanixMachineConfigList { if in == nil { return nil } out := new(NutanixMachineConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *NutanixMachineConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixMachineConfigSpec) DeepCopyInto(out *NutanixMachineConfigSpec) { *out = *in if in.Users != nil { in, out := &in.Users, &out.Users *out = make([]UserConfiguration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } out.MemorySize = in.MemorySize.DeepCopy() in.Image.DeepCopyInto(&out.Image) in.Cluster.DeepCopyInto(&out.Cluster) in.Subnet.DeepCopyInto(&out.Subnet) if in.Project != nil { in, out := &in.Project, &out.Project *out = new(NutanixResourceIdentifier) (*in).DeepCopyInto(*out) } out.SystemDiskSize = in.SystemDiskSize.DeepCopy() if in.AdditionalCategories != nil { in, out := &in.AdditionalCategories, &out.AdditionalCategories *out = make([]NutanixCategoryIdentifier, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixMachineConfigSpec. func (in *NutanixMachineConfigSpec) DeepCopy() *NutanixMachineConfigSpec { if in == nil { return nil } out := new(NutanixMachineConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixMachineConfigStatus) DeepCopyInto(out *NutanixMachineConfigStatus) { *out = *in if in.Addresses != nil { in, out := &in.Addresses, &out.Addresses *out = make([]v1beta1.MachineAddress, len(*in)) copy(*out, *in) } if in.VmUUID != nil { in, out := &in.VmUUID, &out.VmUUID *out = new(string) **out = **in } if in.NodeRef != nil { in, out := &in.NodeRef, &out.NodeRef *out = new(v1.ObjectReference) **out = **in } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make(v1beta1.Conditions, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixMachineConfigStatus. func (in *NutanixMachineConfigStatus) DeepCopy() *NutanixMachineConfigStatus { if in == nil { return nil } out := new(NutanixMachineConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *NutanixResourceIdentifier) DeepCopyInto(out *NutanixResourceIdentifier) { *out = *in if in.UUID != nil { in, out := &in.UUID, &out.UUID *out = new(string) **out = **in } if in.Name != nil { in, out := &in.Name, &out.Name *out = new(string) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new NutanixResourceIdentifier. func (in *NutanixResourceIdentifier) DeepCopy() *NutanixResourceIdentifier { if in == nil { return nil } out := new(NutanixResourceIdentifier) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OCINamespace) DeepCopyInto(out *OCINamespace) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OCINamespace. func (in *OCINamespace) DeepCopy() *OCINamespace { if in == nil { return nil } out := new(OCINamespace) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCConfig) DeepCopyInto(out *OIDCConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCConfig. func (in *OIDCConfig) DeepCopy() *OIDCConfig { if in == nil { return nil } out := new(OIDCConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *OIDCConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCConfigList) DeepCopyInto(out *OIDCConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]OIDCConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCConfigList. func (in *OIDCConfigList) DeepCopy() *OIDCConfigList { if in == nil { return nil } out := new(OIDCConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *OIDCConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCConfigRequiredClaim) DeepCopyInto(out *OIDCConfigRequiredClaim) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCConfigRequiredClaim. func (in *OIDCConfigRequiredClaim) DeepCopy() *OIDCConfigRequiredClaim { if in == nil { return nil } out := new(OIDCConfigRequiredClaim) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCConfigSpec) DeepCopyInto(out *OIDCConfigSpec) { *out = *in if in.RequiredClaims != nil { in, out := &in.RequiredClaims, &out.RequiredClaims *out = make([]OIDCConfigRequiredClaim, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCConfigSpec. func (in *OIDCConfigSpec) DeepCopy() *OIDCConfigSpec { if in == nil { return nil } out := new(OIDCConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *OIDCConfigStatus) DeepCopyInto(out *OIDCConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new OIDCConfigStatus. func (in *OIDCConfigStatus) DeepCopy() *OIDCConfigStatus { if in == nil { return nil } out := new(OIDCConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ObjectMeta) DeepCopyInto(out *ObjectMeta) { *out = *in if in.Annotations != nil { in, out := &in.Annotations, &out.Annotations *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ObjectMeta. func (in *ObjectMeta) DeepCopy() *ObjectMeta { if in == nil { return nil } out := new(ObjectMeta) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PackageConfiguration) DeepCopyInto(out *PackageConfiguration) { *out = *in if in.Controller != nil { in, out := &in.Controller, &out.Controller *out = new(PackageControllerConfiguration) (*in).DeepCopyInto(*out) } if in.CronJob != nil { in, out := &in.CronJob, &out.CronJob *out = new(PackageControllerCronJob) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageConfiguration. func (in *PackageConfiguration) DeepCopy() *PackageConfiguration { if in == nil { return nil } out := new(PackageConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PackageControllerConfiguration) DeepCopyInto(out *PackageControllerConfiguration) { *out = *in if in.Env != nil { in, out := &in.Env, &out.Env *out = make([]string, len(*in)) copy(*out, *in) } out.Resources = in.Resources } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageControllerConfiguration. func (in *PackageControllerConfiguration) DeepCopy() *PackageControllerConfiguration { if in == nil { return nil } out := new(PackageControllerConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PackageControllerCronJob) DeepCopyInto(out *PackageControllerCronJob) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageControllerCronJob. func (in *PackageControllerCronJob) DeepCopy() *PackageControllerCronJob { if in == nil { return nil } out := new(PackageControllerCronJob) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PackageControllerResources) DeepCopyInto(out *PackageControllerResources) { *out = *in out.Requests = in.Requests out.Limits = in.Limits } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageControllerResources. func (in *PackageControllerResources) DeepCopy() *PackageControllerResources { if in == nil { return nil } out := new(PackageControllerResources) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PodIAMConfig) DeepCopyInto(out *PodIAMConfig) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PodIAMConfig. func (in *PodIAMConfig) DeepCopy() *PodIAMConfig { if in == nil { return nil } out := new(PodIAMConfig) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Pods) DeepCopyInto(out *Pods) { *out = *in if in.CidrBlocks != nil { in, out := &in.CidrBlocks, &out.CidrBlocks *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Pods. func (in *Pods) DeepCopy() *Pods { if in == nil { return nil } out := new(Pods) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ProxyConfiguration) DeepCopyInto(out *ProxyConfiguration) { *out = *in if in.NoProxy != nil { in, out := &in.NoProxy, &out.NoProxy *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ProxyConfiguration. func (in *ProxyConfiguration) DeepCopy() *ProxyConfiguration { if in == nil { return nil } out := new(ProxyConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Ref) DeepCopyInto(out *Ref) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Ref. func (in *Ref) DeepCopy() *Ref { if in == nil { return nil } out := new(Ref) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RegistryMirrorConfiguration) DeepCopyInto(out *RegistryMirrorConfiguration) { *out = *in if in.OCINamespaces != nil { in, out := &in.OCINamespaces, &out.OCINamespaces *out = make([]OCINamespace, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RegistryMirrorConfiguration. func (in *RegistryMirrorConfiguration) DeepCopy() *RegistryMirrorConfiguration { if in == nil { return nil } out := new(RegistryMirrorConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ResolvConf) DeepCopyInto(out *ResolvConf) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ResolvConf. func (in *ResolvConf) DeepCopy() *ResolvConf { if in == nil { return nil } out := new(ResolvConf) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Services) DeepCopyInto(out *Services) { *out = *in if in.CidrBlocks != nil { in, out := &in.CidrBlocks, &out.CidrBlocks *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Services. func (in *Services) DeepCopy() *Services { if in == nil { return nil } out := new(Services) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowDatacenterConfig) DeepCopyInto(out *SnowDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowDatacenterConfig. func (in *SnowDatacenterConfig) DeepCopy() *SnowDatacenterConfig { if in == nil { return nil } out := new(SnowDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowDatacenterConfigList) DeepCopyInto(out *SnowDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]SnowDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowDatacenterConfigList. func (in *SnowDatacenterConfigList) DeepCopy() *SnowDatacenterConfigList { if in == nil { return nil } out := new(SnowDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowDatacenterConfigSpec) DeepCopyInto(out *SnowDatacenterConfigSpec) { *out = *in out.IdentityRef = in.IdentityRef } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowDatacenterConfigSpec. func (in *SnowDatacenterConfigSpec) DeepCopy() *SnowDatacenterConfigSpec { if in == nil { return nil } out := new(SnowDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowDatacenterConfigStatus) DeepCopyInto(out *SnowDatacenterConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowDatacenterConfigStatus. func (in *SnowDatacenterConfigStatus) DeepCopy() *SnowDatacenterConfigStatus { if in == nil { return nil } out := new(SnowDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowDirectNetworkInterface) DeepCopyInto(out *SnowDirectNetworkInterface) { *out = *in if in.VlanID != nil { in, out := &in.VlanID, &out.VlanID *out = new(int32) **out = **in } if in.IPPoolRef != nil { in, out := &in.IPPoolRef, &out.IPPoolRef *out = new(Ref) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowDirectNetworkInterface. func (in *SnowDirectNetworkInterface) DeepCopy() *SnowDirectNetworkInterface { if in == nil { return nil } out := new(SnowDirectNetworkInterface) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowIPPool) DeepCopyInto(out *SnowIPPool) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowIPPool. func (in *SnowIPPool) DeepCopy() *SnowIPPool { if in == nil { return nil } out := new(SnowIPPool) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowIPPool) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowIPPoolList) DeepCopyInto(out *SnowIPPoolList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]SnowIPPool, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowIPPoolList. func (in *SnowIPPoolList) DeepCopy() *SnowIPPoolList { if in == nil { return nil } out := new(SnowIPPoolList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowIPPoolList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowIPPoolSpec) DeepCopyInto(out *SnowIPPoolSpec) { *out = *in if in.Pools != nil { in, out := &in.Pools, &out.Pools *out = make([]IPPool, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowIPPoolSpec. func (in *SnowIPPoolSpec) DeepCopy() *SnowIPPoolSpec { if in == nil { return nil } out := new(SnowIPPoolSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowIPPoolStatus) DeepCopyInto(out *SnowIPPoolStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowIPPoolStatus. func (in *SnowIPPoolStatus) DeepCopy() *SnowIPPoolStatus { if in == nil { return nil } out := new(SnowIPPoolStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowMachineConfig) DeepCopyInto(out *SnowMachineConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowMachineConfig. func (in *SnowMachineConfig) DeepCopy() *SnowMachineConfig { if in == nil { return nil } out := new(SnowMachineConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowMachineConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowMachineConfigList) DeepCopyInto(out *SnowMachineConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]SnowMachineConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowMachineConfigList. func (in *SnowMachineConfigList) DeepCopy() *SnowMachineConfigList { if in == nil { return nil } out := new(SnowMachineConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *SnowMachineConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowMachineConfigSpec) DeepCopyInto(out *SnowMachineConfigSpec) { *out = *in if in.Devices != nil { in, out := &in.Devices, &out.Devices *out = make([]string, len(*in)) copy(*out, *in) } if in.ContainersVolume != nil { in, out := &in.ContainersVolume, &out.ContainersVolume *out = new(snowapiv1beta1.Volume) **out = **in } if in.NonRootVolumes != nil { in, out := &in.NonRootVolumes, &out.NonRootVolumes *out = make([]*snowapiv1beta1.Volume, len(*in)) for i := range *in { if (*in)[i] != nil { in, out := &(*in)[i], &(*out)[i] *out = new(snowapiv1beta1.Volume) **out = **in } } } in.Network.DeepCopyInto(&out.Network) if in.HostOSConfiguration != nil { in, out := &in.HostOSConfiguration, &out.HostOSConfiguration *out = new(HostOSConfiguration) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowMachineConfigSpec. func (in *SnowMachineConfigSpec) DeepCopy() *SnowMachineConfigSpec { if in == nil { return nil } out := new(SnowMachineConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowMachineConfigStatus) DeepCopyInto(out *SnowMachineConfigStatus) { *out = *in if in.FailureMessage != nil { in, out := &in.FailureMessage, &out.FailureMessage *out = new(string) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowMachineConfigStatus. func (in *SnowMachineConfigStatus) DeepCopy() *SnowMachineConfigStatus { if in == nil { return nil } out := new(SnowMachineConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *SnowNetwork) DeepCopyInto(out *SnowNetwork) { *out = *in if in.DirectNetworkInterfaces != nil { in, out := &in.DirectNetworkInterfaces, &out.DirectNetworkInterfaces *out = make([]SnowDirectNetworkInterface, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SnowNetwork. func (in *SnowNetwork) DeepCopy() *SnowNetwork { if in == nil { return nil } out := new(SnowNetwork) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in SymlinkMaps) DeepCopyInto(out *SymlinkMaps) { { in := &in *out = make(SymlinkMaps, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SymlinkMaps. func (in SymlinkMaps) DeepCopy() SymlinkMaps { if in == nil { return nil } out := new(SymlinkMaps) in.DeepCopyInto(out) return *out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellDatacenterConfig) DeepCopyInto(out *TinkerbellDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellDatacenterConfig. func (in *TinkerbellDatacenterConfig) DeepCopy() *TinkerbellDatacenterConfig { if in == nil { return nil } out := new(TinkerbellDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellDatacenterConfigList) DeepCopyInto(out *TinkerbellDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]TinkerbellDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellDatacenterConfigList. func (in *TinkerbellDatacenterConfigList) DeepCopy() *TinkerbellDatacenterConfigList { if in == nil { return nil } out := new(TinkerbellDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellDatacenterConfigSpec) DeepCopyInto(out *TinkerbellDatacenterConfigSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellDatacenterConfigSpec. func (in *TinkerbellDatacenterConfigSpec) DeepCopy() *TinkerbellDatacenterConfigSpec { if in == nil { return nil } out := new(TinkerbellDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellDatacenterConfigStatus) DeepCopyInto(out *TinkerbellDatacenterConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellDatacenterConfigStatus. func (in *TinkerbellDatacenterConfigStatus) DeepCopy() *TinkerbellDatacenterConfigStatus { if in == nil { return nil } out := new(TinkerbellDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellMachineConfig) DeepCopyInto(out *TinkerbellMachineConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellMachineConfig. func (in *TinkerbellMachineConfig) DeepCopy() *TinkerbellMachineConfig { if in == nil { return nil } out := new(TinkerbellMachineConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellMachineConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellMachineConfigList) DeepCopyInto(out *TinkerbellMachineConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]TinkerbellMachineConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellMachineConfigList. func (in *TinkerbellMachineConfigList) DeepCopy() *TinkerbellMachineConfigList { if in == nil { return nil } out := new(TinkerbellMachineConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellMachineConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellMachineConfigSpec) DeepCopyInto(out *TinkerbellMachineConfigSpec) { *out = *in if in.HardwareSelector != nil { in, out := &in.HardwareSelector, &out.HardwareSelector *out = make(HardwareSelector, len(*in)) for key, val := range *in { (*out)[key] = val } } out.TemplateRef = in.TemplateRef if in.Users != nil { in, out := &in.Users, &out.Users *out = make([]UserConfiguration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.HostOSConfiguration != nil { in, out := &in.HostOSConfiguration, &out.HostOSConfiguration *out = new(HostOSConfiguration) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellMachineConfigSpec. func (in *TinkerbellMachineConfigSpec) DeepCopy() *TinkerbellMachineConfigSpec { if in == nil { return nil } out := new(TinkerbellMachineConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellMachineConfigStatus) DeepCopyInto(out *TinkerbellMachineConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellMachineConfigStatus. func (in *TinkerbellMachineConfigStatus) DeepCopy() *TinkerbellMachineConfigStatus { if in == nil { return nil } out := new(TinkerbellMachineConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellTemplateConfig) DeepCopyInto(out *TinkerbellTemplateConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellTemplateConfig. func (in *TinkerbellTemplateConfig) DeepCopy() *TinkerbellTemplateConfig { if in == nil { return nil } out := new(TinkerbellTemplateConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellTemplateConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellTemplateConfigList) DeepCopyInto(out *TinkerbellTemplateConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]TinkerbellTemplateConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellTemplateConfigList. func (in *TinkerbellTemplateConfigList) DeepCopy() *TinkerbellTemplateConfigList { if in == nil { return nil } out := new(TinkerbellTemplateConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *TinkerbellTemplateConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellTemplateConfigSpec) DeepCopyInto(out *TinkerbellTemplateConfigSpec) { *out = *in in.Template.DeepCopyInto(&out.Template) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellTemplateConfigSpec. func (in *TinkerbellTemplateConfigSpec) DeepCopy() *TinkerbellTemplateConfigSpec { if in == nil { return nil } out := new(TinkerbellTemplateConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *TinkerbellTemplateConfigStatus) DeepCopyInto(out *TinkerbellTemplateConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TinkerbellTemplateConfigStatus. func (in *TinkerbellTemplateConfigStatus) DeepCopy() *TinkerbellTemplateConfigStatus { if in == nil { return nil } out := new(TinkerbellTemplateConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *UserConfiguration) DeepCopyInto(out *UserConfiguration) { *out = *in if in.SshAuthorizedKeys != nil { in, out := &in.SshAuthorizedKeys, &out.SshAuthorizedKeys *out = make([]string, len(*in)) copy(*out, *in) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new UserConfiguration. func (in *UserConfiguration) DeepCopy() *UserConfiguration { if in == nil { return nil } out := new(UserConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereDatacenterConfig) DeepCopyInto(out *VSphereDatacenterConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) out.Spec = in.Spec in.Status.DeepCopyInto(&out.Status) } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereDatacenterConfig. func (in *VSphereDatacenterConfig) DeepCopy() *VSphereDatacenterConfig { if in == nil { return nil } out := new(VSphereDatacenterConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VSphereDatacenterConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereDatacenterConfigList) DeepCopyInto(out *VSphereDatacenterConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]VSphereDatacenterConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereDatacenterConfigList. func (in *VSphereDatacenterConfigList) DeepCopy() *VSphereDatacenterConfigList { if in == nil { return nil } out := new(VSphereDatacenterConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VSphereDatacenterConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereDatacenterConfigSpec) DeepCopyInto(out *VSphereDatacenterConfigSpec) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereDatacenterConfigSpec. func (in *VSphereDatacenterConfigSpec) DeepCopy() *VSphereDatacenterConfigSpec { if in == nil { return nil } out := new(VSphereDatacenterConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereDatacenterConfigStatus) DeepCopyInto(out *VSphereDatacenterConfigStatus) { *out = *in if in.FailureMessage != nil { in, out := &in.FailureMessage, &out.FailureMessage *out = new(string) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereDatacenterConfigStatus. func (in *VSphereDatacenterConfigStatus) DeepCopy() *VSphereDatacenterConfigStatus { if in == nil { return nil } out := new(VSphereDatacenterConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereMachineConfig) DeepCopyInto(out *VSphereMachineConfig) { *out = *in out.TypeMeta = in.TypeMeta in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) in.Spec.DeepCopyInto(&out.Spec) out.Status = in.Status } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereMachineConfig. func (in *VSphereMachineConfig) DeepCopy() *VSphereMachineConfig { if in == nil { return nil } out := new(VSphereMachineConfig) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VSphereMachineConfig) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereMachineConfigList) DeepCopyInto(out *VSphereMachineConfigList) { *out = *in out.TypeMeta = in.TypeMeta in.ListMeta.DeepCopyInto(&out.ListMeta) if in.Items != nil { in, out := &in.Items, &out.Items *out = make([]VSphereMachineConfig, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereMachineConfigList. func (in *VSphereMachineConfigList) DeepCopy() *VSphereMachineConfigList { if in == nil { return nil } out := new(VSphereMachineConfigList) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. func (in *VSphereMachineConfigList) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereMachineConfigSpec) DeepCopyInto(out *VSphereMachineConfigSpec) { *out = *in if in.Users != nil { in, out := &in.Users, &out.Users *out = make([]UserConfiguration, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.TagIDs != nil { in, out := &in.TagIDs, &out.TagIDs *out = make([]string, len(*in)) copy(*out, *in) } if in.HostOSConfiguration != nil { in, out := &in.HostOSConfiguration, &out.HostOSConfiguration *out = new(HostOSConfiguration) (*in).DeepCopyInto(*out) } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereMachineConfigSpec. func (in *VSphereMachineConfigSpec) DeepCopy() *VSphereMachineConfigSpec { if in == nil { return nil } out := new(VSphereMachineConfigSpec) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VSphereMachineConfigStatus) DeepCopyInto(out *VSphereMachineConfigStatus) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VSphereMachineConfigStatus. func (in *VSphereMachineConfigStatus) DeepCopy() *VSphereMachineConfigStatus { if in == nil { return nil } out := new(VSphereMachineConfigStatus) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WorkerNodeGroupConfiguration) DeepCopyInto(out *WorkerNodeGroupConfiguration) { *out = *in if in.Count != nil { in, out := &in.Count, &out.Count *out = new(int) **out = **in } if in.AutoScalingConfiguration != nil { in, out := &in.AutoScalingConfiguration, &out.AutoScalingConfiguration *out = new(AutoScalingConfiguration) **out = **in } if in.MachineGroupRef != nil { in, out := &in.MachineGroupRef, &out.MachineGroupRef *out = new(Ref) **out = **in } if in.Taints != nil { in, out := &in.Taints, &out.Taints *out = make([]v1.Taint, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Labels != nil { in, out := &in.Labels, &out.Labels *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } if in.UpgradeRolloutStrategy != nil { in, out := &in.UpgradeRolloutStrategy, &out.UpgradeRolloutStrategy *out = new(WorkerNodesUpgradeRolloutStrategy) **out = **in } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkerNodeGroupConfiguration. func (in *WorkerNodeGroupConfiguration) DeepCopy() *WorkerNodeGroupConfiguration { if in == nil { return nil } out := new(WorkerNodeGroupConfiguration) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WorkerNodesRollingUpdateParams) DeepCopyInto(out *WorkerNodesRollingUpdateParams) { *out = *in } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkerNodesRollingUpdateParams. func (in *WorkerNodesRollingUpdateParams) DeepCopy() *WorkerNodesRollingUpdateParams { if in == nil { return nil } out := new(WorkerNodesRollingUpdateParams) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *WorkerNodesUpgradeRolloutStrategy) DeepCopyInto(out *WorkerNodesUpgradeRolloutStrategy) { *out = *in out.RollingUpdate = in.RollingUpdate } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WorkerNodesUpgradeRolloutStrategy. func (in *WorkerNodesUpgradeRolloutStrategy) DeepCopy() *WorkerNodesUpgradeRolloutStrategy { if in == nil { return nil } out := new(WorkerNodesUpgradeRolloutStrategy) in.DeepCopyInto(out) return out }
3,067
eks-anywhere
aws
Go
// Package represents https://pkg.go.dev/github.com/tinkerbell/[email protected]/workflow#pkg-types with json tags. // +kubebuilder:object:generate=true package tinkerbell // Workflow represents a workflow to be executed. type Workflow struct { Version string `json:"version"` Name string `json:"name"` ID string `json:"id"` GlobalTimeout int `json:"global_timeout"` Tasks []Task `json:"tasks"` } // Task represents a task to be executed as part of a workflow. type Task struct { Name string `json:"name"` WorkerAddr string `json:"worker"` Actions []Action `json:"actions"` Volumes []string `json:"volumes,omitempty"` Environment map[string]string `json:"environment,omitempty"` } // Action is the basic executional unit for a workflow. type Action struct { Name string `json:"name"` Image string `json:"image"` Timeout int64 `json:"timeout"` Command []string `json:"command,omitempty"` OnTimeout []string `json:"on-timeout,omitempty"` OnFailure []string `json:"on-failure,omitempty"` Volumes []string `json:"volumes,omitempty"` Environment map[string]string `json:"environment,omitempty" yaml:"environment,omitempty"` Pid string `json:"pid,omitempty"` }
35
eks-anywhere
aws
Go
//go:build !ignore_autogenerated // +build !ignore_autogenerated // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. // // 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. // Code generated by controller-gen. DO NOT EDIT. package tinkerbell import () // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Action) DeepCopyInto(out *Action) { *out = *in if in.Command != nil { in, out := &in.Command, &out.Command *out = make([]string, len(*in)) copy(*out, *in) } if in.OnTimeout != nil { in, out := &in.OnTimeout, &out.OnTimeout *out = make([]string, len(*in)) copy(*out, *in) } if in.OnFailure != nil { in, out := &in.OnFailure, &out.OnFailure *out = make([]string, len(*in)) copy(*out, *in) } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes *out = make([]string, len(*in)) copy(*out, *in) } if in.Environment != nil { in, out := &in.Environment, &out.Environment *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Action. func (in *Action) DeepCopy() *Action { if in == nil { return nil } out := new(Action) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Task) DeepCopyInto(out *Task) { *out = *in if in.Actions != nil { in, out := &in.Actions, &out.Actions *out = make([]Action, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } if in.Volumes != nil { in, out := &in.Volumes, &out.Volumes *out = make([]string, len(*in)) copy(*out, *in) } if in.Environment != nil { in, out := &in.Environment, &out.Environment *out = make(map[string]string, len(*in)) for key, val := range *in { (*out)[key] = val } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Task. func (in *Task) DeepCopy() *Task { if in == nil { return nil } out := new(Task) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Workflow) DeepCopyInto(out *Workflow) { *out = *in if in.Tasks != nil { in, out := &in.Tasks, &out.Tasks *out = make([]Task, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Workflow. func (in *Workflow) DeepCopy() *Workflow { if in == nil { return nil } out := new(Workflow) in.DeepCopyInto(out) return out }
121
eks-anywhere
aws
Go
package aws import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" ) // Client provides the single API client to make operations call to aws services. type Client struct { ec2 EC2Client imds IMDSClient snowballDevice SnowballDeviceClient } // Clients are a map between aws profile and its aws client. type Clients map[string]*Client type ServiceEndpoint struct { ServiceID string URL string SigningRegion string } type AwsConfigOpt = config.LoadOptionsFunc func AwsConfigOptSet(opts ...AwsConfigOpt) AwsConfigOpt { return func(conf *config.LoadOptions) error { for _, opt := range opts { if err := opt(conf); err != nil { return err } } return nil } } // LoadConfig reads the optional aws configurations, and populates an AWS Config // with the values from the configurations. func LoadConfig(ctx context.Context, opts ...AwsConfigOpt) (aws.Config, error) { optFns := []func(*config.LoadOptions) error{} for _, opt := range opts { optFns = append(optFns, opt) } cfg, err := config.LoadDefaultConfig(ctx, optFns...) if err != nil { return aws.Config{}, fmt.Errorf("setting aws config: %v", err) } return cfg, nil } // ClientOpt updates an aws.Client. type ClientOpt func(*Client) // WithEC2 returns a ClientOpt that sets the ec2 client. func WithEC2(ec2 EC2Client) ClientOpt { return func(c *Client) { c.ec2 = ec2 } } // WithIMDS returns a ClientOpt that sets the imds client. func WithIMDS(imds IMDSClient) ClientOpt { return func(c *Client) { c.imds = imds } } // WithSnowballDevice returns a ClientOpt that sets the snowballdevice client. func WithSnowballDevice(snowballdevice SnowballDeviceClient) ClientOpt { return func(c *Client) { c.snowballDevice = snowballdevice } } // NewClient builds an aws Client. func NewClient(opts ...ClientOpt) *Client { c := &Client{} for _, o := range opts { o(c) } return c } // NewClientFromConfig builds an aws client with ec2 and snowballdevice apis from aws config. func NewClientFromConfig(cfg aws.Config) *Client { return NewClient( WithEC2(NewEC2Client(cfg)), WithSnowballDevice(NewSnowballClient(cfg)), ) }
99
eks-anywhere
aws
Go
package aws_test import ( "context" "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/aws" ) type awsTest struct { *WithT ctx context.Context } func newAwsTest(t *testing.T) *awsTest { return &awsTest{ WithT: NewWithT(t), ctx: context.Background(), } } func TestLoadConfig(t *testing.T) { tt := newAwsTest(t) _, err := aws.LoadConfig(tt.ctx) tt.Expect(err).To(Succeed()) } func TestLoadConfigSnow(t *testing.T) { tt := newAwsTest(t) config, err := aws.LoadConfig(tt.ctx, aws.WithSnowEndpointAccess("1.2.3.4", certificatesFile, credentialsFile)) tt.Expect(err).To(Succeed()) snowballDeviceEndpoint, err := config.EndpointResolverWithOptions.ResolveEndpoint("Snowball Device", "snow") tt.Expect(snowballDeviceEndpoint.URL).To(Equal("https://1.2.3.4:9092")) tt.Expect(err).To(Succeed()) ec2Endpoint, err := config.EndpointResolverWithOptions.ResolveEndpoint("EC2", "snow") tt.Expect(ec2Endpoint.URL).To(Equal("https://1.2.3.4:8243")) tt.Expect(err).To(Succeed()) }
41
eks-anywhere
aws
Go
package aws import ( "bufio" "encoding/base64" "errors" "fmt" "io" "net" "os" "regexp" "github.com/aws/eks-anywhere/pkg/validations" ) const ( EksaAwsCredentialsFileKey = "EKSA_AWS_CREDENTIALS_FILE" EksaAwsCABundlesFileKey = "EKSA_AWS_CA_BUNDLES_FILE" ) func AwsCredentialsFile() (filePath string, err error) { return validateFileFromEnv(EksaAwsCredentialsFileKey) } func AwsCABundlesFile() (filePath string, err error) { return validateFileFromEnv(EksaAwsCABundlesFileKey) } func validateFileFromEnv(envKey string) (filePath string, err error) { filePath, ok := os.LookupEnv(envKey) if !ok || len(filePath) <= 0 { return "", fmt.Errorf("env '%s' is not set or is empty", envKey) } if !validations.FileExists(filePath) { return "", fmt.Errorf("file '%s' does not exist", filePath) } return filePath, nil } func EncodeFileFromEnv(envKey string) (string, error) { filePath, err := validateFileFromEnv(envKey) if err != nil { return "", err } content, err := os.ReadFile(filePath) if err != nil { return "", fmt.Errorf("unable to read file due to: %v", err) } return base64.StdEncoding.EncodeToString(content), nil } func ParseDeviceIPsFromFile(filePath string) ([]string, error) { file, err := os.Open(filePath) if err != nil { return nil, err } defer file.Close() return ParseDeviceIPs(file) } func ParseDeviceIPs(r io.Reader) ([]string, error) { ips := []string{} scanner := bufio.NewScanner(r) for scanner.Scan() { line := subtractProfileName(scanner.Text()) if net.ParseIP(line) != nil { ips = append(ips, line) } } if len(ips) == 0 { return nil, errors.New("no ip address profile found in content") } if err := scanner.Err(); err != nil { return nil, err } return ips, nil } func subtractProfileName(input string) string { re := regexp.MustCompile(`^\[((.*?))\]$`) if match := re.FindStringSubmatch(input); match != nil { return match[1] } return "" }
91
eks-anywhere
aws
Go
package aws_test import ( "os" "strings" "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/aws" ) const ( credentialsFile = "testdata/valid_credentials" certificatesFile = "testdata/valid_certificates" ) func TestAwsCredentialsFile(t *testing.T) { tt := newAwsTest(t) t.Setenv(aws.EksaAwsCredentialsFileKey, credentialsFile) _, err := aws.AwsCredentialsFile() tt.Expect(err).To(Succeed()) } func TestAwsCredentialsFileEnvNotSet(t *testing.T) { tt := newAwsTest(t) os.Unsetenv(aws.EksaAwsCredentialsFileKey) _, err := aws.AwsCredentialsFile() tt.Expect(err).To((MatchError(ContainSubstring("env 'EKSA_AWS_CREDENTIALS_FILE' is not set or is empty")))) } func TestAwsCredentialsFileNotExists(t *testing.T) { tt := newAwsTest(t) t.Setenv(aws.EksaAwsCredentialsFileKey, "testdata/not_exists_credentials") _, err := aws.AwsCredentialsFile() tt.Expect(err).To((MatchError(ContainSubstring("file 'testdata/not_exists_credentials' does not exist")))) } func TestAwsCABundlesFile(t *testing.T) { tt := newAwsTest(t) t.Setenv(aws.EksaAwsCABundlesFileKey, certificatesFile) _, err := aws.AwsCABundlesFile() tt.Expect(err).To(Succeed()) } func TestAwsCABundlesFileEnvNotSet(t *testing.T) { tt := newAwsTest(t) os.Unsetenv(aws.EksaAwsCABundlesFileKey) _, err := aws.AwsCABundlesFile() tt.Expect(err).To((MatchError(ContainSubstring("env 'EKSA_AWS_CA_BUNDLES_FILE' is not set or is empty")))) } func TestAwsCABundlesFileNotExists(t *testing.T) { tt := newAwsTest(t) t.Setenv(aws.EksaAwsCABundlesFileKey, "testdata/not_exists_certificates") _, err := aws.AwsCABundlesFile() tt.Expect(err).To((MatchError(ContainSubstring("file 'testdata/not_exists_certificates' does not exist")))) } func TestEncodeFileFromEnv(t *testing.T) { tt := newAwsTest(t) t.Setenv(aws.EksaAwsCredentialsFileKey, credentialsFile) strB64, err := aws.EncodeFileFromEnv(aws.EksaAwsCredentialsFileKey) tt.Expect(err).To(Succeed()) tt.Expect(strB64).To(Equal("WzEuMi4zLjRdCmF3c19hY2Nlc3Nfa2V5X2lkID0gQUJDREVGR0hJSktMTU5PUFFSMlQKYXdzX3NlY3JldF9hY2Nlc3Nfa2V5ID0gQWZTRDdzWXovVEJadHprUmVCbDZQdXVJU3pKMld0TmtlZVB3K25OekoKcmVnaW9uID0gc25vdwoKWzEuMi4zLjVdCmF3c19hY2Nlc3Nfa2V5X2lkID0gQUJDREVGR0hJSktMTU5PUFFSMlQKYXdzX3NlY3JldF9hY2Nlc3Nfa2V5ID0gQWZTRDdzWXovVEJadHprUmVCbDZQdXVJU3pKMld0TmtlZVB3K25OekoKcmVnaW9uID0gc25vdw==")) } func TestParseDeviceIPsFromFile(t *testing.T) { tests := []struct { name string creds string want []string wantErr string }{ { name: "validate creds", creds: `[1.2.3.4] aws_access_key_id = ABCDEFGHIJKLMNOPQR2T aws_secret_access_key = AfSD7sYz/TBZtzkReBl6PuuISzJ2WtNkeePw+nNzJ region = snow [1.2.3.5] aws_access_key_id = ABCDEFGHIJKLMNOPQR2T aws_secret_access_key = AfSD7sYz/TBZtzkReBl6PuuISzJ2WtNkeePw+nNzJ region = snow`, want: []string{ "1.2.3.4", "1.2.3.5", }, wantErr: "", }, { name: "no ip in profile", creds: `[invalid profile] aws_access_key_id = ABCDEFGHIJKLMNOPQR2T aws_secret_access_key = AfSD7sYz/TBZtzkReBl6PuuISzJ2WtNkeePw+nNzJ region = snow`, wantErr: "no ip address profile found", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := newAwsTest(t) got, err := aws.ParseDeviceIPs(strings.NewReader(tt.creds)) if tt.wantErr == "" { g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(tt.want)) } else { g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) } }) } }
117
eks-anywhere
aws
Go
package aws import ( "context" "errors" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/smithy-go" ) // EC2Client is an ec2 client that wraps around the aws sdk ec2 client. type EC2Client interface { DescribeImages(ctx context.Context, params *ec2.DescribeImagesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error) DescribeKeyPairs(ctx context.Context, params *ec2.DescribeKeyPairsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeKeyPairsOutput, error) DescribeInstanceTypes(ctx context.Context, params *ec2.DescribeInstanceTypesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeInstanceTypesOutput, error) ImportKeyPair(ctx context.Context, params *ec2.ImportKeyPairInput, optFns ...func(*ec2.Options)) (*ec2.ImportKeyPairOutput, error) } // NewEC2Client builds a new ec2 client. func NewEC2Client(config aws.Config) *ec2.Client { return ec2.NewFromConfig(config) } // EC2ImageExists calls aws sdk ec2.DescribeImages with filter imageID to fetch a // specified images (AMIs, AKIs, and ARIs) available. // Returns (false, nil) if the image does not exist, (true, nil) if image exists, // and (false, err) if there is an non 400 status code error from ec2.DescribeImages. func (c *Client) EC2ImageExists(ctx context.Context, imageID string) (bool, error) { params := &ec2.DescribeImagesInput{ ImageIds: []string{imageID}, } _, err := c.ec2.DescribeImages(ctx, params) if err == nil { return true, nil } var apiErr smithy.APIError if errors.As(err, &apiErr) && apiErr.ErrorCode() == "400" { return false, nil } return false, fmt.Errorf("aws describe image [imageID=%s]: %v", imageID, err) } // EC2KeyNameExists calls aws sdk ec2.DescribeKeyPairs with filter keyName to fetch a // specified key pair available in aws. // Returns (false, nil) if the key pair does not exist, (true, nil) if key pair exists, // and (false, err) if there is an error from ec2.DescribeKeyPairs. func (c *Client) EC2KeyNameExists(ctx context.Context, keyName string) (bool, error) { params := &ec2.DescribeKeyPairsInput{ KeyNames: []string{keyName}, } out, err := c.ec2.DescribeKeyPairs(ctx, params) if err != nil { return false, fmt.Errorf("aws describe key pair [keyName=%s]: %v", keyName, err) } if len(out.KeyPairs) <= 0 { return false, nil } return true, nil } // EC2ImportKeyPair calls aws sdk ec2.ImportKeyPair to import a key pair to ec2. func (c *Client) EC2ImportKeyPair(ctx context.Context, keyName string, keyMaterial []byte) error { params := &ec2.ImportKeyPairInput{ KeyName: &keyName, PublicKeyMaterial: keyMaterial, } _, err := c.ec2.ImportKeyPair(ctx, params) if err != nil { return fmt.Errorf("importing key pairs in ec2: %v", err) } return nil } // EC2InstanceType has the information of an ec2 instance type. type EC2InstanceType struct { Name string DefaultVCPU *int32 } // EC2InstanceTypes calls aws sdk ec2.DescribeInstanceTypes to get a list of supported instance type for a device. func (c *Client) EC2InstanceTypes(ctx context.Context) ([]EC2InstanceType, error) { out, err := c.ec2.DescribeInstanceTypes(ctx, &ec2.DescribeInstanceTypesInput{}) if err != nil { return nil, fmt.Errorf("describing ec2 instance type in device: %v", err) } instanceTypes := make([]EC2InstanceType, 0, len(out.InstanceTypes)) for _, it := range out.InstanceTypes { instanceTypes = append(instanceTypes, EC2InstanceType{ Name: string(it.InstanceType), DefaultVCPU: it.VCpuInfo.DefaultVCpus, }) } return instanceTypes, nil }
99
eks-anywhere
aws
Go
package aws_test import ( "context" "errors" "testing" "github.com/aws/aws-sdk-go-v2/service/ec2" "github.com/aws/aws-sdk-go-v2/service/ec2/types" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/aws" "github.com/aws/eks-anywhere/pkg/aws/mocks" "github.com/aws/eks-anywhere/pkg/utils/ptr" ) type ec2Test struct { *WithT ctx context.Context client *aws.Client ec2 *mocks.MockEC2Client } func newEC2Test(t *testing.T) *ec2Test { ctx := context.Background() ctrl := gomock.NewController(t) ec2 := mocks.NewMockEC2Client(ctrl) return &ec2Test{ WithT: NewWithT(t), ctx: ctx, ec2: ec2, client: aws.NewClient(aws.WithEC2(ec2)), } } func TestEC2ImageExists(t *testing.T) { g := newEC2Test(t) image := "image-1" params := &ec2.DescribeImagesInput{ ImageIds: []string{image}, } g.ec2.EXPECT().DescribeImages(g.ctx, params).Return(nil, nil) got, err := g.client.EC2ImageExists(g.ctx, image) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(true)) } func TestEC2ImageExistsError(t *testing.T) { g := newEC2Test(t) image := "image-1" params := &ec2.DescribeImagesInput{ ImageIds: []string{image}, } g.ec2.EXPECT().DescribeImages(g.ctx, params).Return(nil, errors.New("error")) got, err := g.client.EC2ImageExists(g.ctx, image) g.Expect(err).NotTo(Succeed()) g.Expect(got).To(Equal(false)) } func TestEC2KeyNameExists(t *testing.T) { g := newEC2Test(t) key := "default" params := &ec2.DescribeKeyPairsInput{ KeyNames: []string{key}, } out := &ec2.DescribeKeyPairsOutput{ KeyPairs: []types.KeyPairInfo{ { KeyName: &key, }, }, } g.ec2.EXPECT().DescribeKeyPairs(g.ctx, params).Return(out, nil) got, err := g.client.EC2KeyNameExists(g.ctx, key) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(true)) } func TestKeyPairNotExists(t *testing.T) { g := newEC2Test(t) key := "default" params := &ec2.DescribeKeyPairsInput{ KeyNames: []string{key}, } out := &ec2.DescribeKeyPairsOutput{ KeyPairs: []types.KeyPairInfo{}, } g.ec2.EXPECT().DescribeKeyPairs(g.ctx, params).Return(out, nil) got, err := g.client.EC2KeyNameExists(g.ctx, key) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(false)) } func TestEC2KeyNameExistsError(t *testing.T) { g := newEC2Test(t) key := "default" params := &ec2.DescribeKeyPairsInput{ KeyNames: []string{key}, } g.ec2.EXPECT().DescribeKeyPairs(g.ctx, params).Return(nil, errors.New("error")) got, err := g.client.EC2KeyNameExists(g.ctx, key) g.Expect(err).NotTo(Succeed()) g.Expect(got).To(Equal(false)) } func TestEC2ImportKeyPair(t *testing.T) { g := newEC2Test(t) key := "default" val := []byte("pem") params := &ec2.ImportKeyPairInput{ KeyName: &key, PublicKeyMaterial: []byte(val), } out := &ec2.ImportKeyPairOutput{} g.ec2.EXPECT().ImportKeyPair(g.ctx, params).Return(out, nil) err := g.client.EC2ImportKeyPair(g.ctx, key, val) g.Expect(err).To(Succeed()) } func TestEC2InstanceTypes(t *testing.T) { g := newEC2Test(t) out := &ec2.DescribeInstanceTypesOutput{ InstanceTypes: []types.InstanceTypeInfo{ { InstanceType: types.InstanceTypeC1Medium, VCpuInfo: &types.VCpuInfo{ DefaultVCpus: ptr.Int32(8), }, }, { InstanceType: types.InstanceTypeA1Large, VCpuInfo: &types.VCpuInfo{ DefaultVCpus: ptr.Int32(2), }, }, }, } want := []aws.EC2InstanceType{ { Name: "c1.medium", DefaultVCPU: ptr.Int32(8), }, { Name: "a1.large", DefaultVCPU: ptr.Int32(2), }, } g.ec2.EXPECT().DescribeInstanceTypes(g.ctx, &ec2.DescribeInstanceTypesInput{}).Return(out, nil) got, err := g.client.EC2InstanceTypes(g.ctx) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(want)) } func TestEC2InstanceTypesError(t *testing.T) { g := newEC2Test(t) g.ec2.EXPECT().DescribeInstanceTypes(g.ctx, &ec2.DescribeInstanceTypesInput{}).Return(nil, errors.New("describe instance type error")) _, err := g.client.EC2InstanceTypes(g.ctx) g.Expect(err).To(MatchError(ContainSubstring("describing ec2 instance type in device"))) }
161
eks-anywhere
aws
Go
package aws import ( "context" "errors" "fmt" "io" "reflect" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" ) // IMDSClient is an imds client that wraps around the aws sdk imds client. type IMDSClient interface { GetMetadata(ctx context.Context, params *imds.GetMetadataInput, optFns ...func(*imds.Options)) (*imds.GetMetadataOutput, error) } // NewIMDSClient builds a new imds client. func NewIMDSClient(config aws.Config) *imds.Client { return imds.NewFromConfig(config) } // BuildIMDS builds or overrides the imds client in the Client with default aws config. func (c *Client) BuildIMDS(ctx context.Context) error { cfg, err := LoadConfig(ctx) if err != nil { return fmt.Errorf("loading default aws config: %v", err) } c.imds = NewIMDSClient(cfg) return nil } // EC2InstanceIP calls aws sdk imds.GetMetadata with public-ipv4 path to fetch the instance ip from metadata service. func (c *Client) EC2InstanceIP(ctx context.Context) (string, error) { if c.imds == nil || reflect.ValueOf(c.imds).IsNil() { return "", errors.New("imds client is not initialized") } params := &imds.GetMetadataInput{ Path: "public-ipv4", } out, err := c.imds.GetMetadata(ctx, params) if err != nil { return "", fmt.Errorf("fetching instance IP from IMDSv2: %v", err) } defer out.Content.Close() b, err := io.ReadAll(out.Content) if err != nil { return "", fmt.Errorf("reading output content from IMDSv2 instance ip endpoint: %v", err) } return string(b), nil }
58
eks-anywhere
aws
Go
package aws_test import ( "context" "errors" "io" "strings" "testing" awsv2 "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/aws" "github.com/aws/eks-anywhere/pkg/aws/mocks" ) type imdsTest struct { *WithT ctx context.Context client *aws.Client imds *mocks.MockIMDSClient } func newIMDSTest(t *testing.T) *imdsTest { ctx := context.Background() ctrl := gomock.NewController(t) imds := mocks.NewMockIMDSClient(ctrl) return &imdsTest{ WithT: NewWithT(t), ctx: ctx, imds: imds, client: aws.NewClient(aws.WithIMDS(imds)), } } func TestNewIMDSClient(t *testing.T) { _ = aws.NewIMDSClient(awsv2.Config{}) } func TestBuildIMDS(t *testing.T) { g := newIMDSTest(t) err := g.client.BuildIMDS(g.ctx) g.Expect(err).To(Succeed()) } func TestEC2InstanceIPIMDSNotInit(t *testing.T) { g := newIMDSTest(t) g.client = aws.NewClient() _, err := g.client.EC2InstanceIP(g.ctx) g.Expect(err).To(MatchError(ContainSubstring("imds client is not initialized"))) } func TestEC2InstanceIP(t *testing.T) { g := newIMDSTest(t) params := &imds.GetMetadataInput{ Path: "public-ipv4", } want := "1.2.3.4" out := &imds.GetMetadataOutput{ Content: io.NopCloser(strings.NewReader(want)), } g.imds.EXPECT().GetMetadata(g.ctx, params).Return(out, nil) got, err := g.client.EC2InstanceIP(g.ctx) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(want)) } func TestEC2InstanceIPGetMetadataError(t *testing.T) { g := newIMDSTest(t) params := &imds.GetMetadataInput{ Path: "public-ipv4", } g.imds.EXPECT().GetMetadata(g.ctx, params).Return(nil, errors.New("error")) _, err := g.client.EC2InstanceIP(g.ctx) g.Expect(err).NotTo(Succeed()) }
80
eks-anywhere
aws
Go
package aws import ( "bufio" "context" "fmt" "os" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" ) const ( snowEC2Port = 8243 snowballDevicePort = 9092 ) func BuildClients(ctx context.Context) (Clients, error) { credsFile, err := AwsCredentialsFile() if err != nil { return nil, fmt.Errorf("fetching aws credentials from env: %v", err) } certsFile, err := AwsCABundlesFile() if err != nil { return nil, fmt.Errorf("fetching aws CA bundles from env: %v", err) } deviceIps, err := ParseDeviceIPsFromFile(credsFile) if err != nil { return nil, fmt.Errorf("getting device ips from aws credentials: %v", err) } deviceClientMap := make(Clients, len(deviceIps)) for _, ip := range deviceIps { config, err := LoadConfig(ctx, WithSnowEndpointAccess(ip, certsFile, credsFile)) if err != nil { return nil, fmt.Errorf("setting up aws client: %v", err) } deviceClientMap[ip] = NewClientFromConfig(config) } return deviceClientMap, nil } func snowEndpoints(deviceIP string) []ServiceEndpoint { return []ServiceEndpoint{ { ServiceID: "EC2", SigningRegion: "snow", URL: fmt.Sprintf("https://%s:%d", deviceIP, snowEC2Port), }, { ServiceID: "Snowball Device", SigningRegion: "snow", URL: fmt.Sprintf("https://%s:%d", deviceIP, snowballDevicePort), }, } } // WithCustomCABundleFile is a helper function to construct functional options // that reads an aws certificates file and sets CustomCABundle on config's LoadOptions. func WithCustomCABundleFile(certsFile string) AwsConfigOpt { return func(opts *config.LoadOptions) error { caPEM, err := os.Open(certsFile) if err != nil { return fmt.Errorf("reading aws certificates file: %w", err) } customBundleOpt := config.WithCustomCABundle(bufio.NewReader(caPEM)) if err := customBundleOpt(opts); err != nil { return err } return nil } } // WithSnowEndpointAccess gathers all the config's LoadOptions for snow, // which includes snowball ec2 endpoint, snow credentials for a specific profile, // and CA bundles for accessing the https endpoint. func WithSnowEndpointAccess(deviceIP string, certsFile, credsFile string) AwsConfigOpt { return AwsConfigOptSet( WithCustomCABundleFile(certsFile), config.WithSharedCredentialsFiles([]string{credsFile}), config.WithSharedConfigProfile(deviceIP), config.WithEndpointResolverWithOptions(SnowEndpointResolver(deviceIP)), ) } func SnowEndpointResolver(deviceIP string) aws.EndpointResolverWithOptionsFunc { return aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { for _, endpoint := range snowEndpoints(deviceIP) { if service == endpoint.ServiceID { return aws.Endpoint{ URL: endpoint.URL, SigningRegion: endpoint.SigningRegion, }, nil } } // returning EndpointNotFoundError allows the service to fallback to it's default resolution return aws.Endpoint{}, &aws.EndpointNotFoundError{} }) }
104
eks-anywhere
aws
Go
package aws import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/eks-anywhere/internal/aws-sdk-go-v2/service/snowballdevice" "github.com/aws/eks-anywhere/internal/aws-sdk-go-v2/service/snowballdevice/types" ) type SnowballDeviceClient interface { DescribeDevice(ctx context.Context, params *snowballdevice.DescribeDeviceInput, optFns ...func(*snowballdevice.Options)) (*snowballdevice.DescribeDeviceOutput, error) DescribeDeviceSoftware(ctx context.Context, params *snowballdevice.DescribeDeviceSoftwareInput, optFns ...func(*snowballdevice.Options)) (*snowballdevice.DescribeDeviceSoftwareOutput, error) } func NewSnowballClient(config aws.Config) *snowballdevice.Client { return snowballdevice.NewFromConfig(config) } func (c *Client) IsSnowballDeviceUnlocked(ctx context.Context) (bool, error) { out, err := c.snowballDevice.DescribeDevice(ctx, nil) if err != nil { return false, fmt.Errorf("describing snowball device: %v", err) } return out.UnlockStatus.State == types.UnlockStatusStateUnlocked, nil } func (c *Client) SnowballDeviceSoftwareVersion(ctx context.Context) (string, error) { out, err := c.snowballDevice.DescribeDeviceSoftware(ctx, nil) if err != nil { return "", fmt.Errorf("describing snowball device software: %v", err) } return *out.InstalledVersion, nil }
37
eks-anywhere
aws
Go
package aws_test import ( "context" "errors" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/internal/aws-sdk-go-v2/service/snowballdevice" "github.com/aws/eks-anywhere/internal/aws-sdk-go-v2/service/snowballdevice/types" "github.com/aws/eks-anywhere/pkg/aws" "github.com/aws/eks-anywhere/pkg/aws/mocks" ) type snowballDeviceTest struct { *WithT ctx context.Context client *aws.Client snowballDevice *mocks.MockSnowballDeviceClient } func newSnowballDeviceTest(t *testing.T) *snowballDeviceTest { ctx := context.Background() ctrl := gomock.NewController(t) sbd := mocks.NewMockSnowballDeviceClient(ctrl) return &snowballDeviceTest{ WithT: NewWithT(t), ctx: ctx, snowballDevice: sbd, client: aws.NewClient(aws.WithSnowballDevice(sbd)), } } func TestIsSnowballDeviceUnlockedSuccess(t *testing.T) { g := newSnowballDeviceTest(t) out := &snowballdevice.DescribeDeviceOutput{ UnlockStatus: &types.UnlockStatus{ State: "UNLOCKED", }, } g.snowballDevice.EXPECT().DescribeDevice(g.ctx, nil).Return(out, nil) got, err := g.client.IsSnowballDeviceUnlocked(g.ctx) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(true)) } func TestIsSnowballDeviceUnlockedDescribeDeviceError(t *testing.T) { g := newSnowballDeviceTest(t) g.snowballDevice.EXPECT().DescribeDevice(g.ctx, nil).Return(nil, errors.New("error")) got, err := g.client.IsSnowballDeviceUnlocked(g.ctx) g.Expect(err).NotTo(Succeed()) g.Expect(got).To(Equal(false)) } func TestIsSnowballDeviceUnlockedDeviceLocked(t *testing.T) { g := newSnowballDeviceTest(t) out := &snowballdevice.DescribeDeviceOutput{ UnlockStatus: &types.UnlockStatus{ State: "LOCKED", }, } g.snowballDevice.EXPECT().DescribeDevice(g.ctx, nil).Return(out, nil) got, err := g.client.IsSnowballDeviceUnlocked(g.ctx) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(false)) } func TestSnowballDeviceSoftwareVersionSuccess(t *testing.T) { g := newSnowballDeviceTest(t) version := "100" out := &snowballdevice.DescribeDeviceSoftwareOutput{ InstalledVersion: &version, } g.snowballDevice.EXPECT().DescribeDeviceSoftware(g.ctx, nil).Return(out, nil) got, err := g.client.SnowballDeviceSoftwareVersion(g.ctx) g.Expect(err).To(Succeed()) g.Expect(got).To(Equal(version)) } func TestSnowballDeviceSoftwareVersionDescribeDeviceSoftwareError(t *testing.T) { g := newSnowballDeviceTest(t) g.snowballDevice.EXPECT().DescribeDeviceSoftware(g.ctx, nil).Return(nil, errors.New("error")) got, err := g.client.SnowballDeviceSoftwareVersion(g.ctx) g.Expect(err).NotTo(Succeed()) g.Expect(got).To(Equal("")) }
89
eks-anywhere
aws
Go
package aws_test import ( "context" "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/aws" ) func TestLoadConfigWithSnow(t *testing.T) { tests := []struct { name string certsFilePath string wantErr string }{ { name: "validate certs", certsFilePath: "testdata/valid_certificates", wantErr: "", }, { name: "invalidate certs", certsFilePath: "testdata/invalid_certificates", wantErr: "failed to load custom CA bundle PEM file", }, { name: "certs not exists", certsFilePath: "testdata/nonexists_certificates", wantErr: "no such file or directory", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := newAwsTest(t) _, err := aws.LoadConfig(g.ctx, aws.WithSnowEndpointAccess("device-ip", tt.certsFilePath, "")) if tt.wantErr == "" { g.Expect(err).To(Succeed()) } else { g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) } }) } } func TestBuildSnowAwsClientMap(t *testing.T) { tests := []struct { name string credsFilePath string certsFilePath string wantErr string }{ { name: "valid", credsFilePath: credentialsFile, certsFilePath: certificatesFile, wantErr: "", }, { name: "nonexistent creds", credsFilePath: "testdata/nonexistent", certsFilePath: certificatesFile, wantErr: "fetching aws credentials from env: file 'testdata/nonexistent' does not exist", }, { name: "nonexistent certs", credsFilePath: credentialsFile, certsFilePath: "testdata/nonexistent", wantErr: "fetching aws CA bundles from env: file 'testdata/nonexistent' does not exist", }, { name: "invalid ips in creds", credsFilePath: "testdata/invalid_credentials_no_ips", certsFilePath: certificatesFile, wantErr: "getting device ips from aws credentials: no ip address profile found in content", }, { name: "missing access key in creds", credsFilePath: "testdata/invalid_credentials_no_access_key", certsFilePath: certificatesFile, wantErr: "setting up aws client: setting aws config:", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := newAwsTest(t) ctx := context.Background() t.Setenv(aws.EksaAwsCredentialsFileKey, tt.credsFilePath) t.Setenv(aws.EksaAwsCABundlesFileKey, tt.certsFilePath) _, err := aws.BuildClients(ctx) if tt.wantErr == "" { g.Expect(err).To(Succeed()) } else { g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) } }) } }
102
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/aws/ec2.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" ec2 "github.com/aws/aws-sdk-go-v2/service/ec2" gomock "github.com/golang/mock/gomock" ) // MockEC2Client is a mock of EC2Client interface. type MockEC2Client struct { ctrl *gomock.Controller recorder *MockEC2ClientMockRecorder } // MockEC2ClientMockRecorder is the mock recorder for MockEC2Client. type MockEC2ClientMockRecorder struct { mock *MockEC2Client } // NewMockEC2Client creates a new mock instance. func NewMockEC2Client(ctrl *gomock.Controller) *MockEC2Client { mock := &MockEC2Client{ctrl: ctrl} mock.recorder = &MockEC2ClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockEC2Client) EXPECT() *MockEC2ClientMockRecorder { return m.recorder } // DescribeImages mocks base method. func (m *MockEC2Client) DescribeImages(ctx context.Context, params *ec2.DescribeImagesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeImagesOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DescribeImages", varargs...) ret0, _ := ret[0].(*ec2.DescribeImagesOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // DescribeImages indicates an expected call of DescribeImages. func (mr *MockEC2ClientMockRecorder) DescribeImages(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeImages", reflect.TypeOf((*MockEC2Client)(nil).DescribeImages), varargs...) } // DescribeInstanceTypes mocks base method. func (m *MockEC2Client) DescribeInstanceTypes(ctx context.Context, params *ec2.DescribeInstanceTypesInput, optFns ...func(*ec2.Options)) (*ec2.DescribeInstanceTypesOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DescribeInstanceTypes", varargs...) ret0, _ := ret[0].(*ec2.DescribeInstanceTypesOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // DescribeInstanceTypes indicates an expected call of DescribeInstanceTypes. func (mr *MockEC2ClientMockRecorder) DescribeInstanceTypes(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeInstanceTypes", reflect.TypeOf((*MockEC2Client)(nil).DescribeInstanceTypes), varargs...) } // DescribeKeyPairs mocks base method. func (m *MockEC2Client) DescribeKeyPairs(ctx context.Context, params *ec2.DescribeKeyPairsInput, optFns ...func(*ec2.Options)) (*ec2.DescribeKeyPairsOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DescribeKeyPairs", varargs...) ret0, _ := ret[0].(*ec2.DescribeKeyPairsOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // DescribeKeyPairs indicates an expected call of DescribeKeyPairs. func (mr *MockEC2ClientMockRecorder) DescribeKeyPairs(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeKeyPairs", reflect.TypeOf((*MockEC2Client)(nil).DescribeKeyPairs), varargs...) } // ImportKeyPair mocks base method. func (m *MockEC2Client) ImportKeyPair(ctx context.Context, params *ec2.ImportKeyPairInput, optFns ...func(*ec2.Options)) (*ec2.ImportKeyPairOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "ImportKeyPair", varargs...) ret0, _ := ret[0].(*ec2.ImportKeyPairOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // ImportKeyPair indicates an expected call of ImportKeyPair. func (mr *MockEC2ClientMockRecorder) ImportKeyPair(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImportKeyPair", reflect.TypeOf((*MockEC2Client)(nil).ImportKeyPair), varargs...) }
117
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/aws/imds.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" imds "github.com/aws/aws-sdk-go-v2/feature/ec2/imds" gomock "github.com/golang/mock/gomock" ) // MockIMDSClient is a mock of IMDSClient interface. type MockIMDSClient struct { ctrl *gomock.Controller recorder *MockIMDSClientMockRecorder } // MockIMDSClientMockRecorder is the mock recorder for MockIMDSClient. type MockIMDSClientMockRecorder struct { mock *MockIMDSClient } // NewMockIMDSClient creates a new mock instance. func NewMockIMDSClient(ctrl *gomock.Controller) *MockIMDSClient { mock := &MockIMDSClient{ctrl: ctrl} mock.recorder = &MockIMDSClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockIMDSClient) EXPECT() *MockIMDSClientMockRecorder { return m.recorder } // GetMetadata mocks base method. func (m *MockIMDSClient) GetMetadata(ctx context.Context, params *imds.GetMetadataInput, optFns ...func(*imds.Options)) (*imds.GetMetadataOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "GetMetadata", varargs...) ret0, _ := ret[0].(*imds.GetMetadataOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // GetMetadata indicates an expected call of GetMetadata. func (mr *MockIMDSClientMockRecorder) GetMetadata(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMetadata", reflect.TypeOf((*MockIMDSClient)(nil).GetMetadata), varargs...) }
57
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/aws/snowballdevice.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" snowballdevice "github.com/aws/eks-anywhere/internal/aws-sdk-go-v2/service/snowballdevice" gomock "github.com/golang/mock/gomock" ) // MockSnowballDeviceClient is a mock of SnowballDeviceClient interface. type MockSnowballDeviceClient struct { ctrl *gomock.Controller recorder *MockSnowballDeviceClientMockRecorder } // MockSnowballDeviceClientMockRecorder is the mock recorder for MockSnowballDeviceClient. type MockSnowballDeviceClientMockRecorder struct { mock *MockSnowballDeviceClient } // NewMockSnowballDeviceClient creates a new mock instance. func NewMockSnowballDeviceClient(ctrl *gomock.Controller) *MockSnowballDeviceClient { mock := &MockSnowballDeviceClient{ctrl: ctrl} mock.recorder = &MockSnowballDeviceClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockSnowballDeviceClient) EXPECT() *MockSnowballDeviceClientMockRecorder { return m.recorder } // DescribeDevice mocks base method. func (m *MockSnowballDeviceClient) DescribeDevice(ctx context.Context, params *snowballdevice.DescribeDeviceInput, optFns ...func(*snowballdevice.Options)) (*snowballdevice.DescribeDeviceOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DescribeDevice", varargs...) ret0, _ := ret[0].(*snowballdevice.DescribeDeviceOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // DescribeDevice indicates an expected call of DescribeDevice. func (mr *MockSnowballDeviceClientMockRecorder) DescribeDevice(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeDevice", reflect.TypeOf((*MockSnowballDeviceClient)(nil).DescribeDevice), varargs...) } // DescribeDeviceSoftware mocks base method. func (m *MockSnowballDeviceClient) DescribeDeviceSoftware(ctx context.Context, params *snowballdevice.DescribeDeviceSoftwareInput, optFns ...func(*snowballdevice.Options)) (*snowballdevice.DescribeDeviceSoftwareOutput, error) { m.ctrl.T.Helper() varargs := []interface{}{ctx, params} for _, a := range optFns { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DescribeDeviceSoftware", varargs...) ret0, _ := ret[0].(*snowballdevice.DescribeDeviceSoftwareOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // DescribeDeviceSoftware indicates an expected call of DescribeDeviceSoftware. func (mr *MockSnowballDeviceClientMockRecorder) DescribeDeviceSoftware(ctx, params interface{}, optFns ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, params}, optFns...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DescribeDeviceSoftware", reflect.TypeOf((*MockSnowballDeviceClient)(nil).DescribeDeviceSoftware), varargs...) }
77
eks-anywhere
aws
Go
package awsiamauth import ( "context" "encoding/base64" "fmt" "time" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/retrier" "github.com/aws/eks-anywhere/pkg/types" ) // Client is a Kubernetes client. type Client interface { ApplyKubeSpecFromBytes(ctx context.Context, cluster *types.Cluster, data []byte) error GetApiServerUrl(ctx context.Context, cluster *types.Cluster) (string, error) GetObject(ctx context.Context, resourceType string, name string, namespace string, kubeconfig string, obj runtime.Object) error } // RetrierClient wraps basic kubernetes API operations around a retrier. type RetrierClient struct { client Client retrier retrier.Retrier } // RetrierClientOpt allows to customize a RetrierClient // on construction. type RetrierClientOpt func(*RetrierClient) // RetrierClientRetrier allows to use a custom retrier. func RetrierClientRetrier(retrier retrier.Retrier) RetrierClientOpt { return func(u *RetrierClient) { u.retrier = retrier } } // NewRetrierClient constructs a new RetrierClient. func NewRetrierClient(client Client, opts ...RetrierClientOpt) RetrierClient { c := &RetrierClient{ client: client, retrier: *retrier.NewWithMaxRetries(10, time.Second), } for _, opt := range opts { opt(c) } return *c } // Apply creates/updates the data objects for a cluster. func (c RetrierClient) Apply(ctx context.Context, cluster *types.Cluster, data []byte) error { return c.retrier.Retry( func() error { return c.client.ApplyKubeSpecFromBytes(ctx, cluster, data) }, ) } // GetAPIServerURL gets the api server url from K8s config. func (c RetrierClient) GetAPIServerURL(ctx context.Context, cluster *types.Cluster) (string, error) { var url string err := c.retrier.Retry( func() error { var err error url, err = c.client.GetApiServerUrl(ctx, cluster) return err }, ) if err != nil { return "", err } return url, nil } // GetClusterCACert gets the ca cert for a cluster from a secret. func (c RetrierClient) GetClusterCACert(ctx context.Context, cluster *types.Cluster, clusterName string) ([]byte, error) { secret := &corev1.Secret{} secretName := fmt.Sprintf("%s-ca", clusterName) err := c.retrier.Retry( func() error { return c.client.GetObject(ctx, "secret", secretName, constants.EksaSystemNamespace, cluster.KubeconfigFile, secret) }, ) if err != nil { return nil, err } if crt, ok := secret.Data["tls.crt"]; ok { b64EncodedCrt := make([]byte, base64.StdEncoding.EncodedLen(len(crt))) base64.StdEncoding.Encode(b64EncodedCrt, crt) return b64EncodedCrt, nil } return nil, fmt.Errorf("tls.crt not found in secret [%s]", secretName) }
102
eks-anywhere
aws
Go
package awsiamauth_test import ( "context" "errors" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" "github.com/aws/eks-anywhere/pkg/awsiamauth" "github.com/aws/eks-anywhere/pkg/awsiamauth/mocks" "github.com/aws/eks-anywhere/pkg/retrier" "github.com/aws/eks-anywhere/pkg/types" ) type retrierTest struct { *WithT ctx context.Context r awsiamauth.RetrierClient c *mocks.MockClient cluster *types.Cluster } func newRetrierTest(t *testing.T) *retrierTest { ctrl := gomock.NewController(t) c := mocks.NewMockClient(ctrl) return &retrierTest{ WithT: NewWithT(t), ctx: context.Background(), r: awsiamauth.NewRetrierClient(c, awsiamauth.RetrierClientRetrier(*retrier.NewWithMaxRetries(5, 0))), c: c, cluster: &types.Cluster{ KubeconfigFile: "kubeconfig", }, } } func TestRetrierClientApplySuccess(t *testing.T) { tt := newRetrierTest(t) data := []byte("data") tt.c.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(errors.New("error in apply")).Times(4) tt.c.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(nil).Times(1) tt.Expect(tt.r.Apply(tt.ctx, tt.cluster, data)).To(Succeed(), "retrierClient.apply() should succeed after 5 tries") } func TestRetrierClientApplyError(t *testing.T) { tt := newRetrierTest(t) data := []byte("data") tt.c.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(errors.New("error in apply")).Times(5) tt.c.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(nil).AnyTimes() tt.Expect(tt.r.Apply(tt.ctx, tt.cluster, data)).To(MatchError(ContainSubstring("error in apply")), "retrierClient.apply() should fail after 5 tries") } func TestRetrierClientGetAPIServerURLSuccess(t *testing.T) { tt := newRetrierTest(t) tt.c.EXPECT().GetApiServerUrl(tt.ctx, tt.cluster).Return("", errors.New("error in GetApiServerUrl")).Times(4) tt.c.EXPECT().GetApiServerUrl(tt.ctx, tt.cluster).Return("apiserverurl", nil).Times(1) url, err := tt.r.GetAPIServerURL(tt.ctx, tt.cluster) tt.Expect(url).To(Equal("apiserverurl")) tt.Expect(err).To(Succeed(), "retrierClient.GetApiServerUrl() should succeed after 5 tries") } func TestRetrierClientGetAPIServerURLError(t *testing.T) { tt := newRetrierTest(t) tt.c.EXPECT().GetApiServerUrl(tt.ctx, tt.cluster).Return("", errors.New("error in GetApiServerUrl")).Times(5) tt.c.EXPECT().GetApiServerUrl(tt.ctx, tt.cluster).Return("apiserverurl", nil).AnyTimes() url, err := tt.r.GetAPIServerURL(tt.ctx, tt.cluster) tt.Expect(url).To(Equal("")) tt.Expect(err).To(MatchError(ContainSubstring("error in GetApiServerUrl")), "retrierClient.GetApiServerUrl() should fail after 5 tries") } func TestRetrierClientGetClusterCACertSuccess(t *testing.T) { tt := newRetrierTest(t) tt.c.EXPECT().GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}).Return(errors.New("error in GetObject")).Times(4) tt.c.EXPECT(). GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}). DoAndReturn(func(_ context.Context, _, _, _, _ string, obj *corev1.Secret) error { obj.Data = map[string][]byte{ "tls.crt": []byte("cert"), } return nil }).Times(1) cert, err := tt.r.GetClusterCACert(tt.ctx, tt.cluster, "test-cluster") tt.Expect(cert).To(Equal([]byte("Y2VydA=="))) tt.Expect(err).To(Succeed(), "retrierClient.GetObject() should succeed after 5 tries") } func TestRetrierClientGetClusterCACertError(t *testing.T) { tt := newRetrierTest(t) tt.c.EXPECT().GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}).Return(errors.New("error in GetObject")).Times(5) tt.c.EXPECT().GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}).Return(nil).AnyTimes() cert, err := tt.r.GetClusterCACert(tt.ctx, tt.cluster, "test-cluster") tt.Expect(cert).To(BeNil()) tt.Expect(err).To(MatchError(ContainSubstring("error in GetObject")), "retrierClient.GetObject() should fail after 5 tries") } func TestRetrierClientGetClusterCACertNotFound(t *testing.T) { tt := newRetrierTest(t) tt.c.EXPECT().GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}).Return(errors.New("error in GetObject")).Times(4) tt.c.EXPECT(). GetObject(tt.ctx, "secret", "test-cluster-ca", "eksa-system", tt.cluster.KubeconfigFile, &corev1.Secret{}). DoAndReturn(func(_ context.Context, _, _, _, _ string, obj *corev1.Secret) error { obj.Data = map[string][]byte{ "tls.crt.invalid": []byte("cert"), } return nil }).Times(1) cert, err := tt.r.GetClusterCACert(tt.ctx, tt.cluster, "test-cluster") tt.Expect(cert).To(BeNil()) tt.Expect(err).To(MatchError(ContainSubstring("tls.crt not found in secret [test-cluster-ca]"))) }
121
eks-anywhere
aws
Go
package awsiamauth import ( "context" "errors" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/workflow" "github.com/aws/eks-anywhere/pkg/workflow/management" "github.com/aws/eks-anywhere/pkg/workflow/workflowcontext" ) // HookRegistrar is responsible for binding AWS IAM Auth hooks to workflows so it can be // installed. type HookRegistrar struct { *Installer // Spec is the configuration for the cluster we're trying to create. spec *cluster.Spec } // NewHookRegistrar creates a HookRegistrar instance. func NewHookRegistrar(installer *Installer, spec *cluster.Spec) HookRegistrar { return HookRegistrar{ Installer: installer, spec: spec, } } func (r HookRegistrar) RegisterCreateManagementClusterHooks(binder workflow.HookBinder) { // We need to generate and install a CA certificate to the bootstrap cluster. The secret is // used to populate KubeadmControlPlane objects. The names used for the secret are // hard coded in the KubeadmControlPlane object template files. binder.BindPostTaskHook( management.CreateBootstrapCluster, workflow.TaskFunc(func(ctx context.Context) (context.Context, error) { cluster := workflowcontext.BootstrapCluster(ctx) if cluster == nil { return ctx, errors.New("cluster not found in context") } return ctx, r.CreateAndInstallAWSIAMAuthCASecret(ctx, cluster, r.spec.Cluster.Name) }), ) // Bind a hook to install AWS IAM Authenticator into the permanent workload cluster. binder.BindPostTaskHook( management.CreateWorkloadCluster, workflow.TaskFunc(func(ctx context.Context) (context.Context, error) { management := workflowcontext.BootstrapCluster(ctx) if management == nil { return ctx, errors.New("management cluster not found in context") } workload := workflowcontext.WorkloadCluster(ctx) if workload == nil { return ctx, errors.New("workload cluster not found in context") } return ctx, r.InstallAWSIAMAuth(ctx, management, workload, r.spec) }), ) }
64
eks-anywhere
aws
Go
package awsiamauth import ( "context" "fmt" "github.com/google/uuid" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/crypto" "github.com/aws/eks-anywhere/pkg/filewriter" "github.com/aws/eks-anywhere/pkg/logger" "github.com/aws/eks-anywhere/pkg/types" ) // KubernetesClient provides Kubernetes API access. type KubernetesClient interface { Apply(ctx context.Context, cluster *types.Cluster, data []byte) error GetAPIServerURL(ctx context.Context, cluster *types.Cluster) (string, error) GetClusterCACert(ctx context.Context, cluster *types.Cluster, clusterName string) ([]byte, error) } // Installer provides the necessary behavior for installing the AWS IAM Authenticator. type Installer struct { certgen crypto.CertificateGenerator templateBuilder *TemplateBuilder clusterID uuid.UUID k8s KubernetesClient writer filewriter.FileWriter } // NewInstaller creates a new installer instance. func NewInstaller( certgen crypto.CertificateGenerator, clusterID uuid.UUID, k8s KubernetesClient, writer filewriter.FileWriter, ) *Installer { return &Installer{ certgen: certgen, templateBuilder: &TemplateBuilder{}, clusterID: clusterID, k8s: k8s, writer: writer, } } // CreateAndInstallAWSIAMAuthCASecret creates a Kubernetes Secret in cluster containing a // self-signed certificate and key for a cluster identified by clusterName. func (i *Installer) CreateAndInstallAWSIAMAuthCASecret(ctx context.Context, managementCluster *types.Cluster, clusterName string) error { secret, err := i.generateCertKeyPairSecret(clusterName) if err != nil { return fmt.Errorf("generating aws-iam-authenticator ca secret: %v", err) } if err = i.k8s.Apply(ctx, managementCluster, secret); err != nil { return fmt.Errorf("applying aws-iam-authenticator ca secret: %v", err) } return nil } // InstallAWSIAMAuth installs AWS IAM Authenticator deployment manifests into the workload cluster. // It writes a Kubeconfig to disk for kubectl access using AWS IAM Authentication. func (i *Installer) InstallAWSIAMAuth( ctx context.Context, management, workload *types.Cluster, spec *cluster.Spec, ) error { manifest, err := i.generateManifest(spec) if err != nil { return fmt.Errorf("generating aws-iam-authenticator manifest: %v", err) } if err = i.k8s.Apply(ctx, workload, manifest); err != nil { return fmt.Errorf("applying aws-iam-authenticator manifest: %v", err) } if err = i.generateKubeconfig(ctx, management, workload, spec); err != nil { return err } return nil } // UpgradeAWSIAMAuth upgrades an AWS IAM Authenticator deployment in cluster. func (i *Installer) UpgradeAWSIAMAuth(ctx context.Context, cluster *types.Cluster, spec *cluster.Spec) error { awsIamAuthManifest, err := i.generateManifestForUpgrade(spec) if err != nil { return fmt.Errorf("generating manifest: %v", err) } err = i.k8s.Apply(ctx, cluster, awsIamAuthManifest) if err != nil { return fmt.Errorf("applying manifest: %v", err) } return nil } func (i *Installer) generateManifest(clusterSpec *cluster.Spec) ([]byte, error) { return i.templateBuilder.GenerateManifest(clusterSpec, i.clusterID) } func (i *Installer) generateManifestForUpgrade(clusterSpec *cluster.Spec) ([]byte, error) { return i.templateBuilder.GenerateManifest(clusterSpec, uuid.Nil) } func (i *Installer) generateCertKeyPairSecret(managementClusterName string) ([]byte, error) { return i.templateBuilder.GenerateCertKeyPairSecret(i.certgen, managementClusterName) } func (i *Installer) generateInstallerKubeconfig(clusterSpec *cluster.Spec, serverURL, tlsCert string) ([]byte, error) { return i.templateBuilder.GenerateKubeconfig(clusterSpec, i.clusterID, serverURL, tlsCert) } func (i *Installer) generateKubeconfig( ctx context.Context, management, workload *types.Cluster, spec *cluster.Spec, ) error { fileName := fmt.Sprintf("%s-aws.kubeconfig", workload.Name) serverURL, err := i.k8s.GetAPIServerURL(ctx, workload) if err != nil { return fmt.Errorf("generating aws-iam-authenticator kubeconfig: %v", err) } tlsCert, err := i.k8s.GetClusterCACert( ctx, management, workload.Name, ) if err != nil { return fmt.Errorf("generating aws-iam-authenticator kubeconfig: %v", err) } awsIamAuthKubeconfigContent, err := i.generateInstallerKubeconfig(spec, serverURL, string(tlsCert)) if err != nil { return fmt.Errorf("generating aws-iam-authenticator kubeconfig: %v", err) } writtenFile, err := i.writer.Write( fileName, awsIamAuthKubeconfigContent, filewriter.PersistentFile, filewriter.Permission0600, ) if err != nil { return fmt.Errorf("writing aws-iam-authenticator kubeconfig to %s: %v", writtenFile, err) } logger.V(3).Info("Generated aws-iam-authenticator kubeconfig", "kubeconfig", writtenFile) return nil }
156
eks-anywhere
aws
Go
package awsiamauth_test import ( "context" "errors" "strings" "testing" "github.com/golang/mock/gomock" "github.com/google/uuid" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/internal/test" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/awsiamauth" "github.com/aws/eks-anywhere/pkg/cluster" cryptomocks "github.com/aws/eks-anywhere/pkg/crypto/mocks" "github.com/aws/eks-anywhere/pkg/filewriter" filewritermock "github.com/aws/eks-anywhere/pkg/filewriter/mocks" "github.com/aws/eks-anywhere/pkg/types" releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1" ) func TestInstallAWSIAMAuth(t *testing.T) { ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) clusterID := uuid.MustParse("36db102f-9e1e-4ca4-8300-271d30b14161") var manifest []byte k8s := NewMockKubernetesClient(ctrl) k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(ctx context.Context, cluster *types.Cluster, data []byte) error { manifest = data return nil }, ) k8s.EXPECT().GetAPIServerURL(gomock.Any(), gomock.Any()).Return("api-server-url", nil) k8s.EXPECT().GetClusterCACert(gomock.Any(), gomock.Any(), gomock.Any()).Return([]byte("ca-cert"), nil) var kubeconfig []byte writer := filewritermock.NewMockFileWriter(ctrl) writer.EXPECT().Write(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(fileName string, content []byte, f ...filewriter.FileOptionsFunc) (string, error) { kubeconfig = content return "some file", nil }, ) spec := &cluster.Spec{ Config: &cluster.Config{ Cluster: &v1alpha1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", }, Spec: v1alpha1.ClusterSpec{ KubernetesVersion: v1alpha1.Kube124, }, }, }, VersionsBundle: &cluster.VersionsBundle{ VersionsBundle: &releasev1.VersionsBundle{ Eksa: releasev1.EksaBundle{ DiagnosticCollector: releasev1.Image{ URI: "public.ecr.aws/eks-anywhere/diagnostic-collector:v0.9.1-eks-a-10", }, }, }, KubeDistro: &cluster.KubeDistro{ AwsIamAuthImage: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-sigs/aws-iam-authenticator:v0.5.2-eks-1-18-11", }, }, }, AWSIamConfig: &v1alpha1.AWSIamConfig{ Spec: v1alpha1.AWSIamConfigSpec{ AWSRegion: "test-region", BackendMode: []string{"mode1", "mode2"}, MapRoles: []v1alpha1.MapRoles{ { RoleARN: "test-role-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, MapUsers: []v1alpha1.MapUsers{ { UserARN: "test-user-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, Partition: "test", }, }, } installer := awsiamauth.NewInstaller(certs, clusterID, k8s, writer) err := installer.InstallAWSIAMAuth(context.Background(), &types.Cluster{}, &types.Cluster{}, spec) if err != nil { t.Fatal(err) } test.AssertContentToFile(t, string(kubeconfig), "testdata/InstallAWSIAMAuth-kubeconfig.yaml") test.AssertContentToFile(t, string(manifest), "testdata/InstallAWSIAMAuth-manifest.yaml") } func TestInstallAWSIAMAuthErrors(t *testing.T) { cases := []struct { Name string ConfigureMocks func(err error, k8s *MockKubernetesClient, writer *filewritermock.MockFileWriter) }{ { Name: "ApplyFails", ConfigureMocks: func(err error, k8s *MockKubernetesClient, writer *filewritermock.MockFileWriter) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(err) }, }, { Name: "GetAPIServerURLFails", ConfigureMocks: func(err error, k8s *MockKubernetesClient, writer *filewritermock.MockFileWriter) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) k8s.EXPECT().GetAPIServerURL(gomock.Any(), gomock.Any()).Return("", err) }, }, { Name: "GetClusterCACertFails", ConfigureMocks: func(err error, k8s *MockKubernetesClient, writer *filewritermock.MockFileWriter) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) k8s.EXPECT().GetAPIServerURL(gomock.Any(), gomock.Any()).Return("api-server-url", nil) k8s.EXPECT().GetClusterCACert(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, err) }, }, { Name: "WriteFails", ConfigureMocks: func(err error, k8s *MockKubernetesClient, writer *filewritermock.MockFileWriter) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) k8s.EXPECT().GetAPIServerURL(gomock.Any(), gomock.Any()).Return("api-server-url", nil) k8s.EXPECT().GetClusterCACert(gomock.Any(), gomock.Any(), gomock.Any()).Return([]byte("ca-cert"), nil) writer.EXPECT().Write(gomock.Any(), gomock.Any(), gomock.Any()).Return("", err) }, }, } for _, tc := range cases { t.Run(tc.Name, func(t *testing.T) { ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) clusterID := uuid.MustParse("36db102f-9e1e-4ca4-8300-271d30b14161") k8s := NewMockKubernetesClient(ctrl) writer := filewritermock.NewMockFileWriter(ctrl) tc.ConfigureMocks(errors.New(tc.Name), k8s, writer) spec := &cluster.Spec{ Config: &cluster.Config{ Cluster: &v1alpha1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", }, Spec: v1alpha1.ClusterSpec{ KubernetesVersion: v1alpha1.Kube124, }, }, }, VersionsBundle: &cluster.VersionsBundle{ VersionsBundle: &releasev1.VersionsBundle{ Eksa: releasev1.EksaBundle{ DiagnosticCollector: releasev1.Image{ URI: "public.ecr.aws/eks-anywhere/diagnostic-collector:v0.9.1-eks-a-10", }, }, }, KubeDistro: &cluster.KubeDistro{ AwsIamAuthImage: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-sigs/aws-iam-authenticator:v0.5.2-eks-1-18-11", }, }, }, AWSIamConfig: &v1alpha1.AWSIamConfig{ Spec: v1alpha1.AWSIamConfigSpec{ AWSRegion: "test-region", BackendMode: []string{"mode1", "mode2"}, MapRoles: []v1alpha1.MapRoles{ { RoleARN: "test-role-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, MapUsers: []v1alpha1.MapUsers{ { UserARN: "test-user-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, Partition: "test", }, }, } installer := awsiamauth.NewInstaller(certs, clusterID, k8s, writer) err := installer.InstallAWSIAMAuth(context.Background(), &types.Cluster{}, &types.Cluster{}, spec) if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tc.Name) { t.Fatalf("expected error to contain %q, got %q", tc.Name, err.Error()) } }) } } func TestCreateAndInstallAWSIAMAuthCASecret(t *testing.T) { ctrl := gomock.NewController(t) clusterID := uuid.MustParse("36db102f-9e1e-4ca4-8300-271d30b14161") writer := filewritermock.NewMockFileWriter(ctrl) var manifest []byte k8s := NewMockKubernetesClient(ctrl) k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(ctx context.Context, cluster *types.Cluster, data []byte) error { manifest = data return nil }, ) certs := cryptomocks.NewMockCertificateGenerator(ctrl) certs.EXPECT().GenerateIamAuthSelfSignCertKeyPair().Return([]byte("ca-cert"), []byte("ca-key"), nil) installer := awsiamauth.NewInstaller(certs, clusterID, k8s, writer) err := installer.CreateAndInstallAWSIAMAuthCASecret(context.Background(), &types.Cluster{}, "test-cluster") if err != nil { t.Fatal(err) } test.AssertContentToFile(t, string(manifest), "testdata/CreateAndInstallAWSIAMAuthCASecret-manifest.yaml") } func TestCreateAndInstallAWSIAMAuthCASecretErrors(t *testing.T) { cases := []struct { Name string ConfigureMocks func(err error, k8s *MockKubernetesClient, certs *cryptomocks.MockCertificateGenerator) }{ { Name: "ApplyError", ConfigureMocks: func(err error, k8s *MockKubernetesClient, certs *cryptomocks.MockCertificateGenerator) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(err) }, }, { Name: "GenerateIamAuthSelfSignCertKeyPairError", ConfigureMocks: func(err error, k8s *MockKubernetesClient, certs *cryptomocks.MockCertificateGenerator) { k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) certs.EXPECT().GenerateIamAuthSelfSignCertKeyPair().Return(nil, nil, err) }, }, } for _, tc := range cases { t.Run(tc.Name, func(t *testing.T) { ctrl := gomock.NewController(t) clusterID := uuid.MustParse("36db102f-9e1e-4ca4-8300-271d30b14161") writer := filewritermock.NewMockFileWriter(ctrl) k8s := NewMockKubernetesClient(ctrl) k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).Return(errors.New(tc.Name)) certs := cryptomocks.NewMockCertificateGenerator(ctrl) certs.EXPECT().GenerateIamAuthSelfSignCertKeyPair().Return([]byte("ca-cert"), []byte("ca-key"), nil) installer := awsiamauth.NewInstaller(certs, clusterID, k8s, writer) err := installer.CreateAndInstallAWSIAMAuthCASecret(context.Background(), &types.Cluster{}, "test-cluster") if err == nil { t.Fatal("expected error, got nil") } if !strings.Contains(err.Error(), tc.Name) { t.Fatalf("expected error to contain %q, got %q", tc.Name, err.Error()) } }) } } func TestUpgradeAWSIAMAuth(t *testing.T) { clusterID := uuid.Nil ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) writer := filewritermock.NewMockFileWriter(ctrl) k8s := NewMockKubernetesClient(ctrl) var manifest []byte k8s.EXPECT().Apply(gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(ctx context.Context, cluster *types.Cluster, data []byte) error { manifest = data return nil }, ) installer := awsiamauth.NewInstaller(certs, clusterID, k8s, writer) spec := &cluster.Spec{ Config: &cluster.Config{ Cluster: &v1alpha1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "test-cluster", }, Spec: v1alpha1.ClusterSpec{ KubernetesVersion: v1alpha1.Kube123, }, }, }, VersionsBundle: &cluster.VersionsBundle{ VersionsBundle: &releasev1.VersionsBundle{ Eksa: releasev1.EksaBundle{ DiagnosticCollector: releasev1.Image{ URI: "public.ecr.aws/eks-anywhere/diagnostic-collector:v0.9.1-eks-a-10", }, }, }, KubeDistro: &cluster.KubeDistro{ AwsIamAuthImage: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-sigs/aws-iam-authenticator:v0.5.2-eks-1-18-11", }, }, }, AWSIamConfig: &v1alpha1.AWSIamConfig{ Spec: v1alpha1.AWSIamConfigSpec{ AWSRegion: "test-region", BackendMode: []string{"mode1", "mode2"}, MapRoles: []v1alpha1.MapRoles{ { RoleARN: "test-role-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, MapUsers: []v1alpha1.MapUsers{ { UserARN: "test-user-arn", Username: "test", Groups: []string{"group1", "group2"}, }, }, Partition: "test", }, }, } err := installer.UpgradeAWSIAMAuth(context.Background(), &types.Cluster{}, spec) if err != nil { t.Fatalf("Received unexpected error: %v", err) } test.AssertContentToFile(t, string(manifest), "testdata/UpgradeAWSIAMAuth-manifest.yaml") }
366
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/awsiamauth/installer.go // Package awsiamauth_test is a generated GoMock package. package awsiamauth_test import ( context "context" reflect "reflect" types "github.com/aws/eks-anywhere/pkg/types" gomock "github.com/golang/mock/gomock" ) // MockKubernetesClient is a mock of KubernetesClient interface. type MockKubernetesClient struct { ctrl *gomock.Controller recorder *MockKubernetesClientMockRecorder } // MockKubernetesClientMockRecorder is the mock recorder for MockKubernetesClient. type MockKubernetesClientMockRecorder struct { mock *MockKubernetesClient } // NewMockKubernetesClient creates a new mock instance. func NewMockKubernetesClient(ctrl *gomock.Controller) *MockKubernetesClient { mock := &MockKubernetesClient{ctrl: ctrl} mock.recorder = &MockKubernetesClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKubernetesClient) EXPECT() *MockKubernetesClientMockRecorder { return m.recorder } // Apply mocks base method. func (m *MockKubernetesClient) Apply(ctx context.Context, cluster *types.Cluster, data []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Apply", ctx, cluster, data) ret0, _ := ret[0].(error) return ret0 } // Apply indicates an expected call of Apply. func (mr *MockKubernetesClientMockRecorder) Apply(ctx, cluster, data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockKubernetesClient)(nil).Apply), ctx, cluster, data) } // GetAPIServerURL mocks base method. func (m *MockKubernetesClient) GetAPIServerURL(ctx context.Context, cluster *types.Cluster) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetAPIServerURL", ctx, cluster) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAPIServerURL indicates an expected call of GetAPIServerURL. func (mr *MockKubernetesClientMockRecorder) GetAPIServerURL(ctx, cluster interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAPIServerURL", reflect.TypeOf((*MockKubernetesClient)(nil).GetAPIServerURL), ctx, cluster) } // GetClusterCACert mocks base method. func (m *MockKubernetesClient) GetClusterCACert(ctx context.Context, cluster *types.Cluster, clusterName string) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetClusterCACert", ctx, cluster, clusterName) ret0, _ := ret[0].([]byte) ret1, _ := ret[1].(error) return ret0, ret1 } // GetClusterCACert indicates an expected call of GetClusterCACert. func (mr *MockKubernetesClientMockRecorder) GetClusterCACert(ctx, cluster, clusterName interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClusterCACert", reflect.TypeOf((*MockKubernetesClient)(nil).GetClusterCACert), ctx, cluster, clusterName) }
81
eks-anywhere
aws
Go
package awsiamauth import "fmt" const ( awsIamAuthCaSecretSuffix = "aws-iam-authenticator-ca" awsIamAuthKubeconfigSuffix = "aws-iam-kubeconfig" // AwsIamAuthConfigMapName is the name of AWS IAM Authenticator configuration. AwsIamAuthConfigMapName = "aws-iam-authenticator" // AwsAuthConfigMapName is the name of IAM roles and users mapping for AWS IAM Authenticator. AwsAuthConfigMapName = "aws-auth" ) // CASecretName returns the name of AWS IAM Authenticator secret containing the CA for the cluster. func CASecretName(clusterName string) string { return fmt.Sprintf("%s-%s", clusterName, awsIamAuthCaSecretSuffix) } // KubeconfigSecretName returns the name of the AWS IAM Authenticator kubeconfig secret for the cluster. func KubeconfigSecretName(clusterName string) string { return fmt.Sprintf("%s-%s", clusterName, awsIamAuthKubeconfigSuffix) }
25
eks-anywhere
aws
Go
package awsiamauth_test import ( "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/awsiamauth" ) func TestKubeconfigSecretName(t *testing.T) { g := NewWithT(t) g.Expect(awsiamauth.KubeconfigSecretName("my-cluster")).To(Equal("my-cluster-aws-iam-kubeconfig")) }
15
eks-anywhere
aws
Go
package awsiamauth import ( _ "embed" "encoding/base64" "fmt" "strings" "github.com/google/uuid" "gopkg.in/yaml.v3" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/crypto" "github.com/aws/eks-anywhere/pkg/templater" ) //go:embed config/aws-iam-authenticator.yaml var awsIamAuthTemplate string //go:embed config/aws-iam-authenticator-ca-secret.yaml var awsIamAuthCaSecretTemplate string //go:embed config/aws-iam-authenticator-kubeconfig.yaml var awsIamAuthKubeconfigTemplate string // TemplateBuilder generates manifest files from templates. type TemplateBuilder struct{} // GenerateManifest generates a YAML Kubernetes manifest for deploying the AWS IAM Authenticator. func (t *TemplateBuilder) GenerateManifest(clusterSpec *cluster.Spec, clusterID uuid.UUID) ([]byte, error) { // Give uuid.Nil semantics that result in no ConfigMap being generated containing the cluster ID var clusterIDValue string if clusterID == uuid.Nil { clusterIDValue = "" } else { clusterIDValue = clusterID.String() } data := map[string]interface{}{ "image": clusterSpec.VersionsBundle.KubeDistro.AwsIamAuthImage.VersionedImage(), "initContainerImage": clusterSpec.VersionsBundle.Eksa.DiagnosticCollector.VersionedImage(), "awsRegion": clusterSpec.AWSIamConfig.Spec.AWSRegion, "clusterID": clusterIDValue, "backendMode": strings.Join(clusterSpec.AWSIamConfig.Spec.BackendMode, ","), "partition": clusterSpec.AWSIamConfig.Spec.Partition, } nodeSelector, err := t.setControlPlaneNodeSelector(clusterSpec.Cluster.Spec.KubernetesVersion) if err != nil { return nil, fmt.Errorf("setting control plane node selector: %v", err) } data["cpNodeSelector"] = nodeSelector if clusterSpec.Cluster.Spec.ControlPlaneConfiguration.Taints != nil { data["controlPlaneTaints"] = clusterSpec.Cluster.Spec.ControlPlaneConfiguration.Taints } mapRoles, err := t.mapRolesToYaml(clusterSpec.AWSIamConfig.Spec.MapRoles) if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator manifest: %v", err) } data["mapRoles"] = mapRoles mapUsers, err := t.mapUsersToYaml(clusterSpec.AWSIamConfig.Spec.MapUsers) if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator manifest: %v", err) } data["mapUsers"] = mapUsers awsIamAuthManifest, err := templater.Execute(awsIamAuthTemplate, data) if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator manifest: %v", err) } return awsIamAuthManifest, nil } func (t *TemplateBuilder) mapRolesToYaml(m []v1alpha1.MapRoles) (string, error) { if len(m) == 0 { return "", nil } b, err := yaml.Marshal(m) if err != nil { return "", fmt.Errorf("marshalling AWSIamConfig MapRoles: %v", err) } s := string(b) s = strings.TrimSuffix(s, "\n") return s, nil } func (t *TemplateBuilder) mapUsersToYaml(m []v1alpha1.MapUsers) (string, error) { if len(m) == 0 { return "", nil } b, err := yaml.Marshal(m) if err != nil { return "", fmt.Errorf("marshalling AWSIamConfig MapUsers: %v", err) } s := string(b) s = strings.TrimSuffix(s, "\n") return s, nil } func (t *TemplateBuilder) setControlPlaneNodeSelector(kubeVersion v1alpha1.KubernetesVersion) (string, error) { var nodeSelector string clusterKubeVersionSemver, err := v1alpha1.KubeVersionToSemver(kubeVersion) if err != nil { return "", fmt.Errorf("converting kubeVersion %v to semver %v", kubeVersion, err) } kube124Semver, err := v1alpha1.KubeVersionToSemver(v1alpha1.Kube124) if err != nil { return "", fmt.Errorf("converting kubeVersion %v to semver %v", v1alpha1.Kube124, err) } if clusterKubeVersionSemver.Compare(kube124Semver) != -1 { nodeSelector = `node-role.kubernetes.io/control-plane: ""` } else { nodeSelector = `node-role.kubernetes.io/master: ""` } return nodeSelector, nil } // GenerateCertKeyPairSecret generates a YAML Kubernetes Secret for deploying the AWS IAM Authenticator. func (t *TemplateBuilder) GenerateCertKeyPairSecret(certgen crypto.CertificateGenerator, managementClusterName string) ([]byte, error) { certPemBytes, keyPemBytes, err := certgen.GenerateIamAuthSelfSignCertKeyPair() if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator cert key pair secret: %v", err) } data := map[string]string{ "name": CASecretName(managementClusterName), "namespace": constants.EksaSystemNamespace, "certPemBytes": base64.StdEncoding.EncodeToString(certPemBytes), "keyPemBytes": base64.StdEncoding.EncodeToString(keyPemBytes), } awsIamAuthCaSecret, err := templater.Execute(awsIamAuthCaSecretTemplate, data) if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator cert key pair secret: %v", err) } return awsIamAuthCaSecret, nil } // GenerateKubeconfig generates a Kubeconfig in yaml format to authenticate with AWS IAM Authenticator. func (t *TemplateBuilder) GenerateKubeconfig(clusterSpec *cluster.Spec, clusterID uuid.UUID, serverURL, tlsCert string) ([]byte, error) { data := map[string]string{ "clusterName": clusterSpec.Cluster.Name, "server": serverURL, "cert": tlsCert, "clusterID": clusterID.String(), } awsIamAuthKubeconfig, err := templater.Execute(awsIamAuthKubeconfigTemplate, data) if err != nil { return nil, fmt.Errorf("generating aws-iam-authenticator kubeconfig content: %v", err) } return awsIamAuthKubeconfig, nil }
157
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/awsiamauth/client.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" types "github.com/aws/eks-anywhere/pkg/types" gomock "github.com/golang/mock/gomock" runtime "k8s.io/apimachinery/pkg/runtime" ) // MockClient is a mock of Client interface. type MockClient struct { ctrl *gomock.Controller recorder *MockClientMockRecorder } // MockClientMockRecorder is the mock recorder for MockClient. type MockClientMockRecorder struct { mock *MockClient } // NewMockClient creates a new mock instance. func NewMockClient(ctrl *gomock.Controller) *MockClient { mock := &MockClient{ctrl: ctrl} mock.recorder = &MockClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockClient) EXPECT() *MockClientMockRecorder { return m.recorder } // ApplyKubeSpecFromBytes mocks base method. func (m *MockClient) ApplyKubeSpecFromBytes(ctx context.Context, cluster *types.Cluster, data []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ApplyKubeSpecFromBytes", ctx, cluster, data) ret0, _ := ret[0].(error) return ret0 } // ApplyKubeSpecFromBytes indicates an expected call of ApplyKubeSpecFromBytes. func (mr *MockClientMockRecorder) ApplyKubeSpecFromBytes(ctx, cluster, data interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyKubeSpecFromBytes", reflect.TypeOf((*MockClient)(nil).ApplyKubeSpecFromBytes), ctx, cluster, data) } // GetApiServerUrl mocks base method. func (m *MockClient) GetApiServerUrl(ctx context.Context, cluster *types.Cluster) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetApiServerUrl", ctx, cluster) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetApiServerUrl indicates an expected call of GetApiServerUrl. func (mr *MockClientMockRecorder) GetApiServerUrl(ctx, cluster interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetApiServerUrl", reflect.TypeOf((*MockClient)(nil).GetApiServerUrl), ctx, cluster) } // GetObject mocks base method. func (m *MockClient) GetObject(ctx context.Context, resourceType, name, namespace, kubeconfig string, obj runtime.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetObject", ctx, resourceType, name, namespace, kubeconfig, obj) ret0, _ := ret[0].(error) return ret0 } // GetObject indicates an expected call of GetObject. func (mr *MockClientMockRecorder) GetObject(ctx, resourceType, name, namespace, kubeconfig, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetObject", reflect.TypeOf((*MockClient)(nil).GetObject), ctx, resourceType, name, namespace, kubeconfig, obj) }
81
eks-anywhere
aws
Go
package reconciler import ( "context" "encoding/base64" "fmt" "github.com/go-logr/logr" "github.com/google/uuid" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/awsiamauth" anywhereCluster "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/clusterapi" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/controller" "github.com/aws/eks-anywhere/pkg/controller/clientutil" "github.com/aws/eks-anywhere/pkg/controller/clusters" "github.com/aws/eks-anywhere/pkg/controller/serverside" "github.com/aws/eks-anywhere/pkg/crypto" ) // RemoteClientRegistry defines methods for remote cluster controller clients. type RemoteClientRegistry interface { GetClient(ctx context.Context, cluster client.ObjectKey) (client.Client, error) } // Reconciler allows to reconcile AWSIamConfig. type Reconciler struct { certgen crypto.CertificateGenerator templateBuilder *awsiamauth.TemplateBuilder generateUUID UUIDGenerator client client.Client remoteClientRegistry RemoteClientRegistry } // UUIDGenerator generates a new UUID. type UUIDGenerator func() uuid.UUID // New returns a new Reconciler. func New(certgen crypto.CertificateGenerator, generateUUID UUIDGenerator, client client.Client, remoteClientRegistry RemoteClientRegistry) *Reconciler { return &Reconciler{ certgen: certgen, templateBuilder: &awsiamauth.TemplateBuilder{}, generateUUID: generateUUID, client: client, remoteClientRegistry: remoteClientRegistry, } } // EnsureCASecret ensures the AWS IAM Authenticator secret is present. // It uses a controller.Result to indicate when requeues are needed. func (r *Reconciler) EnsureCASecret(ctx context.Context, log logr.Logger, cluster *anywherev1.Cluster) (controller.Result, error) { clusterName := cluster.Name secretName := awsiamauth.CASecretName(clusterName) s := &corev1.Secret{} err := r.client.Get(ctx, types.NamespacedName{Name: secretName, Namespace: constants.EksaSystemNamespace}, s) if apierrors.IsNotFound(err) { log.Info("Creating aws-iam-authenticator CA secret") return controller.Result{}, r.createCASecret(ctx, cluster) } if err != nil { return controller.Result{}, errors.Wrapf(err, "fetching secret %s", secretName) } log.Info("aws-iam-authenticator CA secret found. Skipping secret create.", "name", secretName) return controller.Result{}, nil } func (r *Reconciler) createCASecret(ctx context.Context, cluster *anywherev1.Cluster) error { yaml, err := r.templateBuilder.GenerateCertKeyPairSecret(r.certgen, cluster.Name) if err != nil { return errors.Wrap(err, "generating aws-iam-authenticator ca secret") } objs, err := clientutil.YamlToClientObjects(yaml) if err != nil { return errors.Wrap(err, "converting aws-iam-authenticator ca secret yaml to objects") } for _, o := range objs { if err := r.client.Create(ctx, o); err != nil { return errors.Wrap(err, "creating aws-iam-authenticator ca secret") } } return nil } // Reconcile takes the AWS IAM Authenticator installation to the desired state defined in AWSIAMConfig. // It uses a controller.Result to indicate when requeues are needed. // Intended to be used in a kubernetes controller. func (r *Reconciler) Reconcile(ctx context.Context, log logr.Logger, cluster *anywherev1.Cluster) (controller.Result, error) { clusterSpec, err := anywhereCluster.BuildSpec(ctx, clientutil.NewKubeClient(r.client), cluster) if err != nil { return controller.Result{}, err } // CheckControlPlaneReady was not meant to be used here. // It was intended as a phase in cluster reconciliation. // TODO (pokearu): Break down the function to better reuse it. result, err := clusters.CheckControlPlaneReady(ctx, r.client, log, cluster) if err != nil { return controller.Result{}, errors.Wrap(err, "checking controlplane ready") } if result.Return() { return result, nil } rClient, err := r.remoteClientRegistry.GetClient(ctx, controller.CapiClusterObjectKey(cluster)) if err != nil { return controller.Result{}, errors.Wrap(err, "getting workload cluster's client to reconcile AWS IAM auth") } var clusterID uuid.UUID cm := &corev1.ConfigMap{} err = rClient.Get(ctx, types.NamespacedName{Name: awsiamauth.AwsIamAuthConfigMapName, Namespace: constants.KubeSystemNamespace}, cm) if apierrors.IsNotFound(err) { // If configmap is not found, this is a first time install of aws-iam-authenticator on the cluster. // We use a newly generated UUID. // The configmap clusterID and kubeconfig token need to match. Hence the kubeconfig secret is created for first install. clusterID = r.generateUUID() log.Info("Creating aws-iam-authenticator kubeconfig secret") if err := r.createKubeconfigSecret(ctx, clusterSpec, cluster, clusterID); err != nil { return controller.Result{}, err } } else if err != nil { return controller.Result{}, errors.Wrapf(err, "fetching configmap %s", awsiamauth.AwsIamAuthConfigMapName) } log.Info("Applying aws-iam-authenticator manifest") if err := r.applyIAMAuthManifest(ctx, rClient, clusterSpec, clusterID); err != nil { return controller.Result{}, errors.Wrap(err, "applying aws-iam-authenticator manifest") } return controller.Result{}, nil } func (r *Reconciler) applyIAMAuthManifest(ctx context.Context, client client.Client, clusterSpec *anywhereCluster.Spec, clusterID uuid.UUID) error { yaml, err := r.templateBuilder.GenerateManifest(clusterSpec, clusterID) if err != nil { return errors.Wrap(err, "generating aws-iam-authenticator manifest") } return serverside.ReconcileYaml(ctx, client, yaml) } func (r *Reconciler) createKubeconfigSecret(ctx context.Context, clusterSpec *anywhereCluster.Spec, cluster *anywherev1.Cluster, clusterID uuid.UUID) error { apiServerEndpoint := fmt.Sprintf("https://%s:6443", cluster.Spec.ControlPlaneConfiguration.Endpoint.Host) clusterCaSecretName := clusterapi.ClusterCASecretName(cluster.Name) clusterCaSecret := &corev1.Secret{} if err := r.client.Get(ctx, types.NamespacedName{Name: clusterCaSecretName, Namespace: constants.EksaSystemNamespace}, clusterCaSecret); err != nil { return errors.Wrap(err, "fetching cluster ca secret") } clusterTLSCrt, ok := clusterCaSecret.Data["tls.crt"] if !ok { return errors.Errorf("tls.crt key not found in cluster CA secret %s", clusterCaSecret.Name) } yaml, err := r.templateBuilder.GenerateKubeconfig(clusterSpec, clusterID, apiServerEndpoint, base64.StdEncoding.EncodeToString(clusterTLSCrt)) if err != nil { return errors.Wrap(err, "generating aws-iam-authenticator kubeconfig") } kubeconfigSecret := &corev1.Secret{ ObjectMeta: v1.ObjectMeta{ Name: awsiamauth.KubeconfigSecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, StringData: map[string]string{ "value": string(yaml), }, } if err := r.client.Create(ctx, kubeconfigSecret); err != nil { return errors.Wrap(err, "creating aws-iam-authenticator kubeconfig secret") } return nil } // ReconcileDelete deletes any AWS Iam authenticator specific resources leftover on the eks-a cluster. func (r *Reconciler) ReconcileDelete(ctx context.Context, log logr.Logger, cluster *anywherev1.Cluster) error { secretName := awsiamauth.CASecretName(cluster.Name) secret := &corev1.Secret{ ObjectMeta: v1.ObjectMeta{ Name: secretName, Namespace: constants.EksaSystemNamespace, }, } log.Info("Deleting aws-iam-authenticator ca secret", "secret", klog.KObj(secret)) if err := r.deleteObject(ctx, secret); err != nil { return err } kubeconfigSecName := awsiamauth.KubeconfigSecretName(cluster.Name) kubeConfigSecret := &corev1.Secret{ ObjectMeta: v1.ObjectMeta{ Name: kubeconfigSecName, Namespace: constants.EksaSystemNamespace, }, } log.Info("Deleting aws-iam-authenticator kubeconfig secret", "secret", klog.KObj(kubeConfigSecret)) if err := r.deleteObject(ctx, kubeConfigSecret); err != nil { return err } return nil } // deleteObject deletes a kubernetes object. It's idempotent, if the object doesn't exist, // it doesn't return an error. func (r *Reconciler) deleteObject(ctx context.Context, obj client.Object) error { err := r.client.Delete(ctx, obj) if apierrors.IsNotFound(err) { return nil } if err != nil { return errors.Wrapf(err, "deleting aws-iam-authenticator %s %s", obj.GetObjectKind(), obj.GetName()) } return nil }
237
eks-anywhere
aws
Go
package reconciler_test import ( "context" "errors" "testing" "time" eksdv1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/go-logr/logr" "github.com/golang/mock/gomock" "github.com/google/uuid" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" logf "sigs.k8s.io/controller-runtime/pkg/log" "github.com/aws/eks-anywhere/internal/test" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/awsiamauth" "github.com/aws/eks-anywhere/pkg/awsiamauth/reconciler" reconcilermocks "github.com/aws/eks-anywhere/pkg/awsiamauth/reconciler/mocks" "github.com/aws/eks-anywhere/pkg/clusterapi" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/controller" cryptomocks "github.com/aws/eks-anywhere/pkg/crypto/mocks" releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1" ) func TestEnsureCASecretSecretFound(t *testing.T) { g := NewWithT(t) ctx := context.Background() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, } sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: awsiamauth.CASecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, } objs := []runtime.Object{sec} cb := fake.NewClientBuilder() cl := cb.WithRuntimeObjects(objs...).Build() r := newReconciler(t, cl) result, err := r.EnsureCASecret(ctx, nullLog(), cluster) g.Expect(err).ToNot(HaveOccurred()) g.Expect(result).To(Equal(controller.Result{})) } func TestEnsureCASecretSecretNotFound(t *testing.T) { g := NewWithT(t) ctx := context.Background() cb := fake.NewClientBuilder() scheme := runtime.NewScheme() _ = anywherev1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) cl := cb.WithScheme(scheme).Build() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, } r := newReconciler(t, cl) result, err := r.EnsureCASecret(ctx, nullLog(), cluster) g.Expect(err).ToNot(HaveOccurred()) g.Expect(result).To(Equal(controller.Result{})) } func TestReconcileDeleteSuccess(t *testing.T) { g := NewWithT(t) ctx := context.Background() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, } sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: awsiamauth.CASecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, } kubeSec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: awsiamauth.KubeconfigSecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, } objs := []runtime.Object{sec, kubeSec} cb := fake.NewClientBuilder() cl := cb.WithRuntimeObjects(objs...).Build() r := newReconciler(t, cl) err := r.ReconcileDelete(ctx, nullLog(), cluster) g.Expect(err).ToNot(HaveOccurred()) } func TestReconcileDeleteNoSecretError(t *testing.T) { g := NewWithT(t) ctx := context.Background() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, } cb := fake.NewClientBuilder() cl := cb.Build() r := newReconciler(t, cl) err := r.ReconcileDelete(ctx, nullLog(), cluster) g.Expect(err).ToNot(HaveOccurred()) } func newReconciler(t *testing.T, client client.WithWatch) *reconciler.Reconciler { ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) generateUUID := uuid.New remoteClientRegistry := reconcilermocks.NewMockRemoteClientRegistry(ctrl) certs.EXPECT().GenerateIamAuthSelfSignCertKeyPair().Return([]byte("ca-cert"), []byte("ca-key"), nil).MinTimes(0).MaxTimes(1) return reconciler.New(certs, generateUUID, client, remoteClientRegistry) } func nullLog() logr.Logger { return logr.New(logf.NullLogSink{}) } func TestReconcileBuildClusterSpecError(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) generateUUID := uuid.New remoteClientRegistry := reconcilermocks.NewMockRemoteClientRegistry(ctrl) cb := fake.NewClientBuilder() cl := cb.Build() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, } r := reconciler.New(certs, generateUUID, cl, remoteClientRegistry) result, err := r.Reconcile(ctx, nullLog(), cluster) g.Expect(err).To(HaveOccurred()) g.Expect(result).To(Equal(controller.Result{})) } func TestReconcileCAPIClusterNotFound(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) generateUUID := uuid.New remoteClientRegistry := reconcilermocks.NewMockRemoteClientRegistry(ctrl) bundle := test.Bundle() eksdRelease := test.EksdRelease() objs := []runtime.Object{bundle, eksdRelease} cb := fake.NewClientBuilder() scheme := runtime.NewScheme() _ = releasev1.AddToScheme(scheme) _ = eksdv1.AddToScheme(scheme) _ = clusterv1.AddToScheme(scheme) cl := cb.WithScheme(scheme).WithRuntimeObjects(objs...).Build() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, Spec: anywherev1.ClusterSpec{ KubernetesVersion: "1.22", BundlesRef: &anywherev1.BundlesRef{ Name: bundle.Name, Namespace: bundle.Namespace, APIVersion: bundle.APIVersion, }, }, } r := reconciler.New(certs, generateUUID, cl, remoteClientRegistry) result, err := r.Reconcile(ctx, nullLog(), cluster) g.Expect(err).ToNot(HaveOccurred()) g.Expect(result).To(Equal(controller.ResultWithRequeue(5 * time.Second))) } func TestReconcileRemoteGetClientError(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) generateUUID := uuid.New remoteClientRegistry := reconcilermocks.NewMockRemoteClientRegistry(ctrl) bundle := test.Bundle() eksdRelease := test.EksdRelease() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, Spec: anywherev1.ClusterSpec{ KubernetesVersion: "1.22", BundlesRef: &anywherev1.BundlesRef{ Name: bundle.Name, Namespace: bundle.Namespace, APIVersion: bundle.APIVersion, }, }, } capiCluster := test.CAPICluster(func(c *clusterv1.Cluster) { c.Name = cluster.Name }) sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: awsiamauth.CASecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, } objs := []runtime.Object{bundle, eksdRelease, capiCluster, sec} cb := fake.NewClientBuilder() scheme := runtime.NewScheme() _ = releasev1.AddToScheme(scheme) _ = eksdv1.AddToScheme(scheme) _ = clusterv1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) cl := cb.WithScheme(scheme).WithRuntimeObjects(objs...).Build() remoteClientRegistry.EXPECT().GetClient(context.Background(), gomock.AssignableToTypeOf(client.ObjectKey{})).Return(nil, errors.New("client error")) r := reconciler.New(certs, generateUUID, cl, remoteClientRegistry) result, err := r.Reconcile(ctx, nullLog(), cluster) g.Expect(err).To(HaveOccurred()) g.Expect(result).To(Equal(controller.Result{})) } func TestReconcileConfigMapNotFoundApplyError(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) certs := cryptomocks.NewMockCertificateGenerator(ctrl) generateUUID := uuid.New remoteClientRegistry := reconcilermocks.NewMockRemoteClientRegistry(ctrl) bundle := test.Bundle() eksdRelease := test.EksdRelease() cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "eksa-system", }, Spec: anywherev1.ClusterSpec{ KubernetesVersion: "1.22", ControlPlaneConfiguration: anywherev1.ControlPlaneConfiguration{ Endpoint: &anywherev1.Endpoint{ Host: "1.2.3.4", }, }, BundlesRef: &anywherev1.BundlesRef{ Name: bundle.Name, Namespace: bundle.Namespace, APIVersion: bundle.APIVersion, }, IdentityProviderRefs: []anywherev1.Ref{ { Name: "aws-config", Kind: "AWSIamConfig", }, }, }, } capiCluster := test.CAPICluster(func(c *clusterv1.Cluster) { c.Name = cluster.Name }) sec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: awsiamauth.CASecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, } caSec := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Name: clusterapi.ClusterCASecretName(cluster.Name), Namespace: constants.EksaSystemNamespace, }, Data: map[string][]byte{ "tls.crt": []byte("LS0tLS1CRUdJTiBDRVJUSUZJQ0FUR"), }, } awsiamconfig := &anywherev1.AWSIamConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "aws-config", Namespace: "eksa-system", }, } objs := []runtime.Object{bundle, eksdRelease, capiCluster, sec, awsiamconfig, caSec} cb := fake.NewClientBuilder() scheme := runtime.NewScheme() _ = anywherev1.AddToScheme(scheme) _ = releasev1.AddToScheme(scheme) _ = eksdv1.AddToScheme(scheme) _ = clusterv1.AddToScheme(scheme) _ = corev1.AddToScheme(scheme) cl := cb.WithScheme(scheme).WithRuntimeObjects(objs...).Build() rCb := fake.NewClientBuilder() rCl := rCb.Build() remoteClientRegistry.EXPECT().GetClient(context.Background(), gomock.AssignableToTypeOf(client.ObjectKey{})).Return(rCl, nil) r := reconciler.New(certs, generateUUID, cl, remoteClientRegistry) result, err := r.Reconcile(ctx, nullLog(), cluster) g.Expect(err).To(HaveOccurred()) g.Expect(result).To(Equal(controller.Result{})) }
334
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/awsiamauth/reconciler/reconciler.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" gomock "github.com/golang/mock/gomock" client "sigs.k8s.io/controller-runtime/pkg/client" ) // MockRemoteClientRegistry is a mock of RemoteClientRegistry interface. type MockRemoteClientRegistry struct { ctrl *gomock.Controller recorder *MockRemoteClientRegistryMockRecorder } // MockRemoteClientRegistryMockRecorder is the mock recorder for MockRemoteClientRegistry. type MockRemoteClientRegistryMockRecorder struct { mock *MockRemoteClientRegistry } // NewMockRemoteClientRegistry creates a new mock instance. func NewMockRemoteClientRegistry(ctrl *gomock.Controller) *MockRemoteClientRegistry { mock := &MockRemoteClientRegistry{ctrl: ctrl} mock.recorder = &MockRemoteClientRegistryMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockRemoteClientRegistry) EXPECT() *MockRemoteClientRegistryMockRecorder { return m.recorder } // GetClient mocks base method. func (m *MockRemoteClientRegistry) GetClient(ctx context.Context, cluster client.ObjectKey) (client.Client, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetClient", ctx, cluster) ret0, _ := ret[0].(client.Client) ret1, _ := ret[1].(error) return ret0, ret1 } // GetClient indicates an expected call of GetClient. func (mr *MockRemoteClientRegistryMockRecorder) GetClient(ctx, cluster interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClient", reflect.TypeOf((*MockRemoteClientRegistry)(nil).GetClient), ctx, cluster) }
52
eks-anywhere
aws
Go
package bootstrapper import ( "context" "errors" "fmt" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/logger" "github.com/aws/eks-anywhere/pkg/types" ) type Bootstrapper struct { clusterClient ClusterClient } type ClusterClient interface { Apply(ctx context.Context, cluster *types.Cluster, data []byte) error CreateNamespace(ctx context.Context, kubeconfig, namespace string) error GetCAPIClusterCRD(ctx context.Context, cluster *types.Cluster) error GetCAPIClusters(ctx context.Context, cluster *types.Cluster) ([]types.CAPICluster, error) KindClusterExists(ctx context.Context, clusterName string) (bool, error) GetKindClusterKubeconfig(ctx context.Context, clusterName string) (string, error) CreateBootstrapCluster(ctx context.Context, clusterSpec *cluster.Spec, opts ...BootstrapClusterClientOption) (string, error) DeleteKindCluster(ctx context.Context, cluster *types.Cluster) error WithExtraDockerMounts() BootstrapClusterClientOption WithExtraPortMappings([]int) BootstrapClusterClientOption WithEnv(env map[string]string) BootstrapClusterClientOption } type ( BootstrapClusterClientOption func() error BootstrapClusterOption func(b *Bootstrapper) BootstrapClusterClientOption ) // New constructs a new bootstrapper. func New(clusterClient ClusterClient) *Bootstrapper { return &Bootstrapper{ clusterClient: clusterClient, } } func (b *Bootstrapper) CreateBootstrapCluster(ctx context.Context, clusterSpec *cluster.Spec, opts ...BootstrapClusterOption) (*types.Cluster, error) { kubeconfigFile, err := b.clusterClient.CreateBootstrapCluster(ctx, clusterSpec, b.getClientOptions(opts)...) if err != nil { return nil, fmt.Errorf("creating bootstrap cluster: %v, try rerunning with --force-cleanup to force delete previously created bootstrap cluster", err) } c := &types.Cluster{ Name: clusterSpec.Cluster.Name, KubeconfigFile: kubeconfigFile, } if err = b.clusterClient.CreateNamespace(ctx, c.KubeconfigFile, constants.EksaSystemNamespace); err != nil { return nil, err } return c, nil } func (b *Bootstrapper) DeleteBootstrapCluster(ctx context.Context, cluster *types.Cluster, operationType constants.Operation, isForceCleanup bool) error { clusterExists, err := b.clusterClient.KindClusterExists(ctx, cluster.Name) if err != nil { return fmt.Errorf("deleting bootstrap cluster: %v", err) } if !clusterExists { logger.V(4).Info("Skipping delete bootstrap cluster, cluster doesn't exist") return nil } mgmtCluster, err := b.managementInCluster(ctx, cluster) if err != nil { return fmt.Errorf("deleting bootstrap cluster: %v", err) } if mgmtCluster != nil { if !isForceCleanup && (operationType == constants.Upgrade || mgmtCluster.Status.Phase == "Provisioned") { return errors.New("error deleting bootstrap cluster: management cluster in bootstrap cluster") } } return b.clusterClient.DeleteKindCluster(ctx, cluster) } func (b *Bootstrapper) managementInCluster(ctx context.Context, cluster *types.Cluster) (*types.CAPICluster, error) { if cluster.KubeconfigFile == "" { kubeconfig, err := b.clusterClient.GetKindClusterKubeconfig(ctx, cluster.Name) if err != nil { return nil, fmt.Errorf("fetching bootstrap cluster's kubeconfig: %v", err) } cluster.KubeconfigFile = kubeconfig } err := b.clusterClient.GetCAPIClusterCRD(ctx, cluster) if err == nil { clusters, err := b.clusterClient.GetCAPIClusters(ctx, cluster) if err != nil { return nil, err } if len(clusters) != 0 { return &clusters[0], nil } } return nil, nil } func (b *Bootstrapper) getClientOptions(opts []BootstrapClusterOption) []BootstrapClusterClientOption { clientOpts := make([]BootstrapClusterClientOption, 0, len(opts)) for _, o := range opts { clientOpts = append(clientOpts, o(b)) } return clientOpts } func WithExtraDockerMounts() BootstrapClusterOption { return func(b *Bootstrapper) BootstrapClusterClientOption { return b.clusterClient.WithExtraDockerMounts() } } func WithExtraPortMappings(ports []int) BootstrapClusterOption { return func(b *Bootstrapper) BootstrapClusterClientOption { return b.clusterClient.WithExtraPortMappings(ports) } } func WithEnv(env map[string]string) BootstrapClusterOption { return func(b *Bootstrapper) BootstrapClusterClientOption { return b.clusterClient.WithEnv(env) } }
133
eks-anywhere
aws
Go
package bootstrapper_test import ( "context" "errors" "reflect" "testing" "github.com/golang/mock/gomock" "github.com/aws/eks-anywhere/internal/test" "github.com/aws/eks-anywhere/pkg/bootstrapper" "github.com/aws/eks-anywhere/pkg/bootstrapper/mocks" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/types" ) func TestBootstrapperCreateBootstrapClusterSuccess(t *testing.T) { kubeconfigFile := "c.kubeconfig" clusterName := "cluster-name" clusterSpec, wantCluster := given(t, clusterName, kubeconfigFile) tests := []struct { testName string opts []bootstrapper.BootstrapClusterOption }{ { testName: "no options", opts: []bootstrapper.BootstrapClusterOption{}, }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().CreateBootstrapCluster(ctx, clusterSpec).Return(kubeconfigFile, nil) client.EXPECT().CreateNamespace(ctx, kubeconfigFile, constants.EksaSystemNamespace) got, err := b.CreateBootstrapCluster(ctx, clusterSpec, tt.opts...) if err != nil { t.Fatalf("Bootstrapper.CreateBootstrapCluster() error = %v, wantErr nil", err) } if !reflect.DeepEqual(got, wantCluster) { t.Fatalf("Bootstrapper.CreateBootstrapCluster() cluster = %#v, want %#v", got, wantCluster) } }) } } func TestBootstrapperCreateBootstrapClusterFailureOnCreateNamespaceIfNotPresentFailure(t *testing.T) { kubeconfigFile := "c.kubeconfig" clusterName := "cluster-name" clusterSpec, _ := given(t, clusterName, kubeconfigFile) clusterSpec.VersionsBundle.KubeVersion = "1.20" clusterSpec.VersionsBundle.KubeDistro.CoreDNS.Tag = "v1.8.3-eks-1-20-1" ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().CreateBootstrapCluster(ctx, clusterSpec).Return(kubeconfigFile, nil) client.EXPECT().CreateNamespace(ctx, kubeconfigFile, constants.EksaSystemNamespace).Return(errors.New("")) _, err := b.CreateBootstrapCluster(ctx, clusterSpec) if err == nil { t.Fatalf("Bootstrapper.CreateBootstrapCluster() error == nil, wantErr %v", err) } } func TestBootstrapperDeleteBootstrapClusterNoBootstrap(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(false, nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Delete, false) if err != nil { t.Fatalf("Bootstrapper.DeleteBootstrapCluster() error = %v, wantErr nil", err) } } func TestBootstrapperDeleteBootstrapClusterNoKubeconfig(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().GetKindClusterKubeconfig(ctx, cluster.Name).Return("c.kubeconfig", nil) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(nil) client.EXPECT().GetCAPIClusters(ctx, cluster).Return(nil, nil) client.EXPECT().DeleteKindCluster(ctx, cluster).Return(nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Delete, false) if err != nil { t.Fatalf("Bootstrapper.DeleteBootstrapCluster() error = %v, wantErr nil", err) } } func TestBootstrapperDeleteBootstrapClusterNoClusterCRD(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(errors.New("cluster crd not found")) client.EXPECT().DeleteKindCluster(ctx, cluster).Return(nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Delete, false) if err != nil { t.Fatalf("Bootstrapper.DeleteBootstrapCluster() error = %v, wantErr nil", err) } } func TestBootstrapperDeleteBootstrapClusterNoManagement(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(nil) client.EXPECT().DeleteKindCluster(ctx, cluster).Return(nil) client.EXPECT().GetCAPIClusters(ctx, cluster).Return(nil, nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Delete, false) if err != nil { t.Fatalf("Bootstrapper.DeleteBootstrapCluster() error = %v, wantErr nil", err) } } func TestBootstrapperDeleteBootstrapClusterErrorWithManagement(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(nil) capiClusters := []types.CAPICluster{ { Metadata: types.Metadata{ Name: "cluster-name", }, Status: types.ClusterStatus{ Phase: "Provisioned", }, }, } client.EXPECT().GetCAPIClusters(ctx, cluster).Return(capiClusters, nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Upgrade, false) if err == nil { t.Fatalf("Bootstrapper.DeleteBootstrapCluster() error == nil, wantErr %v", err) } } func TestBootstrapperDeleteBootstrapClusterCreateOrDelete(t *testing.T) { tests := []struct { testName string clusterPhase string }{ { testName: "ok to delete if phase is Pending", clusterPhase: "Pending", }, { testName: "ok to delete if phase is Provisioning", clusterPhase: "Provisioning", }, { testName: "ok to delete if phase is Failed", clusterPhase: "Failed", }, { testName: "ok to delete if phase is Failed", clusterPhase: "Unknown", }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(nil) capiClusters := []types.CAPICluster{ { Metadata: types.Metadata{ Name: "cluster-name", }, Status: types.ClusterStatus{ Phase: tt.clusterPhase, }, }, } client.EXPECT().GetCAPIClusters(ctx, cluster).Return(capiClusters, nil) client.EXPECT().DeleteKindCluster(ctx, cluster).Return(nil) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Delete, false) if err != nil { t.Fatalf("It shoud be possible to delete a management cluster while in %s phase. Expected error == nil, got %v", tt.clusterPhase, err) } }) } } func TestBootstrapperDeleteBootstrapClusterUpgrade(t *testing.T) { tests := []struct { testName string clusterPhase string }{ { testName: "do not delete if phase is Provisioned during an Upgrade", clusterPhase: "Provisioned", }, { testName: "do not delete if phase is Pending during an Upgrade", clusterPhase: "Pending", }, { testName: "do not delete if phase is Provisioning during an Upgrade", clusterPhase: "Provisioning", }, { testName: "do not delete if phase is Failed during an Upgrade", clusterPhase: "Failed", }, { testName: "do not delete if phase is Failed during an Upgrade", clusterPhase: "Unknown", }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { cluster := &types.Cluster{ Name: "cluster-name", KubeconfigFile: "c.kubeconfig", } ctx := context.Background() b, client := newBootstrapper(t) client.EXPECT().KindClusterExists(ctx, cluster.Name).Return(true, nil) client.EXPECT().GetCAPIClusterCRD(ctx, cluster).Return(nil) capiClusters := []types.CAPICluster{ { Metadata: types.Metadata{ Name: "cluster-name", }, Status: types.ClusterStatus{ Phase: tt.clusterPhase, }, }, } client.EXPECT().GetCAPIClusters(ctx, cluster).Return(capiClusters, nil) client.EXPECT().DeleteKindCluster(ctx, cluster).Return(nil).Times(0) err := b.DeleteBootstrapCluster(ctx, cluster, constants.Upgrade, false) if err == nil { t.Fatalf("upgrade should not delete a management cluster. Expected error == nil, got %v", err) } }) } } func newBootstrapper(t *testing.T) (*bootstrapper.Bootstrapper, *mocks.MockClusterClient) { mockCtrl := gomock.NewController(t) client := mocks.NewMockClusterClient(mockCtrl) b := bootstrapper.New(client) return b, client } func given(t *testing.T, clusterName, kubeconfig string) (clusterSpec *cluster.Spec, wantCluster *types.Cluster) { return test.NewClusterSpec(func(s *cluster.Spec) { s.Cluster.Name = clusterName s.VersionsBundle.KubeVersion = "1.19" s.VersionsBundle.KubeDistro.CoreDNS.Tag = "v1.8.3-eks-1-20-1" }), &types.Cluster{ Name: clusterName, KubeconfigFile: kubeconfig, } }
312
eks-anywhere
aws
Go
package bootstrapper import ( "context" "time" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/retrier" "github.com/aws/eks-anywhere/pkg/types" ) // KindClient is a Kind client. type KindClient interface { CreateBootstrapCluster(ctx context.Context, clusterSpec *cluster.Spec, opts ...BootstrapClusterClientOption) (kubeconfig string, err error) DeleteBootstrapCluster(ctx context.Context, cluster *types.Cluster) error WithExtraDockerMounts() BootstrapClusterClientOption WithExtraPortMappings([]int) BootstrapClusterClientOption WithEnv(env map[string]string) BootstrapClusterClientOption GetKubeconfig(ctx context.Context, clusterName string) (string, error) ClusterExists(ctx context.Context, clusterName string) (bool, error) } // KubernetesClient is a Kubernetes client. type KubernetesClient interface { ApplyKubeSpecFromBytes(ctx context.Context, cluster *types.Cluster, data []byte) error GetClusters(ctx context.Context, cluster *types.Cluster) ([]types.CAPICluster, error) ValidateClustersCRD(ctx context.Context, cluster *types.Cluster) error CreateNamespaceIfNotPresent(ctx context.Context, kubeconfig string, namespace string) error } // RetrierClientOpt allows to customize a RetrierClient // on construction. type RetrierClientOpt func(*RetrierClient) // WithRetrierClientRetrier allows to use a custom retrier. func WithRetrierClientRetrier(retrier retrier.Retrier) RetrierClientOpt { return func(u *RetrierClient) { u.retrier = retrier } } // RetrierClient wraps kind and kubernetes APIs around a retrier. type RetrierClient struct { KindClient k8s KubernetesClient retrier retrier.Retrier } // NewRetrierClient constructs a new RetrierClient. func NewRetrierClient(kind KindClient, k8s KubernetesClient, opts ...RetrierClientOpt) RetrierClient { c := &RetrierClient{ k8s: k8s, KindClient: kind, retrier: *retrier.NewWithMaxRetries(10, 5*time.Second), } for _, opt := range opts { opt(c) } return *c } // Apply creates/updates the data objects for a cluster. func (c RetrierClient) Apply(ctx context.Context, cluster *types.Cluster, data []byte) error { return c.retrier.Retry( func() error { return c.k8s.ApplyKubeSpecFromBytes(ctx, cluster, data) }, ) } // CreateNamespace creates a namespace if the namespace does not exist. func (c RetrierClient) CreateNamespace(ctx context.Context, kubeconfig, namespace string) error { return c.retrier.Retry( func() error { return c.k8s.CreateNamespaceIfNotPresent(ctx, kubeconfig, namespace) }, ) } // GetCAPIClusterCRD gets the capi cluster crd in a K8s cluster. func (c RetrierClient) GetCAPIClusterCRD(ctx context.Context, cluster *types.Cluster) error { return c.retrier.Retry( func() error { return c.k8s.ValidateClustersCRD(ctx, cluster) }, ) } // GetCAPIClusters gets all the capi clusters in a K8s cluster. func (c RetrierClient) GetCAPIClusters(ctx context.Context, cluster *types.Cluster) ([]types.CAPICluster, error) { clusters := []types.CAPICluster{} err := c.retrier.Retry( func() error { var err error clusters, err = c.k8s.GetClusters(ctx, cluster) return err }, ) if err != nil { return nil, err } return clusters, nil } // KindClusterExists checks whether a kind cluster exists by a cluster name. func (c RetrierClient) KindClusterExists(ctx context.Context, clusterName string) (bool, error) { var exists bool err := c.retrier.Retry( func() error { var err error exists, err = c.KindClient.ClusterExists(ctx, clusterName) return err }, ) if err != nil { return false, err } return exists, nil } // GetKindClusterKubeconfig gets the kubeconfig for a kind cluster by cluster name. func (c RetrierClient) GetKindClusterKubeconfig(ctx context.Context, clusterName string) (string, error) { var kubeconfig string err := c.retrier.Retry( func() error { var err error kubeconfig, err = c.KindClient.GetKubeconfig(ctx, clusterName) return err }, ) if err != nil { return "", err } return kubeconfig, nil } // DeleteKindCluster deletes a kind cluster by cluster name. func (c RetrierClient) DeleteKindCluster(ctx context.Context, cluster *types.Cluster) error { return c.retrier.Retry( func() error { return c.KindClient.DeleteBootstrapCluster(ctx, cluster) }, ) }
150
eks-anywhere
aws
Go
package bootstrapper_test import ( "context" "errors" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/internal/test" "github.com/aws/eks-anywhere/pkg/bootstrapper" "github.com/aws/eks-anywhere/pkg/bootstrapper/mocks" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/retrier" "github.com/aws/eks-anywhere/pkg/types" ) type retrierTest struct { *WithT ctx context.Context r bootstrapper.RetrierClient kind *mocks.MockKindClient k8s *mocks.MockKubernetesClient cluster *types.Cluster clusterSpec *cluster.Spec } func newRetrierTest(t *testing.T) *retrierTest { ctrl := gomock.NewController(t) kind := mocks.NewMockKindClient(ctrl) k8s := mocks.NewMockKubernetesClient(ctrl) return &retrierTest{ WithT: NewWithT(t), ctx: context.Background(), r: bootstrapper.NewRetrierClient(kind, k8s, bootstrapper.WithRetrierClientRetrier(*retrier.NewWithMaxRetries(5, 0))), kind: kind, k8s: k8s, cluster: &types.Cluster{ KubeconfigFile: "kubeconfig", }, clusterSpec: test.NewClusterSpec(), } } func TestRetrierClientApplySuccess(t *testing.T) { tt := newRetrierTest(t) data := []byte("data") tt.k8s.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(errors.New("error in apply")).Times(4) tt.k8s.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(nil).Times(1) tt.Expect(tt.r.Apply(tt.ctx, tt.cluster, data)).To(Succeed(), "retrierClient.apply() should succeed after 5 tries") } func TestRetrierClientApplyError(t *testing.T) { tt := newRetrierTest(t) data := []byte("data") tt.k8s.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(errors.New("error in apply")).Times(5) tt.k8s.EXPECT().ApplyKubeSpecFromBytes(tt.ctx, tt.cluster, data).Return(nil).AnyTimes() tt.Expect(tt.r.Apply(tt.ctx, tt.cluster, data)).To(MatchError(ContainSubstring("error in apply")), "retrierClient.apply() should fail after 5 tries") } func TestRetrierClientCreateNamespaceSuccess(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().CreateNamespaceIfNotPresent(tt.ctx, "kubeconfig", "test-namespace").Return(errors.New("error in CreateNamespaceIfNotPresent")).Times(4) tt.k8s.EXPECT().CreateNamespaceIfNotPresent(tt.ctx, "kubeconfig", "test-namespace").Return(nil).Times(1) tt.Expect(tt.r.CreateNamespace(tt.ctx, "kubeconfig", "test-namespace")).To(Succeed(), "retrierClient.CreateNamespace() should succeed after 5 tries") } func TestRetrierClientCreateNamespaceError(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().CreateNamespaceIfNotPresent(tt.ctx, "kubeconfig", "test-namespace").Return(errors.New("error in CreateNamespaceIfNotPresent")).Times(5) tt.k8s.EXPECT().CreateNamespaceIfNotPresent(tt.ctx, "kubeconfig", "test-namespace").Return(nil).AnyTimes() tt.Expect(tt.r.CreateNamespace(tt.ctx, "kubeconfig", "test-namespace")).To(MatchError(ContainSubstring("error in CreateNamespace")), "retrierClient.CreateNamespace() should fail after 5 tries") } func TestRetrierClientGetCAPIClusterCRDSuccess(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().ValidateClustersCRD(tt.ctx, tt.cluster).Return(errors.New("error in ValidateClustersCRD")).Times(4) tt.k8s.EXPECT().ValidateClustersCRD(tt.ctx, tt.cluster).Return(nil).Times(1) tt.Expect(tt.r.GetCAPIClusterCRD(tt.ctx, tt.cluster)).To(Succeed(), "retrierClient.GetCAPIClusterCRD() should succeed after 5 tries") } func TestRetrierClientGetCAPIClusterCRDError(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().ValidateClustersCRD(tt.ctx, tt.cluster).Return(errors.New("error in ValidateClustersCRD")).Times(5) tt.k8s.EXPECT().ValidateClustersCRD(tt.ctx, tt.cluster).Return(nil).AnyTimes() tt.Expect(tt.r.GetCAPIClusterCRD(tt.ctx, tt.cluster)).To(MatchError(ContainSubstring("error in ValidateClustersCRD")), "retrierClient.GetCAPIClusterCRD() should fail after 5 tries") } func TestRetrierClientGetCAPIClustersSuccess(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().GetClusters(tt.ctx, tt.cluster).Return(nil, errors.New("error in GetClusters")).Times(4) tt.k8s.EXPECT().GetClusters(tt.ctx, tt.cluster).Return(nil, nil).Times(1) _, err := tt.r.GetCAPIClusters(tt.ctx, tt.cluster) tt.Expect(err).To(Succeed(), "retrierClient.GetCAPIClusters() should succeed after 5 tries") } func TestRetrierClientGetCAPIClustersError(t *testing.T) { tt := newRetrierTest(t) tt.k8s.EXPECT().GetClusters(tt.ctx, tt.cluster).Return(nil, errors.New("error in GetClusters")).Times(5) tt.k8s.EXPECT().GetClusters(tt.ctx, tt.cluster).Return(nil, nil).AnyTimes() _, err := tt.r.GetCAPIClusters(tt.ctx, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("error in GetClusters")), "retrierClient.GetCAPIClusters() should fail after 5 tries") } func TestRetrierClientKindClusterExistsSuccess(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().ClusterExists(tt.ctx, "test-cluster").Return(false, errors.New("error in ClusterExists")).Times(4) tt.kind.EXPECT().ClusterExists(tt.ctx, "test-cluster").Return(true, nil).Times(1) exists, err := tt.r.KindClusterExists(tt.ctx, "test-cluster") tt.Expect(exists).To(Equal(true)) tt.Expect(err).To(Succeed(), "retrierClient.KindClusterExists() should succeed after 5 tries") } func TestRetrierClientKindClusterExistsError(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().ClusterExists(tt.ctx, "test-cluster").Return(false, errors.New("error in ClusterExists")).Times(5) tt.kind.EXPECT().ClusterExists(tt.ctx, "test-cluster").Return(true, nil).AnyTimes() _, err := tt.r.KindClusterExists(tt.ctx, "test-cluster") tt.Expect(err).To(MatchError(ContainSubstring("error in ClusterExists")), "retrierClient.KindClusterExists() should fail after 5 tries") } func TestRetrierClientGetKindClusterKubeconfigSuccess(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().GetKubeconfig(tt.ctx, "test-cluster").Return("", errors.New("error in GetKubeconfig")).Times(4) tt.kind.EXPECT().GetKubeconfig(tt.ctx, "test-cluster").Return("kubeconfig", nil).Times(1) kubeconfig, err := tt.r.GetKindClusterKubeconfig(tt.ctx, "test-cluster") tt.Expect(kubeconfig).To(Equal("kubeconfig")) tt.Expect(err).To(Succeed(), "retrierClient.GetKindClusterKubeconfig() should succeed after 5 tries") } func TestRetrierClientGetKindClusterKubeconfigError(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().GetKubeconfig(tt.ctx, "test-cluster").Return("", errors.New("error in GetKubeconfig")).Times(5) tt.kind.EXPECT().GetKubeconfig(tt.ctx, "test-cluster").Return("kubeconfig", nil).AnyTimes() _, err := tt.r.GetKindClusterKubeconfig(tt.ctx, "test-cluster") tt.Expect(err).To(MatchError(ContainSubstring("error in GetKubeconfig")), "retrierClient.GetKindClusterKubeconfig() should fail after 5 tries") } func TestRetrierClientDeleteKindClusterSuccess(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().DeleteBootstrapCluster(tt.ctx, tt.cluster).Return(errors.New("error in DeleteBootstrapCluster")).Times(4) tt.kind.EXPECT().DeleteBootstrapCluster(tt.ctx, tt.cluster).Return(nil).Times(1) tt.Expect(tt.r.DeleteKindCluster(tt.ctx, tt.cluster)).To(Succeed(), "retrierClient.DeleteKindCluster() should succeed after 5 tries") } func TestRetrierClientDeleteKindClusterError(t *testing.T) { tt := newRetrierTest(t) tt.kind.EXPECT().DeleteBootstrapCluster(tt.ctx, tt.cluster).Return(errors.New("error in DeleteBootstrapCluster")).Times(5) tt.kind.EXPECT().DeleteBootstrapCluster(tt.ctx, tt.cluster).Return(nil).AnyTimes() tt.Expect(tt.r.DeleteKindCluster(tt.ctx, tt.cluster)).To(MatchError(ContainSubstring("error in DeleteBootstrapCluster")), "retrierClient.DeleteKindCluster() should fail after 5 tries") }
156
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-anywhere/pkg/bootstrapper (interfaces: ClusterClient) // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" bootstrapper "github.com/aws/eks-anywhere/pkg/bootstrapper" cluster "github.com/aws/eks-anywhere/pkg/cluster" types "github.com/aws/eks-anywhere/pkg/types" gomock "github.com/golang/mock/gomock" ) // MockClusterClient is a mock of ClusterClient interface. type MockClusterClient struct { ctrl *gomock.Controller recorder *MockClusterClientMockRecorder } // MockClusterClientMockRecorder is the mock recorder for MockClusterClient. type MockClusterClientMockRecorder struct { mock *MockClusterClient } // NewMockClusterClient creates a new mock instance. func NewMockClusterClient(ctrl *gomock.Controller) *MockClusterClient { mock := &MockClusterClient{ctrl: ctrl} mock.recorder = &MockClusterClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockClusterClient) EXPECT() *MockClusterClientMockRecorder { return m.recorder } // Apply mocks base method. func (m *MockClusterClient) Apply(arg0 context.Context, arg1 *types.Cluster, arg2 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Apply", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // Apply indicates an expected call of Apply. func (mr *MockClusterClientMockRecorder) Apply(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockClusterClient)(nil).Apply), arg0, arg1, arg2) } // CreateBootstrapCluster mocks base method. func (m *MockClusterClient) CreateBootstrapCluster(arg0 context.Context, arg1 *cluster.Spec, arg2 ...bootstrapper.BootstrapClusterClientOption) (string, error) { m.ctrl.T.Helper() varargs := []interface{}{arg0, arg1} for _, a := range arg2 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "CreateBootstrapCluster", varargs...) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // CreateBootstrapCluster indicates an expected call of CreateBootstrapCluster. func (mr *MockClusterClientMockRecorder) CreateBootstrapCluster(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0, arg1}, arg2...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBootstrapCluster", reflect.TypeOf((*MockClusterClient)(nil).CreateBootstrapCluster), varargs...) } // CreateNamespace mocks base method. func (m *MockClusterClient) CreateNamespace(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateNamespace", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // CreateNamespace indicates an expected call of CreateNamespace. func (mr *MockClusterClientMockRecorder) CreateNamespace(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNamespace", reflect.TypeOf((*MockClusterClient)(nil).CreateNamespace), arg0, arg1, arg2) } // DeleteKindCluster mocks base method. func (m *MockClusterClient) DeleteKindCluster(arg0 context.Context, arg1 *types.Cluster) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteKindCluster", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // DeleteKindCluster indicates an expected call of DeleteKindCluster. func (mr *MockClusterClientMockRecorder) DeleteKindCluster(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteKindCluster", reflect.TypeOf((*MockClusterClient)(nil).DeleteKindCluster), arg0, arg1) } // GetCAPIClusterCRD mocks base method. func (m *MockClusterClient) GetCAPIClusterCRD(arg0 context.Context, arg1 *types.Cluster) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCAPIClusterCRD", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // GetCAPIClusterCRD indicates an expected call of GetCAPIClusterCRD. func (mr *MockClusterClientMockRecorder) GetCAPIClusterCRD(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCAPIClusterCRD", reflect.TypeOf((*MockClusterClient)(nil).GetCAPIClusterCRD), arg0, arg1) } // GetCAPIClusters mocks base method. func (m *MockClusterClient) GetCAPIClusters(arg0 context.Context, arg1 *types.Cluster) ([]types.CAPICluster, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCAPIClusters", arg0, arg1) ret0, _ := ret[0].([]types.CAPICluster) ret1, _ := ret[1].(error) return ret0, ret1 } // GetCAPIClusters indicates an expected call of GetCAPIClusters. func (mr *MockClusterClientMockRecorder) GetCAPIClusters(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCAPIClusters", reflect.TypeOf((*MockClusterClient)(nil).GetCAPIClusters), arg0, arg1) } // GetKindClusterKubeconfig mocks base method. func (m *MockClusterClient) GetKindClusterKubeconfig(arg0 context.Context, arg1 string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetKindClusterKubeconfig", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetKindClusterKubeconfig indicates an expected call of GetKindClusterKubeconfig. func (mr *MockClusterClientMockRecorder) GetKindClusterKubeconfig(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetKindClusterKubeconfig", reflect.TypeOf((*MockClusterClient)(nil).GetKindClusterKubeconfig), arg0, arg1) } // KindClusterExists mocks base method. func (m *MockClusterClient) KindClusterExists(arg0 context.Context, arg1 string) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "KindClusterExists", arg0, arg1) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // KindClusterExists indicates an expected call of KindClusterExists. func (mr *MockClusterClientMockRecorder) KindClusterExists(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "KindClusterExists", reflect.TypeOf((*MockClusterClient)(nil).KindClusterExists), arg0, arg1) } // WithEnv mocks base method. func (m *MockClusterClient) WithEnv(arg0 map[string]string) bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithEnv", arg0) ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithEnv indicates an expected call of WithEnv. func (mr *MockClusterClientMockRecorder) WithEnv(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithEnv", reflect.TypeOf((*MockClusterClient)(nil).WithEnv), arg0) } // WithExtraDockerMounts mocks base method. func (m *MockClusterClient) WithExtraDockerMounts() bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithExtraDockerMounts") ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithExtraDockerMounts indicates an expected call of WithExtraDockerMounts. func (mr *MockClusterClientMockRecorder) WithExtraDockerMounts() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithExtraDockerMounts", reflect.TypeOf((*MockClusterClient)(nil).WithExtraDockerMounts)) } // WithExtraPortMappings mocks base method. func (m *MockClusterClient) WithExtraPortMappings(arg0 []int) bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithExtraPortMappings", arg0) ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithExtraPortMappings indicates an expected call of WithExtraPortMappings. func (mr *MockClusterClientMockRecorder) WithExtraPortMappings(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithExtraPortMappings", reflect.TypeOf((*MockClusterClient)(nil).WithExtraPortMappings), arg0) }
202
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/aws/eks-anywhere/pkg/bootstrapper (interfaces: KindClient,KubernetesClient) // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" bootstrapper "github.com/aws/eks-anywhere/pkg/bootstrapper" cluster "github.com/aws/eks-anywhere/pkg/cluster" types "github.com/aws/eks-anywhere/pkg/types" gomock "github.com/golang/mock/gomock" ) // MockKindClient is a mock of KindClient interface. type MockKindClient struct { ctrl *gomock.Controller recorder *MockKindClientMockRecorder } // MockKindClientMockRecorder is the mock recorder for MockKindClient. type MockKindClientMockRecorder struct { mock *MockKindClient } // NewMockKindClient creates a new mock instance. func NewMockKindClient(ctrl *gomock.Controller) *MockKindClient { mock := &MockKindClient{ctrl: ctrl} mock.recorder = &MockKindClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKindClient) EXPECT() *MockKindClientMockRecorder { return m.recorder } // ClusterExists mocks base method. func (m *MockKindClient) ClusterExists(arg0 context.Context, arg1 string) (bool, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ClusterExists", arg0, arg1) ret0, _ := ret[0].(bool) ret1, _ := ret[1].(error) return ret0, ret1 } // ClusterExists indicates an expected call of ClusterExists. func (mr *MockKindClientMockRecorder) ClusterExists(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ClusterExists", reflect.TypeOf((*MockKindClient)(nil).ClusterExists), arg0, arg1) } // CreateBootstrapCluster mocks base method. func (m *MockKindClient) CreateBootstrapCluster(arg0 context.Context, arg1 *cluster.Spec, arg2 ...bootstrapper.BootstrapClusterClientOption) (string, error) { m.ctrl.T.Helper() varargs := []interface{}{arg0, arg1} for _, a := range arg2 { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "CreateBootstrapCluster", varargs...) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // CreateBootstrapCluster indicates an expected call of CreateBootstrapCluster. func (mr *MockKindClientMockRecorder) CreateBootstrapCluster(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{arg0, arg1}, arg2...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateBootstrapCluster", reflect.TypeOf((*MockKindClient)(nil).CreateBootstrapCluster), varargs...) } // DeleteBootstrapCluster mocks base method. func (m *MockKindClient) DeleteBootstrapCluster(arg0 context.Context, arg1 *types.Cluster) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBootstrapCluster", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // DeleteBootstrapCluster indicates an expected call of DeleteBootstrapCluster. func (mr *MockKindClientMockRecorder) DeleteBootstrapCluster(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBootstrapCluster", reflect.TypeOf((*MockKindClient)(nil).DeleteBootstrapCluster), arg0, arg1) } // GetKubeconfig mocks base method. func (m *MockKindClient) GetKubeconfig(arg0 context.Context, arg1 string) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetKubeconfig", arg0, arg1) ret0, _ := ret[0].(string) ret1, _ := ret[1].(error) return ret0, ret1 } // GetKubeconfig indicates an expected call of GetKubeconfig. func (mr *MockKindClientMockRecorder) GetKubeconfig(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetKubeconfig", reflect.TypeOf((*MockKindClient)(nil).GetKubeconfig), arg0, arg1) } // WithEnv mocks base method. func (m *MockKindClient) WithEnv(arg0 map[string]string) bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithEnv", arg0) ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithEnv indicates an expected call of WithEnv. func (mr *MockKindClientMockRecorder) WithEnv(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithEnv", reflect.TypeOf((*MockKindClient)(nil).WithEnv), arg0) } // WithExtraDockerMounts mocks base method. func (m *MockKindClient) WithExtraDockerMounts() bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithExtraDockerMounts") ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithExtraDockerMounts indicates an expected call of WithExtraDockerMounts. func (mr *MockKindClientMockRecorder) WithExtraDockerMounts() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithExtraDockerMounts", reflect.TypeOf((*MockKindClient)(nil).WithExtraDockerMounts)) } // WithExtraPortMappings mocks base method. func (m *MockKindClient) WithExtraPortMappings(arg0 []int) bootstrapper.BootstrapClusterClientOption { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "WithExtraPortMappings", arg0) ret0, _ := ret[0].(bootstrapper.BootstrapClusterClientOption) return ret0 } // WithExtraPortMappings indicates an expected call of WithExtraPortMappings. func (mr *MockKindClientMockRecorder) WithExtraPortMappings(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "WithExtraPortMappings", reflect.TypeOf((*MockKindClient)(nil).WithExtraPortMappings), arg0) } // MockKubernetesClient is a mock of KubernetesClient interface. type MockKubernetesClient struct { ctrl *gomock.Controller recorder *MockKubernetesClientMockRecorder } // MockKubernetesClientMockRecorder is the mock recorder for MockKubernetesClient. type MockKubernetesClientMockRecorder struct { mock *MockKubernetesClient } // NewMockKubernetesClient creates a new mock instance. func NewMockKubernetesClient(ctrl *gomock.Controller) *MockKubernetesClient { mock := &MockKubernetesClient{ctrl: ctrl} mock.recorder = &MockKubernetesClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKubernetesClient) EXPECT() *MockKubernetesClientMockRecorder { return m.recorder } // ApplyKubeSpecFromBytes mocks base method. func (m *MockKubernetesClient) ApplyKubeSpecFromBytes(arg0 context.Context, arg1 *types.Cluster, arg2 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ApplyKubeSpecFromBytes", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // ApplyKubeSpecFromBytes indicates an expected call of ApplyKubeSpecFromBytes. func (mr *MockKubernetesClientMockRecorder) ApplyKubeSpecFromBytes(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyKubeSpecFromBytes", reflect.TypeOf((*MockKubernetesClient)(nil).ApplyKubeSpecFromBytes), arg0, arg1, arg2) } // CreateNamespaceIfNotPresent mocks base method. func (m *MockKubernetesClient) CreateNamespaceIfNotPresent(arg0 context.Context, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateNamespaceIfNotPresent", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 } // CreateNamespaceIfNotPresent indicates an expected call of CreateNamespaceIfNotPresent. func (mr *MockKubernetesClientMockRecorder) CreateNamespaceIfNotPresent(arg0, arg1, arg2 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateNamespaceIfNotPresent", reflect.TypeOf((*MockKubernetesClient)(nil).CreateNamespaceIfNotPresent), arg0, arg1, arg2) } // GetClusters mocks base method. func (m *MockKubernetesClient) GetClusters(arg0 context.Context, arg1 *types.Cluster) ([]types.CAPICluster, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetClusters", arg0, arg1) ret0, _ := ret[0].([]types.CAPICluster) ret1, _ := ret[1].(error) return ret0, ret1 } // GetClusters indicates an expected call of GetClusters. func (mr *MockKubernetesClientMockRecorder) GetClusters(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClusters", reflect.TypeOf((*MockKubernetesClient)(nil).GetClusters), arg0, arg1) } // ValidateClustersCRD mocks base method. func (m *MockKubernetesClient) ValidateClustersCRD(arg0 context.Context, arg1 *types.Cluster) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ValidateClustersCRD", arg0, arg1) ret0, _ := ret[0].(error) return ret0 } // ValidateClustersCRD indicates an expected call of ValidateClustersCRD. func (mr *MockKubernetesClientMockRecorder) ValidateClustersCRD(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ValidateClustersCRD", reflect.TypeOf((*MockKubernetesClient)(nil).ValidateClustersCRD), arg0, arg1) }
225
eks-anywhere
aws
Go
/* Package cli implements usecases logic that are designed to be run exclusively from the cli and need desambiguation. This is, the same or similar concept exists in an eks-a nontroller. */ package cli
6
eks-anywhere
aws
Go
package kubernetes import ( "context" "sigs.k8s.io/controller-runtime/pkg/client" ) // Object is a Kubernetes object. type Object client.Object // ObjectList is a Kubernetes object list. type ObjectList client.ObjectList // Client is Kubernetes API client. type Client interface { Reader Writer } // Reader knows how to read and list Kubernetes objects. type Reader interface { // Get retrieves an obj for the given name and namespace from the Kubernetes Cluster. Get(ctx context.Context, name, namespace string, obj Object) error // List retrieves list of objects. On a successful call, Items field // in the list will be populated with the result returned from the server. List(ctx context.Context, list ObjectList) error } // Writer knows how to create, delete, and update Kubernetes objects. type Writer interface { // Create saves the object obj in the Kubernetes cluster. Create(ctx context.Context, obj Object) error // Update updates the given obj in the Kubernetes cluster. Update(ctx context.Context, obj Object) error // Delete deletes the given obj from Kubernetes cluster. Delete(ctx context.Context, obj Object) error // DeleteAllOf deletes all objects of the given type matching the given options. DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error } // DeleteAllOfOption is some configuration that modifies options for a delete request. type DeleteAllOfOption interface { // ApplyToDeleteAllOf applies this configuration to the given deletecollection options. ApplyToDeleteAllOf(*DeleteAllOfOptions) } // DeleteAllOfOptions contains options for deletecollection (deleteallof) requests. type DeleteAllOfOptions struct { // HasLabels filters results by label and value. The requirement is an AND match // for all labels. HasLabels map[string]string // Namespace represents the namespace to list for, or empty for // non-namespaced objects, or to list across all namespaces. Namespace string } var _ DeleteAllOfOption = &DeleteAllOfOptions{} // ApplyToDeleteAllOf implements DeleteAllOfOption. func (o *DeleteAllOfOptions) ApplyToDeleteAllOf(do *DeleteAllOfOptions) { if o.HasLabels != nil { do.HasLabels = o.HasLabels } if o.Namespace != "" { do.Namespace = o.Namespace } }
74
eks-anywhere
aws
Go
package kubernetes_test import ( "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" ) func TestDeleteAllOfOptionsApplyToDeleteAllOf(t *testing.T) { tests := []struct { name string option, in, want *kubernetes.DeleteAllOfOptions }{ { name: "empty", option: &kubernetes.DeleteAllOfOptions{}, in: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, }, { name: "only Namespace", option: &kubernetes.DeleteAllOfOptions{ Namespace: "other-ns", }, in: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "other-ns", }, }, { name: "Namespace and labels", option: &kubernetes.DeleteAllOfOptions{ Namespace: "other-ns", HasLabels: map[string]string{ "label2": "value2", }, }, in: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label2": "value2", }, Namespace: "other-ns", }, }, { name: "empty not nil labels", option: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{}, }, in: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.DeleteAllOfOptions{ HasLabels: map[string]string{}, Namespace: "ns", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) tt.option.ApplyToDeleteAllOf(tt.in) g.Expect(tt.in).To(BeComparableTo(tt.want)) }) } }
96
eks-anywhere
aws
Go
package kubernetes import ( "context" ) // KubeconfigClient is an authenticated kubernetes API client // it authenticates using the credentials of a kubeconfig file. type KubeconfigClient struct { client *UnAuthClient kubeconfig string } func NewKubeconfigClient(client *UnAuthClient, kubeconfig string) *KubeconfigClient { return &KubeconfigClient{ client: client, kubeconfig: kubeconfig, } } // Get performs a GET call to the kube API server // and unmarshalls the response into the provided Object. func (c *KubeconfigClient) Get(ctx context.Context, name, namespace string, obj Object) error { return c.client.Get(ctx, name, namespace, c.kubeconfig, obj) } // List retrieves list of objects. On a successful call, Items field // in the list will be populated with the result returned from the server. func (c *KubeconfigClient) List(ctx context.Context, list ObjectList) error { return c.client.List(ctx, c.kubeconfig, list) } // Create saves the object obj in the Kubernetes cluster. func (c *KubeconfigClient) Create(ctx context.Context, obj Object) error { return c.client.Create(ctx, c.kubeconfig, obj) } // Update updates the given obj in the Kubernetes cluster. func (c *KubeconfigClient) Update(ctx context.Context, obj Object) error { return c.client.Update(ctx, c.kubeconfig, obj) } // Delete deletes the given obj from Kubernetes cluster. func (c *KubeconfigClient) Delete(ctx context.Context, obj Object) error { return c.client.Delete(ctx, c.kubeconfig, obj) } // DeleteAllOf deletes all objects of the given type matching the given options. func (c *KubeconfigClient) DeleteAllOf(ctx context.Context, obj Object, opts ...DeleteAllOfOption) error { return c.client.DeleteAllOf(ctx, c.kubeconfig, obj, opts...) }
52
eks-anywhere
aws
Go
package kubernetes_test import ( "context" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" "github.com/aws/eks-anywhere/pkg/clients/kubernetes/mocks" ) func TestKubeconfigClientGet(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" name := "eksa cluster" namespace := "eksa-system" obj := &anywherev1.Cluster{} wantResourceType := "Cluster.v1alpha1.anywhere.eks.amazonaws.com" kubectl.EXPECT().Get( ctx, wantResourceType, kubeconfig, obj, &kubernetes.KubectlGetOptions{Name: name, Namespace: namespace}, ) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) g.Expect(kc.Get(ctx, name, namespace, obj)).To(Succeed()) } func TestKubeconfigClientList(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" list := &corev1.NodeList{} kubectl.EXPECT().Get(ctx, "Node", kubeconfig, list) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) g.Expect(kc.List(ctx, list)).To(Succeed()) } func TestKubeconfigClientCreate(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectl.EXPECT().Create(ctx, kubeconfig, obj) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) g.Expect(kc.Create(ctx, obj)).To(Succeed()) } func TestKubeconfigClientUpdate(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectl.EXPECT().Replace(ctx, kubeconfig, obj) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) g.Expect(kc.Update(ctx, obj)).To(Succeed()) } func TestKubeconfigClientDelete(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "my-pod", Namespace: "my-ns", }, } opts := &kubernetes.KubectlDeleteOptions{ Name: "my-pod", Namespace: "my-ns", } kubectl.EXPECT().Delete(ctx, "Pod", kubeconfig, opts) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) g.Expect(kc.Delete(ctx, obj)).To(Succeed()) } func TestKubeconfigClientDeleteAllOf(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectlOpts := &kubernetes.KubectlDeleteOptions{ Namespace: "my-ns", HasLabels: map[string]string{ "k": "v", }, } kubectl.EXPECT().Delete(ctx, "Pod", kubeconfig, kubectlOpts) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) kc, err := c.BuildClientFromKubeconfig(kubeconfig) g.Expect(err).NotTo(HaveOccurred()) deleteOpts := &kubernetes.DeleteAllOfOptions{ Namespace: "my-ns", HasLabels: map[string]string{ "k": "v", }, } g.Expect(kc.DeleteAllOf(ctx, obj, deleteOpts)).To(Succeed()) }
152
eks-anywhere
aws
Go
package kubernetes import ( "context" "k8s.io/apimachinery/pkg/runtime" ) // Kubectl is a client implemented with the kubectl binary. type Kubectl interface { Get(ctx context.Context, resourceType, kubeconfig string, obj runtime.Object, opts ...KubectlGetOption) error Create(ctx context.Context, kubeconfig string, obj runtime.Object) error Replace(ctx context.Context, kubeconfig string, obj runtime.Object) error Apply(ctx context.Context, kubeconfig string, obj runtime.Object) error Delete(ctx context.Context, resourceType, kubeconfig string, opts ...KubectlDeleteOption) error } // KubectlGetOption is some configuration that modifies options for a get request. type KubectlGetOption interface { // ApplyToGet applies this configuration to the given get options. ApplyToGet(*KubectlGetOptions) } // KubectlGetOptions contains options for get commands. type KubectlGetOptions struct { // Name specifies the name of a resource. If set, only one single resource // will be returned (at most). If set, Namespace is required. Name string // Namespace specifies the namespace to retrieve objects from. If not set, // all namespaces will be used. Namespace string // ClusterScoped identifies the resourced as no namespaced. This is mutually exclusive with // Namespace and requires to also specify a Name. ClusterScoped *bool } var _ KubectlGetOption = &KubectlGetOptions{} // ApplyToGet applies this configuration to the given get options. func (o *KubectlGetOptions) ApplyToGet(kgo *KubectlGetOptions) { if o.Name != "" { kgo.Name = o.Name } if o.Namespace != "" { kgo.Namespace = o.Namespace } if o.ClusterScoped != nil { kgo.ClusterScoped = o.ClusterScoped } } // KubectlDeleteOption is some configuration that modifies options for a get request. type KubectlDeleteOption interface { // ApplyToDelete applies this configuration to the given delete options. ApplyToDelete(*KubectlDeleteOptions) } // KubectlDeleteOptions contains options for delete commands. type KubectlDeleteOptions struct { // Name specifies the name of a resource. Use to delete a single resource. // If set, Namespace is required. Name string // Namespace specifies the namespace to delete objects from. If not set, // all namespaces will be used. Namespace string // HasLabels applies a filter using labels to the objects to be deleted. // When multiple label-value pairs are specified, the condition is an AND // for all of them. If specified, Name should be empty. HasLabels map[string]string } var _ KubectlDeleteOption = &KubectlDeleteOptions{} // ApplyToDelete applies this configuration to the given delete options. func (o *KubectlDeleteOptions) ApplyToDelete(kdo *KubectlDeleteOptions) { if o.Name != "" { kdo.Name = o.Name } if o.Namespace != "" { kdo.Namespace = o.Namespace } if o.HasLabels != nil { kdo.HasLabels = o.HasLabels } }
90
eks-anywhere
aws
Go
package kubernetes_test import ( "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" "github.com/aws/eks-anywhere/pkg/utils/ptr" ) func TestKubectlGetOptionsApplyToGet(t *testing.T) { tests := []struct { name string option, in, want *kubernetes.KubectlGetOptions }{ { name: "empty", option: &kubernetes.KubectlGetOptions{}, in: &kubernetes.KubectlGetOptions{ Name: "my-name", Namespace: "ns", }, want: &kubernetes.KubectlGetOptions{ Name: "my-name", Namespace: "ns", }, }, { name: "only Namespace", option: &kubernetes.KubectlGetOptions{ Namespace: "other-ns", }, in: &kubernetes.KubectlGetOptions{ Name: "my-name", Namespace: "ns", }, want: &kubernetes.KubectlGetOptions{ Name: "my-name", Namespace: "other-ns", }, }, { name: "Namespace and Name", option: &kubernetes.KubectlGetOptions{ Name: "my-other-name", Namespace: "other-ns", }, in: &kubernetes.KubectlGetOptions{ Name: "my-name", Namespace: "ns", }, want: &kubernetes.KubectlGetOptions{ Name: "my-other-name", Namespace: "other-ns", }, }, { name: "Name and ClusterScope", option: &kubernetes.KubectlGetOptions{ Name: "my-other-name", ClusterScoped: ptr.Bool(true), }, in: &kubernetes.KubectlGetOptions{ Name: "my-name", }, want: &kubernetes.KubectlGetOptions{ Name: "my-other-name", ClusterScoped: ptr.Bool(true), }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) tt.option.ApplyToGet(tt.in) g.Expect(tt.in).To(BeComparableTo(tt.want)) }) } } func TestKubectlDeleteOptionsApplyToDelete(t *testing.T) { tests := []struct { name string option, in, want *kubernetes.KubectlDeleteOptions }{ { name: "empty", option: &kubernetes.KubectlDeleteOptions{}, in: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, }, { name: "only Namespace", option: &kubernetes.KubectlDeleteOptions{ Namespace: "other-ns", }, in: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "other-ns", }, }, { name: "Namespace and labels", option: &kubernetes.KubectlDeleteOptions{ Namespace: "other-ns", HasLabels: map[string]string{ "label2": "value2", }, }, in: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label2": "value2", }, Namespace: "other-ns", }, }, { name: "empty not nil labels", option: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{}, }, in: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{ "label": "value", }, Namespace: "ns", }, want: &kubernetes.KubectlDeleteOptions{ HasLabels: map[string]string{}, Namespace: "ns", }, }, { name: "Namespace and Name", option: &kubernetes.KubectlDeleteOptions{ Name: "my-other-name", Namespace: "other-ns", }, in: &kubernetes.KubectlDeleteOptions{ Name: "my-name", Namespace: "ns", }, want: &kubernetes.KubectlDeleteOptions{ Name: "my-other-name", Namespace: "other-ns", }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) tt.option.ApplyToDelete(tt.in) g.Expect(tt.in).To(BeComparableTo(tt.want)) }) } }
182
eks-anywhere
aws
Go
package kubernetes import ( "fmt" "os" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" ) // ClientFactory builds clients from a kubeconfig file by // wrapping around NewRuntimeClientFromFileName to facilitate mocking. type ClientFactory struct{} // BuildClientFromKubeconfig builds a K8s client from a kubeconfig file. func (f ClientFactory) BuildClientFromKubeconfig(kubeconfigPath string) (client.Client, error) { return NewRuntimeClientFromFileName(kubeconfigPath) } // NewRuntimeClientFromFileName creates a new controller runtime client given a kubeconfig filename. func NewRuntimeClientFromFileName(kubeConfigFilename string) (client.Client, error) { data, err := os.ReadFile(kubeConfigFilename) if err != nil { return nil, fmt.Errorf("failed to create new client: %s", err) } return newRuntimeClient(data, nil, runtime.NewScheme()) } func initScheme(scheme *runtime.Scheme) error { adders := append([]schemeAdder{ clientgoscheme.AddToScheme, }, schemeAdders...) if scheme == nil { return fmt.Errorf("scheme was not provided") } return addToScheme(scheme, adders...) } func newRuntimeClient(data []byte, rc restConfigurator, scheme *runtime.Scheme) (client.Client, error) { if rc == nil { rc = restConfigurator(clientcmd.RESTConfigFromKubeConfig) } restConfig, err := rc.Config(data) if err != nil { return nil, err } if err := initScheme(scheme); err != nil { return nil, fmt.Errorf("failed to init client scheme %v", err) } err = clientgoscheme.AddToScheme(scheme) if err != nil { return nil, err } return client.New(restConfig, client.Options{Scheme: scheme}) } // restConfigurator abstracts the creation of a controller-runtime *rest.Config. // // This abstraction improves testing, as all known methods of instantiating a // *rest.Config try to make network calls, and that's something we'd like to // keep out of our unit tests as much as possible. In addition, where we do // use them in unit tests, we need to be prepared with a controller-runtime // EnvTest environment. // // For normal, non-test use, this can safely be ignored. type restConfigurator func([]byte) (*rest.Config, error) // Config generates and returns a rest.Config from a kubeconfig in bytes. func (c restConfigurator) Config(data []byte) (*rest.Config, error) { return c(data) }
79
eks-anywhere
aws
Go
package kubernetes_test import ( "context" "errors" "testing" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/rest" "github.com/aws/eks-anywhere/internal/test" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" ) func TestNewRuntimeClient(t *testing.T) { g := NewWithT(t) cfg := test.UseEnvTest(t) rc := kubernetes.RestConfigurator(func(_ []byte) (*rest.Config, error) { return cfg, nil }) c, err := kubernetes.NewRuntimeClient([]byte{}, rc, runtime.NewScheme()) g.Expect(err).To(BeNil()) ctx := context.Background() pod := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Namespace: "default", Name: "name", }, Spec: corev1.PodSpec{ Containers: []corev1.Container{ { Image: "nginx", Name: "nginx", }, }, }, } err = c.Create(ctx, pod) g.Expect(err).To(BeNil()) } func TestNewRuntimeClientInvalidRestConfig(t *testing.T) { g := NewWithT(t) rc := kubernetes.RestConfigurator(func(_ []byte) (*rest.Config, error) { return nil, errors.New("failed to build rest.Config") }) _, err := kubernetes.NewRuntimeClient([]byte{}, rc, runtime.NewScheme()) g.Expect(err).To(MatchError(ContainSubstring("failed to build rest.Config"))) } func TestNewRuntimeClientInvalidScheme(t *testing.T) { g := NewWithT(t) cfg := test.UseEnvTest(t) rc := kubernetes.RestConfigurator(func(_ []byte) (*rest.Config, error) { return cfg, nil }) _, err := kubernetes.NewRuntimeClient([]byte{}, rc, nil) g.Expect(err).To(MatchError(ContainSubstring("scheme was not provided"))) } func TestNewRuntimeClientFromFilename(t *testing.T) { g := NewWithT(t) _, err := kubernetes.NewRuntimeClientFromFileName("file-does-not-exist.txt") g.Expect(err).To(MatchError(ContainSubstring("open file-does-not-exist.txt: no such file or directory"))) } func TestClientFactoryBuildClientFromKubeconfigNoFile(t *testing.T) { g := NewWithT(t) f := kubernetes.ClientFactory{} _, err := f.BuildClientFromKubeconfig("file-does-not-exist.txt") g.Expect(err).To(MatchError(ContainSubstring("open file-does-not-exist.txt: no such file or directory"))) }
71
eks-anywhere
aws
Go
package kubernetes var NewRuntimeClient = newRuntimeClient type RestConfigurator = restConfigurator
6
eks-anywhere
aws
Go
package kubernetes import ( eksdv1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" etcdv1 "github.com/aws/etcdadm-controller/api/v1beta1" tinkerbellv1 "github.com/tinkerbell/cluster-api-provider-tinkerbell/api/v1beta1" "k8s.io/apimachinery/pkg/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" cloudstackv1 "sigs.k8s.io/cluster-api-provider-cloudstack/api/v1beta2" vspherev1 "sigs.k8s.io/cluster-api-provider-vsphere/api/v1beta1" clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" bootstrapv1 "sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1beta1" controlplanev1 "sigs.k8s.io/cluster-api/controlplane/kubeadm/api/v1beta1" addonsv1 "sigs.k8s.io/cluster-api/exp/addons/api/v1beta1" dockerv1 "sigs.k8s.io/cluster-api/test/infrastructure/docker/api/v1beta1" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" snowv1 "github.com/aws/eks-anywhere/pkg/providers/snow/api/v1beta1" releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1" ) type schemeAdder func(s *runtime.Scheme) error var schemeAdders = []schemeAdder{ // clientgoscheme adds all the native K8s kinds clientgoscheme.AddToScheme, clusterv1.AddToScheme, controlplanev1.AddToScheme, anywherev1.AddToScheme, snowv1.AddToScheme, cloudstackv1.AddToScheme, bootstrapv1.AddToScheme, dockerv1.AddToScheme, releasev1.AddToScheme, eksdv1alpha1.AddToScheme, vspherev1.AddToScheme, etcdv1.AddToScheme, addonsv1.AddToScheme, tinkerbellv1.AddToScheme, } func addToScheme(scheme *runtime.Scheme, schemeAdders ...schemeAdder) error { for _, adder := range schemeAdders { if err := adder(scheme); err != nil { return err } } return nil }
51
eks-anywhere
aws
Go
package kubernetes import ( "context" "fmt" "strings" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) // UnAuthClient is a generic kubernetes API client that takes a kubeconfig // file on every call in order to authenticate. type UnAuthClient struct { kubectl Kubectl scheme *runtime.Scheme } // NewUnAuthClient builds a new UnAuthClient. func NewUnAuthClient(kubectl Kubectl) *UnAuthClient { return &UnAuthClient{ kubectl: kubectl, scheme: runtime.NewScheme(), } } // Init initializes the client internal API scheme // It has always be invoked at least once before making any API call // It is not thread safe. func (c *UnAuthClient) Init() error { return addToScheme(c.scheme, schemeAdders...) } // Get performs a GET call to the kube API server authenticating with a kubeconfig file // and unmarshalls the response into the provdied Object. func (c *UnAuthClient) Get(ctx context.Context, name, namespace, kubeconfig string, obj runtime.Object) error { resourceType, err := c.resourceTypeForObj(obj) if err != nil { return fmt.Errorf("getting kubernetes resource: %v", err) } return c.kubectl.Get(ctx, resourceType, kubeconfig, obj, &KubectlGetOptions{Name: name, Namespace: namespace}) } // KubeconfigClient returns an equivalent authenticated client. func (c *UnAuthClient) KubeconfigClient(kubeconfig string) Client { return NewKubeconfigClient(c, kubeconfig) } // BuildClientFromKubeconfig returns an equivalent authenticated client. It will never return // an error but this helps satisfy a generic factory interface where errors are possible. It's // basically an alias to KubeconfigClient. func (c *UnAuthClient) BuildClientFromKubeconfig(kubeconfig string) (Client, error) { return c.KubeconfigClient(kubeconfig), nil } // Apply performs an upsert in the form of a client-side apply. func (c *UnAuthClient) Apply(ctx context.Context, kubeconfig string, obj runtime.Object) error { return c.kubectl.Apply(ctx, kubeconfig, obj) } // List retrieves list of objects. On a successful call, Items field // in the list will be populated with the result returned from the server. func (c *UnAuthClient) List(ctx context.Context, kubeconfig string, list ObjectList) error { resourceType, err := c.resourceTypeForObj(list) if err != nil { return fmt.Errorf("getting kubernetes resource: %v", err) } return c.kubectl.Get(ctx, resourceType, kubeconfig, list) } // Create saves the object obj in the Kubernetes cluster. func (c *UnAuthClient) Create(ctx context.Context, kubeconfig string, obj Object) error { return c.kubectl.Create(ctx, kubeconfig, obj) } // Update updates the given obj in the Kubernetes cluster. func (c *UnAuthClient) Update(ctx context.Context, kubeconfig string, obj Object) error { return c.kubectl.Replace(ctx, kubeconfig, obj) } // Delete deletes the given obj from Kubernetes cluster. func (c *UnAuthClient) Delete(ctx context.Context, kubeconfig string, obj Object) error { resourceType, err := c.resourceTypeForObj(obj) if err != nil { return fmt.Errorf("deleting kubernetes resource: %v", err) } o := &KubectlDeleteOptions{ Name: obj.GetName(), Namespace: obj.GetNamespace(), } return c.kubectl.Delete(ctx, resourceType, kubeconfig, o) } // DeleteAllOf deletes all objects of the given type matching the given options. func (c *UnAuthClient) DeleteAllOf(ctx context.Context, kubeconfig string, obj Object, opts ...DeleteAllOfOption) error { resourceType, err := c.resourceTypeForObj(obj) if err != nil { return fmt.Errorf("deleting kubernetes resource: %v", err) } deleteAllOpts := &DeleteAllOfOptions{} for _, opt := range opts { opt.ApplyToDeleteAllOf(deleteAllOpts) } o := &KubectlDeleteOptions{} o.Namespace = deleteAllOpts.Namespace o.HasLabels = deleteAllOpts.HasLabels return c.kubectl.Delete(ctx, resourceType, kubeconfig, o) } func (c *UnAuthClient) resourceTypeForObj(obj runtime.Object) (string, error) { groupVersionKind, err := apiutil.GVKForObject(obj, c.scheme) if err != nil { return "", err } if meta.IsListType(obj) && strings.HasSuffix(groupVersionKind.Kind, "List") { // if obj is a list, treat it as a request for the "individual" item's resource groupVersionKind.Kind = groupVersionKind.Kind[:len(groupVersionKind.Kind)-4] } return groupVersionToKubectlResourceType(groupVersionKind), nil } func groupVersionToKubectlResourceType(g schema.GroupVersionKind) string { if g.Group == "" { // if Group is not set, this probably an obj from "core", which api group is just v1 return g.Kind } return fmt.Sprintf("%s.%s.%s", g.Kind, g.Version, g.Group) }
139
eks-anywhere
aws
Go
package kubernetes_test import ( "context" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" clusterapiv1 "sigs.k8s.io/cluster-api/api/v1beta1" controlplanev1 "sigs.k8s.io/cluster-api/controlplane/kubeadm/api/v1beta1" "sigs.k8s.io/controller-runtime/pkg/client" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" "github.com/aws/eks-anywhere/pkg/clients/kubernetes/mocks" ) func TestUnAuthClientGetSuccess(t *testing.T) { tests := []struct { name string namespace string obj runtime.Object wantResourceType string }{ { name: "eksa cluster", namespace: "eksa-system", obj: &anywherev1.Cluster{}, wantResourceType: "Cluster.v1alpha1.anywhere.eks.amazonaws.com", }, { name: "capi cluster", namespace: "eksa-system", obj: &clusterapiv1.Cluster{}, wantResourceType: "Cluster.v1beta1.cluster.x-k8s.io", }, { name: "capi kubeadm controlplane", namespace: "eksa-system", obj: &controlplanev1.KubeadmControlPlane{}, wantResourceType: "KubeadmControlPlane.v1beta1.controlplane.cluster.x-k8s.io", }, { name: "my-node", namespace: "", obj: &corev1.NodeList{}, wantResourceType: "Node", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" o := &kubernetes.KubectlGetOptions{ Name: tt.name, Namespace: tt.namespace, } kubectl.EXPECT().Get(ctx, tt.wantResourceType, kubeconfig, tt.obj, o) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Get(ctx, tt.name, tt.namespace, kubeconfig, tt.obj)).To(Succeed()) }) } } func TestUnAuthClientGetUnknownObjType(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Get(ctx, "name", "namespace", "kubeconfig", &metav1.Status{})).Error() } func TestUnAuthClientDeleteSuccess(t *testing.T) { tests := []struct { name string obj client.Object wantResourceType string wantOpts []interface{} }{ { name: "eksa cluster", obj: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa-system", }, }, wantOpts: []interface{}{ &kubernetes.KubectlDeleteOptions{ Name: "eksa-cluster", Namespace: "eksa-system", }, }, wantResourceType: "Cluster.v1alpha1.anywhere.eks.amazonaws.com", }, { name: "capi cluster", obj: &clusterapiv1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "capi-cluster", Namespace: "eksa-system", }, }, wantOpts: []interface{}{ &kubernetes.KubectlDeleteOptions{ Name: "capi-cluster", Namespace: "eksa-system", }, }, wantResourceType: "Cluster.v1beta1.cluster.x-k8s.io", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" kubectl.EXPECT().Delete(ctx, tt.wantResourceType, kubeconfig, tt.wantOpts...) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Delete(ctx, kubeconfig, tt.obj)).To(Succeed()) }) } } func TestUnAuthClientApplySuccess(t *testing.T) { tests := []struct { name string namespace string obj client.Object }{ { name: "eksa cluster", namespace: "eksa-system", obj: &anywherev1.Cluster{}, }, { name: "capi cluster", namespace: "eksa-system", obj: &clusterapiv1.Cluster{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" kubectl.EXPECT().Apply(ctx, kubeconfig, tt.obj) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Apply(ctx, kubeconfig, tt.obj)).To(Succeed()) }) } } func TestUnAuthClientDeleteUnknownObjType(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Delete(ctx, "kubeconfig", &unknownType{})).Error() } type unknownType struct { metav1.TypeMeta metav1.ObjectMeta } func (*unknownType) DeepCopyObject() runtime.Object { return nil } func TestUnauthClientList(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" list := &corev1.NodeList{} kubectl.EXPECT().Get(ctx, "Node", kubeconfig, list) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.List(ctx, kubeconfig, list)).To(Succeed()) } func TestUnauthClientCreate(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectl.EXPECT().Create(ctx, kubeconfig, obj) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Create(ctx, kubeconfig, obj)).To(Succeed()) } func TestUnauthClientUpdate(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectl.EXPECT().Replace(ctx, kubeconfig, obj) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Update(ctx, kubeconfig, obj)).To(Succeed()) } func TestUnauthClientDelete(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{ ObjectMeta: metav1.ObjectMeta{ Name: "my-pod", Namespace: "my-ns", }, } opts := &kubernetes.KubectlDeleteOptions{ Name: "my-pod", Namespace: "my-ns", } kubectl.EXPECT().Delete(ctx, "Pod", kubeconfig, opts) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.Delete(ctx, kubeconfig, obj)).To(Succeed()) } func TestUnauthClientDeleteAllOf(t *testing.T) { tests := []struct { name string opts []kubernetes.DeleteAllOfOption wantKubectlOpt *kubernetes.KubectlDeleteOptions }{ { name: "no options", wantKubectlOpt: &kubernetes.KubectlDeleteOptions{}, }, { name: "delete all in namespace", opts: []kubernetes.DeleteAllOfOption{ &kubernetes.DeleteAllOfOptions{ Namespace: "my-ns", }, }, wantKubectlOpt: &kubernetes.KubectlDeleteOptions{ Namespace: "my-ns", }, }, { name: "delete all in namespace with label selector", opts: []kubernetes.DeleteAllOfOption{ &kubernetes.DeleteAllOfOptions{ Namespace: "my-ns", HasLabels: map[string]string{ "label": "value", }, }, }, wantKubectlOpt: &kubernetes.KubectlDeleteOptions{ Namespace: "my-ns", HasLabels: map[string]string{ "label": "value", }, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) ctx := context.Background() ctrl := gomock.NewController(t) kubectl := mocks.NewMockKubectl(ctrl) kubeconfig := "k.kubeconfig" obj := &corev1.Pod{} kubectl.EXPECT().Delete(ctx, "Pod", kubeconfig, tt.wantKubectlOpt) c := kubernetes.NewUnAuthClient(kubectl) g.Expect(c.Init()).To(Succeed()) g.Expect(c.DeleteAllOf(ctx, kubeconfig, obj, tt.opts...)).To(Succeed()) }) } }
332
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/clients/kubernetes/client.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" kubernetes "github.com/aws/eks-anywhere/pkg/clients/kubernetes" gomock "github.com/golang/mock/gomock" ) // MockClient is a mock of Client interface. type MockClient struct { ctrl *gomock.Controller recorder *MockClientMockRecorder } // MockClientMockRecorder is the mock recorder for MockClient. type MockClientMockRecorder struct { mock *MockClient } // NewMockClient creates a new mock instance. func NewMockClient(ctrl *gomock.Controller) *MockClient { mock := &MockClient{ctrl: ctrl} mock.recorder = &MockClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockClient) EXPECT() *MockClientMockRecorder { return m.recorder } // Create mocks base method. func (m *MockClient) Create(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Create indicates an expected call of Create. func (mr *MockClientMockRecorder) Create(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockClient)(nil).Create), ctx, obj) } // Delete mocks base method. func (m *MockClient) Delete(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Delete indicates an expected call of Delete. func (mr *MockClientMockRecorder) Delete(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockClient)(nil).Delete), ctx, obj) } // DeleteAllOf mocks base method. func (m *MockClient) DeleteAllOf(ctx context.Context, obj kubernetes.Object, opts ...kubernetes.DeleteAllOfOption) error { m.ctrl.T.Helper() varargs := []interface{}{ctx, obj} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DeleteAllOf", varargs...) ret0, _ := ret[0].(error) return ret0 } // DeleteAllOf indicates an expected call of DeleteAllOf. func (mr *MockClientMockRecorder) DeleteAllOf(ctx, obj interface{}, opts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, obj}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAllOf", reflect.TypeOf((*MockClient)(nil).DeleteAllOf), varargs...) } // Get mocks base method. func (m *MockClient) Get(ctx context.Context, name, namespace string, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", ctx, name, namespace, obj) ret0, _ := ret[0].(error) return ret0 } // Get indicates an expected call of Get. func (mr *MockClientMockRecorder) Get(ctx, name, namespace, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockClient)(nil).Get), ctx, name, namespace, obj) } // List mocks base method. func (m *MockClient) List(ctx context.Context, list kubernetes.ObjectList) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", ctx, list) ret0, _ := ret[0].(error) return ret0 } // List indicates an expected call of List. func (mr *MockClientMockRecorder) List(ctx, list interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockClient)(nil).List), ctx, list) } // Update mocks base method. func (m *MockClient) Update(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Update", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Update indicates an expected call of Update. func (mr *MockClientMockRecorder) Update(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockClient)(nil).Update), ctx, obj) } // MockReader is a mock of Reader interface. type MockReader struct { ctrl *gomock.Controller recorder *MockReaderMockRecorder } // MockReaderMockRecorder is the mock recorder for MockReader. type MockReaderMockRecorder struct { mock *MockReader } // NewMockReader creates a new mock instance. func NewMockReader(ctrl *gomock.Controller) *MockReader { mock := &MockReader{ctrl: ctrl} mock.recorder = &MockReaderMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockReader) EXPECT() *MockReaderMockRecorder { return m.recorder } // Get mocks base method. func (m *MockReader) Get(ctx context.Context, name, namespace string, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", ctx, name, namespace, obj) ret0, _ := ret[0].(error) return ret0 } // Get indicates an expected call of Get. func (mr *MockReaderMockRecorder) Get(ctx, name, namespace, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockReader)(nil).Get), ctx, name, namespace, obj) } // List mocks base method. func (m *MockReader) List(ctx context.Context, list kubernetes.ObjectList) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", ctx, list) ret0, _ := ret[0].(error) return ret0 } // List indicates an expected call of List. func (mr *MockReaderMockRecorder) List(ctx, list interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockReader)(nil).List), ctx, list) } // MockWriter is a mock of Writer interface. type MockWriter struct { ctrl *gomock.Controller recorder *MockWriterMockRecorder } // MockWriterMockRecorder is the mock recorder for MockWriter. type MockWriterMockRecorder struct { mock *MockWriter } // NewMockWriter creates a new mock instance. func NewMockWriter(ctrl *gomock.Controller) *MockWriter { mock := &MockWriter{ctrl: ctrl} mock.recorder = &MockWriterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockWriter) EXPECT() *MockWriterMockRecorder { return m.recorder } // Create mocks base method. func (m *MockWriter) Create(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Create indicates an expected call of Create. func (mr *MockWriterMockRecorder) Create(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockWriter)(nil).Create), ctx, obj) } // Delete mocks base method. func (m *MockWriter) Delete(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Delete indicates an expected call of Delete. func (mr *MockWriterMockRecorder) Delete(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockWriter)(nil).Delete), ctx, obj) } // DeleteAllOf mocks base method. func (m *MockWriter) DeleteAllOf(ctx context.Context, obj kubernetes.Object, opts ...kubernetes.DeleteAllOfOption) error { m.ctrl.T.Helper() varargs := []interface{}{ctx, obj} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "DeleteAllOf", varargs...) ret0, _ := ret[0].(error) return ret0 } // DeleteAllOf indicates an expected call of DeleteAllOf. func (mr *MockWriterMockRecorder) DeleteAllOf(ctx, obj interface{}, opts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, obj}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAllOf", reflect.TypeOf((*MockWriter)(nil).DeleteAllOf), varargs...) } // Update mocks base method. func (m *MockWriter) Update(ctx context.Context, obj kubernetes.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Update", ctx, obj) ret0, _ := ret[0].(error) return ret0 } // Update indicates an expected call of Update. func (mr *MockWriterMockRecorder) Update(ctx, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockWriter)(nil).Update), ctx, obj) } // MockDeleteAllOfOption is a mock of DeleteAllOfOption interface. type MockDeleteAllOfOption struct { ctrl *gomock.Controller recorder *MockDeleteAllOfOptionMockRecorder } // MockDeleteAllOfOptionMockRecorder is the mock recorder for MockDeleteAllOfOption. type MockDeleteAllOfOptionMockRecorder struct { mock *MockDeleteAllOfOption } // NewMockDeleteAllOfOption creates a new mock instance. func NewMockDeleteAllOfOption(ctrl *gomock.Controller) *MockDeleteAllOfOption { mock := &MockDeleteAllOfOption{ctrl: ctrl} mock.recorder = &MockDeleteAllOfOptionMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockDeleteAllOfOption) EXPECT() *MockDeleteAllOfOptionMockRecorder { return m.recorder } // ApplyToDeleteAllOf mocks base method. func (m *MockDeleteAllOfOption) ApplyToDeleteAllOf(arg0 *kubernetes.DeleteAllOfOptions) { m.ctrl.T.Helper() m.ctrl.Call(m, "ApplyToDeleteAllOf", arg0) } // ApplyToDeleteAllOf indicates an expected call of ApplyToDeleteAllOf. func (mr *MockDeleteAllOfOptionMockRecorder) ApplyToDeleteAllOf(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyToDeleteAllOf", reflect.TypeOf((*MockDeleteAllOfOption)(nil).ApplyToDeleteAllOf), arg0) }
296
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/clients/kubernetes/kubeconfig.go // Package mocks is a generated GoMock package. package mocks
6
eks-anywhere
aws
Go
// Code generated by MockGen. DO NOT EDIT. // Source: pkg/clients/kubernetes/kubectl.go // Package mocks is a generated GoMock package. package mocks import ( context "context" reflect "reflect" kubernetes "github.com/aws/eks-anywhere/pkg/clients/kubernetes" gomock "github.com/golang/mock/gomock" runtime "k8s.io/apimachinery/pkg/runtime" ) // MockKubectl is a mock of Kubectl interface. type MockKubectl struct { ctrl *gomock.Controller recorder *MockKubectlMockRecorder } // MockKubectlMockRecorder is the mock recorder for MockKubectl. type MockKubectlMockRecorder struct { mock *MockKubectl } // NewMockKubectl creates a new mock instance. func NewMockKubectl(ctrl *gomock.Controller) *MockKubectl { mock := &MockKubectl{ctrl: ctrl} mock.recorder = &MockKubectlMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKubectl) EXPECT() *MockKubectlMockRecorder { return m.recorder } // Apply mocks base method. func (m *MockKubectl) Apply(ctx context.Context, kubeconfig string, obj runtime.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Apply", ctx, kubeconfig, obj) ret0, _ := ret[0].(error) return ret0 } // Apply indicates an expected call of Apply. func (mr *MockKubectlMockRecorder) Apply(ctx, kubeconfig, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockKubectl)(nil).Apply), ctx, kubeconfig, obj) } // Create mocks base method. func (m *MockKubectl) Create(ctx context.Context, kubeconfig string, obj runtime.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Create", ctx, kubeconfig, obj) ret0, _ := ret[0].(error) return ret0 } // Create indicates an expected call of Create. func (mr *MockKubectlMockRecorder) Create(ctx, kubeconfig, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockKubectl)(nil).Create), ctx, kubeconfig, obj) } // Delete mocks base method. func (m *MockKubectl) Delete(ctx context.Context, resourceType, kubeconfig string, opts ...kubernetes.KubectlDeleteOption) error { m.ctrl.T.Helper() varargs := []interface{}{ctx, resourceType, kubeconfig} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Delete", varargs...) ret0, _ := ret[0].(error) return ret0 } // Delete indicates an expected call of Delete. func (mr *MockKubectlMockRecorder) Delete(ctx, resourceType, kubeconfig interface{}, opts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, resourceType, kubeconfig}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockKubectl)(nil).Delete), varargs...) } // Get mocks base method. func (m *MockKubectl) Get(ctx context.Context, resourceType, kubeconfig string, obj runtime.Object, opts ...kubernetes.KubectlGetOption) error { m.ctrl.T.Helper() varargs := []interface{}{ctx, resourceType, kubeconfig, obj} for _, a := range opts { varargs = append(varargs, a) } ret := m.ctrl.Call(m, "Get", varargs...) ret0, _ := ret[0].(error) return ret0 } // Get indicates an expected call of Get. func (mr *MockKubectlMockRecorder) Get(ctx, resourceType, kubeconfig, obj interface{}, opts ...interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]interface{}{ctx, resourceType, kubeconfig, obj}, opts...) return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockKubectl)(nil).Get), varargs...) } // Replace mocks base method. func (m *MockKubectl) Replace(ctx context.Context, kubeconfig string, obj runtime.Object) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Replace", ctx, kubeconfig, obj) ret0, _ := ret[0].(error) return ret0 } // Replace indicates an expected call of Replace. func (mr *MockKubectlMockRecorder) Replace(ctx, kubeconfig, obj interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Replace", reflect.TypeOf((*MockKubectl)(nil).Replace), ctx, kubeconfig, obj) } // MockKubectlGetOption is a mock of KubectlGetOption interface. type MockKubectlGetOption struct { ctrl *gomock.Controller recorder *MockKubectlGetOptionMockRecorder } // MockKubectlGetOptionMockRecorder is the mock recorder for MockKubectlGetOption. type MockKubectlGetOptionMockRecorder struct { mock *MockKubectlGetOption } // NewMockKubectlGetOption creates a new mock instance. func NewMockKubectlGetOption(ctrl *gomock.Controller) *MockKubectlGetOption { mock := &MockKubectlGetOption{ctrl: ctrl} mock.recorder = &MockKubectlGetOptionMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKubectlGetOption) EXPECT() *MockKubectlGetOptionMockRecorder { return m.recorder } // ApplyToGet mocks base method. func (m *MockKubectlGetOption) ApplyToGet(arg0 *kubernetes.KubectlGetOptions) { m.ctrl.T.Helper() m.ctrl.Call(m, "ApplyToGet", arg0) } // ApplyToGet indicates an expected call of ApplyToGet. func (mr *MockKubectlGetOptionMockRecorder) ApplyToGet(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyToGet", reflect.TypeOf((*MockKubectlGetOption)(nil).ApplyToGet), arg0) } // MockKubectlDeleteOption is a mock of KubectlDeleteOption interface. type MockKubectlDeleteOption struct { ctrl *gomock.Controller recorder *MockKubectlDeleteOptionMockRecorder } // MockKubectlDeleteOptionMockRecorder is the mock recorder for MockKubectlDeleteOption. type MockKubectlDeleteOptionMockRecorder struct { mock *MockKubectlDeleteOption } // NewMockKubectlDeleteOption creates a new mock instance. func NewMockKubectlDeleteOption(ctrl *gomock.Controller) *MockKubectlDeleteOption { mock := &MockKubectlDeleteOption{ctrl: ctrl} mock.recorder = &MockKubectlDeleteOptionMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockKubectlDeleteOption) EXPECT() *MockKubectlDeleteOptionMockRecorder { return m.recorder } // ApplyToDelete mocks base method. func (m *MockKubectlDeleteOption) ApplyToDelete(arg0 *kubernetes.KubectlDeleteOptions) { m.ctrl.T.Helper() m.ctrl.Call(m, "ApplyToDelete", arg0) } // ApplyToDelete indicates an expected call of ApplyToDelete. func (mr *MockKubectlDeleteOptionMockRecorder) ApplyToDelete(arg0 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyToDelete", reflect.TypeOf((*MockKubectlDeleteOption)(nil).ApplyToDelete), arg0) }
188
eks-anywhere
aws
Go
package cluster import ( "fmt" "k8s.io/apimachinery/pkg/runtime" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) // APIObject represents a kubernetes API object. type APIObject interface { runtime.Object GetName() string } type ObjectLookup map[string]APIObject // GetFromRef searches in a ObjectLookup for an APIObject referenced by a anywherev1.Ref. func (o ObjectLookup) GetFromRef(apiVersion string, ref anywherev1.Ref) APIObject { return o[keyForRef(apiVersion, ref)] } func (o ObjectLookup) add(obj APIObject) { o[keyForObject(obj)] = obj } func keyForRef(apiVersion string, ref anywherev1.Ref) string { return key(apiVersion, ref.Kind, ref.Name) } func key(apiVersion, kind, name string) string { // this assumes we don't allow to have objects in multiple namespaces return fmt.Sprintf("%s%s%s", apiVersion, kind, name) } func keyForObject(o APIObject) string { return key(o.GetObjectKind().GroupVersionKind().GroupVersion().String(), o.GetObjectKind().GroupVersionKind().Kind, o.GetName()) }
40
eks-anywhere
aws
Go
package cluster import ( "context" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func awsIamEntry() *ConfigManagerEntry { return &ConfigManagerEntry{ APIObjectMapping: map[string]APIObjectGenerator{ anywherev1.AWSIamConfigKind: func() APIObject { return &anywherev1.AWSIamConfig{} }, }, Processors: []ParsedProcessor{processAWSIam}, Defaulters: []Defaulter{ func(c *Config) error { for _, a := range c.AWSIAMConfigs { a.SetDefaults() } return nil }, }, Validations: []Validation{ func(c *Config) error { for _, a := range c.AWSIAMConfigs { if err := a.Validate(); err != nil { return err } } return nil }, func(c *Config) error { for _, a := range c.AWSIAMConfigs { if err := validateSameNamespace(c, a); err != nil { return err } } return nil }, }, } } func processAWSIam(c *Config, objects ObjectLookup) { if c.AWSIAMConfigs == nil { c.AWSIAMConfigs = map[string]*anywherev1.AWSIamConfig{} } for _, idr := range c.Cluster.Spec.IdentityProviderRefs { idp := objects.GetFromRef(c.Cluster.APIVersion, idr) if idp == nil { return } if idr.Kind == anywherev1.AWSIamConfigKind { c.AWSIAMConfigs[idp.GetName()] = idp.(*anywherev1.AWSIamConfig) } } } func getAWSIam(ctx context.Context, client Client, c *Config) error { if c.AWSIAMConfigs == nil { c.AWSIAMConfigs = map[string]*anywherev1.AWSIamConfig{} } for _, idr := range c.Cluster.Spec.IdentityProviderRefs { if idr.Kind == anywherev1.AWSIamConfigKind { iamConfig := &anywherev1.AWSIamConfig{} if err := client.Get(ctx, idr.Name, c.Cluster.Namespace, iamConfig); err != nil { return err } c.AWSIAMConfigs[iamConfig.Name] = iamConfig } } return nil }
79
eks-anywhere
aws
Go
package cluster_test import ( "context" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/cluster/mocks" ) func TestDefaultConfigClientBuilderAWSIamConfig(t *testing.T) { g := NewWithT(t) ctx := context.Background() b := cluster.NewDefaultConfigClientBuilder() ctrl := gomock.NewController(t) client := mocks.NewMockClient(ctrl) cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "default", }, Spec: anywherev1.ClusterSpec{ IdentityProviderRefs: []anywherev1.Ref{ { Kind: anywherev1.AWSIamConfigKind, Name: "my-aws-iam", }, }, }, } awsIamConfig := &anywherev1.AWSIamConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "my-aws-iam", Namespace: "default", }, } client.EXPECT().Get(ctx, "my-aws-iam", "default", &anywherev1.AWSIamConfig{}).Return(nil).DoAndReturn( func(ctx context.Context, name, namespace string, obj runtime.Object) error { c := obj.(*anywherev1.AWSIamConfig) c.ObjectMeta = awsIamConfig.ObjectMeta return nil }, ) config, err := b.Build(ctx, client, cluster) g.Expect(err).NotTo(HaveOccurred()) g.Expect(config).NotTo(BeNil()) g.Expect(config.Cluster).To(Equal(cluster)) g.Expect(len(config.AWSIAMConfigs)).To(Equal(1)) g.Expect(config.AWSIAMConfigs["my-aws-iam"]).To(Equal(awsIamConfig)) }
59
eks-anywhere
aws
Go
package cluster // NewDefaultConfigClientBuilder returns a ConfigClientBuilder with the // default processors to build a Config. func NewDefaultConfigClientBuilder() *ConfigClientBuilder { return NewConfigClientBuilder().Register( getCloudStackMachineConfigs, getCloudStackDatacenter, getTinkerbellMachineConfigs, getTinkerbellDatacenter, getDockerDatacenter, getVSphereDatacenter, getVSphereMachineConfigs, getSnowDatacenter, getSnowMachineConfigsAndIPPools, getSnowIdentitySecret, getNutanixDatacenter, getNutanixMachineConfigs, getOIDC, getAWSIam, getGitOps, getFluxConfig, ) }
25
eks-anywhere
aws
Go
package cluster import ( "github.com/pkg/errors" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/manifests" "github.com/aws/eks-anywhere/pkg/manifests/bundles" "github.com/aws/eks-anywhere/pkg/version" releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1" ) // FileSpecBuilder allows to build [Spec] by reading from files. type FileSpecBuilder struct { // TODO(g-gaston): this is very much a CLI thing. Move to `pkg/cli` when available. reader manifests.FileReader cliVersion version.Info releasesManifestURL string bundlesManifestURL string } // FileSpecBuilderOpt allows to configure [FileSpecBuilder]. type FileSpecBuilderOpt func(*FileSpecBuilder) // WithReleasesManifest configures the URL to read the Releases manifest. func WithReleasesManifest(url string) FileSpecBuilderOpt { return func(b *FileSpecBuilder) { b.releasesManifestURL = url } } // WithOverrideBundlesManifest configures the URL to read the Bundles manifest. // This overrides the Bundles declared in the Releases so reading the Releases // manifest is skipped. func WithOverrideBundlesManifest(url string) FileSpecBuilderOpt { return func(b *FileSpecBuilder) { b.bundlesManifestURL = url } } // NewFileSpecBuilder builds a new [FileSpecBuilder]. // cliVersion is used to chose the right Bundles from the the Release manifest. func NewFileSpecBuilder(reader manifests.FileReader, cliVersion version.Info, opts ...FileSpecBuilderOpt) FileSpecBuilder { f := &FileSpecBuilder{ cliVersion: cliVersion, reader: reader, } for _, opt := range opts { opt(f) } return *f } // Build constructs a new [Spec] by reading the cluster config in yaml from a file and // Releases, Bundles and EKS-D manifests from the configured URLs. func (b FileSpecBuilder) Build(clusterConfigURL string) (*Spec, error) { config, err := b.getConfig(clusterConfigURL) if err != nil { return nil, err } bundlesManifest, err := b.getBundles() if err != nil { return nil, errors.Wrapf(err, "getting Bundles file") } bundlesManifest.Namespace = constants.EksaSystemNamespace configManager, err := NewDefaultConfigManager() if err != nil { return nil, err } configManager.RegisterDefaulters(BundlesRefDefaulter()) if err = configManager.SetDefaults(config); err != nil { return nil, err } // We are pulling the latest available Bundles, so making sure we update the ref to make the spec consistent config.Cluster.Spec.BundlesRef.Name = bundlesManifest.Name config.Cluster.Spec.BundlesRef.Namespace = bundlesManifest.Namespace config.Cluster.Spec.BundlesRef.APIVersion = releasev1.GroupVersion.String() versionsBundle, err := GetVersionsBundle(config.Cluster, bundlesManifest) if err != nil { return nil, err } eksd, err := bundles.ReadEKSD(b.reader, *versionsBundle) if err != nil { return nil, err } return NewSpec(config, bundlesManifest, eksd) } func (b FileSpecBuilder) getConfig(clusterConfigURL string) (*Config, error) { yaml, err := b.reader.ReadFile(clusterConfigURL) if err != nil { return nil, errors.Wrapf(err, "reading cluster config file") } return ParseConfig(yaml) } func (b FileSpecBuilder) getBundles() (*releasev1.Bundles, error) { bundlesURL := b.bundlesManifestURL if bundlesURL == "" { var opts []manifests.ReaderOpt if b.releasesManifestURL != "" { opts = append(opts, manifests.WithReleasesManifest(b.releasesManifestURL)) } manifestReader := manifests.NewReader(b.reader, opts...) return manifestReader.ReadBundlesForVersion(b.cliVersion.GitVersion) } return bundles.Read(b.reader, bundlesURL) }
120
eks-anywhere
aws
Go
package cluster_test import ( "testing" . "github.com/onsi/gomega" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/files" "github.com/aws/eks-anywhere/pkg/version" ) func TestFileSpecBuilderBuildError(t *testing.T) { tests := []struct { testName string releaseURL string clusterConfigFile string cliVersion string }{ { testName: "Reading cluster config", clusterConfigFile: "", releaseURL: "testdata/simple_release.yaml", cliVersion: "v1.0.0", }, { testName: "Cli version not supported", clusterConfigFile: "testdata/cluster_1_19.yaml", releaseURL: "testdata/simple_release.yaml", cliVersion: "v1.0.0", }, { testName: "Kubernetes version not supported", clusterConfigFile: "testdata/cluster_1_18.yaml", releaseURL: "testdata/simple_release.yaml", cliVersion: "v0.0.1", }, { testName: "Reading EkdD Release", clusterConfigFile: "testdata/cluster_1_19.yaml", releaseURL: "testdata/release_bundle_missing_eksd.yaml", cliVersion: "v0.0.1", }, } for _, tt := range tests { t.Run(tt.testName, func(t *testing.T) { g := NewWithT(t) v := version.Info{GitVersion: tt.cliVersion} reader := files.NewReader() b := cluster.NewFileSpecBuilder(reader, v, cluster.WithReleasesManifest(tt.releaseURL)) g.Expect(b.Build(tt.clusterConfigFile)).Error().NotTo(Succeed()) }) } } func TestFileSpecBuilderBuildSuccess(t *testing.T) { g := NewWithT(t) v := version.Info{GitVersion: "v0.0.1"} reader := files.NewReader() b := cluster.NewFileSpecBuilder(reader, v, cluster.WithReleasesManifest("testdata/simple_release.yaml")) gotSpec, err := b.Build("testdata/cluster_1_19.yaml") g.Expect(err).NotTo(HaveOccurred()) validateSpecFromSimpleBundle(t, gotSpec) } func TestNewSpecWithBundlesOverrideValid(t *testing.T) { g := NewWithT(t) v := version.Info{GitVersion: "v0.0.1"} reader := files.NewReader() b := cluster.NewFileSpecBuilder(reader, v, cluster.WithReleasesManifest("testdata/invalid_release_version.yaml"), cluster.WithOverrideBundlesManifest("testdata/simple_bundle.yaml"), ) gotSpec, err := b.Build("testdata/cluster_1_19.yaml") g.Expect(err).NotTo(HaveOccurred()) validateSpecFromSimpleBundle(t, gotSpec) }
86
eks-anywhere
aws
Go
package cluster import ( "context" "github.com/pkg/errors" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" ) // Client is a kubernetes API client. type Client interface { Get(ctx context.Context, name, namespace string, obj kubernetes.Object) error } // ConfigClientProcessor updates a Config retrieving objects from // the API server through a client. type ConfigClientProcessor func(ctx context.Context, client Client, c *Config) error // ConfigClientBuilder allows to register processors to build a Config // using a cluster client, retrieving the api objects from the API server. type ConfigClientBuilder struct { processors []ConfigClientProcessor } // NewConfigClientBuilder builds a new ConfigClientBuilder with // no processors registered. func NewConfigClientBuilder() *ConfigClientBuilder { return &ConfigClientBuilder{} } // Register stores processors to be used during Build. func (b *ConfigClientBuilder) Register(processors ...ConfigClientProcessor) *ConfigClientBuilder { b.processors = append(b.processors, processors...) return b } // Build constructs a Config for a cluster using the registered processors. func (b *ConfigClientBuilder) Build(ctx context.Context, client Client, cluster *anywherev1.Cluster) (*Config, error) { c := &Config{ Cluster: cluster, } for _, p := range b.processors { if err := p(ctx, client, c); err != nil { return nil, errors.Wrap(err, "building Config from a cluster client") } } return c, nil }
53
eks-anywhere
aws
Go
package cluster_test import ( "context" "errors" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/cluster/mocks" ) func TestConfigClientBuilderBuildSuccess(t *testing.T) { g := NewWithT(t) builder := cluster.NewConfigClientBuilder() timesCalled := 0 processor := func(ctx context.Context, client cluster.Client, c *cluster.Config) error { timesCalled++ return nil } // register twice, expect two calls builder.Register(processor, processor) ctx := context.Background() ctrl := gomock.NewController(t) client := mocks.NewMockClient(ctrl) cluster := &anywherev1.Cluster{} config, err := builder.Build(ctx, client, cluster) g.Expect(err).NotTo(HaveOccurred()) g.Expect(config).NotTo(BeNil()) g.Expect(config.Cluster).To(Equal(cluster)) g.Expect(timesCalled).To(Equal(2), "processor should be called 2 times") } func TestConfigClientBuilderBuildError(t *testing.T) { g := NewWithT(t) builder := cluster.NewConfigClientBuilder() timesCalled := 0 processor := func(ctx context.Context, client cluster.Client, c *cluster.Config) error { timesCalled++ return nil } processorError := func(ctx context.Context, client cluster.Client, c *cluster.Config) error { return errors.New("processor error") } builder.Register(processor, processorError) ctx := context.Background() ctrl := gomock.NewController(t) client := mocks.NewMockClient(ctrl) cluster := &anywherev1.Cluster{} _, err := builder.Build(ctx, client, cluster) g.Expect(err).To(MatchError(ContainSubstring("processor error"))) g.Expect(timesCalled).To(Equal(1), "processor should be called 1 times") }
68
eks-anywhere
aws
Go
package cluster import ( "context" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func cloudstackEntry() *ConfigManagerEntry { return &ConfigManagerEntry{ APIObjectMapping: map[string]APIObjectGenerator{ anywherev1.CloudStackDatacenterKind: func() APIObject { return &anywherev1.CloudStackDatacenterConfig{} }, anywherev1.CloudStackMachineConfigKind: func() APIObject { return &anywherev1.CloudStackMachineConfig{} }, }, Processors: []ParsedProcessor{ processCloudStackDatacenter, machineConfigsProcessor(processCloudStackMachineConfig), }, Defaulters: []Defaulter{ func(c *Config) error { if c.CloudStackDatacenter != nil { c.CloudStackDatacenter.SetDefaults() } return nil }, func(c *Config) error { for _, mc := range c.CloudStackMachineConfigs { mc.SetUserDefaults() } return nil }, }, Validations: []Validation{ func(c *Config) error { if c.CloudStackDatacenter != nil { return c.CloudStackDatacenter.Validate() } return nil }, func(c *Config) error { for _, m := range c.CloudStackMachineConfigs { if err := m.Validate(); err != nil { return err } } return nil }, func(c *Config) error { if c.CloudStackDatacenter != nil { if err := validateSameNamespace(c, c.CloudStackDatacenter); err != nil { return err } } return nil }, func(c *Config) error { for _, v := range c.CloudStackMachineConfigs { if err := validateSameNamespace(c, v); err != nil { return err } } return nil }, }, } } func processCloudStackDatacenter(c *Config, objects ObjectLookup) { if c.Cluster.Spec.DatacenterRef.Kind == anywherev1.CloudStackDatacenterKind { datacenter := objects.GetFromRef(c.Cluster.APIVersion, c.Cluster.Spec.DatacenterRef) if datacenter != nil { c.CloudStackDatacenter = datacenter.(*anywherev1.CloudStackDatacenterConfig) } } } func processCloudStackMachineConfig(c *Config, objects ObjectLookup, machineRef *anywherev1.Ref) { if machineRef == nil { return } if machineRef.Kind != anywherev1.CloudStackMachineConfigKind { return } if c.CloudStackMachineConfigs == nil { c.CloudStackMachineConfigs = map[string]*anywherev1.CloudStackMachineConfig{} } m := objects.GetFromRef(c.Cluster.APIVersion, *machineRef) if m == nil { return } c.CloudStackMachineConfigs[m.GetName()] = m.(*anywherev1.CloudStackMachineConfig) } func getCloudStackDatacenter(ctx context.Context, client Client, c *Config) error { if c.Cluster.Spec.DatacenterRef.Kind != anywherev1.CloudStackDatacenterKind { return nil } datacenter := &anywherev1.CloudStackDatacenterConfig{} if err := client.Get(ctx, c.Cluster.Spec.DatacenterRef.Name, c.Cluster.Namespace, datacenter); err != nil { return err } c.CloudStackDatacenter = datacenter return nil } func getCloudStackMachineConfigs(ctx context.Context, client Client, c *Config) error { if c.Cluster.Spec.DatacenterRef.Kind != anywherev1.CloudStackDatacenterKind { return nil } if c.CloudStackMachineConfigs == nil { c.CloudStackMachineConfigs = map[string]*anywherev1.CloudStackMachineConfig{} } for _, machineRef := range c.Cluster.MachineConfigRefs() { if machineRef.Kind != anywherev1.CloudStackMachineConfigKind { continue } machine := &anywherev1.CloudStackMachineConfig{} if err := client.Get(ctx, machineRef.Name, c.Cluster.Namespace, machine); err != nil { return err } c.CloudStackMachineConfigs[machine.Name] = machine } return nil }
140
eks-anywhere
aws
Go
package cluster_test import ( "context" "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/aws/eks-anywhere/internal/test" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" ) func TestParseConfigMissingCloudstackDatacenter(t *testing.T) { g := NewWithT(t) got, err := cluster.ParseConfigFromFile("testdata/cluster_cloudstack_missing_datacenter.yaml") g.Expect(err).To(Not(HaveOccurred())) g.Expect(got.CloudStackDatacenter).To(BeNil()) } func TestDefaultConfigClientBuilderBuildCloudStackClusterSuccess(t *testing.T) { g := NewWithT(t) ctx := context.Background() b := cluster.NewDefaultConfigClientBuilder() cluster := cloudStackCluster() datacenter := cloudStackDatacenter() machineControlPlane := cloudStackMachineConfig("cp-machine-1") machineWorker1 := cloudStackMachineConfig("worker-machine-1") machineWorker2 := cloudStackMachineConfig("worker-machine-2") client := test.NewFakeKubeClient(datacenter, machineControlPlane, machineWorker1, machineWorker2) config, err := b.Build(ctx, client, cluster) g.Expect(err).NotTo(HaveOccurred()) g.Expect(config).NotTo(BeNil()) g.Expect(config.Cluster).To(Equal(cluster)) g.Expect(config.CloudStackDatacenter).To(Equal(datacenter)) g.Expect(config.CloudStackMachineConfigs["cp-machine-1"]).To(Equal(machineControlPlane)) g.Expect(config.CloudStackMachineConfigs["worker-machine-1"]).To(Equal(machineWorker1)) } func TestDefaultConfigClientBuilderBuildCloudStackClusterFailure(t *testing.T) { g := NewWithT(t) ctx := context.Background() b := cluster.NewDefaultConfigClientBuilder() cluster := cloudStackCluster() datacenter := cloudStackDatacenter() machineControlPlane := cloudStackMachineConfig("cp-machine-1") machineWorker1 := cloudStackMachineConfig("worker-machine-1") tests := []struct { name string objects []client.Object wantErr string }{ { name: "missing machine config", objects: []client.Object{ datacenter, machineControlPlane, }, wantErr: "cloudstackmachineconfigs.anywhere.eks.amazonaws.com \"worker-machine-1\" not found", }, { name: "missing datacenter config", objects: []client.Object{ machineControlPlane, machineWorker1, }, wantErr: "cloudstackdatacenterconfigs.anywhere.eks.amazonaws.com \"datacenter\" not found", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { client := test.NewFakeKubeClient(tt.objects...) _, err := b.Build(ctx, client, cluster) g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr))) }) } } func cloudStackCluster() *anywherev1.Cluster { return &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "default", }, Spec: anywherev1.ClusterSpec{ DatacenterRef: anywherev1.Ref{ Kind: anywherev1.CloudStackDatacenterKind, Name: "datacenter", }, ControlPlaneConfiguration: anywherev1.ControlPlaneConfiguration{ Count: 1, MachineGroupRef: &anywherev1.Ref{ Name: "cp-machine-1", Kind: anywherev1.CloudStackMachineConfigKind, }, }, WorkerNodeGroupConfigurations: []anywherev1.WorkerNodeGroupConfiguration{ { Name: "md-0", MachineGroupRef: &anywherev1.Ref{ Name: "worker-machine-1", Kind: anywherev1.CloudStackMachineConfigKind, }, }, { Name: "md-1", MachineGroupRef: &anywherev1.Ref{ Name: "worker-machine-2", Kind: anywherev1.VSphereMachineConfigKind, // Should not process this one }, }, }, }, } } func cloudStackDatacenter() *anywherev1.CloudStackDatacenterConfig { return &anywherev1.CloudStackDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.CloudStackDatacenterKind, APIVersion: anywherev1.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "datacenter", Namespace: "default", }, } } func cloudStackMachineConfig(name string) *anywherev1.CloudStackMachineConfig { return &anywherev1.CloudStackMachineConfig{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.CloudStackMachineConfigKind, APIVersion: "anywhere.eks.amazonaws.com/v1alpha1", }, ObjectMeta: metav1.ObjectMeta{ Name: name, Namespace: "default", }, } }
150
eks-anywhere
aws
Go
package cluster func clusterEntry() *ConfigManagerEntry { return &ConfigManagerEntry{ Defaulters: []Defaulter{ func(c *Config) error { c.Cluster.SetDefaults() return nil }, }, Validations: []Validation{ func(c *Config) error { return c.Cluster.Validate() }, }, } }
18
eks-anywhere
aws
Go
package cluster import ( "reflect" v1 "k8s.io/api/core/v1" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/clients/kubernetes" ) type Config struct { Cluster *anywherev1.Cluster CloudStackDatacenter *anywherev1.CloudStackDatacenterConfig VSphereDatacenter *anywherev1.VSphereDatacenterConfig DockerDatacenter *anywherev1.DockerDatacenterConfig SnowDatacenter *anywherev1.SnowDatacenterConfig NutanixDatacenter *anywherev1.NutanixDatacenterConfig TinkerbellDatacenter *anywherev1.TinkerbellDatacenterConfig VSphereMachineConfigs map[string]*anywherev1.VSphereMachineConfig CloudStackMachineConfigs map[string]*anywherev1.CloudStackMachineConfig SnowMachineConfigs map[string]*anywherev1.SnowMachineConfig NutanixMachineConfigs map[string]*anywherev1.NutanixMachineConfig TinkerbellMachineConfigs map[string]*anywherev1.TinkerbellMachineConfig TinkerbellTemplateConfigs map[string]*anywherev1.TinkerbellTemplateConfig OIDCConfigs map[string]*anywherev1.OIDCConfig AWSIAMConfigs map[string]*anywherev1.AWSIamConfig GitOpsConfig *anywherev1.GitOpsConfig FluxConfig *anywherev1.FluxConfig SnowCredentialsSecret *v1.Secret SnowIPPools map[string]*anywherev1.SnowIPPool } func (c *Config) VsphereMachineConfig(name string) *anywherev1.VSphereMachineConfig { return c.VSphereMachineConfigs[name] } func (c *Config) CloudStackMachineConfig(name string) *anywherev1.CloudStackMachineConfig { return c.CloudStackMachineConfigs[name] } func (c *Config) SnowMachineConfig(name string) *anywherev1.SnowMachineConfig { return c.SnowMachineConfigs[name] } // SnowIPPool returns a SnowIPPool based on a name. func (c *Config) SnowIPPool(name string) *anywherev1.SnowIPPool { return c.SnowIPPools[name] } func (c *Config) OIDCConfig(name string) *anywherev1.OIDCConfig { return c.OIDCConfigs[name] } func (c *Config) AWSIamConfig(name string) *anywherev1.AWSIamConfig { return c.AWSIAMConfigs[name] } func (c *Config) NutanixMachineConfig(name string) *anywherev1.NutanixMachineConfig { return c.NutanixMachineConfigs[name] } func (c *Config) DeepCopy() *Config { c2 := &Config{ Cluster: c.Cluster.DeepCopy(), CloudStackDatacenter: c.CloudStackDatacenter.DeepCopy(), VSphereDatacenter: c.VSphereDatacenter.DeepCopy(), NutanixDatacenter: c.NutanixDatacenter.DeepCopy(), DockerDatacenter: c.DockerDatacenter.DeepCopy(), SnowDatacenter: c.SnowDatacenter.DeepCopy(), TinkerbellDatacenter: c.TinkerbellDatacenter.DeepCopy(), GitOpsConfig: c.GitOpsConfig.DeepCopy(), FluxConfig: c.FluxConfig.DeepCopy(), } if c.VSphereMachineConfigs != nil { c2.VSphereMachineConfigs = make(map[string]*anywherev1.VSphereMachineConfig, len(c.VSphereMachineConfigs)) } for k, v := range c.VSphereMachineConfigs { c2.VSphereMachineConfigs[k] = v.DeepCopy() } if c.CloudStackMachineConfigs != nil { c2.CloudStackMachineConfigs = make(map[string]*anywherev1.CloudStackMachineConfig, len(c.CloudStackMachineConfigs)) } for k, v := range c.CloudStackMachineConfigs { c2.CloudStackMachineConfigs[k] = v.DeepCopy() } if c.OIDCConfigs != nil { c2.OIDCConfigs = make(map[string]*anywherev1.OIDCConfig, len(c.OIDCConfigs)) } for k, v := range c.OIDCConfigs { c2.OIDCConfigs[k] = v.DeepCopy() } if c.AWSIAMConfigs != nil { c2.AWSIAMConfigs = make(map[string]*anywherev1.AWSIamConfig, len(c.AWSIAMConfigs)) } for k, v := range c.AWSIAMConfigs { c2.AWSIAMConfigs[k] = v.DeepCopy() } if c.NutanixMachineConfigs != nil { c2.NutanixMachineConfigs = make(map[string]*anywherev1.NutanixMachineConfig, len(c.NutanixMachineConfigs)) } for k, v := range c.NutanixMachineConfigs { c2.NutanixMachineConfigs[k] = v.DeepCopy() } if c.SnowMachineConfigs != nil { c2.SnowMachineConfigs = make(map[string]*anywherev1.SnowMachineConfig, len(c.SnowMachineConfigs)) } for k, v := range c.SnowMachineConfigs { c2.SnowMachineConfigs[k] = v.DeepCopy() } if c.SnowIPPools != nil { c2.SnowIPPools = make(map[string]*anywherev1.SnowIPPool, len(c.SnowIPPools)) } for k, v := range c.SnowIPPools { c2.SnowIPPools[k] = v.DeepCopy() } if c.TinkerbellMachineConfigs != nil { c2.TinkerbellMachineConfigs = make(map[string]*anywherev1.TinkerbellMachineConfig, len(c.TinkerbellMachineConfigs)) } for k, v := range c.TinkerbellMachineConfigs { c2.TinkerbellMachineConfigs[k] = v.DeepCopy() } if c.TinkerbellTemplateConfigs != nil { c2.TinkerbellTemplateConfigs = make(map[string]*anywherev1.TinkerbellTemplateConfig, len(c.TinkerbellTemplateConfigs)) } for k, v := range c.TinkerbellTemplateConfigs { c2.TinkerbellTemplateConfigs[k] = v.DeepCopy() } return c2 } // ChildObjects returns all API objects in Config except the Cluster. func (c *Config) ChildObjects() []kubernetes.Object { objs := make( []kubernetes.Object, 0, len(c.VSphereMachineConfigs)+len(c.SnowMachineConfigs)+len(c.CloudStackMachineConfigs)+4, // machine configs length + datacenter + OIDC + IAM + gitops ) objs = appendIfNotNil(objs, c.CloudStackDatacenter, c.VSphereDatacenter, c.NutanixDatacenter, c.DockerDatacenter, c.SnowDatacenter, c.TinkerbellDatacenter, c.GitOpsConfig, c.FluxConfig, ) for _, e := range c.VSphereMachineConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.CloudStackMachineConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.SnowMachineConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.SnowIPPools { objs = appendIfNotNil(objs, e) } for _, e := range c.NutanixMachineConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.TinkerbellMachineConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.TinkerbellTemplateConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.OIDCConfigs { objs = appendIfNotNil(objs, e) } for _, e := range c.AWSIAMConfigs { objs = appendIfNotNil(objs, e) } return objs } func appendIfNotNil(objs []kubernetes.Object, elems ...kubernetes.Object) []kubernetes.Object { for _, e := range elems { // Since we receive interfaces, these will never be nil since they contain // the type of the original implementing struct // I can't find another clean option of doing this if !reflect.ValueOf(e).IsNil() { objs = append(objs, e) } } return objs }
214
eks-anywhere
aws
Go
package cluster import ( "errors" "fmt" "regexp" "strings" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" utilerrors "k8s.io/apimachinery/pkg/util/errors" "sigs.k8s.io/yaml" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/logger" ) // ConfigManager allows to parse from yaml, set defaults and validate a Cluster struct // It allows to dynamically register configuration for all those operations. type ConfigManager struct { // TODO: find a better name entry *ConfigManagerEntry } // NewConfigManager builds a ConfigManager with empty configuration. func NewConfigManager() *ConfigManager { return &ConfigManager{ entry: NewConfigManagerEntry(), } } // Register records the configuration defined in a ConfigManagerEntry into the ConfigManager // This is equivalent to the individual register methods. func (c *ConfigManager) Register(entries ...*ConfigManagerEntry) error { return c.entry.Merge(entries...) } // RegisterMapping records the mapping between a kubernetes Kind and an API concrete type. func (c *ConfigManager) RegisterMapping(kind string, generator APIObjectGenerator) error { return c.entry.RegisterMapping(kind, generator) } // RegisterProcessors records setters to fill the Config struct from the parsed API objects. func (c *ConfigManager) RegisterProcessors(processors ...ParsedProcessor) { c.entry.RegisterProcessors(processors...) } // RegisterValidations records validations for a Config struct. func (c *ConfigManager) RegisterValidations(validations ...Validation) { c.entry.RegisterValidations(validations...) } // RegisterDefaulters records defaults for a Config struct. func (c *ConfigManager) RegisterDefaulters(defaulters ...Defaulter) { c.entry.RegisterDefaulters(defaulters...) } // Parse reads yaml manifest with at least one cluster object and generates the corresponding Config. func (c *ConfigManager) Parse(yamlManifest []byte) (*Config, error) { parsed, err := c.unmarshal(yamlManifest) if err != nil { return nil, err } return c.buildConfigFromParsed(parsed) } // Parse set the registered defaults in a Config struct. func (c *ConfigManager) SetDefaults(config *Config) error { var allErrs []error for _, d := range c.entry.Defaulters { if err := d(config); err != nil { allErrs = append(allErrs, err) } } if len(allErrs) > 0 { aggregate := utilerrors.NewAggregate(allErrs) return fmt.Errorf("setting defaults on cluster config: %v", aggregate) } return nil } // Validate performs the registered validations in a Config struct. func (c *ConfigManager) Validate(config *Config) error { var allErrs []error for _, v := range c.entry.Validations { if err := v(config); err != nil { allErrs = append(allErrs, err) } } if len(allErrs) > 0 { aggregate := utilerrors.NewAggregate(allErrs) return fmt.Errorf("invalid cluster config: %v", aggregate) } return nil } type basicAPIObject struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` } func (k *basicAPIObject) empty() bool { return k.APIVersion == "" && k.Kind == "" } type parsed struct { objects ObjectLookup cluster *anywherev1.Cluster } var separatorRegex = regexp.MustCompile(`(?m)^---$`) func (c *ConfigManager) unmarshal(yamlManifest []byte) (*parsed, error) { parsed := &parsed{ objects: ObjectLookup{}, } yamlObjs := separatorRegex.Split(string(yamlManifest), -1) for _, yamlObj := range yamlObjs { trimmedYamlObj := strings.TrimSuffix(yamlObj, "\n") k := &basicAPIObject{} err := yaml.Unmarshal([]byte(trimmedYamlObj), k) if err != nil { return nil, err } // Ignore empty objects. // Empty objects are generated if there are weird things in manifest files like e.g. two --- in a row without a yaml doc in the middle if k.empty() { continue } var obj APIObject if k.Kind == anywherev1.ClusterKind { if parsed.cluster != nil { return nil, errors.New("only one Cluster per yaml manifest is allowed") } parsed.cluster = &anywherev1.Cluster{} obj = parsed.cluster } else if generateApiObj, ok := c.entry.APIObjectMapping[k.Kind]; ok { obj = generateApiObj() } else { logger.V(2).Info("Ignoring object in yaml of unknown type when parsing cluster Config", "kind", k.Kind) continue } if err := yaml.Unmarshal([]byte(trimmedYamlObj), obj); err != nil { return nil, err } parsed.objects.add(obj) } return parsed, nil } func (c *ConfigManager) buildConfigFromParsed(p *parsed) (*Config, error) { if p.cluster == nil { return nil, errors.New("no Cluster found in manifest") } config := &Config{ Cluster: p.cluster, } for _, processor := range c.entry.Processors { processor(config, p.objects) } return config, nil } // machineConfigsProcessor is a helper to generate a ParsedProcessor for all machine configs in a Cluster. func machineConfigsProcessor(processMachineRef func(c *Config, o ObjectLookup, machineRef *anywherev1.Ref)) ParsedProcessor { return func(c *Config, o ObjectLookup) { for _, m := range c.Cluster.MachineConfigRefs() { processMachineRef(c, o, &m) } } }
186
eks-anywhere
aws
Go
package cluster_test import ( "errors" "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/aws/eks-anywhere/internal/test" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/utils/ptr" ) func TestConfigManagerParseSuccess(t *testing.T) { g := NewWithT(t) c := cluster.NewConfigManager() g.Expect(c.RegisterMapping(anywherev1.DockerDatacenterKind, func() cluster.APIObject { return &anywherev1.DockerDatacenterConfig{} })).To(Succeed()) c.RegisterProcessors(func(c *cluster.Config, ol cluster.ObjectLookup) { d := ol.GetFromRef(c.Cluster.APIVersion, c.Cluster.Spec.DatacenterRef) c.DockerDatacenter = d.(*anywherev1.DockerDatacenterConfig) }) yamlManifest := []byte(test.ReadFile(t, "testdata/docker_cluster_oidc_awsiam_flux.yaml")) wantCluster := &anywherev1.Cluster{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.ClusterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "m-docker", }, Spec: anywherev1.ClusterSpec{ KubernetesVersion: "1.21", ManagementCluster: anywherev1.ManagementCluster{ Name: "m-docker", }, ControlPlaneConfiguration: anywherev1.ControlPlaneConfiguration{ Count: 1, }, WorkerNodeGroupConfigurations: []anywherev1.WorkerNodeGroupConfiguration{ { Name: "workers-1", Count: ptr.Int(1), }, }, DatacenterRef: anywherev1.Ref{ Kind: anywherev1.DockerDatacenterKind, Name: "m-docker", }, ClusterNetwork: anywherev1.ClusterNetwork{ Pods: anywherev1.Pods{ CidrBlocks: []string{"192.168.0.0/16"}, }, Services: anywherev1.Services{ CidrBlocks: []string{"10.96.0.0/12"}, }, CNI: "cilium", }, IdentityProviderRefs: []anywherev1.Ref{ { Kind: anywherev1.OIDCConfigKind, Name: "eksa-unit-test", }, { Kind: anywherev1.AWSIamConfigKind, Name: "eksa-unit-test", }, }, GitOpsRef: &anywherev1.Ref{ Kind: anywherev1.FluxConfigKind, Name: "eksa-unit-test", }, }, } wantDockerDatacenter := &anywherev1.DockerDatacenterConfig{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.DockerDatacenterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "m-docker", }, } wantConfig := &cluster.Config{ Cluster: wantCluster, DockerDatacenter: wantDockerDatacenter, } config, err := c.Parse(yamlManifest) g.Expect(err).To(BeNil()) g.Expect(config).To(Equal(wantConfig)) } func TestConfigManagerParseMissingCluster(t *testing.T) { g := NewWithT(t) c := cluster.NewConfigManager() _, err := c.Parse([]byte{}) g.Expect(err).To(MatchError(ContainSubstring("no Cluster found in manifest"))) } func TestConfigManagerParseTwoClusters(t *testing.T) { g := NewWithT(t) manifest := `apiVersion: anywhere.eks.amazonaws.com/v1alpha1 kind: Cluster metadata: name: eksa-unit-test --- apiVersion: anywhere.eks.amazonaws.com/v1alpha1 kind: Cluster metadata: name: eksa-unit-test-2 ` c := cluster.NewConfigManager() _, err := c.Parse([]byte(manifest)) g.Expect(err).To(MatchError(ContainSubstring("only one Cluster per yaml manifest is allowed"))) } func TestConfigManagerParseUnknownKind(t *testing.T) { g := NewWithT(t) manifest := `apiVersion: anywhere.eks.amazonaws.com/v1alpha1 kind: Cluster metadata: name: eksa-unit-test --- apiVersion: anywhere.eks.amazonaws.com/v1alpha1 kind: MysteryCRD ` wantCluster := &anywherev1.Cluster{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.ClusterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, } wantConfig := &cluster.Config{ Cluster: wantCluster, } c := cluster.NewConfigManager() g.Expect(c.Parse([]byte(manifest))).To(Equal(wantConfig)) } func TestConfigManagerSetDefaultsSuccess(t *testing.T) { g := NewWithT(t) defaultNamespace := "default" c := cluster.NewConfigManager() c.RegisterDefaulters(func(c *cluster.Config) error { if c.Cluster.Namespace == "" { c.Cluster.Namespace = defaultNamespace } return nil }) config := &cluster.Config{ Cluster: &anywherev1.Cluster{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.ClusterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, }, } g.Expect(c.SetDefaults(config)).To(Succeed()) g.Expect(config.Cluster.Namespace).To(Equal(defaultNamespace)) } func TestConfigManagerValidateMultipleErrors(t *testing.T) { g := NewWithT(t) c := cluster.NewConfigManager() c.RegisterValidations( func(c *cluster.Config) error { if c.Cluster.Namespace == "" { return errors.New("cluster namespace can't be empty") } return nil }, func(c *cluster.Config) error { if c.Cluster.Name == "" { return errors.New("cluster name can't be empty") } return nil }, func(c *cluster.Config) error { if c.Cluster.Spec.KubernetesVersion == "" { return errors.New("cluster kubernetes version can't be empty") } return nil }, ) config := &cluster.Config{ Cluster: &anywherev1.Cluster{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.ClusterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, }, } g.Expect(c.Validate(config)).To(MatchError(ContainSubstring( "invalid cluster config: [cluster namespace can't be empty, cluster kubernetes version can't be empty]", ))) } func TestConfigManagerValidateMultipleSuccess(t *testing.T) { g := NewWithT(t) c := cluster.NewConfigManager() c.RegisterValidations( func(c *cluster.Config) error { if c.Cluster.Name == "" { return errors.New("cluster name can't be empty") } return nil }, ) config := &cluster.Config{ Cluster: &anywherev1.Cluster{ TypeMeta: metav1.TypeMeta{ Kind: anywherev1.ClusterKind, APIVersion: anywherev1.SchemeBuilder.GroupVersion.String(), }, ObjectMeta: metav1.ObjectMeta{ Name: "eksa-unit-test", }, }, } g.Expect(c.Validate(config)).To(Succeed()) }
244
eks-anywhere
aws
Go
package cluster_test import ( "reflect" "testing" . "github.com/onsi/gomega" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" ) func TestConfigChildObjects(t *testing.T) { g := NewWithT(t) config := &cluster.Config{ Cluster: &anywherev1.Cluster{}, SnowDatacenter: &anywherev1.SnowDatacenterConfig{}, CloudStackDatacenter: &anywherev1.CloudStackDatacenterConfig{}, VSphereDatacenter: &anywherev1.VSphereDatacenterConfig{}, NutanixDatacenter: &anywherev1.NutanixDatacenterConfig{}, TinkerbellDatacenter: &anywherev1.TinkerbellDatacenterConfig{}, SnowMachineConfigs: map[string]*anywherev1.SnowMachineConfig{ "machine1": {}, "machine2": {}, }, SnowIPPools: map[string]*anywherev1.SnowIPPool{ "pool1": {}, "pool2": {}, }, VSphereMachineConfigs: map[string]*anywherev1.VSphereMachineConfig{ "machine1": {}, "machine2": {}, }, CloudStackMachineConfigs: map[string]*anywherev1.CloudStackMachineConfig{ "machine1": {}, "machine2": {}, }, NutanixMachineConfigs: map[string]*anywherev1.NutanixMachineConfig{ "machine1": {}, "machine2": {}, }, TinkerbellMachineConfigs: map[string]*anywherev1.TinkerbellMachineConfig{ "machine1": {}, "machine2": {}, }, TinkerbellTemplateConfigs: map[string]*anywherev1.TinkerbellTemplateConfig{ "template1": {}, "tenplate2": {}, }, OIDCConfigs: map[string]*anywherev1.OIDCConfig{ "machine1": {}, }, AWSIAMConfigs: map[string]*anywherev1.AWSIamConfig{ "config1": {}, }, FluxConfig: &anywherev1.FluxConfig{}, } objs := config.ChildObjects() g.Expect(objs).To(HaveLen(22)) for _, o := range objs { g.Expect(reflect.ValueOf(o).IsNil()).To(BeFalse()) } } func TestConfigDeepCopy(t *testing.T) { g := NewWithT(t) config := &cluster.Config{ Cluster: &anywherev1.Cluster{}, CloudStackDatacenter: &anywherev1.CloudStackDatacenterConfig{}, VSphereDatacenter: &anywherev1.VSphereDatacenterConfig{}, DockerDatacenter: &anywherev1.DockerDatacenterConfig{}, SnowDatacenter: &anywherev1.SnowDatacenterConfig{}, NutanixDatacenter: &anywherev1.NutanixDatacenterConfig{}, TinkerbellDatacenter: &anywherev1.TinkerbellDatacenterConfig{}, GitOpsConfig: &anywherev1.GitOpsConfig{}, SnowMachineConfigs: map[string]*anywherev1.SnowMachineConfig{ "machine1": {}, "machine2": {}, }, SnowIPPools: map[string]*anywherev1.SnowIPPool{ "pool1": {}, "pool2": {}, }, VSphereMachineConfigs: map[string]*anywherev1.VSphereMachineConfig{ "machine1": {}, "machine2": {}, }, CloudStackMachineConfigs: map[string]*anywherev1.CloudStackMachineConfig{ "machine1": {}, "machine2": {}, }, NutanixMachineConfigs: map[string]*anywherev1.NutanixMachineConfig{ "machine1": {}, "machine2": {}, }, TinkerbellMachineConfigs: map[string]*anywherev1.TinkerbellMachineConfig{ "machine1": {}, "machine2": {}, }, TinkerbellTemplateConfigs: map[string]*anywherev1.TinkerbellTemplateConfig{ "template1": {}, "tenplate2": {}, }, OIDCConfigs: map[string]*anywherev1.OIDCConfig{ "machine1": {}, }, AWSIAMConfigs: map[string]*anywherev1.AWSIamConfig{ "config1": {}, }, FluxConfig: &anywherev1.FluxConfig{}, } copyConf := config.DeepCopy() g.Expect(copyConf).To(BeEquivalentTo(config)) }
103
eks-anywhere
aws
Go
package cluster func SetConfigDefaults(c *Config) error { return manager().SetDefaults(c) }
6
eks-anywhere
aws
Go
package cluster_test import ( "testing" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" ) func TestSetDefaultFluxConfigPath(t *testing.T) { tests := []struct { name string config *cluster.Config wantConfigPath string }{ { name: "self-managed cluster", config: &cluster.Config{ Cluster: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "c-1", }, Spec: anywherev1.ClusterSpec{ ManagementCluster: anywherev1.ManagementCluster{ Name: "c-1", }, }, }, FluxConfig: &anywherev1.FluxConfig{}, }, wantConfigPath: "clusters/c-1", }, { name: "managed cluster", config: &cluster.Config{ Cluster: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "c-1", }, Spec: anywherev1.ClusterSpec{ ManagementCluster: anywherev1.ManagementCluster{ Name: "c-m", }, }, }, FluxConfig: &anywherev1.FluxConfig{}, }, wantConfigPath: "clusters/c-m", }, { name: "config path is already set", config: &cluster.Config{ Cluster: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "c-1", }, Spec: anywherev1.ClusterSpec{ ManagementCluster: anywherev1.ManagementCluster{ Name: "c-m", }, }, }, FluxConfig: &anywherev1.FluxConfig{ Spec: anywherev1.FluxConfigSpec{ ClusterConfigPath: "my-path", }, }, }, wantConfigPath: "my-path", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) g.Expect(cluster.SetDefaultFluxConfigPath(tt.config)).To(Succeed()) g.Expect(tt.config.FluxConfig.Spec.ClusterConfigPath).To(Equal(tt.wantConfigPath)) }) } } func TestSetConfigDefaults(t *testing.T) { g := NewWithT(t) c := clusterConfigFromFile(t, "testdata/cluster_1_19.yaml") originalC := clusterConfigFromFile(t, "testdata/cluster_1_19.yaml") g.Expect(cluster.SetConfigDefaults(c)).To(Succeed()) g.Expect(c).NotTo(Equal(originalC)) }
92
eks-anywhere
aws
Go
package cluster var defaultManager *ConfigManager func init() { var err error defaultManager, err = NewDefaultConfigManager() if err != nil { panic(err) } } func manager() *ConfigManager { return defaultManager } func NewDefaultConfigManager() (*ConfigManager, error) { m := NewConfigManager() err := m.Register( clusterEntry(), oidcEntry(), awsIamEntry(), gitOpsEntry(), fluxEntry(), vsphereEntry(), cloudstackEntry(), dockerEntry(), snowEntry(), tinkerbellEntry(), nutanixEntry(), ) if err != nil { return nil, err } return m, nil }
38
eks-anywhere
aws
Go
package cluster import ( "context" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" ) func dockerEntry() *ConfigManagerEntry { return &ConfigManagerEntry{ APIObjectMapping: map[string]APIObjectGenerator{ anywherev1.DockerDatacenterKind: func() APIObject { return &anywherev1.DockerDatacenterConfig{} }, }, Processors: []ParsedProcessor{ processDockerDatacenter, }, Validations: []Validation{ func(c *Config) error { if c.DockerDatacenter != nil { return c.DockerDatacenter.Validate() } return nil }, func(c *Config) error { if c.DockerDatacenter != nil { if err := validateSameNamespace(c, c.DockerDatacenter); err != nil { return err } } return nil }, }, } } func processDockerDatacenter(c *Config, objects ObjectLookup) { if c.Cluster.Spec.DatacenterRef.Kind == anywherev1.DockerDatacenterKind { datacenter := objects.GetFromRef(c.Cluster.APIVersion, c.Cluster.Spec.DatacenterRef) if datacenter != nil { c.DockerDatacenter = datacenter.(*anywherev1.DockerDatacenterConfig) } } } func getDockerDatacenter(ctx context.Context, client Client, c *Config) error { if c.Cluster.Spec.DatacenterRef.Kind != anywherev1.DockerDatacenterKind { return nil } datacenter := &anywherev1.DockerDatacenterConfig{} if err := client.Get(ctx, c.Cluster.Spec.DatacenterRef.Name, c.Cluster.Namespace, datacenter); err != nil { return err } c.DockerDatacenter = datacenter return nil }
60
eks-anywhere
aws
Go
package cluster_test import ( "context" "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/cluster/mocks" ) func TestParseConfigMissingDockerDatacenter(t *testing.T) { g := NewWithT(t) got, err := cluster.ParseConfigFromFile("testdata/cluster_docker_missing_datacenter.yaml") g.Expect(err).To(Not(HaveOccurred())) g.Expect(got.DockerDatacenter).To(BeNil()) } func TestDefaultConfigClientBuilderDockerCluster(t *testing.T) { g := NewWithT(t) ctx := context.Background() b := cluster.NewDefaultConfigClientBuilder() ctrl := gomock.NewController(t) client := mocks.NewMockClient(ctrl) cluster := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "my-cluster", Namespace: "default", }, Spec: anywherev1.ClusterSpec{ DatacenterRef: anywherev1.Ref{ Kind: anywherev1.DockerDatacenterKind, Name: "datacenter", }, ControlPlaneConfiguration: anywherev1.ControlPlaneConfiguration{ Count: 1, }, WorkerNodeGroupConfigurations: []anywherev1.WorkerNodeGroupConfiguration{ { Name: "md-0", }, }, }, } datacenter := &anywherev1.DockerDatacenterConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "datacenter", Namespace: "default", }, } client.EXPECT().Get(ctx, "datacenter", "default", &anywherev1.DockerDatacenterConfig{}).Return(nil).DoAndReturn( func(ctx context.Context, name, namespace string, obj runtime.Object) error { d := obj.(*anywherev1.DockerDatacenterConfig) d.ObjectMeta = datacenter.ObjectMeta d.Spec = datacenter.Spec return nil }, ) config, err := b.Build(ctx, client, cluster) g.Expect(err).NotTo(HaveOccurred()) g.Expect(config).NotTo(BeNil()) g.Expect(config.Cluster).To(Equal(cluster)) g.Expect(config.DockerDatacenter).To(Equal(datacenter)) }
73
eks-anywhere
aws
Go
package cluster import ( "context" "fmt" eksdv1alpha1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/constants" "github.com/aws/eks-anywhere/pkg/logger" v1alpha1release "github.com/aws/eks-anywhere/release/api/v1alpha1" ) type BundlesFetch func(ctx context.Context, name, namespace string) (*v1alpha1release.Bundles, error) type GitOpsFetch func(ctx context.Context, name, namespace string) (*v1alpha1.GitOpsConfig, error) type FluxConfigFetch func(ctx context.Context, name, namespace string) (*v1alpha1.FluxConfig, error) type EksdReleaseFetch func(ctx context.Context, name, namespace string) (*eksdv1alpha1.Release, error) type OIDCFetch func(ctx context.Context, name, namespace string) (*v1alpha1.OIDCConfig, error) type AWSIamConfigFetch func(ctx context.Context, name, namespace string) (*v1alpha1.AWSIamConfig, error) // BuildSpecForCluster constructs a cluster.Spec for an eks-a cluster by retrieving all // necessary objects using fetch methods // This is deprecated in favour of BuildSpec. func BuildSpecForCluster(ctx context.Context, cluster *v1alpha1.Cluster, bundlesFetch BundlesFetch, eksdReleaseFetch EksdReleaseFetch, gitOpsFetch GitOpsFetch, fluxConfigFetch FluxConfigFetch, oidcFetch OIDCFetch, awsIamConfigFetch AWSIamConfigFetch) (*Spec, error) { bundles, err := GetBundlesForCluster(ctx, cluster, bundlesFetch) if err != nil { return nil, err } var fluxConfig *v1alpha1.FluxConfig var gitOpsConfig *v1alpha1.GitOpsConfig if cluster.Spec.GitOpsRef != nil { if cluster.Spec.GitOpsRef.Kind == v1alpha1.FluxConfigKind { fluxConfig, err = GetFluxConfigForCluster(ctx, cluster, fluxConfigFetch) if err != nil { return nil, err } } if cluster.Spec.GitOpsRef.Kind == v1alpha1.GitOpsConfigKind { gitOpsConfig, err = GetGitOpsForCluster(ctx, cluster, gitOpsFetch) if err != nil { return nil, err } fluxConfig = gitOpsConfig.ConvertToFluxConfig() } } eksd, err := GetEksdReleaseForCluster(ctx, cluster, bundles, eksdReleaseFetch) if err != nil { return nil, err } oidcConfig, err := GetOIDCForCluster(ctx, cluster, oidcFetch) if err != nil { return nil, err } awsIamConfig, err := GetAWSIamConfigForCluster(ctx, cluster, awsIamConfigFetch) if err != nil { return nil, err } // This Config is incomplete, if you need the whole thing use [BuildSpec] config := &Config{ Cluster: cluster, GitOpsConfig: gitOpsConfig, FluxConfig: fluxConfig, } if oidcConfig != nil { config.OIDCConfigs = map[string]*v1alpha1.OIDCConfig{ oidcConfig.Name: oidcConfig, } } if awsIamConfig != nil { config.AWSIAMConfigs = map[string]*v1alpha1.AWSIamConfig{ awsIamConfig.Name: awsIamConfig, } } return NewSpec(config, bundles, eksd) } func GetBundlesForCluster(ctx context.Context, cluster *v1alpha1.Cluster, fetch BundlesFetch) (*v1alpha1release.Bundles, error) { name, namespace := bundlesNamespacedKey(cluster) bundles, err := fetch(ctx, name, namespace) if err != nil { return nil, fmt.Errorf("fetching Bundles for cluster: %v", err) } return bundles, nil } func bundlesNamespacedKey(cluster *v1alpha1.Cluster) (name, namespace string) { if cluster.Spec.BundlesRef != nil { name = cluster.Spec.BundlesRef.Name namespace = cluster.Spec.BundlesRef.Namespace } else { // Handles old clusters that don't contain a reference yet to the Bundles // For those clusters, the Bundles was created with the same name as the cluster // and in the same namespace name = cluster.Name namespace = cluster.Namespace } return name, namespace } func GetFluxConfigForCluster(ctx context.Context, cluster *v1alpha1.Cluster, fetch FluxConfigFetch) (*v1alpha1.FluxConfig, error) { if fetch == nil || cluster.Spec.GitOpsRef == nil { return nil, nil } fluxConfig, err := fetch(ctx, cluster.Spec.GitOpsRef.Name, cluster.Namespace) if err != nil { return nil, fmt.Errorf("fetching FluxCOnfig for cluster: %v", err) } return fluxConfig, nil } func GetGitOpsForCluster(ctx context.Context, cluster *v1alpha1.Cluster, fetch GitOpsFetch) (*v1alpha1.GitOpsConfig, error) { if fetch == nil || cluster.Spec.GitOpsRef == nil { return nil, nil } gitops, err := fetch(ctx, cluster.Spec.GitOpsRef.Name, cluster.Namespace) if err != nil { return nil, fmt.Errorf("failed fetching GitOpsConfig for cluster: %v", err) } return gitops, nil } func GetEksdReleaseForCluster(ctx context.Context, cluster *v1alpha1.Cluster, bundles *v1alpha1release.Bundles, fetch EksdReleaseFetch) (*eksdv1alpha1.Release, error) { versionsBundle, err := GetVersionsBundle(cluster, bundles) if err != nil { return nil, fmt.Errorf("failed fetching versions bundle: %v", err) } eksd, err := fetch(ctx, versionsBundle.EksD.Name, constants.EksaSystemNamespace) if err != nil { logger.V(4).Info("EKS-D release objects cannot be retrieved from the cluster. Fetching EKS-D release manifest from the URL in the bundle") return nil, nil } return eksd, nil } func GetVersionsBundle(clusterConfig *v1alpha1.Cluster, bundles *v1alpha1release.Bundles) (*v1alpha1release.VersionsBundle, error) { return getVersionsBundleForKubernetesVersion(clusterConfig.Spec.KubernetesVersion, bundles) } func getVersionsBundleForKubernetesVersion(kubernetesVersion v1alpha1.KubernetesVersion, bundles *v1alpha1release.Bundles) (*v1alpha1release.VersionsBundle, error) { for _, versionsBundle := range bundles.Spec.VersionsBundles { if versionsBundle.KubeVersion == string(kubernetesVersion) { return &versionsBundle, nil } } return nil, fmt.Errorf("kubernetes version %s is not supported by bundles manifest %d", kubernetesVersion, bundles.Spec.Number) } func GetOIDCForCluster(ctx context.Context, cluster *v1alpha1.Cluster, fetch OIDCFetch) (*v1alpha1.OIDCConfig, error) { if fetch == nil || cluster.Spec.IdentityProviderRefs == nil { return nil, nil } for _, identityProvider := range cluster.Spec.IdentityProviderRefs { if identityProvider.Kind == v1alpha1.OIDCConfigKind { oidc, err := fetch(ctx, identityProvider.Name, cluster.Namespace) if err != nil { return nil, fmt.Errorf("failed fetching OIDCConfig for cluster: %v", err) } return oidc, nil } } return nil, nil } func GetAWSIamConfigForCluster(ctx context.Context, cluster *v1alpha1.Cluster, fetch AWSIamConfigFetch) (*v1alpha1.AWSIamConfig, error) { if fetch == nil || cluster.Spec.IdentityProviderRefs == nil { return nil, nil } for _, identityProvider := range cluster.Spec.IdentityProviderRefs { if identityProvider.Kind == v1alpha1.AWSIamConfigKind { awsIamConfig, err := fetch(ctx, identityProvider.Name, cluster.Namespace) if err != nil { return nil, fmt.Errorf("failed fetching AWSIamConfig for cluster: %v", err) } return awsIamConfig, nil } } return nil, nil } // BuildSpec constructs a cluster.Spec for an eks-a cluster by retrieving all // necessary objects from the cluster using a kubernetes client. func BuildSpec(ctx context.Context, client Client, cluster *v1alpha1.Cluster) (*Spec, error) { configBuilder := NewDefaultConfigClientBuilder() config, err := configBuilder.Build(ctx, client, cluster) if err != nil { return nil, err } return BuildSpecFromConfig(ctx, client, config) } // BuildSpecFromConfig constructs a cluster.Spec for an eks-a cluster config by retrieving all dependencies objects from the cluster using a kubernetes client. func BuildSpecFromConfig(ctx context.Context, client Client, config *Config) (*Spec, error) { bundlesName, bundlesNamespace := bundlesNamespacedKey(config.Cluster) bundles := &v1alpha1release.Bundles{} if err := client.Get(ctx, bundlesName, bundlesNamespace, bundles); err != nil { return nil, err } versionsBundle, err := GetVersionsBundle(config.Cluster, bundles) if err != nil { return nil, err } // Ideally we would use the same namespace as the Bundles, but Bundles can be in any namespace and // the eksd release is always in eksa-system eksdRelease := &eksdv1alpha1.Release{} if err = client.Get(ctx, versionsBundle.EksD.Name, constants.EksaSystemNamespace, eksdRelease); err != nil { return nil, err } return NewSpec(config, bundles, eksdRelease) }
234
eks-anywhere
aws
Go
package cluster_test import ( "context" "errors" "testing" eksdv1 "github.com/aws/eks-distro-build-tooling/release/api/v1alpha1" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1" "github.com/aws/eks-anywhere/pkg/cluster" "github.com/aws/eks-anywhere/pkg/cluster/mocks" releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1" ) func TestBuildSpecForCluster(t *testing.T) { g := NewWithT(t) ctx := context.Background() oidcConfig := &anywherev1.OIDCConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "myconfig", }, } awsIamConfig := &anywherev1.AWSIamConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "myconfig", }, } fluxConfig := &anywherev1.FluxConfig{ ObjectMeta: metav1.ObjectMeta{ Name: "myconfig", }, } config := &cluster.Config{ Cluster: &anywherev1.Cluster{ Spec: anywherev1.ClusterSpec{ KubernetesVersion: anywherev1.Kube124, IdentityProviderRefs: []anywherev1.Ref{ { Kind: anywherev1.OIDCConfigKind, Name: "myconfig", }, { Kind: anywherev1.AWSIamConfigKind, Name: "myconfig", }, }, GitOpsRef: &anywherev1.Ref{ Kind: anywherev1.FluxConfigKind, Name: "myconfig", }, }, }, OIDCConfigs: map[string]*anywherev1.OIDCConfig{ "myconfig": oidcConfig, }, AWSIAMConfigs: map[string]*anywherev1.AWSIamConfig{ "myconfig": awsIamConfig, }, FluxConfig: fluxConfig, } bundles := &releasev1.Bundles{ Spec: releasev1.BundlesSpec{ Number: 2, VersionsBundles: []releasev1.VersionsBundle{ { KubeVersion: "1.24", }, }, }, } eksdRelease := readEksdRelease(t, "testdata/eksd_valid.yaml") bundlesFetch := func(_ context.Context, _, _ string) (*releasev1.Bundles, error) { return bundles, nil } eksdFetch := func(_ context.Context, _, _ string) (*eksdv1.Release, error) { return eksdRelease, nil } gitOpsFetch := func(_ context.Context, name, namespace string) (*anywherev1.GitOpsConfig, error) { return nil, nil } fluxConfigFetch := func(_ context.Context, _, _ string) (*anywherev1.FluxConfig, error) { return fluxConfig, nil } oidcFetch := func(_ context.Context, _, _ string) (*anywherev1.OIDCConfig, error) { return oidcConfig, nil } awsIamConfigFetch := func(_ context.Context, _, _ string) (*anywherev1.AWSIamConfig, error) { return awsIamConfig, nil } spec, err := cluster.BuildSpecForCluster(ctx, config.Cluster, bundlesFetch, eksdFetch, gitOpsFetch, fluxConfigFetch, oidcFetch, awsIamConfigFetch) g.Expect(err).NotTo(HaveOccurred()) g.Expect(spec.Config).To(Equal(config)) g.Expect(spec.OIDCConfig).To(Equal(oidcConfig)) g.Expect(spec.AWSIamConfig).To(Equal(awsIamConfig)) g.Expect(spec.Bundles).To(Equal(bundles)) } func TestGetBundlesForCluster(t *testing.T) { testCases := []struct { testName string cluster *anywherev1.Cluster wantName, wantNamespace string }{ { testName: "no bundles ref", cluster: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{}, }, wantName: "eksa-cluster", wantNamespace: "eksa", }, { testName: "bundles ref", cluster: &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{ BundlesRef: &anywherev1.BundlesRef{ Name: "bundles-1", Namespace: "eksa-system", APIVersion: "anywhere.eks.amazonaws.com/v1alpha1", }, }, }, wantName: "bundles-1", wantNamespace: "eksa-system", }, } for _, tt := range testCases { t.Run(tt.testName, func(t *testing.T) { g := NewWithT(t) wantBundles := &releasev1.Bundles{} mockFetch := func(ctx context.Context, name, namespace string) (*releasev1.Bundles, error) { g.Expect(name).To(Equal(tt.wantName)) g.Expect(namespace).To(Equal(tt.wantNamespace)) return wantBundles, nil } gotBundles, err := cluster.GetBundlesForCluster(context.Background(), tt.cluster, mockFetch) g.Expect(err).To(BeNil()) g.Expect(gotBundles).To(Equal(wantBundles)) }) } } func TestGetFluxConfigForClusterIsNil(t *testing.T) { g := NewWithT(t) c := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{ GitOpsRef: nil, }, } var wantFlux *anywherev1.FluxConfig mockFetch := func(ctx context.Context, name, namespace string) (*anywherev1.FluxConfig, error) { g.Expect(name).To(Equal(c.Name)) g.Expect(namespace).To(Equal(c.Namespace)) return wantFlux, nil } gotFlux, err := cluster.GetFluxConfigForCluster(context.Background(), c, mockFetch) g.Expect(err).To(BeNil()) g.Expect(gotFlux).To(Equal(wantFlux)) } func TestGetFluxConfigForCluster(t *testing.T) { g := NewWithT(t) c := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{ GitOpsRef: &anywherev1.Ref{ Kind: anywherev1.FluxConfigKind, Name: "eksa-cluster", }, }, } wantFlux := &anywherev1.FluxConfig{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{}, Spec: anywherev1.FluxConfigSpec{}, Status: anywherev1.FluxConfigStatus{}, } mockFetch := func(ctx context.Context, name, namespace string) (*anywherev1.FluxConfig, error) { g.Expect(name).To(Equal(c.Name)) g.Expect(namespace).To(Equal(c.Namespace)) return wantFlux, nil } gotFlux, err := cluster.GetFluxConfigForCluster(context.Background(), c, mockFetch) g.Expect(err).To(BeNil()) g.Expect(gotFlux).To(Equal(wantFlux)) } func TestGetAWSIamConfigForCluster(t *testing.T) { g := NewWithT(t) c := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{ IdentityProviderRefs: []anywherev1.Ref{ { Kind: anywherev1.AWSIamConfigKind, Name: "eksa-cluster", }, }, }, } wantIamConfig := &anywherev1.AWSIamConfig{ TypeMeta: metav1.TypeMeta{}, ObjectMeta: metav1.ObjectMeta{}, Spec: anywherev1.AWSIamConfigSpec{}, Status: anywherev1.AWSIamConfigStatus{}, } mockFetch := func(ctx context.Context, name, namespace string) (*anywherev1.AWSIamConfig, error) { g.Expect(name).To(Equal(c.Name)) g.Expect(namespace).To(Equal(c.Namespace)) return wantIamConfig, nil } gotIamConfig, err := cluster.GetAWSIamConfigForCluster(context.Background(), c, mockFetch) g.Expect(err).To(BeNil()) g.Expect(gotIamConfig).To(Equal(wantIamConfig)) } func TestGetAWSIamConfigForClusterIsNil(t *testing.T) { g := NewWithT(t) c := &anywherev1.Cluster{ ObjectMeta: metav1.ObjectMeta{ Name: "eksa-cluster", Namespace: "eksa", }, Spec: anywherev1.ClusterSpec{ IdentityProviderRefs: nil, }, } var wantIamConfig *anywherev1.AWSIamConfig mockFetch := func(ctx context.Context, name, namespace string) (*anywherev1.AWSIamConfig, error) { g.Expect(name).To(Equal(c.Name)) g.Expect(namespace).To(Equal(c.Namespace)) return wantIamConfig, nil } gotIamConfig, err := cluster.GetAWSIamConfigForCluster(context.Background(), c, mockFetch) g.Expect(err).To(BeNil()) g.Expect(gotIamConfig).To(Equal(wantIamConfig)) } type buildSpecTest struct { *WithT ctx context.Context ctrl *gomock.Controller client *mocks.MockClient cluster *anywherev1.Cluster bundles *releasev1.Bundles eksdRelease *eksdv1.Release kubeDistro *cluster.KubeDistro } func newBuildSpecTest(t *testing.T) *buildSpecTest { ctrl := gomock.NewController(t) client := mocks.NewMockClient(ctrl) cluster := &anywherev1.Cluster{ Spec: anywherev1.ClusterSpec{ BundlesRef: &anywherev1.BundlesRef{ Name: "bundles-1", Namespace: "my-namespace", }, KubernetesVersion: anywherev1.Kube123, }, } bundles := &releasev1.Bundles{ ObjectMeta: metav1.ObjectMeta{ Name: "bundles-1", }, Spec: releasev1.BundlesSpec{ VersionsBundles: []releasev1.VersionsBundle{ { KubeVersion: "1.23", EksD: releasev1.EksDRelease{ Name: "eksd-123", }, }, }, }, } eksdRelease, kubeDistro := wantKubeDistroForEksdRelease() return &buildSpecTest{ WithT: NewWithT(t), ctx: context.Background(), ctrl: ctrl, client: client, cluster: cluster, bundles: bundles, eksdRelease: eksdRelease, kubeDistro: kubeDistro, } } func (tt *buildSpecTest) expectGetBundles() { tt.client.EXPECT().Get(tt.ctx, "bundles-1", "my-namespace", &releasev1.Bundles{}).DoAndReturn( func(ctx context.Context, name, namespace string, obj runtime.Object) error { o := obj.(*releasev1.Bundles) o.ObjectMeta = tt.bundles.ObjectMeta o.Spec = tt.bundles.Spec return nil }, ) } func (tt *buildSpecTest) expectGetEksd() { tt.client.EXPECT().Get(tt.ctx, "eksd-123", "eksa-system", &eksdv1.Release{}).DoAndReturn( func(ctx context.Context, name, namespace string, obj runtime.Object) error { o := obj.(*eksdv1.Release) o.ObjectMeta = tt.eksdRelease.ObjectMeta o.Status = tt.eksdRelease.Status return nil }, ) } func TestBuildSpec(t *testing.T) { tt := newBuildSpecTest(t) tt.expectGetBundles() tt.expectGetEksd() wantSpec := &cluster.Spec{ Config: &cluster.Config{ Cluster: tt.cluster, OIDCConfigs: map[string]*anywherev1.OIDCConfig{}, AWSIAMConfigs: map[string]*anywherev1.AWSIamConfig{}, }, VersionsBundle: &cluster.VersionsBundle{ VersionsBundle: &tt.bundles.Spec.VersionsBundles[0], KubeDistro: tt.kubeDistro, }, Bundles: tt.bundles, } spec, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).NotTo(HaveOccurred()) tt.Expect(spec.Config).To(Equal(wantSpec.Config)) tt.Expect(spec.AWSIamConfig).To(Equal(wantSpec.AWSIamConfig)) tt.Expect(spec.OIDCConfig).To(Equal(wantSpec.OIDCConfig)) tt.Expect(spec.Bundles).To(Equal(wantSpec.Bundles)) tt.Expect(spec.VersionsBundle).To(Equal(wantSpec.VersionsBundle)) } func TestBuildSpecGetBundlesError(t *testing.T) { tt := newBuildSpecTest(t) tt.client.EXPECT().Get(tt.ctx, "bundles-1", "my-namespace", &releasev1.Bundles{}).Return(errors.New("client error")) _, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("client error"))) } func TestBuildSpecGetEksdError(t *testing.T) { tt := newBuildSpecTest(t) tt.expectGetBundles() tt.client.EXPECT().Get(tt.ctx, "eksd-123", "eksa-system", &eksdv1.Release{}).Return(errors.New("client error")) _, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("client error"))) } func TestBuildSpecBuildConfigError(t *testing.T) { tt := newBuildSpecTest(t) tt.cluster.Namespace = "default" tt.cluster.Spec.GitOpsRef = &anywherev1.Ref{ Name: "my-flux", Kind: anywherev1.FluxConfigKind, } tt.client.EXPECT().Get(tt.ctx, "my-flux", "default", &anywherev1.FluxConfig{}).Return(errors.New("client error")) _, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("client error"))) } func TestBuildSpecUnsupportedKubernetesVersionError(t *testing.T) { tt := newBuildSpecTest(t) tt.bundles.Spec.VersionsBundles = []releasev1.VersionsBundle{} tt.bundles.Spec.Number = 2 tt.expectGetBundles() _, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("kubernetes version 1.23 is not supported by bundles manifest 2"))) } func TestBuildSpecInitError(t *testing.T) { tt := newBuildSpecTest(t) tt.eksdRelease.Status.Components = []eksdv1.Component{} tt.expectGetBundles() tt.expectGetEksd() _, err := cluster.BuildSpec(tt.ctx, tt.client, tt.cluster) tt.Expect(err).To(MatchError(ContainSubstring("is no present in eksd release"))) } func wantKubeDistroForEksdRelease() (*eksdv1.Release, *cluster.KubeDistro) { eksdRelease := &eksdv1.Release{ ObjectMeta: metav1.ObjectMeta{ Name: "eksd-123", }, Status: eksdv1.ReleaseStatus{ Components: []eksdv1.Component{ { Name: "etcd", GitTag: "v3.4.14", }, { Name: "comp-1", Assets: []eksdv1.Asset{ { Name: "external-provisioner-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/external-provisioner:v2.1.1", }, }, { Name: "node-driver-registrar-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/node-driver-registrar:v2.1.0", }, }, { Name: "livenessprobe-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/livenessprobe:v2.2.0", }, }, { Name: "external-attacher-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/external-attacher:v3.1.0", }, }, { Name: "pause-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes/pause:v1.19.8", }, }, { Name: "coredns-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/coredns/coredns:v1.8.0", }, }, { Name: "etcd-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/etcd-io/etcd:v3.4.14", }, }, { Name: "aws-iam-authenticator-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes-sigs/aws-iam-authenticator:v0.5.2", }, }, { Name: "kube-apiserver-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes/kube-apiserver:v1.19.8", }, }, { Name: "kube-proxy-image", Image: &eksdv1.AssetImage{ URI: "public.ecr.aws/eks-distro/kubernetes/kube-proxy:v1.19.8", }, }, }, }, }, }, } kubeDistro := &cluster.KubeDistro{ Kubernetes: cluster.VersionedRepository{ Repository: "public.ecr.aws/eks-distro/kubernetes", Tag: "v1.19.8", }, CoreDNS: cluster.VersionedRepository{ Repository: "public.ecr.aws/eks-distro/coredns", Tag: "v1.8.0", }, Etcd: cluster.VersionedRepository{ Repository: "public.ecr.aws/eks-distro/etcd-io", Tag: "v3.4.14", }, NodeDriverRegistrar: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/node-driver-registrar:v2.1.0", }, LivenessProbe: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/livenessprobe:v2.2.0", }, ExternalAttacher: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/external-attacher:v3.1.0", }, ExternalProvisioner: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-csi/external-provisioner:v2.1.1", }, Pause: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes/pause:v1.19.8", }, EtcdImage: releasev1.Image{ URI: "public.ecr.aws/eks-distro/etcd-io/etcd:v3.4.14", }, AwsIamAuthImage: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes-sigs/aws-iam-authenticator:v0.5.2", }, KubeProxy: releasev1.Image{ URI: "public.ecr.aws/eks-distro/kubernetes/kube-proxy:v1.19.8", }, EtcdVersion: "3.4.14", } return eksdRelease, kubeDistro }
548