diff --git a/.golangci.yml b/.golangci.yml index f030c47aed..02a98c8bd2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,45 @@ +linters: + disable-all: true + enable: + - asciicheck + - bodyclose + - deadcode + - depguard + - dogsled + - errcheck + - exportloopref + - goconst + - gocritic + - gocyclo + - godot + - gofmt + - goheader + - goimports + - goprintffuncname + - gosec + - gosimple + - govet + - ifshort + - importas + - ineffassign + - maligned + - misspell + - nakedret + - nilerr + - noctx + - nolintlint + - prealloc + - revive + - rowserrcheck + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + - unparam + - varcheck + - whitespace + linters-settings: # Restrict revive to exported. revive: @@ -7,48 +49,43 @@ linters-settings: rules: - name: exported severity: warning -linters: - disable-all: true - enable: - - asciicheck - - bodyclose - - deadcode - - depguard - - dogsled - - goconst - - gocyclo - - gofmt - - goheader - - goimports - - goprintffuncname - - gosimple - - govet - - ineffassign - - maligned - - misspell - - nakedret - - noctx - - nolintlint - - rowserrcheck - - staticcheck - - structcheck - - typecheck - - unconvert - - unparam - - unused - - varcheck - - revive - # Run with --fast=false for more extensive checks - fast: true + ifshort: + # Maximum length of variable declaration measured in number of characters, after which linter won't suggest using short syntax. + max-decl-chars: 50 + importas: + no-unaliased: true + alias: + # Kubernetes + - pkg: k8s.io/api/core/v1 + alias: corev1 + - pkg: k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1 + alias: apiextensionsv1 + - pkg: k8s.io/apimachinery/pkg/apis/meta/v1 + alias: metav1 + - pkg: k8s.io/apimachinery/pkg/api/errors + alias: apierrors + - pkg: k8s.io/apimachinery/pkg/util/errors + alias: kerrors + # Controller Runtime + - pkg: sigs.k8s.io/controller-runtime + alias: ctrl + staticcheck: + go: "1.16" + stylecheck: + go: "1.16" issues: max-same-issues: 0 - max-per-linter: 0 - # List of regexps of issue texts to exclude, empty list by default. + max-issues-per-linter: 0 + # We are disabling default golangci exclusions because we want to help reviewers to focus on reviewing the most relevant + # changes in PRs and avoid nitpicking. exclude-use-default: false + # List of regexps of issue texts to exclude, empty list by default. exclude: - - "G108: Profiling endpoint is automatically exposed on /debug/pprof" - - "exported: exported method .*\\.(Reconcile|SetupWithManager|SetupWebhookWithManager) should have comment or be unexported" + - (Expect directory permissions to be 0750 or less|Expect file permissions to be 0600 or less) + - "exported: exported (const|function|method|type|var) (.+) should have comment or be unexported" - "exported: (func|type) name will be used as (.+) by other packages, and that stutters; consider calling this (.+)" + - (G104|G107|G404|G505|ST1000) + - "G108: Profiling endpoint is automatically exposed on /debug/pprof" # Exclude noctx error for calling http.Get directly. # See https://pkg.go.dev/github.com/sonatard/noctx#readme-how-to-fix for reasons it breaks and ways to fix it. # This exclusion should be removed if the decision is made to fix the error. @@ -67,11 +104,55 @@ issues: - revive text: exported (method|function|type|const) (.+) should have comment or be unexported path: .*test/(providers|framework|e2e).*.go + - linters: + - errcheck + text: Error return value is not checked + path: _test\.go + - linters: + - errcheck + text: Error return value of (.+) is not checked + path: _test\.go + - linters: + - gosec + text: "G108: Profiling endpoint is automatically exposed on /debug/pprof" + - linters: + - godot + text: "Comment should end in a period" + path: "(.*)/(v1alpha3|v1alpha4|v1alpha1)/(.*)types.go" + - linters: + - errcheck + text: Error return value of .((os\.)?std(out|err)\..*|.*Close|.*Flush|os\.Remove(All)?|.*print(f|ln)?|os\.(Un)?Setenv). is not checked + # With Go 1.16, the new embed directive can be used with an un-named import, + # revive (previously, golint) only allows these to be imported in a main.go, which wouldn't work for us. + # This directive allows the embed package to be imported with an underscore everywhere. + - linters: + - revive + source: _ "embed" + # This directive allows the variable in defaults.go files to have underscore + - linters: + - revive + text: "var-naming: don't use underscores in Go names; func (.+) should be (.+)" + path: .*/defaults.go + # Disable unparam "always receives" which might not be really + # useful when building libraries. + - linters: + - unparam + text: always receives + - linters: + - unparam + text: (.+) - (`t`|`g`) is unused + - path: _test\.go + text: cyclomatic complexity + # Append should be able to assign to a different var/slice. + - linters: + - gocritic + text: "appendAssign: append result not assigned to the same slice" + run: timeout: 10m - tests: false skip-files: - - "zz_generated.*\\.go$" - # Skip autogenerated doc.go files - - "doc\\.go" - - "mock\\.go" + - "zz_generated.*\\.go$" + - ".*conversion.*\\.go$" + skip-dirs: + - third_party + allow-parallel-runners: true \ No newline at end of file diff --git a/api/v1alpha3/awscluster_types.go b/api/v1alpha3/awscluster_types.go index 989a7356b3..9e655271d3 100644 --- a/api/v1alpha3/awscluster_types.go +++ b/api/v1alpha3/awscluster_types.go @@ -26,7 +26,7 @@ const ( // removing it from the apiserver. ClusterFinalizer = "awscluster.infrastructure.cluster.x-k8s.io" - // AWSClusterControllerIdentityName is the name of the AWSClusterControllerIdentity singleton + // AWSClusterControllerIdentityName is the name of the AWSClusterControllerIdentity singleton. AWSClusterControllerIdentityName = "default" ) @@ -95,13 +95,13 @@ type AWSClusterSpec struct { type AWSIdentityKind string var ( - // ControllerIdentityKind defines identity reference kind as AWSClusterControllerIdentity + // ControllerIdentityKind defines identity reference kind as AWSClusterControllerIdentity. ControllerIdentityKind = AWSIdentityKind("AWSClusterControllerIdentity") - // ClusterRoleIdentityKind defines identity reference kind as AWSClusterRoleIdentity + // ClusterRoleIdentityKind defines identity reference kind as AWSClusterRoleIdentity. ClusterRoleIdentityKind = AWSIdentityKind("AWSClusterRoleIdentity") - // ClusterStaticIdentityKind defines identity reference kind as AWSClusterStaticIdentity + // ClusterStaticIdentityKind defines identity reference kind as AWSClusterStaticIdentity. ClusterStaticIdentityKind = AWSIdentityKind("AWSClusterStaticIdentity") ) @@ -144,7 +144,7 @@ type Bastion struct { AMI string `json:"ami,omitempty"` } -// AWSLoadBalancerSpec defines the desired state of an AWS load balancer +// AWSLoadBalancerSpec defines the desired state of an AWS load balancer. type AWSLoadBalancerSpec struct { // Scheme sets the scheme of the load balancer (defaults to Internet-facing) // +kubebuilder:default=Internet-facing @@ -167,7 +167,7 @@ type AWSLoadBalancerSpec struct { // +optional Subnets []string `json:"subnets,omitempty"` - // AdditionalSecurityGroups sets the security groups used by the load balancer. Expected to be security group IDs. + // AdditionalSecurityGroups sets the security groups used by the load balancer. Expected to be security group IDs // This is optional - if not provided new security groups will be created for the load balancer // +optional AdditionalSecurityGroups []string `json:"additionalSecurityGroups,omitempty"` @@ -203,7 +203,7 @@ type AWSCluster struct { // +kubebuilder:object:root=true -// AWSClusterList contains a list of AWSCluster +// AWSClusterList contains a list of AWSCluster. type AWSClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha3/awsidentity_types.go b/api/v1alpha3/awsidentity_types.go index 37a53036e3..168665db80 100644 --- a/api/v1alpha3/awsidentity_types.go +++ b/api/v1alpha3/awsidentity_types.go @@ -85,7 +85,7 @@ type AWSClusterStaticIdentity struct { // +kubebuilder:object:root=true -// AWSClusterStaticIdentityList contains a list of AWSClusterStaticIdentity +// AWSClusterStaticIdentityList contains a list of AWSClusterStaticIdentity. type AWSClusterStaticIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -118,7 +118,7 @@ type AWSClusterRoleIdentity struct { // +kubebuilder:object:root=true -// AWSClusterRoleIdentityList contains a list of AWSClusterRoleIdentity +// AWSClusterRoleIdentityList contains a list of AWSClusterRoleIdentity. type AWSClusterRoleIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -161,7 +161,7 @@ type AWSClusterControllerIdentity struct { // +kubebuilder:object:root=true -// AWSClusterControllerIdentityList contains a list of AWSClusterControllerIdentity +// AWSClusterControllerIdentityList contains a list of AWSClusterControllerIdentity. type AWSClusterControllerIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha3/awsmachine_types.go b/api/v1alpha3/awsmachine_types.go index fe356c53ee..004ee7e18c 100644 --- a/api/v1alpha3/awsmachine_types.go +++ b/api/v1alpha3/awsmachine_types.go @@ -32,10 +32,10 @@ const ( type SecretBackend string var ( - // SecretBackendSSMParameterStore defines AWS Systems Manager Parameter Store as the secret backend + // SecretBackendSSMParameterStore defines AWS Systems Manager Parameter Store as the secret backend. SecretBackendSSMParameterStore = SecretBackend("ssm-parameter-store") - // SecretBackendSecretsManager defines AWS Secrets Manager as the secret backend + // SecretBackendSecretsManager defines AWS Secrets Manager as the secret backend. SecretBackendSecretsManager = SecretBackend("secrets-manager") ) @@ -267,7 +267,7 @@ func (r *AWSMachine) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSMachineList contains a list of AWSMachine +// AWSMachineList contains a list of AWSMachine. type AWSMachineList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha3/awsmachinetemplate_types.go b/api/v1alpha3/awsmachinetemplate_types.go index 0da904fc39..97b6f255b1 100644 --- a/api/v1alpha3/awsmachinetemplate_types.go +++ b/api/v1alpha3/awsmachinetemplate_types.go @@ -38,7 +38,7 @@ type AWSMachineTemplate struct { // +kubebuilder:object:root=true -// AWSMachineTemplateList contains a list of AWSMachineTemplate +// AWSMachineTemplateList contains a list of AWSMachineTemplate. type AWSMachineTemplateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha3/conditions_consts.go b/api/v1alpha3/conditions_consts.go index b1215c069b..605c7aeca9 100644 --- a/api/v1alpha3/conditions_consts.go +++ b/api/v1alpha3/conditions_consts.go @@ -31,24 +31,24 @@ const ( // PrincipalUsageUnauthorizedReason used when AWSCluster namespace is not in the identity's allowed namespaces list. PrincipalUsageUnauthorizedReason = "PrincipalUsageUnauthorized" // SourcePrincipalUsageUnauthorizedReason used when AWSCluster is not in the intersection of source identity allowed namespaces - // and allowed namespaces of the identities that source identity depends to + // and allowed namespaces of the identities that source identity depends to. SourcePrincipalUsageUnauthorizedReason = "SourcePrincipalUsageUnauthorized" ) const ( - // VpcReadyCondition reports on the successful reconciliation of a VPC + // VpcReadyCondition reports on the successful reconciliation of a VPC. VpcReadyCondition clusterv1.ConditionType = "VpcReady" // VpcCreationStartedReason used when attempting to create a VPC for a managed cluster. // Will not be applied to unmanaged clusters. VpcCreationStartedReason = "VpcCreationStarted" - // VpcReconciliationFailedReason used when errors occur during VPC reconciliation + // VpcReconciliationFailedReason used when errors occur during VPC reconciliation. VpcReconciliationFailedReason = "VpcReconciliationFailed" ) const ( // SubnetsReadyCondition reports on the successful reconciliation of subnets. SubnetsReadyCondition clusterv1.ConditionType = "SubnetsReady" - // SubnetsReconciliationFailedReason used to report failures while reconciling subnets + // SubnetsReconciliationFailedReason used to report failures while reconciling subnets. SubnetsReconciliationFailedReason = "SubnetsReconciliationFailed" ) @@ -56,7 +56,7 @@ const ( // InternetGatewayReadyCondition reports on the successful reconciliation of internet gateways. // Only applicable to managed clusters. InternetGatewayReadyCondition clusterv1.ConditionType = "InternetGatewayReady" - // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation + // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation. InternetGatewayFailedReason = "InternetGatewayFailed" ) @@ -95,22 +95,22 @@ const ( const ( // BastionHostReadyCondition reports whether a bastion host is ready. Depending on the configuration, a cluster - // may not require a bastion host and this condition will be skipped + // may not require a bastion host and this condition will be skipped. BastionHostReadyCondition clusterv1.ConditionType = "BastionHostReady" - // BastionCreationStartedReason used when creating a new bastion host + // BastionCreationStartedReason used when creating a new bastion host. BastionCreationStartedReason = "BastionCreationStarted" - // BastionHostFailedReason used when an error occurs during the creation of a bastion host + // BastionHostFailedReason used when an error occurs during the creation of a bastion host. BastionHostFailedReason = "BastionHostFailed" ) const ( // LoadBalancerReadyCondition reports on whether a control plane load balancer was successfully reconciled. LoadBalancerReadyCondition clusterv1.ConditionType = "LoadBalancerReady" - // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated + // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated. WaitForDNSNameReason = "WaitForDNSName" - // WaitForDNSNameResolveReason used while waiting for DNS name to resolve + // WaitForDNSNameResolveReason used while waiting for DNS name to resolve. WaitForDNSNameResolveReason = "WaitForDNSNameResolve" - // LoadBalancerFailedReason used when an error occurs during load balancer reconciliation + // LoadBalancerFailedReason used when an error occurs during load balancer reconciliation. LoadBalancerFailedReason = "LoadBalancerFailed" ) @@ -140,7 +140,7 @@ const ( // SecurityGroupsReadyCondition indicates the security groups are up to date on the AWSMachine. SecurityGroupsReadyCondition clusterv1.ConditionType = "SecurityGroupsReady" - // SecurityGroupsFailedReason used when the security groups could not be synced + // SecurityGroupsFailedReason used when the security groups could not be synced. SecurityGroupsFailedReason = "SecurityGroupsSyncFailed" ) @@ -150,8 +150,8 @@ const ( // Note this is only applicable to control plane machines. ELBAttachedCondition clusterv1.ConditionType = "ELBAttached" - // ELBAttachFailedReason used when a control plane node fails to attach to the ELB + // ELBAttachFailedReason used when a control plane node fails to attach to the ELB. ELBAttachFailedReason = "ELBAttachFailed" - // ELBDetachFailedReason used when a control plane node fails to detach from an ELB + // ELBDetachFailedReason used when a control plane node fails to detach from an ELB. ELBDetachFailedReason = "ELBDetachFailed" ) diff --git a/api/v1alpha3/defaults.go b/api/v1alpha3/defaults.go index ec25a02404..2c6e539811 100644 --- a/api/v1alpha3/defaults.go +++ b/api/v1alpha3/defaults.go @@ -18,7 +18,7 @@ package v1alpha3 // TODO (richardcase): get this working with defaulter-gen -// SetDefaults_Bastion is used by defaulter-gen +// SetDefaults_Bastion is used by defaulter-gen. func SetDefaults_Bastion(obj *Bastion) { //nolint:golint,stylecheck // Default to allow open access to the bastion host if no CIDR Blocks have been set if len(obj.AllowedCIDRBlocks) == 0 && !obj.DisableIngressRules { @@ -26,7 +26,7 @@ func SetDefaults_Bastion(obj *Bastion) { //nolint:golint,stylecheck } } -// SetDefaults_NetworkSpec is used by defaulter-gen +// SetDefaults_NetworkSpec is used by defaulter-gen. func SetDefaults_NetworkSpec(obj *NetworkSpec) { //nolint:golint,stylecheck // Default to Calico ingress rules if no rules have been set if obj.CNI == nil { diff --git a/api/v1alpha3/doc.go b/api/v1alpha3/doc.go index 4a1d8dcebc..8c6221959c 100644 --- a/api/v1alpha3/doc.go +++ b/api/v1alpha3/doc.go @@ -15,4 +15,5 @@ limitations under the License. */ // +k8s:conversion-gen=sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4 + package v1alpha3 diff --git a/api/v1alpha3/groupversion_info.go b/api/v1alpha3/groupversion_info.go index 5a60237421..a047bf3581 100644 --- a/api/v1alpha3/groupversion_info.go +++ b/api/v1alpha3/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1alpha3"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/api/v1alpha3/tags.go b/api/v1alpha3/tags.go index 192eb242be..5739616750 100644 --- a/api/v1alpha3/tags.go +++ b/api/v1alpha3/tags.go @@ -44,7 +44,7 @@ func (t Tags) HasAWSCloudProviderOwned(cluster string) bool { return ok && ResourceLifecycle(value) == ResourceLifecycleOwned } -// GetRole returns the Cluster API role for the tagged resource +// GetRole returns the Cluster API role for the tagged resource. func (t Tags) GetRole() string { return t[NameAWSClusterAPIRole] } @@ -71,7 +71,7 @@ func (t Tags) Merge(other Tags) { } } -// ResourceLifecycle configures the lifecycle of a resource +// ResourceLifecycle configures the lifecycle of a resource. type ResourceLifecycle string const ( @@ -90,17 +90,17 @@ const ( // to be permissive about state changes. // logically independent clusters running in the same AZ. // The tag key = NameKubernetesAWSCloudProviderPrefix + clusterID - // The tag value is an ownership value + // The tag value is an ownership value. NameKubernetesAWSCloudProviderPrefix = "kubernetes.io/cluster/" // NameAWSProviderPrefix is the tag prefix we use to differentiate // cluster-api-provider-aws owned components from other tooling that - // uses NameKubernetesClusterPrefix + // uses NameKubernetesClusterPrefix. NameAWSProviderPrefix = "sigs.k8s.io/cluster-api-provider-aws/" // NameAWSProviderOwned is the tag name we use to differentiate // cluster-api-provider-aws owned components from other tooling that - // uses NameKubernetesClusterPrefix + // uses NameKubernetesClusterPrefix. NameAWSProviderOwned = NameAWSProviderPrefix + "cluster/" // NameAWSClusterAPIRole is the tag name we use to mark roles for resources @@ -113,22 +113,22 @@ const ( // SecondarySubnetTagValue describes the value for the secondary subnet. SecondarySubnetTagValue = "secondary" - // APIServerRoleTagValue describes the value for the apiserver role + // APIServerRoleTagValue describes the value for the apiserver role. APIServerRoleTagValue = "apiserver" - // BastionRoleTagValue describes the value for the bastion role + // BastionRoleTagValue describes the value for the bastion role. BastionRoleTagValue = "bastion" - // CommonRoleTagValue describes the value for the common role + // CommonRoleTagValue describes the value for the common role. CommonRoleTagValue = "common" - // PublicRoleTagValue describes the value for the public role + // PublicRoleTagValue describes the value for the public role. PublicRoleTagValue = "public" - // PrivateRoleTagValue describes the value for the private role + // PrivateRoleTagValue describes the value for the private role. PrivateRoleTagValue = "private" - // MachineNameTagKey is the key for machine name + // MachineNameTagKey is the key for machine name. MachineNameTagKey = "MachineName" ) @@ -167,14 +167,14 @@ type BuildParams struct { } // WithMachineName tags the namespaced machine name -// The machine name will be tagged with key "MachineName" +// The machine name will be tagged with key "MachineName". func (b BuildParams) WithMachineName(m *clusterv1.Machine) BuildParams { machineNamespacedName := types.NamespacedName{Namespace: m.Namespace, Name: m.Name} b.Additional[MachineNameTagKey] = machineNamespacedName.String() return b } -// WithCloudProvider tags the cluster ownership for a resource +// WithCloudProvider tags the cluster ownership for a resource. func (b BuildParams) WithCloudProvider(name string) BuildParams { b.Additional[ClusterAWSCloudProviderTagKey(name)] = string(ResourceLifecycleOwned) return b diff --git a/api/v1alpha3/types.go b/api/v1alpha3/types.go index 275217d7c0..506955c60c 100644 --- a/api/v1alpha3/types.go +++ b/api/v1alpha3/types.go @@ -64,10 +64,10 @@ type Filter struct { Values []string `json:"values"` } -// AWSMachineProviderConditionType is a valid value for AWSMachineProviderCondition.Type +// AWSMachineProviderConditionType is a valid value for AWSMachineProviderCondition.Type. type AWSMachineProviderConditionType string -// Valid conditions for an AWS machine instance +// Valid conditions for an AWS machine instance. const ( // MachineCreated indicates whether the machine has been created or not. If not, // it should include a reason and message for the failure. @@ -88,7 +88,7 @@ type ClassicELBScheme string var ( // ClassicELBSchemeInternetFacing defines an internet-facing, publicly - // accessible AWS Classic ELB scheme + // accessible AWS Classic ELB scheme. ClassicELBSchemeInternetFacing = ClassicELBScheme("Internet-facing") // ClassicELBSchemeInternal defines an internal-only facing @@ -100,16 +100,16 @@ var ( type ClassicELBProtocol string var ( - // ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol + // ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol. ClassicELBProtocolTCP = ClassicELBProtocol("TCP") - // ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol + // ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol. ClassicELBProtocolSSL = ClassicELBProtocol("SSL") - // ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7 + // ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7. ClassicELBProtocolHTTP = ClassicELBProtocol("HTTP") - // ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7 + // ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7. ClassicELBProtocolHTTPS = ClassicELBProtocol("HTTPS") ) @@ -179,10 +179,10 @@ type ClassicELBHealthCheck struct { type AZSelectionScheme string var ( - // AZSelectionSchemeOrdered will select AZs based on alphabetical order + // AZSelectionSchemeOrdered will select AZs based on alphabetical order. AZSelectionSchemeOrdered = AZSelectionScheme("Ordered") - // AZSelectionSchemeRandom will select AZs randomly + // AZSelectionSchemeRandom will select AZs randomly. AZSelectionSchemeRandom = AZSelectionScheme("Random") ) @@ -300,7 +300,7 @@ func (s Subnets) ToMap() map[string]*SubnetSpec { return res } -// IDs returns a slice of the subnet ids +// IDs returns a slice of the subnet ids. func (s Subnets) IDs() []string { res := []string{} for _, subnet := range s { @@ -362,7 +362,7 @@ func (s Subnets) FilterByZone(zone string) (res Subnets) { return } -// GetUniqueZones returns a slice containing the unique zones of the subnets +// GetUniqueZones returns a slice containing the unique zones of the subnets. func (s Subnets) GetUniqueZones() []string { keys := make(map[string]bool) zones := []string{} @@ -375,14 +375,14 @@ func (s Subnets) GetUniqueZones() []string { return zones } -// CNISpec defines configuration for CNI +// CNISpec defines configuration for CNI. type CNISpec struct { // CNIIngressRules specify rules to apply to control plane and worker node security groups. // The source for the rule will be set to control plane and worker security group IDs. CNIIngressRules CNIIngressRules `json:"cniIngressRules,omitempty"` } -// CNIIngressRules is a slice of CNIIngressRule +// CNIIngressRules is a slice of CNIIngressRule. type CNIIngressRules []*CNIIngressRule // CNIIngressRule defines an AWS ingress rule for CNI requirements. @@ -402,22 +402,22 @@ type RouteTable struct { type SecurityGroupRole string var ( - // SecurityGroupBastion defines an SSH bastion role + // SecurityGroupBastion defines an SSH bastion role. SecurityGroupBastion = SecurityGroupRole("bastion") - // SecurityGroupNode defines a Kubernetes workload node role + // SecurityGroupNode defines a Kubernetes workload node role. SecurityGroupNode = SecurityGroupRole("node") - // SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes + // SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes. SecurityGroupEKSNodeAdditional = SecurityGroupRole("node-eks-additional") - // SecurityGroupControlPlane defines a Kubernetes control plane node role + // SecurityGroupControlPlane defines a Kubernetes control plane node role. SecurityGroupControlPlane = SecurityGroupRole("controlplane") - // SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role + // SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role. SecurityGroupAPIServerLB = SecurityGroupRole("apiserver-lb") - // SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules + // SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules. SecurityGroupLB = SecurityGroupRole("lb") ) @@ -446,22 +446,22 @@ func (s *SecurityGroup) String() string { type SecurityGroupProtocol string var ( - // SecurityGroupProtocolAll is a wildcard for all IP protocols + // SecurityGroupProtocolAll is a wildcard for all IP protocols. SecurityGroupProtocolAll = SecurityGroupProtocol("-1") - // SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules + // SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules. SecurityGroupProtocolIPinIP = SecurityGroupProtocol("4") - // SecurityGroupProtocolTCP represents the TCP protocol in ingress rules + // SecurityGroupProtocolTCP represents the TCP protocol in ingress rules. SecurityGroupProtocolTCP = SecurityGroupProtocol("tcp") - // SecurityGroupProtocolUDP represents the UDP protocol in ingress rules + // SecurityGroupProtocolUDP represents the UDP protocol in ingress rules. SecurityGroupProtocolUDP = SecurityGroupProtocol("udp") - // SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules + // SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules. SecurityGroupProtocolICMP = SecurityGroupProtocol("icmp") - // SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules + // SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules. SecurityGroupProtocolICMPv6 = SecurityGroupProtocol("58") ) @@ -508,7 +508,7 @@ func (i IngressRules) Difference(o IngressRules) (out IngressRules) { return } -// Equals returns true if two IngressRule are equal +// Equals returns true if two IngressRule are equal. func (i *IngressRule) Equals(o *IngressRule) bool { if len(i.CidrBlocks) != len(o.CidrBlocks) { return false @@ -560,35 +560,35 @@ func (i *IngressRule) Equals(o *IngressRule) bool { type InstanceState string var ( - // InstanceStatePending is the string representing an instance in a pending state + // InstanceStatePending is the string representing an instance in a pending state. InstanceStatePending = InstanceState("pending") - // InstanceStateRunning is the string representing an instance in a running state + // InstanceStateRunning is the string representing an instance in a running state. InstanceStateRunning = InstanceState("running") - // InstanceStateShuttingDown is the string representing an instance shutting down + // InstanceStateShuttingDown is the string representing an instance shutting down. InstanceStateShuttingDown = InstanceState("shutting-down") - // InstanceStateTerminated is the string representing an instance that has been terminated + // InstanceStateTerminated is the string representing an instance that has been terminated. InstanceStateTerminated = InstanceState("terminated") // InstanceStateStopping is the string representing an instance - // that is in the process of being stopped and can be restarted + // that is in the process of being stopped and can be restarted. InstanceStateStopping = InstanceState("stopping") // InstanceStateStopped is the string representing an instance - // that has been stopped and can be restarted + // that has been stopped and can be restarted. InstanceStateStopped = InstanceState("stopped") // InstanceRunningStates defines the set of states in which an EC2 instance is - // running or going to be running soon + // running or going to be running soon. InstanceRunningStates = sets.NewString( string(InstanceStatePending), string(InstanceStateRunning), ) // InstanceOperationalStates defines the set of states in which an EC2 instance is - // or can return to running, and supports all EC2 operations + // or can return to running, and supports all EC2 operations. InstanceOperationalStates = InstanceRunningStates.Union( sets.NewString( string(InstanceStateStopping), @@ -596,7 +596,7 @@ var ( ), ) - // InstanceKnownStates represents all known EC2 instance states + // InstanceKnownStates represents all known EC2 instance states. InstanceKnownStates = InstanceOperationalStates.Union( sets.NewString( string(InstanceStateShuttingDown), diff --git a/api/v1alpha3/validate.go b/api/v1alpha3/validate.go index 17866ee569..49a783a0ee 100644 --- a/api/v1alpha3/validate.go +++ b/api/v1alpha3/validate.go @@ -23,7 +23,7 @@ import ( "k8s.io/apimachinery/pkg/util/validation/field" ) -// Validate will validate the bastion fields +// Validate will validate the bastion fields. func (b *Bastion) Validate() []*field.Error { var errs field.ErrorList diff --git a/api/v1alpha3/webhook_suite_test.go b/api/v1alpha3/webhook_suite_test.go index 5e095ef110..41e24738d5 100644 --- a/api/v1alpha3/webhook_suite_test.go +++ b/api/v1alpha3/webhook_suite_test.go @@ -20,9 +20,10 @@ import ( "fmt" "os" "path" - infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" "testing" + infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -31,7 +32,6 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/test/helpers" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/envtest/printer" - "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" // +kubebuilder:scaffold:imports ) @@ -61,7 +61,7 @@ func TestMain(m *testing.M) { func setup() { utilruntime.Must(AddToScheme(scheme.Scheme)) - utilruntime.Must(v1alpha4.AddToScheme(scheme.Scheme)) + utilruntime.Must(infrav1.AddToScheme(scheme.Scheme)) testEnvConfig := helpers.NewTestEnvironmentConfiguration([]string{ path.Join("config", "crd", "bases"), diff --git a/api/v1alpha4/awscluster_types.go b/api/v1alpha4/awscluster_types.go index b5a78833f7..fce73a1ef5 100644 --- a/api/v1alpha4/awscluster_types.go +++ b/api/v1alpha4/awscluster_types.go @@ -26,7 +26,7 @@ const ( // removing it from the apiserver. ClusterFinalizer = "awscluster.infrastructure.cluster.x-k8s.io" - // AWSClusterControllerIdentityName is the name of the AWSClusterControllerIdentity singleton + // AWSClusterControllerIdentityName is the name of the AWSClusterControllerIdentity singleton. AWSClusterControllerIdentityName = "default" ) @@ -95,13 +95,13 @@ type AWSClusterSpec struct { type AWSIdentityKind string var ( - // ControllerIdentityKind defines identity reference kind as AWSClusterControllerIdentity + // ControllerIdentityKind defines identity reference kind as AWSClusterControllerIdentity. ControllerIdentityKind = AWSIdentityKind("AWSClusterControllerIdentity") - // ClusterRoleIdentityKind defines identity reference kind as AWSClusterRoleIdentity + // ClusterRoleIdentityKind defines identity reference kind as AWSClusterRoleIdentity. ClusterRoleIdentityKind = AWSIdentityKind("AWSClusterRoleIdentity") - // ClusterStaticIdentityKind defines identity reference kind as AWSClusterStaticIdentity + // ClusterStaticIdentityKind defines identity reference kind as AWSClusterStaticIdentity. ClusterStaticIdentityKind = AWSIdentityKind("AWSClusterStaticIdentity") ) @@ -144,7 +144,7 @@ type Bastion struct { AMI string `json:"ami,omitempty"` } -// AWSLoadBalancerSpec defines the desired state of an AWS load balancer +// AWSLoadBalancerSpec defines the desired state of an AWS load balancer. type AWSLoadBalancerSpec struct { // Scheme sets the scheme of the load balancer (defaults to Internet-facing) // +kubebuilder:default=Internet-facing @@ -167,7 +167,7 @@ type AWSLoadBalancerSpec struct { // +optional Subnets []string `json:"subnets,omitempty"` - // AdditionalSecurityGroups sets the security groups used by the load balancer. Expected to be security group IDs. + // AdditionalSecurityGroups sets the security groups used by the load balancer. Expected to be security group IDs // This is optional - if not provided new security groups will be created for the load balancer // +optional AdditionalSecurityGroups []string `json:"additionalSecurityGroups,omitempty"` @@ -204,7 +204,7 @@ type AWSCluster struct { // +kubebuilder:object:root=true -// AWSClusterList contains a list of AWSCluster +// AWSClusterList contains a list of AWSCluster. type AWSClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha4/awsclusterstaticidentity_webhook_test.go b/api/v1alpha4/awsclusterstaticidentity_webhook_test.go index d08c6bda1c..e7d64f1887 100644 --- a/api/v1alpha4/awsclusterstaticidentity_webhook_test.go +++ b/api/v1alpha4/awsclusterstaticidentity_webhook_test.go @@ -101,7 +101,7 @@ func TestAWSClusterStaticValidateUpdate(t *testing.T) { name: "do not allow any spec changes", identity: &AWSClusterStaticIdentity{ Spec: AWSClusterStaticIdentitySpec{ - SecretRef:"test", + SecretRef: "test", }, }, wantError: true, diff --git a/api/v1alpha4/awsiam_types.go b/api/v1alpha4/awsiam_types.go index 27f9630c33..0b0dfe01bd 100644 --- a/api/v1alpha4/awsiam_types.go +++ b/api/v1alpha4/awsiam_types.go @@ -73,7 +73,7 @@ const ( ) // PolicyDocument represents an AWS IAM policy document, and can be -// converted into JSON using "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/converters" +// converted into JSON using "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/converters". type PolicyDocument struct { Version string Statement Statements @@ -91,13 +91,13 @@ type StatementEntry struct { Condition Conditions `json:"Condition,omitempty"` } -// Statements is the list of StatementEntries +// Statements is the list of StatementEntries. type Statements []StatementEntry -// Principals is the map of all identities a statement entry refers to +// Principals is the map of all identities a statement entry refers to. type Principals map[PrincipalType]PrincipalID -// Actions is the list of actions +// Actions is the list of actions. type Actions []string // UnmarshalJSON is an Actions Unmarshaler. @@ -115,10 +115,10 @@ func (actions *Actions) UnmarshalJSON(data []byte) error { return nil } -// Resources is the list of resources +// Resources is the list of resources. type Resources []string -// PrincipalID represents the list of all identities, such as ARNs +// PrincipalID represents the list of all identities, such as ARNs. type PrincipalID []string // UnmarshalJSON defines an Unmarshaler for a PrincipalID. diff --git a/api/v1alpha4/awsidentity_types.go b/api/v1alpha4/awsidentity_types.go index 3bcfd6689a..ab57d70075 100644 --- a/api/v1alpha4/awsidentity_types.go +++ b/api/v1alpha4/awsidentity_types.go @@ -85,7 +85,7 @@ type AWSClusterStaticIdentity struct { // +kubebuilder:object:root=true -// AWSClusterStaticIdentityList contains a list of AWSClusterStaticIdentity +// AWSClusterStaticIdentityList contains a list of AWSClusterStaticIdentity. type AWSClusterStaticIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -119,7 +119,7 @@ type AWSClusterRoleIdentity struct { // +kubebuilder:object:root=true -// AWSClusterRoleIdentityList contains a list of AWSClusterRoleIdentity +// AWSClusterRoleIdentityList contains a list of AWSClusterRoleIdentity. type AWSClusterRoleIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -163,7 +163,7 @@ type AWSClusterControllerIdentity struct { // +kubebuilder:object:root=true -// AWSClusterControllerIdentityList contains a list of AWSClusterControllerIdentity +// AWSClusterControllerIdentityList contains a list of AWSClusterControllerIdentity. type AWSClusterControllerIdentityList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha4/awsmachine_types.go b/api/v1alpha4/awsmachine_types.go index d90f403f0f..97e5bab257 100644 --- a/api/v1alpha4/awsmachine_types.go +++ b/api/v1alpha4/awsmachine_types.go @@ -32,10 +32,10 @@ const ( type SecretBackend string var ( - // SecretBackendSSMParameterStore defines AWS Systems Manager Parameter Store as the secret backend + // SecretBackendSSMParameterStore defines AWS Systems Manager Parameter Store as the secret backend. SecretBackendSSMParameterStore = SecretBackend("ssm-parameter-store") - // SecretBackendSecretsManager defines AWS Secrets Manager as the secret backend + // SecretBackendSecretsManager defines AWS Secrets Manager as the secret backend. SecretBackendSecretsManager = SecretBackend("secrets-manager") ) @@ -268,7 +268,7 @@ func (r *AWSMachine) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSMachineList contains a list of AWSMachine +// AWSMachineList contains a list of AWSMachine. type AWSMachineList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha4/awsmachine_webhook.go b/api/v1alpha4/awsmachine_webhook.go index 13a84d423d..66e89a1f0c 100644 --- a/api/v1alpha4/awsmachine_webhook.go +++ b/api/v1alpha4/awsmachine_webhook.go @@ -45,7 +45,7 @@ var ( _ webhook.Defaulter = &AWSMachine{} ) -// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachine) ValidateCreate() error { var allErrs field.ErrorList @@ -58,7 +58,7 @@ func (r *AWSMachine) ValidateCreate() error { return aggregateObjErrors(r.GroupVersionKind().GroupKind(), r.Name, allErrs) } -// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachine) ValidateUpdate(old runtime.Object) error { newAWSMachine, err := runtime.DefaultUnstructuredConverter.ToUnstructured(r) if err != nil { @@ -176,13 +176,13 @@ func (r *AWSMachine) validateNonRootVolumes() field.ErrorList { return allErrs } -// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachine) ValidateDelete() error { return nil } // Default implements webhook.Defaulter such that an empty CloudInit will be defined with a default -// SecureSecretsBackend as SecretBackendSecretsManager iff InsecureSkipSecretsManager is unset +// SecureSecretsBackend as SecretBackendSecretsManager iff InsecureSkipSecretsManager is unset. func (r *AWSMachine) Default() { if !r.Spec.CloudInit.InsecureSkipSecretsManager && r.Spec.CloudInit.SecureSecretsBackend == "" { r.Spec.CloudInit.SecureSecretsBackend = SecretBackendSecretsManager diff --git a/api/v1alpha4/awsmachinetemplate_types.go b/api/v1alpha4/awsmachinetemplate_types.go index 9edd50efbc..9de9b7da64 100644 --- a/api/v1alpha4/awsmachinetemplate_types.go +++ b/api/v1alpha4/awsmachinetemplate_types.go @@ -39,7 +39,7 @@ type AWSMachineTemplate struct { // +kubebuilder:object:root=true -// AWSMachineTemplateList contains a list of AWSMachineTemplate +// AWSMachineTemplateList contains a list of AWSMachineTemplate. type AWSMachineTemplateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/api/v1alpha4/awsmachinetemplate_webhook.go b/api/v1alpha4/awsmachinetemplate_webhook.go index 979107cb04..8d0014e1de 100644 --- a/api/v1alpha4/awsmachinetemplate_webhook.go +++ b/api/v1alpha4/awsmachinetemplate_webhook.go @@ -38,7 +38,7 @@ var ( _ webhook.Validator = &AWSMachineTemplate{} ) -// ValidateCreate implements webhook.Validator so a webhook will be registered for the type +// ValidateCreate implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachineTemplate) ValidateCreate() error { var allErrs field.ErrorList spec := r.Spec.Template.Spec @@ -58,7 +58,7 @@ func (r *AWSMachineTemplate) ValidateCreate() error { return aggregateObjErrors(r.GroupVersionKind().GroupKind(), r.Name, allErrs) } -// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type +// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachineTemplate) ValidateUpdate(old runtime.Object) error { oldAWSMachineTemplate := old.(*AWSMachineTemplate) @@ -68,14 +68,13 @@ func (r *AWSMachineTemplate) ValidateUpdate(old runtime.Object) error { } if !reflect.DeepEqual(r.Spec, oldAWSMachineTemplate.Spec) { - return apierrors.NewBadRequest("AWSMachineTemplate.Spec is immutable") } return nil } -// ValidateDelete implements webhook.Validator so a webhook will be registered for the type +// ValidateDelete implements webhook.Validator so a webhook will be registered for the type. func (r *AWSMachineTemplate) ValidateDelete() error { return nil } diff --git a/api/v1alpha4/awsmachinetemplate_webhook_test.go b/api/v1alpha4/awsmachinetemplate_webhook_test.go index f47f8720cc..dc6ca6d0e2 100644 --- a/api/v1alpha4/awsmachinetemplate_webhook_test.go +++ b/api/v1alpha4/awsmachinetemplate_webhook_test.go @@ -117,7 +117,6 @@ func TestAWSMachineTemplateValidateUpdate(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ctx := context.TODO() template := &AWSMachineTemplate{ ObjectMeta: metav1.ObjectMeta{ diff --git a/api/v1alpha4/conditions_consts.go b/api/v1alpha4/conditions_consts.go index cb9cba1598..6cf83d4f72 100644 --- a/api/v1alpha4/conditions_consts.go +++ b/api/v1alpha4/conditions_consts.go @@ -31,24 +31,24 @@ const ( // PrincipalUsageUnauthorizedReason used when AWSCluster namespace is not in the identity's allowed namespaces list. PrincipalUsageUnauthorizedReason = "PrincipalUsageUnauthorized" // SourcePrincipalUsageUnauthorizedReason used when AWSCluster is not in the intersection of source identity allowed namespaces - // and allowed namespaces of the identities that source identity depends to + // and allowed namespaces of the identities that source identity depends to. SourcePrincipalUsageUnauthorizedReason = "SourcePrincipalUsageUnauthorized" ) const ( - // VpcReadyCondition reports on the successful reconciliation of a VPC + // VpcReadyCondition reports on the successful reconciliation of a VPC. VpcReadyCondition clusterv1.ConditionType = "VpcReady" // VpcCreationStartedReason used when attempting to create a VPC for a managed cluster. // Will not be applied to unmanaged clusters. VpcCreationStartedReason = "VpcCreationStarted" - // VpcReconciliationFailedReason used when errors occur during VPC reconciliation + // VpcReconciliationFailedReason used when errors occur during VPC reconciliation. VpcReconciliationFailedReason = "VpcReconciliationFailed" ) const ( // SubnetsReadyCondition reports on the successful reconciliation of subnets. SubnetsReadyCondition clusterv1.ConditionType = "SubnetsReady" - // SubnetsReconciliationFailedReason used to report failures while reconciling subnets + // SubnetsReconciliationFailedReason used to report failures while reconciling subnets. SubnetsReconciliationFailedReason = "SubnetsReconciliationFailed" ) @@ -56,7 +56,7 @@ const ( // InternetGatewayReadyCondition reports on the successful reconciliation of internet gateways. // Only applicable to managed clusters. InternetGatewayReadyCondition clusterv1.ConditionType = "InternetGatewayReady" - // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation + // InternetGatewayFailedReason used when errors occur during internet gateway reconciliation. InternetGatewayFailedReason = "InternetGatewayFailed" ) @@ -95,22 +95,22 @@ const ( const ( // BastionHostReadyCondition reports whether a bastion host is ready. Depending on the configuration, a cluster - // may not require a bastion host and this condition will be skipped + // may not require a bastion host and this condition will be skipped. BastionHostReadyCondition clusterv1.ConditionType = "BastionHostReady" - // BastionCreationStartedReason used when creating a new bastion host + // BastionCreationStartedReason used when creating a new bastion host. BastionCreationStartedReason = "BastionCreationStarted" - // BastionHostFailedReason used when an error occurs during the creation of a bastion host + // BastionHostFailedReason used when an error occurs during the creation of a bastion host. BastionHostFailedReason = "BastionHostFailed" ) const ( // LoadBalancerReadyCondition reports on whether a control plane load balancer was successfully reconciled. LoadBalancerReadyCondition clusterv1.ConditionType = "LoadBalancerReady" - // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated + // WaitForDNSNameReason used while waiting for a DNS name for the API server to be populated. WaitForDNSNameReason = "WaitForDNSName" - // WaitForDNSNameResolveReason used while waiting for DNS name to resolve + // WaitForDNSNameResolveReason used while waiting for DNS name to resolve. WaitForDNSNameResolveReason = "WaitForDNSNameResolve" - // LoadBalancerFailedReason used when an error occurs during load balancer reconciliation + // LoadBalancerFailedReason used when an error occurs during load balancer reconciliation. LoadBalancerFailedReason = "LoadBalancerFailed" ) @@ -140,7 +140,7 @@ const ( // SecurityGroupsReadyCondition indicates the security groups are up to date on the AWSMachine. SecurityGroupsReadyCondition clusterv1.ConditionType = "SecurityGroupsReady" - // SecurityGroupsFailedReason used when the security groups could not be synced + // SecurityGroupsFailedReason used when the security groups could not be synced. SecurityGroupsFailedReason = "SecurityGroupsSyncFailed" ) @@ -148,10 +148,11 @@ const ( // ELBAttachedCondition will report true when a control plane is successfully registered with an ELB. // When set to false, severity can be an Error if the subnet is not found or unavailable in the instance's AZ. // Note this is only applicable to control plane machines. + // Only applicable to control plane machines. ELBAttachedCondition clusterv1.ConditionType = "ELBAttached" - // ELBAttachFailedReason used when a control plane node fails to attach to the ELB + // ELBAttachFailedReason used when a control plane node fails to attach to the ELB. ELBAttachFailedReason = "ELBAttachFailed" - // ELBDetachFailedReason used when a control plane node fails to detach from an ELB + // ELBDetachFailedReason used when a control plane node fails to detach from an ELB. ELBDetachFailedReason = "ELBDetachFailed" ) diff --git a/api/v1alpha4/defaults.go b/api/v1alpha4/defaults.go index 08110b21f2..0dd555d13e 100644 --- a/api/v1alpha4/defaults.go +++ b/api/v1alpha4/defaults.go @@ -18,7 +18,7 @@ package v1alpha4 // TODO (richardcase): get this working with defaulter-gen -// SetDefaults_Bastion is used by defaulter-gen +// SetDefaults_Bastion is used by defaulter-gen. func SetDefaults_Bastion(obj *Bastion) { //nolint:golint,stylecheck // Default to allow open access to the bastion host if no CIDR Blocks have been set if len(obj.AllowedCIDRBlocks) == 0 && !obj.DisableIngressRules { @@ -26,7 +26,7 @@ func SetDefaults_Bastion(obj *Bastion) { //nolint:golint,stylecheck } } -// SetDefaults_NetworkSpec is used by defaulter-gen +// SetDefaults_NetworkSpec is used by defaulter-gen. func SetDefaults_NetworkSpec(obj *NetworkSpec) { //nolint:golint,stylecheck // Default to Calico ingress rules if no rules have been set if obj.CNI == nil { diff --git a/api/v1alpha4/doc.go b/api/v1alpha4/doc.go index 2abdf95598..0ab416e390 100644 --- a/api/v1alpha4/doc.go +++ b/api/v1alpha4/doc.go @@ -16,4 +16,5 @@ limitations under the License. // +gencrdrefdocs:force // +groupName=infrastructure.cluster.x-k8s.io + package v1alpha4 diff --git a/api/v1alpha4/groupversion_info.go b/api/v1alpha4/groupversion_info.go index c9ceb24ed6..7953553546 100644 --- a/api/v1alpha4/groupversion_info.go +++ b/api/v1alpha4/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/api/v1alpha4/sshkeyname_test.go b/api/v1alpha4/sshkeyname_test.go index d92c8bda9e..ea12ec66bd 100644 --- a/api/v1alpha4/sshkeyname_test.go +++ b/api/v1alpha4/sshkeyname_test.go @@ -18,9 +18,10 @@ package v1alpha4 import ( "context" - "sigs.k8s.io/controller-runtime/pkg/client" "testing" + "sigs.k8s.io/controller-runtime/pkg/client" + "github.com/aws/aws-sdk-go/aws" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/api/v1alpha4/suite_test.go b/api/v1alpha4/suite_test.go index b88323f76d..6c7e765ea3 100644 --- a/api/v1alpha4/suite_test.go +++ b/api/v1alpha4/suite_test.go @@ -18,10 +18,8 @@ package v1alpha4 import ( "fmt" - "math/rand" "os" "path" - "strconv" "testing" . "github.com/onsi/ginkgo" @@ -101,7 +99,3 @@ func teardown() { panic(fmt.Sprintf("Failed to stop envtest: %v", err)) } } - -func randomName() string { - return strconv.FormatInt(rand.Int63(), 10) -} diff --git a/api/v1alpha4/tags.go b/api/v1alpha4/tags.go index 4676e7b85d..6733897232 100644 --- a/api/v1alpha4/tags.go +++ b/api/v1alpha4/tags.go @@ -44,7 +44,7 @@ func (t Tags) HasAWSCloudProviderOwned(cluster string) bool { return ok && ResourceLifecycle(value) == ResourceLifecycleOwned } -// GetRole returns the Cluster API role for the tagged resource +// GetRole returns the Cluster API role for the tagged resource. func (t Tags) GetRole() string { return t[NameAWSClusterAPIRole] } @@ -71,7 +71,7 @@ func (t Tags) Merge(other Tags) { } } -// ResourceLifecycle configures the lifecycle of a resource +// ResourceLifecycle configures the lifecycle of a resource. type ResourceLifecycle string const ( @@ -90,45 +90,46 @@ const ( // to be permissive about state changes. // logically independent clusters running in the same AZ. // The tag key = NameKubernetesAWSCloudProviderPrefix + clusterID - // The tag value is an ownership value + // The tag value is an ownership value. NameKubernetesAWSCloudProviderPrefix = "kubernetes.io/cluster/" // NameAWSProviderPrefix is the tag prefix we use to differentiate // cluster-api-provider-aws owned components from other tooling that - // uses NameKubernetesClusterPrefix + // uses NameKubernetesClusterPrefix. NameAWSProviderPrefix = "sigs.k8s.io/cluster-api-provider-aws/" // NameAWSProviderOwned is the tag name we use to differentiate // cluster-api-provider-aws owned components from other tooling that - // uses NameKubernetesClusterPrefix + // uses NameKubernetesClusterPrefix. NameAWSProviderOwned = NameAWSProviderPrefix + "cluster/" // NameAWSClusterAPIRole is the tag name we use to mark roles for resources // dedicated to this cluster api provider implementation. NameAWSClusterAPIRole = NameAWSProviderPrefix + "role" - // NameAWSSubnetAssociation is the tag name we use to mark subnet associations. + // NameAWSSubnetAssociation is the tag name we use to mark association for resources + // dedicated to this cluster api provider implementation. NameAWSSubnetAssociation = NameAWSProviderPrefix + "association" - // SecondarySubnetTagValue describes the value for the secondary subnet. + // SecondarySubnetTagValue is the secondary subnet tag constant value. SecondarySubnetTagValue = "secondary" - // APIServerRoleTagValue describes the value for the apiserver role + // APIServerRoleTagValue describes the value for the apiserver role. APIServerRoleTagValue = "apiserver" - // BastionRoleTagValue describes the value for the bastion role + // BastionRoleTagValue describes the value for the bastion role. BastionRoleTagValue = "bastion" - // CommonRoleTagValue describes the value for the common role + // CommonRoleTagValue describes the value for the common role. CommonRoleTagValue = "common" - // PublicRoleTagValue describes the value for the public role + // PublicRoleTagValue describes the value for the public role. PublicRoleTagValue = "public" - // PrivateRoleTagValue describes the value for the private role + // PrivateRoleTagValue describes the value for the private role. PrivateRoleTagValue = "private" - // MachineNameTagKey is the key for machine name + // MachineNameTagKey is the key for machine name. MachineNameTagKey = "MachineName" ) @@ -167,14 +168,14 @@ type BuildParams struct { } // WithMachineName tags the namespaced machine name -// The machine name will be tagged with key "MachineName" +// The machine name will be tagged with key "MachineName". func (b BuildParams) WithMachineName(m *clusterv1.Machine) BuildParams { machineNamespacedName := types.NamespacedName{Namespace: m.Namespace, Name: m.Name} b.Additional[MachineNameTagKey] = machineNamespacedName.String() return b } -// WithCloudProvider tags the cluster ownership for a resource +// WithCloudProvider tags the cluster ownership for a resource. func (b BuildParams) WithCloudProvider(name string) BuildParams { b.Additional[ClusterAWSCloudProviderTagKey(name)] = string(ResourceLifecycleOwned) return b diff --git a/api/v1alpha4/types.go b/api/v1alpha4/types.go index 812d56fea0..28e03b788a 100644 --- a/api/v1alpha4/types.go +++ b/api/v1alpha4/types.go @@ -64,10 +64,10 @@ type Filter struct { Values []string `json:"values"` } -// AWSMachineProviderConditionType is a valid value for AWSMachineProviderCondition.Type +// AWSMachineProviderConditionType is a valid value for AWSMachineProviderCondition.Type. type AWSMachineProviderConditionType string -// Valid conditions for an AWS machine instance +// Valid conditions for an AWS machine instance. const ( // MachineCreated indicates whether the machine has been created or not. If not, // it should include a reason and message for the failure. @@ -88,7 +88,7 @@ type ClassicELBScheme string var ( // ClassicELBSchemeInternetFacing defines an internet-facing, publicly - // accessible AWS Classic ELB scheme + // accessible AWS Classic ELB scheme. ClassicELBSchemeInternetFacing = ClassicELBScheme("Internet-facing") // ClassicELBSchemeInternal defines an internal-only facing @@ -100,16 +100,16 @@ var ( type ClassicELBProtocol string var ( - // ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol + // ClassicELBProtocolTCP defines the ELB API string representing the TCP protocol. ClassicELBProtocolTCP = ClassicELBProtocol("TCP") - // ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol + // ClassicELBProtocolSSL defines the ELB API string representing the TLS protocol. ClassicELBProtocolSSL = ClassicELBProtocol("SSL") - // ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7 + // ClassicELBProtocolHTTP defines the ELB API string representing the HTTP protocol at L7. ClassicELBProtocolHTTP = ClassicELBProtocol("HTTP") - // ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7 + // ClassicELBProtocolHTTPS defines the ELB API string representing the HTTP protocol at L7. ClassicELBProtocolHTTPS = ClassicELBProtocol("HTTPS") ) @@ -179,10 +179,10 @@ type ClassicELBHealthCheck struct { type AZSelectionScheme string var ( - // AZSelectionSchemeOrdered will select AZs based on alphabetical order + // AZSelectionSchemeOrdered will select AZs based on alphabetical order. AZSelectionSchemeOrdered = AZSelectionScheme("Ordered") - // AZSelectionSchemeRandom will select AZs randomly + // AZSelectionSchemeRandom will select AZs randomly. AZSelectionSchemeRandom = AZSelectionScheme("Random") ) @@ -300,7 +300,7 @@ func (s Subnets) ToMap() map[string]*SubnetSpec { return res } -// IDs returns a slice of the subnet ids +// IDs returns a slice of the subnet ids. func (s Subnets) IDs() []string { res := []string{} for _, subnet := range s { @@ -362,7 +362,7 @@ func (s Subnets) FilterByZone(zone string) (res Subnets) { return } -// GetUniqueZones returns a slice containing the unique zones of the subnets +// GetUniqueZones returns a slice containing the unique zones of the subnets. func (s Subnets) GetUniqueZones() []string { keys := make(map[string]bool) zones := []string{} @@ -375,14 +375,14 @@ func (s Subnets) GetUniqueZones() []string { return zones } -// CNISpec defines configuration for CNI +// CNISpec defines configuration for CNI. type CNISpec struct { // CNIIngressRules specify rules to apply to control plane and worker node security groups. // The source for the rule will be set to control plane and worker security group IDs. CNIIngressRules CNIIngressRules `json:"cniIngressRules,omitempty"` } -// CNIIngressRules is a slice of CNIIngressRule +// CNIIngressRules is a slice of CNIIngressRule. type CNIIngressRules []*CNIIngressRule // CNIIngressRule defines an AWS ingress rule for CNI requirements. @@ -402,22 +402,22 @@ type RouteTable struct { type SecurityGroupRole string var ( - // SecurityGroupBastion defines an SSH bastion role + // SecurityGroupBastion defines an SSH bastion role. SecurityGroupBastion = SecurityGroupRole("bastion") - // SecurityGroupNode defines a Kubernetes workload node role + // SecurityGroupNode defines a Kubernetes workload node role. SecurityGroupNode = SecurityGroupRole("node") - // SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes + // SecurityGroupEKSNodeAdditional defines an extra node group from eks nodes. SecurityGroupEKSNodeAdditional = SecurityGroupRole("node-eks-additional") - // SecurityGroupControlPlane defines a Kubernetes control plane node role + // SecurityGroupControlPlane defines a Kubernetes control plane node role. SecurityGroupControlPlane = SecurityGroupRole("controlplane") - // SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role + // SecurityGroupAPIServerLB defines a Kubernetes API Server Load Balancer role. SecurityGroupAPIServerLB = SecurityGroupRole("apiserver-lb") - // SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules + // SecurityGroupLB defines a container for the cloud provider to inject its load balancer ingress rules. SecurityGroupLB = SecurityGroupRole("lb") ) @@ -446,22 +446,22 @@ func (s *SecurityGroup) String() string { type SecurityGroupProtocol string var ( - // SecurityGroupProtocolAll is a wildcard for all IP protocols + // SecurityGroupProtocolAll is a wildcard for all IP protocols. SecurityGroupProtocolAll = SecurityGroupProtocol("-1") - // SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules + // SecurityGroupProtocolIPinIP represents the IP in IP protocol in ingress rules. SecurityGroupProtocolIPinIP = SecurityGroupProtocol("4") - // SecurityGroupProtocolTCP represents the TCP protocol in ingress rules + // SecurityGroupProtocolTCP represents the TCP protocol in ingress rules. SecurityGroupProtocolTCP = SecurityGroupProtocol("tcp") - // SecurityGroupProtocolUDP represents the UDP protocol in ingress rules + // SecurityGroupProtocolUDP represents the UDP protocol in ingress rules. SecurityGroupProtocolUDP = SecurityGroupProtocol("udp") - // SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules + // SecurityGroupProtocolICMP represents the ICMP protocol in ingress rules. SecurityGroupProtocolICMP = SecurityGroupProtocol("icmp") - // SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules + // SecurityGroupProtocolICMPv6 represents the ICMPv6 protocol in ingress rules. SecurityGroupProtocolICMPv6 = SecurityGroupProtocol("58") ) @@ -508,7 +508,7 @@ func (i IngressRules) Difference(o IngressRules) (out IngressRules) { return } -// Equals returns true if two IngressRule are equal +// Equals returns true if two IngressRule are equal. func (i *IngressRule) Equals(o *IngressRule) bool { if len(i.CidrBlocks) != len(o.CidrBlocks) { return false @@ -560,35 +560,35 @@ func (i *IngressRule) Equals(o *IngressRule) bool { type InstanceState string var ( - // InstanceStatePending is the string representing an instance in a pending state + // InstanceStatePending is the string representing an instance in a pending state. InstanceStatePending = InstanceState("pending") - // InstanceStateRunning is the string representing an instance in a running state + // InstanceStateRunning is the string representing an instance in a running state. InstanceStateRunning = InstanceState("running") - // InstanceStateShuttingDown is the string representing an instance shutting down + // InstanceStateShuttingDown is the string representing an instance shutting down. InstanceStateShuttingDown = InstanceState("shutting-down") - // InstanceStateTerminated is the string representing an instance that has been terminated + // InstanceStateTerminated is the string representing an instance that has been terminated. InstanceStateTerminated = InstanceState("terminated") // InstanceStateStopping is the string representing an instance - // that is in the process of being stopped and can be restarted + // that is in the process of being stopped and can be restarted. InstanceStateStopping = InstanceState("stopping") // InstanceStateStopped is the string representing an instance - // that has been stopped and can be restarted + // that has been stopped and can be restarted. InstanceStateStopped = InstanceState("stopped") // InstanceRunningStates defines the set of states in which an EC2 instance is - // running or going to be running soon + // running or going to be running soon. InstanceRunningStates = sets.NewString( string(InstanceStatePending), string(InstanceStateRunning), ) // InstanceOperationalStates defines the set of states in which an EC2 instance is - // or can return to running, and supports all EC2 operations + // or can return to running, and supports all EC2 operations. InstanceOperationalStates = InstanceRunningStates.Union( sets.NewString( string(InstanceStateStopping), @@ -596,7 +596,7 @@ var ( ), ) - // InstanceKnownStates represents all known EC2 instance states + // InstanceKnownStates represents all known EC2 instance states. InstanceKnownStates = InstanceOperationalStates.Union( sets.NewString( string(InstanceStateShuttingDown), diff --git a/api/v1alpha4/validate.go b/api/v1alpha4/validate.go index dd7ba7151b..cca9ac5fdd 100644 --- a/api/v1alpha4/validate.go +++ b/api/v1alpha4/validate.go @@ -28,7 +28,7 @@ var ( sshKeyValidNameRegex = regexp.MustCompile(`^[[:graph:]]+([[:print:]]*[[:graph:]]+)*$`) ) -// Validate will validate the bastion fields +// Validate will validate the bastion fields. func (b *Bastion) Validate() []*field.Error { var errs field.ErrorList diff --git a/bootstrap/eks/api/v1alpha3/conversion_test.go b/bootstrap/eks/api/v1alpha3/conversion_test.go index fa56f50d67..9a3025df87 100644 --- a/bootstrap/eks/api/v1alpha3/conversion_test.go +++ b/bootstrap/eks/api/v1alpha3/conversion_test.go @@ -34,13 +34,13 @@ func TestFuzzyConversion(t *testing.T) { t.Run("for EKSConfig", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.EKSConfig{}, - Spoke: &EKSConfig{}, + Hub: &v1alpha4.EKSConfig{}, + Spoke: &EKSConfig{}, })) t.Run("for EKSConfigTemplate", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.EKSConfigTemplate{}, - Spoke: &EKSConfigTemplate{}, + Hub: &v1alpha4.EKSConfigTemplate{}, + Spoke: &EKSConfigTemplate{}, })) } diff --git a/bootstrap/eks/api/v1alpha3/doc.go b/bootstrap/eks/api/v1alpha3/doc.go index 95178de1b8..62c04c4cb9 100644 --- a/bootstrap/eks/api/v1alpha3/doc.go +++ b/bootstrap/eks/api/v1alpha3/doc.go @@ -15,4 +15,5 @@ limitations under the License. */ // +k8s:conversion-gen=sigs.k8s.io/cluster-api-provider-aws/bootstrap/eks/api/v1alpha4 + package v1alpha3 diff --git a/bootstrap/eks/api/v1alpha3/eksconfig_types.go b/bootstrap/eks/api/v1alpha3/eksconfig_types.go index a32b129f47..aa3a8d0342 100644 --- a/bootstrap/eks/api/v1alpha3/eksconfig_types.go +++ b/bootstrap/eks/api/v1alpha3/eksconfig_types.go @@ -84,7 +84,7 @@ func (r *EKSConfig) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// EKSConfigList contains a list of EKSConfig +// EKSConfigList contains a list of EKSConfig. type EKSConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/bootstrap/eks/api/v1alpha3/eksconfigtemplate_types.go b/bootstrap/eks/api/v1alpha3/eksconfigtemplate_types.go index b1ee4fa6ae..b8f2f5b0f7 100644 --- a/bootstrap/eks/api/v1alpha3/eksconfigtemplate_types.go +++ b/bootstrap/eks/api/v1alpha3/eksconfigtemplate_types.go @@ -43,7 +43,7 @@ type EKSConfigTemplate struct { // +kubebuilder:object:root=true -// EKSConfigTemplateList contains a list of EKSConfigTemplate +// EKSConfigTemplateList contains a list of EKSConfigTemplate. type EKSConfigTemplateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/bootstrap/eks/api/v1alpha3/groupversion_info.go b/bootstrap/eks/api/v1alpha3/groupversion_info.go index e1f6a9e552..93148454db 100644 --- a/bootstrap/eks/api/v1alpha3/groupversion_info.go +++ b/bootstrap/eks/api/v1alpha3/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "bootstrap.cluster.x-k8s.io", Version: "v1alpha3"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/bootstrap/eks/api/v1alpha3/webhook_suite_test.go b/bootstrap/eks/api/v1alpha3/webhook_suite_test.go index 9b6cd2dfe3..22d6faecaa 100644 --- a/bootstrap/eks/api/v1alpha3/webhook_suite_test.go +++ b/bootstrap/eks/api/v1alpha3/webhook_suite_test.go @@ -48,7 +48,7 @@ func setup() { utilruntime.Must(bootstrapv1alpha4.AddToScheme(scheme.Scheme)) testEnvConfig := helpers.NewTestEnvironmentConfiguration([]string{ - path.Join( "bootstrap", "eks", "config", "crd", "bases"), + path.Join("bootstrap", "eks", "config", "crd", "bases"), }, ).WithWebhookConfiguration("unmanaged", path.Join("bootstrap", "eks", "config", "webhook", "manifests.yaml")) var err error diff --git a/bootstrap/eks/api/v1alpha4/doc.go b/bootstrap/eks/api/v1alpha4/doc.go index e9d675ccd9..a9d07c4752 100644 --- a/bootstrap/eks/api/v1alpha4/doc.go +++ b/bootstrap/eks/api/v1alpha4/doc.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// +gencrdrefdocs:force +// +gencrdrefdocs:force // nolint: revive // +groupName=bootstrap.cluster.x-k8s.io + package v1alpha4 diff --git a/bootstrap/eks/api/v1alpha4/eksconfig_types.go b/bootstrap/eks/api/v1alpha4/eksconfig_types.go index ac63fdf497..6de0f62339 100644 --- a/bootstrap/eks/api/v1alpha4/eksconfig_types.go +++ b/bootstrap/eks/api/v1alpha4/eksconfig_types.go @@ -85,7 +85,7 @@ func (r *EKSConfig) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// EKSConfigList contains a list of EKSConfig +// EKSConfigList contains a list of EKSConfig. type EKSConfigList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/bootstrap/eks/api/v1alpha4/eksconfig_webhook.go b/bootstrap/eks/api/v1alpha4/eksconfig_webhook.go index 8bc21c9cfa..6a90f8b3cb 100644 --- a/bootstrap/eks/api/v1alpha4/eksconfig_webhook.go +++ b/bootstrap/eks/api/v1alpha4/eksconfig_webhook.go @@ -22,7 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" ) -// SetupWebhookWithManager will setup the webhooks for the EKSConfig +// SetupWebhookWithManager will setup the webhooks for the EKSConfig. func (r *EKSConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -35,21 +35,21 @@ func (r *EKSConfig) SetupWebhookWithManager(mgr ctrl.Manager) error { var _ webhook.Defaulter = &EKSConfig{} var _ webhook.Validator = &EKSConfig{} -// ValidateCreate will do any extra validation when creating a EKSConfig +// ValidateCreate will do any extra validation when creating a EKSConfig. func (r *EKSConfig) ValidateCreate() error { return nil } -// ValidateUpdate will do any extra validation when updating a EKSConfig +// ValidateUpdate will do any extra validation when updating a EKSConfig. func (r *EKSConfig) ValidateUpdate(old runtime.Object) error { return nil } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *EKSConfig) ValidateDelete() error { return nil } -// Default will set default values for the EKSConfig +// Default will set default values for the EKSConfig. func (r *EKSConfig) Default() { } diff --git a/bootstrap/eks/api/v1alpha4/eksconfigtemplate_types.go b/bootstrap/eks/api/v1alpha4/eksconfigtemplate_types.go index b61cc23fd7..77a9c1a2dd 100644 --- a/bootstrap/eks/api/v1alpha4/eksconfigtemplate_types.go +++ b/bootstrap/eks/api/v1alpha4/eksconfigtemplate_types.go @@ -44,7 +44,7 @@ type EKSConfigTemplate struct { // +kubebuilder:object:root=true -// EKSConfigTemplateList contains a list of EKSConfigTemplate +// EKSConfigTemplateList contains a list of EKSConfigTemplate. type EKSConfigTemplateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/bootstrap/eks/api/v1alpha4/eksconfigtemplate_webhook.go b/bootstrap/eks/api/v1alpha4/eksconfigtemplate_webhook.go index 2ee9441cb9..aa32109337 100644 --- a/bootstrap/eks/api/v1alpha4/eksconfigtemplate_webhook.go +++ b/bootstrap/eks/api/v1alpha4/eksconfigtemplate_webhook.go @@ -22,7 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" ) -// SetupWebhookWithManager will setup the webhooks for the EKSConfigTemplate +// SetupWebhookWithManager will setup the webhooks for the EKSConfigTemplate. func (r *EKSConfigTemplate) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -35,21 +35,21 @@ func (r *EKSConfigTemplate) SetupWebhookWithManager(mgr ctrl.Manager) error { var _ webhook.Defaulter = &EKSConfigTemplate{} var _ webhook.Validator = &EKSConfigTemplate{} -// ValidateCreate will do any extra validation when creating a EKSConfigTemplate +// ValidateCreate will do any extra validation when creating a EKSConfigTemplate. func (r *EKSConfigTemplate) ValidateCreate() error { return nil } -// ValidateUpdate will do any extra validation when updating a EKSConfigTemplate +// ValidateUpdate will do any extra validation when updating a EKSConfigTemplate. func (r *EKSConfigTemplate) ValidateUpdate(old runtime.Object) error { return nil } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *EKSConfigTemplate) ValidateDelete() error { return nil } -// Default will set default values for the EKSConfigTemplate +// Default will set default values for the EKSConfigTemplate. func (r *EKSConfigTemplate) Default() { } diff --git a/bootstrap/eks/api/v1alpha4/groupversion_info.go b/bootstrap/eks/api/v1alpha4/groupversion_info.go index 4607b2bfd2..fcc0433dc0 100644 --- a/bootstrap/eks/api/v1alpha4/groupversion_info.go +++ b/bootstrap/eks/api/v1alpha4/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "bootstrap.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/bootstrap/eks/controllers/eksconfig_controller.go b/bootstrap/eks/controllers/eksconfig_controller.go index de16040312..a6168f0328 100644 --- a/bootstrap/eks/controllers/eksconfig_controller.go +++ b/bootstrap/eks/controllers/eksconfig_controller.go @@ -45,7 +45,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// EKSConfigReconciler reconciles a EKSConfig object +// EKSConfigReconciler reconciles a EKSConfig object. type EKSConfigReconciler struct { client.Client Scheme *runtime.Scheme @@ -283,7 +283,7 @@ func (r *EKSConfigReconciler) storeBootstrapData(ctx context.Context, cluster *c } // MachineToBootstrapMapFunc is a handler.ToRequestsFunc to be used to enqueue requests -// for EKSConfig reconciliation +// for EKSConfig reconciliation. func (r *EKSConfigReconciler) MachineToBootstrapMapFunc(o client.Object) []ctrl.Request { result := []ctrl.Request{} @@ -299,7 +299,7 @@ func (r *EKSConfigReconciler) MachineToBootstrapMapFunc(o client.Object) []ctrl. } // MachinePoolToBootstrapMapFunc is a handler.ToRequestsFunc to be uses to enqueue requests -// for EKSConfig reconciliation +// for EKSConfig reconciliation. func (r *EKSConfigReconciler) MachinePoolToBootstrapMapFunc(o client.Object) []ctrl.Request { result := []ctrl.Request{} @@ -317,7 +317,7 @@ func (r *EKSConfigReconciler) MachinePoolToBootstrapMapFunc(o client.Object) []c } // ClusterToEKSConfigs is a handler.ToRequestsFunc to be used to enqueue requests for -// EKSConfig reconciliation +// EKSConfig reconciliation. func (r *EKSConfigReconciler) ClusterToEKSConfigs(o client.Object) []ctrl.Request { result := []ctrl.Request{} diff --git a/bootstrap/eks/controllers/eksconfig_controller_reconciler_test.go b/bootstrap/eks/controllers/eksconfig_controller_reconciler_test.go index b01aea8d83..35c25c2d18 100644 --- a/bootstrap/eks/controllers/eksconfig_controller_reconciler_test.go +++ b/bootstrap/eks/controllers/eksconfig_controller_reconciler_test.go @@ -57,7 +57,7 @@ func TestEKSConfigReconciler(t *testing.T) { }) } -// newCluster return a CAPI cluster object +// newCluster return a CAPI cluster object. func newCluster(name string) *clusterv1.Cluster { return &clusterv1.Cluster{ TypeMeta: metav1.TypeMeta{ @@ -78,7 +78,7 @@ func newCluster(name string) *clusterv1.Cluster { } } -// newMachine return a CAPI machine object; if cluster is not nil, the machine is linked to the cluster as well +// newMachine return a CAPI machine object; if cluster is not nil, the machine is linked to the cluster as well. func newMachine(cluster *clusterv1.Cluster, name string) *clusterv1.Machine { machine := &clusterv1.Machine{ TypeMeta: metav1.TypeMeta{ @@ -107,7 +107,7 @@ func newMachine(cluster *clusterv1.Cluster, name string) *clusterv1.Machine { return machine } -// newEKSConfig return an EKSConfig object; if machine is not nil, the EKSConfig is linked to the machine as well +// newEKSConfig return an EKSConfig object; if machine is not nil, the EKSConfig is linked to the machine as well. func newEKSConfig(machine *clusterv1.Machine, name string) *bootstrapv1.EKSConfig { config := &bootstrapv1.EKSConfig{ TypeMeta: metav1.TypeMeta{ diff --git a/bootstrap/eks/controllers/suite_test.go b/bootstrap/eks/controllers/suite_test.go index 40237ece8e..1780781582 100644 --- a/bootstrap/eks/controllers/suite_test.go +++ b/bootstrap/eks/controllers/suite_test.go @@ -38,12 +38,12 @@ func TestMain(m *testing.M) { teardown() }() code := m.Run() - os.Exit(code) + os.Exit(code) // nolint:gocritic } func setup() { - //utilruntime.Must(bootstrapv1.AddToScheme(scheme.Scheme)) - //utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) + // utilruntime.Must(bootstrapv1.AddToScheme(scheme.Scheme)) + // utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) testEnvConfig := helpers.NewTestEnvironmentConfiguration([]string{ path.Join("config", "crd", "bases"), }, diff --git a/cmd/clusterawsadm/ami/copy.go b/cmd/clusterawsadm/ami/copy.go index c69baf7460..c71bdc6442 100644 --- a/cmd/clusterawsadm/ami/copy.go +++ b/cmd/clusterawsadm/ami/copy.go @@ -47,7 +47,6 @@ type CopyInput struct { // Copy will create an AWSAMI from a CopyInput. func Copy(input CopyInput) (*amiv1.AWSAMI, error) { - sourceSession, err := session.NewSessionWithOptions(session.Options{ SharedConfigState: session.SharedConfigEnable, Config: aws.Config{Region: aws.String(input.SourceRegion)}, @@ -161,7 +160,6 @@ type copyWithSnapshotInput struct { } func copyWithSnapshot(input copyWithSnapshotInput) (string, string, error) { - ec2Client := ec2.New(input.sess) imgName := *input.image.Name + util.RandomString(3) + strconv.Itoa(int(time.Now().Unix())) log := input.log.WithValues("imageName", imgName) diff --git a/cmd/clusterawsadm/ami/helper.go b/cmd/clusterawsadm/ami/helper.go index 5465a35104..cb24347db9 100644 --- a/cmd/clusterawsadm/ami/helper.go +++ b/cmd/clusterawsadm/ami/helper.go @@ -102,7 +102,7 @@ func latestStableRelease() (string, error) { // If it is the first release, use the previous version instead if latestVersionSemVer.Patch == 0 { - latestVersionSemVer.Minor = latestVersionSemVer.Minor - 1 + latestVersionSemVer.Minor-- // Address to get stable release for a particular version is: https://dl.k8s.io/release/stable-1.19.txt" olderVersion := fmt.Sprintf("-%v.%v", latestVersionSemVer.Major, latestVersionSemVer.Minor) resp, err = http.Get(fmt.Sprintf(latestStableReleaseURL, olderVersion)) diff --git a/cmd/clusterawsadm/api/ami/v1alpha1/register.go b/cmd/clusterawsadm/api/ami/v1alpha1/register.go index cddb82541f..5bd716fad5 100644 --- a/cmd/clusterawsadm/api/ami/v1alpha1/register.go +++ b/cmd/clusterawsadm/api/ami/v1alpha1/register.go @@ -22,18 +22,18 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -// GroupName is the group name used in this package +// GroupName is the group name used in this package. const GroupName = "ami.aws.infrastructure.cluster.x-k8s.io" var ( - // SchemeGroupVersion is the fully qualified group and version + // SchemeGroupVersion is the fully qualified group and version. SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} - // SchemeBuilder is the scheme builder with scheme init functions to run for this API package + // SchemeBuilder is the scheme builder with scheme init functions to run for this API package. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // localSchemeBuilder ïs a pointer to SchemeBuilder instance. Using localSchemeBuilder // defaulting and conversion init funcs are registered as well. localSchemeBuilder = &SchemeBuilder - // AddToScheme is a global function that registers this API group & version to a scheme + // AddToScheme is a global function that registers this API group & version to a scheme. AddToScheme = localSchemeBuilder.AddToScheme ) diff --git a/cmd/clusterawsadm/api/ami/v1alpha1/types.go b/cmd/clusterawsadm/api/ami/v1alpha1/types.go index 8e7a462ce0..21a27fc5c5 100644 --- a/cmd/clusterawsadm/api/ami/v1alpha1/types.go +++ b/cmd/clusterawsadm/api/ami/v1alpha1/types.go @@ -21,6 +21,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) +// Constants. const ( // AWSAMIKind defines an AMI kind. AWSAMIKind = "AWSAMI" @@ -29,7 +30,7 @@ const ( AWSAMIListKind = "AWSAMIList" ) -// AWSAMISpec defines an AMI +// AWSAMISpec defines an AMI. type AWSAMISpec struct { OS string `json:"os"` Region string `json:"region"` @@ -40,7 +41,7 @@ type AWSAMISpec struct { // +kubebuilder:object:root=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// AWSAMI defines an AMI +// AWSAMI defines an AMI. type AWSAMI struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -50,7 +51,7 @@ type AWSAMI struct { // +kubebuilder:object:root=true // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// AWSAMIList defines a list of AMIs +// AWSAMIList defines a list of AMIs. type AWSAMIList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` @@ -89,12 +90,10 @@ func (a *AWSAMIList) ToTable() *metav1.Table { } for _, ami := range a.Items { - row := metav1.TableRow{ Cells: []interface{}{ami.Spec.KubernetesVersion, ami.Spec.Region, ami.Spec.OS, ami.GetName(), ami.Spec.ImageID}, } table.Rows = append(table.Rows, row) - } return table } diff --git a/cmd/clusterawsadm/api/bootstrap/v1alpha1/defaults.go b/cmd/clusterawsadm/api/bootstrap/v1alpha1/defaults.go index 247785f2a0..d6a7feaf78 100644 --- a/cmd/clusterawsadm/api/bootstrap/v1alpha1/defaults.go +++ b/cmd/clusterawsadm/api/bootstrap/v1alpha1/defaults.go @@ -36,14 +36,14 @@ func addDefaultingFuncs(scheme *runtime.Scheme) error { return RegisterDefaults(scheme) } -// SetDefaults_BootstrapUser is used by defaulter-gen +// SetDefaults_BootstrapUser is used by defaulter-gen. func SetDefaults_BootstrapUser(obj *BootstrapUser) { //nolint:golint,stylecheck if obj != nil && obj.UserName == "" { obj.UserName = DefaultBootstrapUserName } } -// SetDefaults_AWSIAMConfigurationSpec is used by defaulter-gen +// SetDefaults_AWSIAMConfigurationSpec is used by defaulter-gen. func SetDefaults_AWSIAMConfigurationSpec(obj *AWSIAMConfigurationSpec) { //nolint:golint,stylecheck if obj.NameSuffix == nil { obj.NameSuffix = utilpointer.StringPtr(infrav1.DefaultNameSuffix) @@ -87,7 +87,7 @@ func SetDefaults_AWSIAMConfigurationSpec(obj *AWSIAMConfigurationSpec) { //nolin } } -// SetDefaults_AWSIAMConfiguration is used by defaulter-gen +// SetDefaults_AWSIAMConfiguration is used by defaulter-gen. func SetDefaults_AWSIAMConfiguration(obj *AWSIAMConfiguration) { //nolint:golint,stylecheck obj.APIVersion = SchemeGroupVersion.String() obj.Kind = "AWSIAMConfiguration" diff --git a/cmd/clusterawsadm/api/bootstrap/v1alpha1/register.go b/cmd/clusterawsadm/api/bootstrap/v1alpha1/register.go index 5a1237e4f7..eedc38aa3e 100644 --- a/cmd/clusterawsadm/api/bootstrap/v1alpha1/register.go +++ b/cmd/clusterawsadm/api/bootstrap/v1alpha1/register.go @@ -22,18 +22,18 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -// GroupName is the group name used in this package +// GroupName is the group name used in this package. const GroupName = "bootstrap.aws.infrastructure.cluster.x-k8s.io" var ( - // SchemeGroupVersion is the fully qualified group and version + // SchemeGroupVersion is the fully qualified group and version. SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} - // SchemeBuilder is the scheme builder with scheme init functions to run for this API package + // SchemeBuilder is the scheme builder with scheme init functions to run for this API package. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // localSchemeBuilder ïs a pointer to SchemeBuilder instance. Using localSchemeBuilder // defaulting and conversion init funcs are registered as well. localSchemeBuilder = &SchemeBuilder - // AddToScheme is a global function that registers this API group & version to a scheme + // AddToScheme is a global function that registers this API group & version to a scheme. AddToScheme = localSchemeBuilder.AddToScheme ) diff --git a/cmd/clusterawsadm/api/bootstrap/v1alpha1/types.go b/cmd/clusterawsadm/api/bootstrap/v1alpha1/types.go index c201e0b803..c8fb1db82b 100644 --- a/cmd/clusterawsadm/api/bootstrap/v1alpha1/types.go +++ b/cmd/clusterawsadm/api/bootstrap/v1alpha1/types.go @@ -70,7 +70,7 @@ type ControlPlane struct { } // AWSIAMRoleSpec defines common configuration for AWS IAM roles created by -// Kubernetes Cluster API Provider AWS +// Kubernetes Cluster API Provider AWS. type AWSIAMRoleSpec struct { // Disable if set to true will not create the AWS IAM role. Defaults to false. Disable bool `json:"disable"` // default: false @@ -89,7 +89,7 @@ type AWSIAMRoleSpec struct { Tags infrav1.Tags `json:"tags,omitempty"` } -// EKSConfig represents the EKS related configuration config +// EKSConfig represents the EKS related configuration config. type EKSConfig struct { // Enable controls whether EKS-related permissions are granted Enable bool `json:"enable"` @@ -110,7 +110,7 @@ type EKSConfig struct { } // EventBridgeConfig represents configuration for enabling experimental feature to consume -// EventBridge EC2 events +// EventBridge EC2 events. type EventBridgeConfig struct { // Enable controls whether permissions are granted to consume EC2 events Enable bool `json:"enable,omitempty"` diff --git a/cmd/clusterawsadm/api/iam/v1alpha1/register.go b/cmd/clusterawsadm/api/iam/v1alpha1/register.go index 7ad9c9912a..97102c3086 100644 --- a/cmd/clusterawsadm/api/iam/v1alpha1/register.go +++ b/cmd/clusterawsadm/api/iam/v1alpha1/register.go @@ -26,18 +26,18 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" ) -// GroupName is the group name used in this package +// GroupName is the group name used in this package. const GroupName = "iam.aws.infrastructure.cluster.x-k8s.io" var ( - // SchemeGroupVersion is the fully qualified group and version + // SchemeGroupVersion is the fully qualified group and version. SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} - // SchemeBuilder is the scheme builder with scheme init functions to run for this API package + // SchemeBuilder is the scheme builder with scheme init functions to run for this API package. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // localSchemeBuilder ïs a pointer to SchemeBuilder instance. Using localSchemeBuilder // defaulting and conversion init funcs are registered as well. localSchemeBuilder = &SchemeBuilder - // AddToScheme is a global function that registers this API group & version to a scheme + // AddToScheme is a global function that registers this API group & version to a scheme. AddToScheme = localSchemeBuilder.AddToScheme ) diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go b/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go index 2095f6b7d9..241322ca67 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/cluster_api_controller.go @@ -380,7 +380,6 @@ func (t Template) ControllersPolicy() *infrav1.PolicyDocument { Effect: infrav1.EffectAllow, }, }...) - } if t.Spec.EventBridge.Enable { diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/iam.go b/cmd/clusterawsadm/cloudformation/bootstrap/iam.go index ee662dac7c..8ac63c8985 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/iam.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/iam.go @@ -28,7 +28,7 @@ import ( // PolicyName defines the name of a managed IAM policy. type PolicyName string -// ManagedIAMPolicyNames slice of managed IAM policies +// ManagedIAMPolicyNames slice of managed IAM policies. var ManagedIAMPolicyNames = [4]PolicyName{ControllersPolicy, ControlPlanePolicy, NodePolicy, CSIPolicy} // IsValid will check if a given policy name is valid. That is, it will check if the given policy name is @@ -42,7 +42,7 @@ func (p PolicyName) IsValid() bool { return false } -// GenerateManagedIAMPolicyDocuments generates JSON representation of policy documents for all ManagedIAMPolicy +// GenerateManagedIAMPolicyDocuments generates JSON representation of policy documents for all ManagedIAMPolicy. func (t Template) GenerateManagedIAMPolicyDocuments(policyDocDir string) error { for _, pn := range ManagedIAMPolicyNames { pd := t.GetPolicyDocFromPolicyName(pn) diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/template.go b/cmd/clusterawsadm/cloudformation/bootstrap/template.go index b0a38ad82d..739b9f947d 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/template.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/template.go @@ -19,12 +19,12 @@ package bootstrap import ( "fmt" + "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" + "github.com/awslabs/goformation/v4/cloudformation" cfn_iam "github.com/awslabs/goformation/v4/cloudformation/iam" bootstrapv1 "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/api/bootstrap/v1alpha1" - - "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/converters" ekscontrolplanev1 "sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1alpha4" infrav1exp "sigs.k8s.io/cluster-api-provider-aws/exp/api/v1alpha4" diff --git a/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go b/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go index 3d69496417..2572226225 100644 --- a/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go +++ b/cmd/clusterawsadm/cloudformation/bootstrap/template_test.go @@ -168,7 +168,7 @@ func Test_RenderCloudformation(t *testing.T) { if err != nil { t.Fatal(err) } - ioutil.WriteFile("/tmp/tmp1", tData, 600) + ioutil.WriteFile("/tmp/tmp1", tData, 0600) // nolint:gosec if string(tData) != string(data) { dmp := diffmatchpatch.New() diff --git a/cmd/clusterawsadm/cloudformation/service/service.go b/cmd/clusterawsadm/cloudformation/service/service.go index e31b38fe98..abdd4feabd 100644 --- a/cmd/clusterawsadm/cloudformation/service/service.go +++ b/cmd/clusterawsadm/cloudformation/service/service.go @@ -14,6 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ +// Package cloudformation provides the API operation methods for making requests to +// AWS CloudFormation. package cloudformation import ( @@ -44,7 +46,7 @@ func NewService(i cloudformationiface.CloudFormationAPI) *Service { } } -// ReconcileBootstrapStack creates or updates bootstrap CloudFormation +// ReconcileBootstrapStack creates or updates bootstrap CloudFormation. func (s *Service) ReconcileBootstrapStack(stackName string, t go_cfn.Template) error { yaml, err := t.YAML() processedYaml := string(yaml) @@ -111,7 +113,7 @@ func (s *Service) updateStack(stackName, yaml string) error { return nil } -// DeleteStack deletes a cloudformation stack +// DeleteStack deletes a cloudformation stack. func (s *Service) DeleteStack(stackName string, retainResources []*string) error { klog.V(2).Infof("deleting AWS CloudFormation stack %q", stackName) var err error @@ -134,7 +136,7 @@ func (s *Service) DeleteStack(stackName string, retainResources []*string) error } // ShowStackResources prints out in tabular format the resources in the -// stack +// stack. func (s *Service) ShowStackResources(stackName string) error { input := &cfn.DescribeStackResourcesInput{ StackName: aws.String(stackName), diff --git a/cmd/clusterawsadm/cmd/alpha/alpha.go b/cmd/clusterawsadm/cmd/alpha/alpha.go index cdff885aec..1e32f0d9a1 100644 --- a/cmd/clusterawsadm/cmd/alpha/alpha.go +++ b/cmd/clusterawsadm/cmd/alpha/alpha.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/cmd/flags" ) -// AlphaCmd is the top-level alpha set of commands +// AlphaCmd is the top-level alpha set of commands. func AlphaCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "alpha", diff --git a/cmd/clusterawsadm/cmd/alpha/bootstrap/bootstrap.go b/cmd/clusterawsadm/cmd/alpha/bootstrap/bootstrap.go index 91658227f0..5cb2d093d9 100644 --- a/cmd/clusterawsadm/cmd/alpha/bootstrap/bootstrap.go +++ b/cmd/clusterawsadm/cmd/alpha/bootstrap/bootstrap.go @@ -39,17 +39,14 @@ var ( extraNodePolicies []string ) -// RootCmd is the root of the `alpha bootstrap command` +// RootCmd is the root of the `alpha bootstrap command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "bootstrap", Short: "bootstrap cloudformation", Long: `Create and apply bootstrap AWS CloudFormation template to create IAM permissions for the Cluster API`, RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } newCmd.AddCommand(generateCmd()) diff --git a/cmd/clusterawsadm/cmd/alpha/migrate/migrate.go b/cmd/clusterawsadm/cmd/alpha/migrate/migrate.go index a924d37cd4..f1b690a177 100644 --- a/cmd/clusterawsadm/cmd/alpha/migrate/migrate.go +++ b/cmd/clusterawsadm/cmd/alpha/migrate/migrate.go @@ -39,7 +39,7 @@ var ( ) // MigrateCmd is the command for migrating AWS resources to be compatible -// with specific CAPA versions +// with specific CAPA versions. func MigrateCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "migrate [target version]", diff --git a/cmd/clusterawsadm/cmd/ami/ami.go b/cmd/clusterawsadm/cmd/ami/ami.go index d6d06e2a1b..16c6742cf5 100644 --- a/cmd/clusterawsadm/cmd/ami/ami.go +++ b/cmd/clusterawsadm/cmd/ami/ami.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cluster-api/cmd/clusterctl/cmd" ) -// RootCmd is the root of the `ami command` +// RootCmd is the root of the `ami command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "ami [command]", @@ -36,10 +36,7 @@ func RootCmd() *cobra.Command { # (to be implemented) List available AMIs `), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/ami/list/list.go b/cmd/clusterawsadm/cmd/ami/list/list.go index 0ac6ba48d7..25c9daab1e 100644 --- a/cmd/clusterawsadm/cmd/ami/list/list.go +++ b/cmd/clusterawsadm/cmd/ami/list/list.go @@ -55,7 +55,6 @@ func ListAMICmd() *cobra.Command { `), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - region, _ := flags.GetRegion(cmd) printer, err := cmdout.New(outputPrinter, os.Stdout) diff --git a/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go b/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go index 96b6585b32..d1ea95b05f 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go +++ b/cmd/clusterawsadm/cmd/bootstrap/bootstrap.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cluster-api/cmd/clusterctl/cmd" ) -// RootCmd is the root of the `alpha bootstrap command` +// RootCmd is the root of the `alpha bootstrap command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "bootstrap [command]", @@ -36,10 +36,7 @@ func RootCmd() *cobra.Command { to use to provision infrastructure. `), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go b/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go index 8cb911481a..6c0619cc3b 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go +++ b/cmd/clusterawsadm/cmd/bootstrap/credentials/credentials.go @@ -36,7 +36,7 @@ const ( backupAWSRegion = "us-east-1" // CredentialHelp provides an explanation as to how credentials are resolved by - // clusterawsadm + // clusterawsadm. CredentialHelp = ` The utility will attempt to find credentials in the following order: @@ -79,7 +79,7 @@ const ( var errInvalidOutputFlag = errors.New("invalid output flag. Expected rawSharedConfig or base64SharedConfig") -// RootCmd is the root of the `alpha bootstrap command` +// RootCmd is the root of the `alpha bootstrap command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "credentials", @@ -89,10 +89,7 @@ func RootCmd() *cobra.Command { ` + CredentialHelp + EncodingHelp), Example: cmd.Examples(examples), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } newCmd.AddCommand(generateAWSDefaultProfileWithChain()) diff --git a/cmd/clusterawsadm/cmd/bootstrap/iam/root.go b/cmd/clusterawsadm/cmd/bootstrap/iam/root.go index ff8aa43a62..c4f2e7498d 100644 --- a/cmd/clusterawsadm/cmd/bootstrap/iam/root.go +++ b/cmd/clusterawsadm/cmd/bootstrap/iam/root.go @@ -21,7 +21,7 @@ import ( "sigs.k8s.io/cluster-api/cmd/clusterctl/cmd" ) -// RootCmd is the root of the `bootstrap iam command` +// RootCmd is the root of the `bootstrap iam command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "iam [command]", @@ -33,10 +33,7 @@ func RootCmd() *cobra.Command { `), Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/controller/controller.go b/cmd/clusterawsadm/cmd/controller/controller.go index d167742ff6..4237b9b8c9 100644 --- a/cmd/clusterawsadm/cmd/controller/controller.go +++ b/cmd/clusterawsadm/cmd/controller/controller.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cluster-api/cmd/clusterctl/cmd" ) -// RootCmd is the root of the `controller command` +// RootCmd is the root of the `controller command`. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "controller [command]", @@ -34,10 +34,7 @@ func RootCmd() *cobra.Command { # Zero controller credentials and rollout controllers `), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } diff --git a/cmd/clusterawsadm/cmd/eks/addons/addons.go b/cmd/clusterawsadm/cmd/eks/addons/addons.go index e976e1e1af..10bc0f73f7 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/addons.go +++ b/cmd/clusterawsadm/cmd/eks/addons/addons.go @@ -24,10 +24,7 @@ func RootCmd() *cobra.Command { Use: "addons", Short: "Commands related to EKS addons", RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } newCmd.AddCommand(listAvailableCmd()) diff --git a/cmd/clusterawsadm/cmd/eks/addons/list_available.go b/cmd/clusterawsadm/cmd/eks/addons/list_available.go index 20d4eba481..4b7def1c3e 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/list_available.go +++ b/cmd/clusterawsadm/cmd/eks/addons/list_available.go @@ -119,7 +119,6 @@ func listAvailableAddons(region, clusterName, printerType *string) error { } addonsList.Addons = append(addonsList.Addons, newAddon) } - } } diff --git a/cmd/clusterawsadm/cmd/eks/addons/types.go b/cmd/clusterawsadm/cmd/eks/addons/types.go index 5b43577e74..e6d82ea0db 100644 --- a/cmd/clusterawsadm/cmd/eks/addons/types.go +++ b/cmd/clusterawsadm/cmd/eks/addons/types.go @@ -78,12 +78,10 @@ func (a *availableAddonsList) ToTable() *metav1.Table { } for _, addon := range a.Addons { - row := metav1.TableRow{ Cells: []interface{}{addon.Name, addon.Type, addon.Version, addon.Architecture, addon.Compatibilities}, } table.Rows = append(table.Rows, row) - } return table @@ -156,7 +154,6 @@ func (a *installedAddonsList) ToTable() *metav1.Table { } for _, addon := range a.Addons { - if addon.RoleARN == nil { addon.RoleARN = aws.String("") } @@ -165,8 +162,6 @@ func (a *installedAddonsList) ToTable() *metav1.Table { Cells: []interface{}{addon.Name, addon.Version, addon.Status, addon.CreatedAt, addon.ModifiedAt, *addon.RoleARN, len(addon.HealthIssues)}, } table.Rows = append(table.Rows, row) - } - return table } diff --git a/cmd/clusterawsadm/cmd/eks/eks.go b/cmd/clusterawsadm/cmd/eks/eks.go index c58709caf4..1062e07b4f 100644 --- a/cmd/clusterawsadm/cmd/eks/eks.go +++ b/cmd/clusterawsadm/cmd/eks/eks.go @@ -28,10 +28,7 @@ func RootCmd() *cobra.Command { Use: "eks", Short: "Commands related to EKS", RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } newCmd.AddCommand(addons.RootCmd()) diff --git a/cmd/clusterawsadm/cmd/flags/common.go b/cmd/clusterawsadm/cmd/flags/common.go index 8752ccb999..1cc615f981 100644 --- a/cmd/clusterawsadm/cmd/flags/common.go +++ b/cmd/clusterawsadm/cmd/flags/common.go @@ -28,8 +28,7 @@ import ( // ResolveAWSError will attempt to resolve an AWS error. func ResolveAWSError(err error) error { - code, _ := awserrors.Code(err) - if code == awserrors.NoCredentialProviders { + if code, _ := awserrors.Code(err); code == awserrors.NoCredentialProviders { return errors.New("could not resolve default credentials. Please see https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html for how to provide credentials") } return err diff --git a/cmd/clusterawsadm/cmd/root.go b/cmd/clusterawsadm/cmd/root.go index 473915242c..08e7204c90 100644 --- a/cmd/clusterawsadm/cmd/root.go +++ b/cmd/clusterawsadm/cmd/root.go @@ -38,7 +38,7 @@ var ( verbosity *int ) -// RootCmd is the Cobra root command +// RootCmd is the Cobra root command. func RootCmd() *cobra.Command { newCmd := &cobra.Command{ Use: "clusterawsadm", @@ -61,15 +61,12 @@ func RootCmd() *cobra.Command { clusterctl init --infrastructure aws `), RunE: func(cmd *cobra.Command, args []string) error { - if err := cmd.Help(); err != nil { - return err - } - return nil + return cmd.Help() }, } newCmd.AddCommand(alpha.AlphaCmd()) newCmd.AddCommand(bootstrap.RootCmd()) - newCmd.AddCommand(version.VersionCmd(os.Stdout)) + newCmd.AddCommand(version.Cmd(os.Stdout)) newCmd.AddCommand(ami.RootCmd()) newCmd.AddCommand(eks.RootCmd()) newCmd.AddCommand(controller.RootCmd()) @@ -77,7 +74,7 @@ func RootCmd() *cobra.Command { return newCmd } -// Execute starts the process +// Execute starts the process. func Execute() { if err := flag.CommandLine.Parse([]string{}); err != nil { fmt.Fprintln(os.Stderr, err) diff --git a/cmd/clusterawsadm/cmd/version/version.go b/cmd/clusterawsadm/cmd/version/version.go index 5a5976917c..da8ddacbce 100644 --- a/cmd/clusterawsadm/cmd/version/version.go +++ b/cmd/clusterawsadm/cmd/version/version.go @@ -27,13 +27,13 @@ import ( "sigs.k8s.io/yaml" ) -// Version provides the version information of clusterawsadm +// Version provides the version information of clusterawsadm. type Version struct { ClientVersion *version.Info `json:"awsProviderVersion"` } -// VersionCmd provides the version information clusterawsadm. -func VersionCmd(out io.Writer) *cobra.Command { +// Cmd provides the version information clusterawsadm. +func Cmd(out io.Writer) *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "Print version of clusterawsadm", diff --git a/cmd/clusterawsadm/configreader/configreader.go b/cmd/clusterawsadm/configreader/configreader.go index 4ade066131..18435e98c7 100644 --- a/cmd/clusterawsadm/configreader/configreader.go +++ b/cmd/clusterawsadm/configreader/configreader.go @@ -54,7 +54,7 @@ type loader interface { Load() (*bootstrapv1.AWSIAMConfiguration, error) } -// fsLoader loads configuration from `configDir` +// fsLoader loads configuration from `configDir`.. type fsLoader struct { // bootstrapCodecs is the scheme used to decode config files @@ -63,12 +63,12 @@ type fsLoader struct { bootstrapFile string } -// ReadFile reads a file +// ReadFile reads a file. func (fsLoader) ReadFile(filename string) ([]byte, error) { - return ioutil.ReadFile(filename) + return ioutil.ReadFile(filepath.Clean(filename)) } -// NewFsLoader returns a Loader that loads a AWSIAMConfiguration from the `config file` +// NewFsLoader returns a Loader that loads a AWSIAMConfiguration from the `config file`. func newFsLoader(bootstrapFile string) (loader, error) { _, bootstrapCodecs, err := bootstrapschemev1.NewSchemeAndCodecs() if err != nil { @@ -104,7 +104,7 @@ func (loader *fsLoader) Load() (*bootstrapv1.AWSIAMConfiguration, error) { return kc, nil } -// resolveRelativePaths makes relative paths absolute by resolving them against `root` +// resolveRelativePaths makes relative paths absolute by resolving them against `root`. func resolveRelativePaths(paths []*string, root string) { for _, path := range paths { // leave empty paths alone, "no path" is a valid input @@ -115,7 +115,7 @@ func resolveRelativePaths(paths []*string, root string) { } } -// DecodeBootstrapConfiguration decodes a serialized AWSIAMConfiguration to the internal type +// DecodeBootstrapConfiguration decodes a serialized AWSIAMConfiguration to the internal type. func DecodeBootstrapConfiguration(bootstrapCodecs *serializer.CodecFactory, data []byte) (*bootstrapv1.AWSIAMConfiguration, error) { obj := &bootstrapv1.AWSIAMConfiguration{} diff --git a/cmd/clusterawsadm/controller/helper.go b/cmd/clusterawsadm/controller/helper.go index 3b5a71d52e..45963f75b6 100644 --- a/cmd/clusterawsadm/controller/helper.go +++ b/cmd/clusterawsadm/controller/helper.go @@ -69,7 +69,7 @@ func PrintBootstrapCredentials(secret *corev1.Secret) { if base64.StdEncoding.EncodeToString(creds) == "Cg==" { fmt.Println("Credentials are zeroed") } else { - fmt.Println(string(creds)) + fmt.Print(string(creds)) } } } diff --git a/cmd/clusterawsadm/converters/cloudformation.go b/cmd/clusterawsadm/converters/cloudformation.go index 6f220a1ca6..fb79e59e5b 100644 --- a/cmd/clusterawsadm/converters/cloudformation.go +++ b/cmd/clusterawsadm/converters/cloudformation.go @@ -21,7 +21,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" ) -// MapToCloudFormationTags converts a infrav1.Tags to []tags.Tag +// MapToCloudFormationTags converts a infrav1.Tags to []tags.Tag. func MapToCloudFormationTags(src infrav1.Tags) []tags.Tag { cfnTags := make([]tags.Tag, 0, len(src)) diff --git a/cmd/clusterawsadm/credentials/credentials.go b/cmd/clusterawsadm/credentials/credentials.go index 8922956407..e5679e0501 100644 --- a/cmd/clusterawsadm/credentials/credentials.go +++ b/cmd/clusterawsadm/credentials/credentials.go @@ -22,10 +22,10 @@ import ( "errors" "text/template" + "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/cmd/util" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" - - "sigs.k8s.io/cluster-api-provider-aws/cmd/clusterawsadm/cmd/util" ) // AWSCredentialsTemplate generates an AWS credentials file that can diff --git a/cmd/clusterawsadm/printers/printers.go b/cmd/clusterawsadm/printers/printers.go index 2cdb7a006e..d2b6ebf78e 100644 --- a/cmd/clusterawsadm/printers/printers.go +++ b/cmd/clusterawsadm/printers/printers.go @@ -29,33 +29,33 @@ import ( cli "k8s.io/cli-runtime/pkg/printers" ) -// PrinterType is a type declaration for a printer type +// PrinterType is a type declaration for a printer type. type PrinterType string var ( - // PrinterTypeTable is a table printer type + // PrinterTypeTable is a table printer type. PrinterTypeTable = PrinterType("table") - // PrinterTypeYAML is a yaml printer type + // PrinterTypeYAML is a yaml printer type. PrinterTypeYAML = PrinterType("yaml") - // PrinterTypeJSON is a json printer type + // PrinterTypeJSON is a json printer type. PrinterTypeJSON = PrinterType("json") ) var ( - // ErrUnknowPrinterType is an error if a printer type isn't known + // ErrUnknowPrinterType is an error if a printer type isn't known. ErrUnknowPrinterType = errors.New("unknown printer type") // ErrTableRequired is an error if the object being printed - // isn't a metav1.Table + // isn't a metav1.Table. ErrTableRequired = errors.New("metav1.Table is required") ) -// Printer is an interface for a printer +// Printer is an interface for a printer. type Printer interface { // Print is a method to print an object Print(in interface{}) error } -// New creates a new printer +// New creates a new printer. func New(printerType string, writer io.Writer) (Printer, error) { switch printerType { case string(PrinterTypeTable): diff --git a/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclusters.yaml b/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclusters.yaml index 0be064a147..3e0c2ea434 100644 --- a/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclusters.yaml +++ b/config/crd/bases/infrastructure.cluster.x-k8s.io_awsclusters.yaml @@ -121,7 +121,7 @@ spec: properties: additionalSecurityGroups: description: AdditionalSecurityGroups sets the security groups - used by the load balancer. Expected to be security group IDs. + used by the load balancer. Expected to be security group IDs This is optional - if not provided new security groups will be created for the load balancer items: @@ -869,7 +869,7 @@ spec: properties: additionalSecurityGroups: description: AdditionalSecurityGroups sets the security groups - used by the load balancer. Expected to be security group IDs. + used by the load balancer. Expected to be security group IDs This is optional - if not provided new security groups will be created for the load balancer items: diff --git a/controllers/awscluster_controller.go b/controllers/awscluster_controller.go index 33c2b520ca..aefe0519fa 100644 --- a/controllers/awscluster_controller.go +++ b/controllers/awscluster_controller.go @@ -53,7 +53,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSClusterReconciler reconciles a AwsCluster object +// AWSClusterReconciler reconciles a AwsCluster object. type AWSClusterReconciler struct { client.Client Recorder record.EventRecorder @@ -250,7 +250,7 @@ func reconcileNormal(clusterScope *scope.ClusterScope) (reconcile.Result, error) if _, err := net.LookupIP(awsCluster.Status.Network.APIServerELB.DNSName); err != nil { conditions.MarkFalse(awsCluster, infrav1.LoadBalancerReadyCondition, infrav1.WaitForDNSNameResolveReason, clusterv1.ConditionSeverityInfo, "") clusterScope.Info("Waiting on API server ELB DNS name to resolve") - return reconcile.Result{RequeueAfter: 15 * time.Second}, nil + return reconcile.Result{RequeueAfter: 15 * time.Second}, nil // nolint:nilerr } conditions.MarkTrue(awsCluster, infrav1.LoadBalancerReadyCondition) diff --git a/controllers/awsmachine_controller.go b/controllers/awsmachine_controller.go index f239d51eb7..ae9dc2a782 100644 --- a/controllers/awsmachine_controller.go +++ b/controllers/awsmachine_controller.go @@ -59,7 +59,7 @@ import ( // InstanceIDIndex defines the aws machine controller's instance ID index. const InstanceIDIndex = ".spec.instanceID" -// AWSMachineReconciler reconciles a AwsMachine object +// AWSMachineReconciler reconciles a AwsMachine object. type AWSMachineReconciler struct { client.Client Log logr.Logger @@ -72,7 +72,7 @@ type AWSMachineReconciler struct { } const ( - // AWSManagedControlPlaneRefKind is the string value indicating that a cluster is AWS managed + // AWSManagedControlPlaneRefKind is the string value indicating that a cluster is AWS managed. AWSManagedControlPlaneRefKind = "AWSManagedControlPlane" ) @@ -854,7 +854,7 @@ func (r *AWSMachineReconciler) getInfraCluster(ctx context.Context, log logr.Log if err := r.Get(ctx, controlPlaneName, controlPlane); err != nil { // AWSManagedControlPlane is not ready - return nil, nil + return nil, nil // nolint:nilerr } managedControlPlaneScope, err = scope.NewManagedControlPlaneScope(scope.ManagedControlPlaneScopeParams{ @@ -881,7 +881,7 @@ func (r *AWSMachineReconciler) getInfraCluster(ctx context.Context, log logr.Log if err := r.Client.Get(ctx, infraClusterName, awsCluster); err != nil { // AWSCluster is not ready - return nil, nil + return nil, nil // nolint:nilerr } // Create the cluster scope diff --git a/controllers/awsmachine_controller_test.go b/controllers/awsmachine_controller_test.go index 47e059a5b6..e73d02fefd 100644 --- a/controllers/awsmachine_controller_test.go +++ b/controllers/awsmachine_controller_test.go @@ -27,6 +27,8 @@ import ( . "github.com/onsi/gomega" . "github.com/onsi/gomega/gstruct" + "testing" + "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -44,7 +46,6 @@ import ( capierrors "sigs.k8s.io/cluster-api/errors" "sigs.k8s.io/cluster-api/util/conditions" "sigs.k8s.io/controller-runtime/pkg/client/fake" - "testing" ) func TestAWSMachineReconciler(t *testing.T) { @@ -218,7 +219,6 @@ func TestAWSMachineReconciler(t *testing.T) { g.Expect(err).To(BeNil()) g.Expect(buf.String()).To(ContainSubstring("Cluster infrastructure is not ready yet")) expectConditions(g, ms.AWSMachine, []conditionAssertion{{infrav1.InstanceReadyCondition, corev1.ConditionFalse, clusterv1.ConditionSeverityInfo, infrav1.WaitingForClusterInfrastructureReason}}) - }) t.Run("should exit immediately if bootstrap data secret reference isn't available", func(t *testing.T) { @@ -302,7 +302,6 @@ func TestAWSMachineReconciler(t *testing.T) { } t.Run("instance security group errors", func(t *testing.T) { - var buf *bytes.Buffer getInstanceSecurityGroups := func(t *testing.T, g *WithT) { buf = new(bytes.Buffer) @@ -381,7 +380,6 @@ func TestAWSMachineReconciler(t *testing.T) { Return(map[string][]string{"eid": {}}, nil) secretSvc.EXPECT().UserData(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil, nil).Times(1) ec2Svc.EXPECT().GetCoreSecurityGroups(gomock.Any()).Return([]string{}, nil) - } t.Run("should reconcile security groups", func(t *testing.T) { g := NewWithT(t) @@ -400,7 +398,6 @@ func TestAWSMachineReconciler(t *testing.T) { _, _ = reconciler.reconcileNormal(context.Background(), ms, cs, cs, cs) expectConditions(g, ms.AWSMachine, []conditionAssertion{{conditionType: infrav1.SecurityGroupsReadyCondition, status: corev1.ConditionTrue}}) - }) t.Run("should not tag anything if there's not tags", func(t *testing.T) { @@ -438,7 +435,6 @@ func TestAWSMachineReconciler(t *testing.T) { _, err := reconciler.reconcileNormal(context.Background(), ms, cs, cs, cs) g.Expect(err).To(BeNil()) }) - }) t.Run("temporarily stopping then starting the AWSMachine", func(t *testing.T) { var buf *bytes.Buffer @@ -494,7 +490,6 @@ func TestAWSMachineReconciler(t *testing.T) { g.Expect(ms.AWSMachine.Status.Ready).To(Equal(true)) g.Expect(buf.String()).To(ContainSubstring(("EC2 instance state changed"))) }) - }) t.Run("deleting the AWSMachine outside of Kubernetes", func(t *testing.T) { var buf *bytes.Buffer @@ -533,9 +528,7 @@ func TestAWSMachineReconciler(t *testing.T) { g.Expect(ms.AWSMachine.Status.FailureMessage).To(PointTo(Equal("EC2 instance state \"terminated\" is unexpected"))) expectConditions(g, ms.AWSMachine, []conditionAssertion{{infrav1.InstanceReadyCondition, corev1.ConditionFalse, clusterv1.ConditionSeverityError, infrav1.InstanceTerminatedReason}}) }) - }) - }) }) @@ -920,7 +913,6 @@ func TestAWSMachineReconciler(t *testing.T) { g.Expect(err).To(BeNil()) g.Expect(ms.AWSMachine.Finalizers).To(ConsistOf(metav1.FinalizerDeleteDependents)) }) - }) }) }) diff --git a/controllers/awsmachine_controller_unit_test.go b/controllers/awsmachine_controller_unit_test.go index 9b838da601..1762f9fb83 100644 --- a/controllers/awsmachine_controller_unit_test.go +++ b/controllers/awsmachine_controller_unit_test.go @@ -22,7 +22,7 @@ import ( . "github.com/onsi/gomega" - v1 "k8s.io/api/core/v1" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/klog/v2/klogr" infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" @@ -43,7 +43,7 @@ func newMachine(clusterName, machineName string) *clusterv1.Machine { func newMachineWithInfrastructureRef(clusterName, machineName string) *clusterv1.Machine { m := newMachine(clusterName, machineName) - m.Spec.InfrastructureRef = v1.ObjectReference{ + m.Spec.InfrastructureRef = corev1.ObjectReference{ Kind: "AWSMachine", Namespace: "", Name: "aws" + machineName, @@ -76,17 +76,17 @@ func TestAWSMachineReconciler_AWSClusterToAWSMachines(t *testing.T) { } requests := reconciler.AWSClusterToAWSMachines(klogr.New())(&infrav1.AWSCluster{ - ObjectMeta: metav1.ObjectMeta{ - Name: clusterName, - Namespace: "default", - OwnerReferences: []metav1.OwnerReference{ - { - Name: clusterName, - Kind: "Cluster", - APIVersion: clusterv1.GroupVersion.String(), - }, + ObjectMeta: metav1.ObjectMeta{ + Name: clusterName, + Namespace: "default", + OwnerReferences: []metav1.OwnerReference{ + { + Name: clusterName, + Kind: "Cluster", + APIVersion: clusterv1.GroupVersion.String(), }, }, + }, }) if len(requests) != 2 { t.Fatalf("Expected 2 but found %d requests", len(requests)) diff --git a/controllers/awsmachine_security_groups.go b/controllers/awsmachine_security_groups.go index 48699e2b1d..1dc9f155a9 100644 --- a/controllers/awsmachine_security_groups.go +++ b/controllers/awsmachine_security_groups.go @@ -51,7 +51,7 @@ func (r *AWSMachineReconciler) ensureSecurityGroups(ec2svc service.EC2MachineInt additionalSecurityGroupsIDs, err := r.getAdditionalSecurityGroupsIDs(ec2svc, additional) if err != nil { - return false, nil + return false, nil // nolint:nilerr } changed, ids := r.securityGroupsChanged(annotation, core, additionalSecurityGroupsIDs, existing) diff --git a/controlplane/eks/api/v1alpha3/awsmanagedcontrolplane_types.go b/controlplane/eks/api/v1alpha3/awsmanagedcontrolplane_types.go index d100097253..f87f183c34 100644 --- a/controlplane/eks/api/v1alpha3/awsmanagedcontrolplane_types.go +++ b/controlplane/eks/api/v1alpha3/awsmanagedcontrolplane_types.go @@ -23,7 +23,7 @@ import ( ) const ( - // ManagedControlPlaneFinalizer allows the controller to clean up resources on delete + // ManagedControlPlaneFinalizer allows the controller to clean up resources on delete. ManagedControlPlaneFinalizer = "awsmanagedcontrolplane.controlplane.cluster.x-k8s.io" ) @@ -162,7 +162,7 @@ type AWSManagedControlPlaneSpec struct { //nolint: maligned DisableVPCCNI bool `json:"disableVPCCNI,omitempty"` } -// EndpointAccess specifies how control plane endpoints are accessible +// EndpointAccess specifies how control plane endpoints are accessible. type EndpointAccess struct { // Public controls whether control plane endpoints are publicly accessible // +optional @@ -175,15 +175,15 @@ type EndpointAccess struct { Private *bool `json:"private,omitempty"` } -// EncryptionConfig specifies the encryption configuration for the EKS clsuter +// EncryptionConfig specifies the encryption configuration for the EKS clsuter. type EncryptionConfig struct { // Provider specifies the ARN or alias of the CMK (in AWS KMS) Provider *string `json:"provider,omitempty"` - //Resources specifies the resources to be encrypted + // Resources specifies the resources to be encrypted Resources []*string `json:"resources,omitempty"` } -// OIDCProviderStatus holds the status of the AWS OIDC identity provider +// OIDCProviderStatus holds the status of the AWS OIDC identity provider. type OIDCProviderStatus struct { // ARN holds the ARN of the provider ARN string `json:"arn,omitempty"` @@ -249,19 +249,19 @@ type AWSManagedControlPlane struct { // +kubebuilder:object:root=true -// AWSManagedControlPlaneList contains a list of AWSManagedControlPlane +// AWSManagedControlPlaneList contains a list of AWSManagedControlPlane. type AWSManagedControlPlaneList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []AWSManagedControlPlane `json:"items"` } -// GetConditions returns the control planes conditions +// GetConditions returns the control planes conditions. func (r *AWSManagedControlPlane) GetConditions() clusterv1.Conditions { return r.Status.Conditions } -// SetConditions sets the status conditions for the AWSManagedControlPlane +// SetConditions sets the status conditions for the AWSManagedControlPlane. func (r *AWSManagedControlPlane) SetConditions(conditions clusterv1.Conditions) { r.Status.Conditions = conditions } diff --git a/controlplane/eks/api/v1alpha3/conditions_consts.go b/controlplane/eks/api/v1alpha3/conditions_consts.go index 595956aeec..06befb9eb7 100644 --- a/controlplane/eks/api/v1alpha3/conditions_consts.go +++ b/controlplane/eks/api/v1alpha3/conditions_consts.go @@ -22,32 +22,32 @@ const ( // EKSControlPlaneReadyCondition condition reports on the successful reconciliation of eks control plane. EKSControlPlaneReadyCondition clusterv1.ConditionType = "EKSControlPlaneReady" // EKSControlPlaneCreatingCondition condition reports on whether the eks - // control plane is creating + // control plane is creating. EKSControlPlaneCreatingCondition clusterv1.ConditionType = "EKSControlPlaneCreating" // EKSControlPlaneUpdatingCondition condition reports on whether the eks - // control plane is updating + // control plane is updating. EKSControlPlaneUpdatingCondition clusterv1.ConditionType = "EKSControlPlaneUpdating" - // EKSControlPlaneReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSControlPlaneReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSControlPlaneReconciliationFailedReason = "EKSControlPlaneReconciliationFailed" ) const ( // IAMControlPlaneRolesReadyCondition condition reports on the successful reconciliation of eks control plane iam roles. IAMControlPlaneRolesReadyCondition clusterv1.ConditionType = "IAMControlPlaneRolesReady" - // IAMControlPlaneRolesReconciliationFailedReason used to report failures while reconciling EKS control plane iam roles + // IAMControlPlaneRolesReconciliationFailedReason used to report failures while reconciling EKS control plane iam roles. IAMControlPlaneRolesReconciliationFailedReason = "IAMControlPlaneRolesReconciliationFailed" ) const ( - // IAMAuthenticatorConfiguredCondition condition reports on the successful reconciliation of aws-iam-authenticator config + // IAMAuthenticatorConfiguredCondition condition reports on the successful reconciliation of aws-iam-authenticator config. IAMAuthenticatorConfiguredCondition clusterv1.ConditionType = "IAMAuthenticatorConfigured" - // IAMAuthenticatorConfigurationFailedReason used to report failures while reconciling the aws-iam-authenticator config + // IAMAuthenticatorConfigurationFailedReason used to report failures while reconciling the aws-iam-authenticator config. IAMAuthenticatorConfigurationFailedReason = "IAMAuthenticatorConfigurationFailed" ) const ( - // EKSAddonsConfiguredCondition condition reports on the successful reconciliation of EKS addons + // EKSAddonsConfiguredCondition condition reports on the successful reconciliation of EKS addons. EKSAddonsConfiguredCondition clusterv1.ConditionType = "EKSAddonsConfigured" - // EKSAddonsConfiguredFailedReason used to report failures while reconciling the EKS addons + // EKSAddonsConfiguredFailedReason used to report failures while reconciling the EKS addons. EKSAddonsConfiguredFailedReason = "EKSAddonsConfiguredFailed" ) diff --git a/controlplane/eks/api/v1alpha3/conversion_test.go b/controlplane/eks/api/v1alpha3/conversion_test.go index af8cde8610..b2a07541b5 100644 --- a/controlplane/eks/api/v1alpha3/conversion_test.go +++ b/controlplane/eks/api/v1alpha3/conversion_test.go @@ -34,7 +34,7 @@ func TestFuzzyConversion(t *testing.T) { t.Run("for AWSManagedControlPlane", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.AWSManagedControlPlane{}, - Spoke: &AWSManagedControlPlane{}, + Hub: &v1alpha4.AWSManagedControlPlane{}, + Spoke: &AWSManagedControlPlane{}, })) } diff --git a/controlplane/eks/api/v1alpha3/doc.go b/controlplane/eks/api/v1alpha3/doc.go index 81f5a95fff..489614382f 100644 --- a/controlplane/eks/api/v1alpha3/doc.go +++ b/controlplane/eks/api/v1alpha3/doc.go @@ -15,4 +15,5 @@ limitations under the License. */ // +k8s:conversion-gen=sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1alpha4 + package v1alpha3 diff --git a/controlplane/eks/api/v1alpha3/groupversion_info.go b/controlplane/eks/api/v1alpha3/groupversion_info.go index 9f59d272ad..642b770599 100644 --- a/controlplane/eks/api/v1alpha3/groupversion_info.go +++ b/controlplane/eks/api/v1alpha3/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1alpha3"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/controlplane/eks/api/v1alpha3/types.go b/controlplane/eks/api/v1alpha3/types.go index bc8c14572d..403f6f6046 100644 --- a/controlplane/eks/api/v1alpha3/types.go +++ b/controlplane/eks/api/v1alpha3/types.go @@ -26,7 +26,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha3" ) -// ControlPlaneLoggingSpec defines what EKS control plane logs that should be enabled +// ControlPlaneLoggingSpec defines what EKS control plane logs that should be enabled. type ControlPlaneLoggingSpec struct { // APIServer indicates if the Kubernetes API Server log (kube-apiserver) shoulkd be enabled // +kubebuilder:default=false @@ -37,7 +37,7 @@ type ControlPlaneLoggingSpec struct { // Authenticator indicates if the iam authenticator log should be enabled // +kubebuilder:default=false Authenticator bool `json:"authenticator"` - //ControllerManager indicates if the controller manager (kube-controller-manager) log should be enabled + // ControllerManager indicates if the controller manager (kube-controller-manager) log should be enabled // +kubebuilder:default=false ControllerManager bool `json:"controllerManager"` // Scheduler indicates if the Kubernetes scheduler (kube-scheduler) log should be enabled @@ -45,7 +45,7 @@ type ControlPlaneLoggingSpec struct { Scheduler bool `json:"scheduler"` } -// IsLogEnabled returns true if the log is enabled +// IsLogEnabled returns true if the log is enabled. func (s *ControlPlaneLoggingSpec) IsLogEnabled(logName string) bool { if s == nil { return false @@ -71,22 +71,22 @@ func (s *ControlPlaneLoggingSpec) IsLogEnabled(logName string) bool { type EKSTokenMethod string var ( - // EKSTokenMethodIAMAuthenticator indicates that IAM autenticator will be used to get a token + // EKSTokenMethodIAMAuthenticator indicates that IAM autenticator will be used to get a token. EKSTokenMethodIAMAuthenticator = EKSTokenMethod("iam-authenticator") // EKSTokenMethodAWSCli indicates that the AWS CLI will be used to get a token - // Version 1.16.156 or greater is required of the AWS CLI + // Version 1.16.156 or greater is required of the AWS CLI. EKSTokenMethodAWSCli = EKSTokenMethod("aws-cli") ) var ( // DefaultEKSControlPlaneRole is the name of the default IAM role to use for the EKS control plane // if no other role is supplied in the spec and if iam role creation is not enabled. The default - // can be created using clusterawsadm or created manually + // can be created using clusterawsadm or created manually. DefaultEKSControlPlaneRole = fmt.Sprintf("eks-controlplane%s", infrav1.DefaultNameSuffix) ) -// IAMAuthenticatorConfig represents an aws-iam-authenticator configuration +// IAMAuthenticatorConfig represents an aws-iam-authenticator configuration. type IAMAuthenticatorConfig struct { // RoleMappings is a list of role mappings // +optional @@ -96,7 +96,7 @@ type IAMAuthenticatorConfig struct { UserMappings []UserMapping `json:"mapUsers,omitempty"` } -// KubernetesMapping represents the kubernetes RBAC mapping +// KubernetesMapping represents the kubernetes RBAC mapping. type KubernetesMapping struct { // UserName is a kubernetes RBAC user subject UserName string `json:"username"` @@ -140,42 +140,42 @@ type Addon struct { ServiceAccountRoleArn *string `json:"serviceAccountRoleARN,omitempty"` } -// AddonResolution defines the method for resolving parameter conflicts +// AddonResolution defines the method for resolving parameter conflicts. type AddonResolution string var ( // AddonResolutionOverwrite indicates that if there are parameter conflicts then - // resolution will be accomplished via overwriting + // resolution will be accomplished via overwriting. AddonResolutionOverwrite = AddonResolution("overwrite") // AddonResolutionNone indicates that if there are parameter conflicts then - // resolution will not be done and an error will be reported + // resolution will not be done and an error will be reported. AddonResolutionNone = AddonResolution("none") ) -// AddonStatus defines the status for an addon +// AddonStatus defines the status for an addon. type AddonStatus string var ( - // AddonStatusCreating is a status to indicate the addon is creating + // AddonStatusCreating is a status to indicate the addon is creating. AddonStatusCreating = "creating" - // AddonStatusActive is a status to indicate the addon is active + // AddonStatusActive is a status to indicate the addon is active. AddonStatusActive = "active" - // AddonStatusCreateFailed is a status to indicate the addon failed creation + // AddonStatusCreateFailed is a status to indicate the addon failed creation. AddonStatusCreateFailed = "create_failed" - // AddonStatusUpdating is a status to indicate the addon is updating + // AddonStatusUpdating is a status to indicate the addon is updating. AddonStatusUpdating = "updating" - // AddonStatusDeleting is a status to indicate the addon is deleting + // AddonStatusDeleting is a status to indicate the addon is deleting. AddonStatusDeleting = "deleting" - // AddonStatusDeleteFailed is a status to indicate the addon failed deletion + // AddonStatusDeleteFailed is a status to indicate the addon failed deletion. AddonStatusDeleteFailed = "delete_failed" - // AddonStatusDegraded is a status to indicate the addon is in a degraded state + // AddonStatusDegraded is a status to indicate the addon is in a degraded state. AddonStatusDegraded = "degraded" ) @@ -211,6 +211,6 @@ type AddonIssue struct { const ( // SecurityGroupCluster is the security group for communication between EKS - // control plane and managed node groups + // control plane and managed node groups. SecurityGroupCluster = infrav1.SecurityGroupRole("cluster") ) diff --git a/controlplane/eks/api/v1alpha3/validate.go b/controlplane/eks/api/v1alpha3/validate.go index 73557297f5..d182bd6faf 100644 --- a/controlplane/eks/api/v1alpha3/validate.go +++ b/controlplane/eks/api/v1alpha3/validate.go @@ -34,7 +34,7 @@ var ( ErrIsNotUserARN = errors.New("supplied ARN is not a user ARN") ) -// Validate will return nil is there are no errors with the role mapping +// Validate will return nil is there are no errors with the role mapping. func (r *RoleMapping) Validate() []error { errs := []error{} @@ -66,7 +66,7 @@ func (r *RoleMapping) Validate() []error { return errs } -// Validate will return nil is there are no errors with the user mapping +// Validate will return nil is there are no errors with the user mapping. func (u *UserMapping) Validate() []error { errs := []error{} diff --git a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_types.go b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_types.go index 5103d64b65..66c47e6a5a 100644 --- a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_types.go +++ b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_types.go @@ -23,7 +23,7 @@ import ( ) const ( - // ManagedControlPlaneFinalizer allows the controller to clean up resources on delete + // ManagedControlPlaneFinalizer allows the controller to clean up resources on delete. ManagedControlPlaneFinalizer = "awsmanagedcontrolplane.controlplane.cluster.x-k8s.io" ) @@ -162,7 +162,7 @@ type AWSManagedControlPlaneSpec struct { //nolint: maligned DisableVPCCNI bool `json:"disableVPCCNI,omitempty"` } -// EndpointAccess specifies how control plane endpoints are accessible +// EndpointAccess specifies how control plane endpoints are accessible. type EndpointAccess struct { // Public controls whether control plane endpoints are publicly accessible // +optional @@ -175,15 +175,15 @@ type EndpointAccess struct { Private *bool `json:"private,omitempty"` } -// EncryptionConfig specifies the encryption configuration for the EKS clsuter +// EncryptionConfig specifies the encryption configuration for the EKS clsuter. type EncryptionConfig struct { // Provider specifies the ARN or alias of the CMK (in AWS KMS) Provider *string `json:"provider,omitempty"` - //Resources specifies the resources to be encrypted + // Resources specifies the resources to be encrypted Resources []*string `json:"resources,omitempty"` } -// OIDCProviderStatus holds the status of the AWS OIDC identity provider +// OIDCProviderStatus holds the status of the AWS OIDC identity provider. type OIDCProviderStatus struct { // ARN holds the ARN of the provider ARN string `json:"arn,omitempty"` @@ -250,19 +250,19 @@ type AWSManagedControlPlane struct { // +kubebuilder:object:root=true -// AWSManagedControlPlaneList contains a list of AWSManagedControlPlane +// AWSManagedControlPlaneList contains a list of AWSManagedControlPlane. type AWSManagedControlPlaneList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []AWSManagedControlPlane `json:"items"` } -// GetConditions returns the control planes conditions +// GetConditions returns the control planes conditions. func (r *AWSManagedControlPlane) GetConditions() clusterv1.Conditions { return r.Status.Conditions } -// SetConditions sets the status conditions for the AWSManagedControlPlane +// SetConditions sets the status conditions for the AWSManagedControlPlane. func (r *AWSManagedControlPlane) SetConditions(conditions clusterv1.Conditions) { r.Status.Conditions = conditions } diff --git a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook.go b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook.go index f6216f3691..1975bf3de4 100644 --- a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook.go +++ b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook.go @@ -47,7 +47,7 @@ const ( vpcCniAddon = "vpc-cni" ) -// SetupWebhookWithManager will setup the webhooks for the AWSManagedControlPlane +// SetupWebhookWithManager will setup the webhooks for the AWSManagedControlPlane. func (r *AWSManagedControlPlane) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -77,7 +77,7 @@ func normalizeVersion(raw string) (string, error) { return fmt.Sprintf("v%d.%d", eksV.Major(), eksV.Minor()), nil } -// ValidateCreate will do any extra validation when creating a AWSManagedControlPlane +// ValidateCreate will do any extra validation when creating a AWSManagedControlPlane. func (r *AWSManagedControlPlane) ValidateCreate() error { mcpLog.Info("AWSManagedControlPlane validate create", "name", r.Name) @@ -105,7 +105,7 @@ func (r *AWSManagedControlPlane) ValidateCreate() error { ) } -// ValidateUpdate will do any extra validation when updating a AWSManagedControlPlane +// ValidateUpdate will do any extra validation when updating a AWSManagedControlPlane. func (r *AWSManagedControlPlane) ValidateUpdate(old runtime.Object) error { mcpLog.Info("AWSManagedControlPlane validate update", "name", r.Name) oldAWSManagedControlplane, ok := old.(*AWSManagedControlPlane) @@ -150,7 +150,7 @@ func (r *AWSManagedControlPlane) ValidateUpdate(old runtime.Object) error { ) } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *AWSManagedControlPlane) ValidateDelete() error { mcpLog.Info("AWSManagedControlPlane validate delete", "name", r.Name) @@ -311,7 +311,7 @@ func (r *AWSManagedControlPlane) validateDisableVPCCNI() field.ErrorList { return allErrs } -// Default will set default values for the AWSManagedControlPlane +// Default will set default values for the AWSManagedControlPlane. func (r *AWSManagedControlPlane) Default() { mcpLog.Info("AWSManagedControlPlane setting defaults", "name", r.Name) diff --git a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook_test.go b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook_test.go index 48c89e31e1..43e30bc772 100644 --- a/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook_test.go +++ b/controlplane/eks/api/v1alpha4/awsmanagedcontrolplane_webhook_test.go @@ -164,7 +164,7 @@ func TestDefaultingWebhook(t *testing.T) { } func TestWebhookCreate(t *testing.T) { - tests := []struct { + tests := []struct { //nolint:maligned name string eksClusterName string expectError bool diff --git a/controlplane/eks/api/v1alpha4/conditions_consts.go b/controlplane/eks/api/v1alpha4/conditions_consts.go index 161882b65f..44d3394fee 100644 --- a/controlplane/eks/api/v1alpha4/conditions_consts.go +++ b/controlplane/eks/api/v1alpha4/conditions_consts.go @@ -22,32 +22,32 @@ const ( // EKSControlPlaneReadyCondition condition reports on the successful reconciliation of eks control plane. EKSControlPlaneReadyCondition clusterv1.ConditionType = "EKSControlPlaneReady" // EKSControlPlaneCreatingCondition condition reports on whether the eks - // control plane is creating + // control plane is creating. EKSControlPlaneCreatingCondition clusterv1.ConditionType = "EKSControlPlaneCreating" // EKSControlPlaneUpdatingCondition condition reports on whether the eks - // control plane is updating + // control plane is updating. EKSControlPlaneUpdatingCondition clusterv1.ConditionType = "EKSControlPlaneUpdating" - // EKSControlPlaneReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSControlPlaneReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSControlPlaneReconciliationFailedReason = "EKSControlPlaneReconciliationFailed" ) const ( // IAMControlPlaneRolesReadyCondition condition reports on the successful reconciliation of eks control plane iam roles. IAMControlPlaneRolesReadyCondition clusterv1.ConditionType = "IAMControlPlaneRolesReady" - // IAMControlPlaneRolesReconciliationFailedReason used to report failures while reconciling EKS control plane iam roles + // IAMControlPlaneRolesReconciliationFailedReason used to report failures while reconciling EKS control plane iam roles. IAMControlPlaneRolesReconciliationFailedReason = "IAMControlPlaneRolesReconciliationFailed" ) const ( - // IAMAuthenticatorConfiguredCondition condition reports on the successful reconciliation of aws-iam-authenticator config + // IAMAuthenticatorConfiguredCondition condition reports on the successful reconciliation of aws-iam-authenticator config. IAMAuthenticatorConfiguredCondition clusterv1.ConditionType = "IAMAuthenticatorConfigured" - // IAMAuthenticatorConfigurationFailedReason used to report failures while reconciling the aws-iam-authenticator config + // IAMAuthenticatorConfigurationFailedReason used to report failures while reconciling the aws-iam-authenticator config. IAMAuthenticatorConfigurationFailedReason = "IAMAuthenticatorConfigurationFailed" ) const ( - // EKSAddonsConfiguredCondition condition reports on the successful reconciliation of EKS addons + // EKSAddonsConfiguredCondition condition reports on the successful reconciliation of EKS addons. EKSAddonsConfiguredCondition clusterv1.ConditionType = "EKSAddonsConfigured" - // EKSAddonsConfiguredFailedReason used to report failures while reconciling the EKS addons + // EKSAddonsConfiguredFailedReason used to report failures while reconciling the EKS addons. EKSAddonsConfiguredFailedReason = "EKSAddonsConfiguredFailed" ) diff --git a/controlplane/eks/api/v1alpha4/groupversion_info.go b/controlplane/eks/api/v1alpha4/groupversion_info.go index 8c080ac633..cc3b075d31 100644 --- a/controlplane/eks/api/v1alpha4/groupversion_info.go +++ b/controlplane/eks/api/v1alpha4/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "controlplane.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/controlplane/eks/api/v1alpha4/suite_test.go b/controlplane/eks/api/v1alpha4/suite_test.go index f3e0974244..82c11b5716 100644 --- a/controlplane/eks/api/v1alpha4/suite_test.go +++ b/controlplane/eks/api/v1alpha4/suite_test.go @@ -68,4 +68,3 @@ func teardown() { panic(fmt.Sprintf("Failed to stop envtest: %v", err)) } } - diff --git a/controlplane/eks/api/v1alpha4/types.go b/controlplane/eks/api/v1alpha4/types.go index c5ca247e07..278087e005 100644 --- a/controlplane/eks/api/v1alpha4/types.go +++ b/controlplane/eks/api/v1alpha4/types.go @@ -26,7 +26,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" ) -// ControlPlaneLoggingSpec defines what EKS control plane logs that should be enabled +// ControlPlaneLoggingSpec defines what EKS control plane logs that should be enabled. type ControlPlaneLoggingSpec struct { // APIServer indicates if the Kubernetes API Server log (kube-apiserver) shoulkd be enabled // +kubebuilder:default=false @@ -37,7 +37,7 @@ type ControlPlaneLoggingSpec struct { // Authenticator indicates if the iam authenticator log should be enabled // +kubebuilder:default=false Authenticator bool `json:"authenticator"` - //ControllerManager indicates if the controller manager (kube-controller-manager) log should be enabled + // ControllerManager indicates if the controller manager (kube-controller-manager) log should be enabled // +kubebuilder:default=false ControllerManager bool `json:"controllerManager"` // Scheduler indicates if the Kubernetes scheduler (kube-scheduler) log should be enabled @@ -45,7 +45,7 @@ type ControlPlaneLoggingSpec struct { Scheduler bool `json:"scheduler"` } -// IsLogEnabled returns true if the log is enabled +// IsLogEnabled returns true if the log is enabled. func (s *ControlPlaneLoggingSpec) IsLogEnabled(logName string) bool { if s == nil { return false @@ -71,22 +71,22 @@ func (s *ControlPlaneLoggingSpec) IsLogEnabled(logName string) bool { type EKSTokenMethod string var ( - // EKSTokenMethodIAMAuthenticator indicates that IAM autenticator will be used to get a token + // EKSTokenMethodIAMAuthenticator indicates that IAM autenticator will be used to get a token. EKSTokenMethodIAMAuthenticator = EKSTokenMethod("iam-authenticator") // EKSTokenMethodAWSCli indicates that the AWS CLI will be used to get a token - // Version 1.16.156 or greater is required of the AWS CLI + // Version 1.16.156 or greater is required of the AWS CLI. EKSTokenMethodAWSCli = EKSTokenMethod("aws-cli") ) var ( // DefaultEKSControlPlaneRole is the name of the default IAM role to use for the EKS control plane // if no other role is supplied in the spec and if iam role creation is not enabled. The default - // can be created using clusterawsadm or created manually + // can be created using clusterawsadm or created manually. DefaultEKSControlPlaneRole = fmt.Sprintf("eks-controlplane%s", infrav1.DefaultNameSuffix) ) -// IAMAuthenticatorConfig represents an aws-iam-authenticator configuration +// IAMAuthenticatorConfig represents an aws-iam-authenticator configuration. type IAMAuthenticatorConfig struct { // RoleMappings is a list of role mappings // +optional @@ -96,7 +96,7 @@ type IAMAuthenticatorConfig struct { UserMappings []UserMapping `json:"mapUsers,omitempty"` } -// KubernetesMapping represents the kubernetes RBAC mapping +// KubernetesMapping represents the kubernetes RBAC mapping. type KubernetesMapping struct { // UserName is a kubernetes RBAC user subject UserName string `json:"username"` @@ -140,42 +140,42 @@ type Addon struct { ServiceAccountRoleArn *string `json:"serviceAccountRoleARN,omitempty"` } -// AddonResolution defines the method for resolving parameter conflicts +// AddonResolution defines the method for resolving parameter conflicts. type AddonResolution string var ( // AddonResolutionOverwrite indicates that if there are parameter conflicts then - // resolution will be accomplished via overwriting + // resolution will be accomplished via overwriting. AddonResolutionOverwrite = AddonResolution("overwrite") // AddonResolutionNone indicates that if there are parameter conflicts then - // resolution will not be done and an error will be reported + // resolution will not be done and an error will be reported. AddonResolutionNone = AddonResolution("none") ) -// AddonStatus defines the status for an addon +// AddonStatus defines the status for an addon. type AddonStatus string var ( - // AddonStatusCreating is a status to indicate the addon is creating + // AddonStatusCreating is a status to indicate the addon is creating. AddonStatusCreating = "creating" - // AddonStatusActive is a status to indicate the addon is active + // AddonStatusActive is a status to indicate the addon is active. AddonStatusActive = "active" - // AddonStatusCreateFailed is a status to indicate the addon failed creation + // AddonStatusCreateFailed is a status to indicate the addon failed creation. AddonStatusCreateFailed = "create_failed" - // AddonStatusUpdating is a status to indicate the addon is updating + // AddonStatusUpdating is a status to indicate the addon is updating. AddonStatusUpdating = "updating" - // AddonStatusDeleting is a status to indicate the addon is deleting + // AddonStatusDeleting is a status to indicate the addon is deleting. AddonStatusDeleting = "deleting" - // AddonStatusDeleteFailed is a status to indicate the addon failed deletion + // AddonStatusDeleteFailed is a status to indicate the addon failed deletion. AddonStatusDeleteFailed = "delete_failed" - // AddonStatusDegraded is a status to indicate the addon is in a degraded state + // AddonStatusDegraded is a status to indicate the addon is in a degraded state. AddonStatusDegraded = "degraded" ) @@ -211,6 +211,6 @@ type AddonIssue struct { const ( // SecurityGroupCluster is the security group for communication between EKS - // control plane and managed node groups + // control plane and managed node groups. SecurityGroupCluster = infrav1.SecurityGroupRole("cluster") ) diff --git a/controlplane/eks/api/v1alpha4/validate.go b/controlplane/eks/api/v1alpha4/validate.go index 7c95b900b6..76ca15f418 100644 --- a/controlplane/eks/api/v1alpha4/validate.go +++ b/controlplane/eks/api/v1alpha4/validate.go @@ -34,7 +34,7 @@ var ( ErrIsNotUserARN = errors.New("supplied ARN is not a user ARN") ) -// Validate will return nil is there are no errors with the role mapping +// Validate will return nil is there are no errors with the role mapping. func (r *RoleMapping) Validate() []error { errs := []error{} @@ -66,7 +66,7 @@ func (r *RoleMapping) Validate() []error { return errs } -// Validate will return nil is there are no errors with the user mapping +// Validate will return nil is there are no errors with the user mapping. func (u *UserMapping) Validate() []error { errs := []error{} diff --git a/controlplane/eks/controllers/awsmanagedcontrolplane_controller.go b/controlplane/eks/controllers/awsmanagedcontrolplane_controller.go index f3500113db..3dc1402eb0 100644 --- a/controlplane/eks/controllers/awsmanagedcontrolplane_controller.go +++ b/controlplane/eks/controllers/awsmanagedcontrolplane_controller.go @@ -57,7 +57,7 @@ const ( deleteRequeueAfter = 20 * time.Second ) -// AWSManagedControlPlaneReconciler reconciles a AWSManagedControlPlane object +// AWSManagedControlPlaneReconciler reconciles a AWSManagedControlPlane object. type AWSManagedControlPlaneReconciler struct { client.Client Recorder record.EventRecorder @@ -68,7 +68,7 @@ type AWSManagedControlPlaneReconciler struct { WatchFilterValue string } -// SetupWithManager is used to setup the controller +// SetupWithManager is used to setup the controller. func (r *AWSManagedControlPlaneReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error { log := ctrl.LoggerFrom(ctx) @@ -110,7 +110,7 @@ func (r *AWSManagedControlPlaneReconciler) SetupWithManager(ctx context.Context, // +kubebuilder:rbac:groups=controlplane.cluster.x-k8s.io,resources=awsmanagedcontrolplanes/status,verbs=get;update;patch // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=awsclusterroleidentities;awsclusterstaticidentities;awsclustercontrolleridentities,verbs=get;list;watch -// Reconcile will reconcile AWSManagedControlPlane Resources +// Reconcile will reconcile AWSManagedControlPlane Resources. func (r *AWSManagedControlPlaneReconciler) Reconcile(ctx context.Context, req ctrl.Request) (res ctrl.Result, reterr error) { log := ctrl.LoggerFrom(ctx) diff --git a/docs/book/cmd/clusterawsadmdocs/main.go b/docs/book/cmd/clusterawsadmdocs/main.go index fca29331e0..007fa0e997 100644 --- a/docs/book/cmd/clusterawsadmdocs/main.go +++ b/docs/book/cmd/clusterawsadmdocs/main.go @@ -67,7 +67,6 @@ func commandSummary(tree commandLeaf, prefix int) { } func buildCommandTree(tree commandLeaf, cmd *cobra.Command) { - children := cmd.Commands() sort.Sort(byName(children)) diff --git a/exp/api/v1alpha3/awsfargateprofile_types.go b/exp/api/v1alpha3/awsfargateprofile_types.go index fbb4981d3e..5068e3a5fb 100644 --- a/exp/api/v1alpha3/awsfargateprofile_types.go +++ b/exp/api/v1alpha3/awsfargateprofile_types.go @@ -27,14 +27,14 @@ import ( ) const ( - // FargateProfileFinalizer allows the controller to clean up resources on delete + // FargateProfileFinalizer allows the controller to clean up resources on delete. FargateProfileFinalizer = "awsfargateprofile.infrastructure.cluster.x-k8s.io" ) var ( // DefaultEKSFargateRole is the name of the default IAM role to use for fargate // profiles if no other role is supplied in the spec and if iam role creation - // is not enabled. The default can be created using clusterawsadm or created manually + // is not enabled. The default can be created using clusterawsadm or created manually. DefaultEKSFargateRole = fmt.Sprintf("eks-fargate%s", infrav1.DefaultNameSuffix) ) @@ -155,7 +155,7 @@ func (r *AWSFargateProfile) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSFargateProfileList contains a list of FargateProfiles +// AWSFargateProfileList contains a list of FargateProfiles. type AWSFargateProfileList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha3/awsmachinepool_types.go b/exp/api/v1alpha3/awsmachinepool_types.go index dfce90775f..5809164153 100644 --- a/exp/api/v1alpha3/awsmachinepool_types.go +++ b/exp/api/v1alpha3/awsmachinepool_types.go @@ -24,6 +24,7 @@ import ( "sigs.k8s.io/cluster-api/errors" ) +// Constants. const ( // MachinePoolFinalizer is the finalizer for the machine pool. MachinePoolFinalizer = "awsmachinepool.infrastructure.cluster.x-k8s.io" @@ -199,7 +200,7 @@ type AWSMachinePool struct { // +kubebuilder:object:root=true -// AWSMachinePoolList contains a list of AWSMachinePool +// AWSMachinePoolList contains a list of AWSMachinePool. type AWSMachinePoolList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha3/awsmanagedcluster_types.go b/exp/api/v1alpha3/awsmanagedcluster_types.go index 073155e693..d569457a94 100644 --- a/exp/api/v1alpha3/awsmanagedcluster_types.go +++ b/exp/api/v1alpha3/awsmanagedcluster_types.go @@ -58,7 +58,7 @@ type AWSManagedCluster struct { // +kubebuilder:object:root=true -// AWSManagedClusterList contains a list of AWSManagedCluster +// AWSManagedClusterList contains a list of AWSManagedCluster. type AWSManagedClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha3/awsmanagedmachinepool_types.go b/exp/api/v1alpha3/awsmanagedmachinepool_types.go index 4595834bf3..ef884ac76d 100644 --- a/exp/api/v1alpha3/awsmanagedmachinepool_types.go +++ b/exp/api/v1alpha3/awsmanagedmachinepool_types.go @@ -27,26 +27,26 @@ import ( ) const ( - // ManagedMachinePoolFinalizer allows the controller to clean up resources on delete + // ManagedMachinePoolFinalizer allows the controller to clean up resources on delete. ManagedMachinePoolFinalizer = "awsmanagedmachinepools.infrastructure.cluster.x-k8s.io" ) -// ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool +// ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool. type ManagedMachineAMIType string const ( - // Al2x86_64 is the default AMI type + // Al2x86_64 is the default AMI type. Al2x86_64 ManagedMachineAMIType = "AL2_x86_64" - // Al2x86_64GPU is the x86-64 GPU AMI type + // Al2x86_64GPU is the x86-64 GPU AMI type. Al2x86_64GPU ManagedMachineAMIType = "AL2_x86_64_GPU" - // Al2Arm64 is the Arm AMI type + // Al2Arm64 is the Arm AMI type. Al2Arm64 ManagedMachineAMIType = "AL2_ARM_64" ) var ( // DefaultEKSNodegroupRole is the name of the default IAM role to use for EKS nodegroups // if no other role is supplied in the spec and if iam role creation is not enabled. The default - // can be created using clusterawsadm or created manually + // can be created using clusterawsadm or created manually. DefaultEKSNodegroupRole = fmt.Sprintf("eks-nodegroup%s", infrav1.DefaultNameSuffix) ) @@ -119,13 +119,13 @@ type AWSManagedMachinePoolSpec struct { ProviderIDList []string `json:"providerIDList,omitempty"` } -// ManagedMachinePoolScaling specifies scaling options +// ManagedMachinePoolScaling specifies scaling options. type ManagedMachinePoolScaling struct { MinSize *int32 `json:"minSize,omitempty"` MaxSize *int32 `json:"maxSize,omitempty"` } -// ManagedRemoteAccess specifies remote access settings for EC2 instances +// ManagedRemoteAccess specifies remote access settings for EC2 instances. type ManagedRemoteAccess struct { // SSHKeyName specifies which EC2 SSH key can be used to access machines. // If left empty, the key from the control plane is used. @@ -219,7 +219,7 @@ func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSManagedMachinePoolList contains a list of AWSManagedMachinePools +// AWSManagedMachinePoolList contains a list of AWSManagedMachinePools. type AWSManagedMachinePoolList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha3/conditions_consts.go b/exp/api/v1alpha3/conditions_consts.go index 09a15196e3..45ff97da84 100644 --- a/exp/api/v1alpha3/conditions_consts.go +++ b/exp/api/v1alpha3/conditions_consts.go @@ -19,7 +19,7 @@ package v1alpha3 import clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha3" const ( - // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned + // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned. ASGReadyCondition clusterv1.ConditionType = "ASGReady" // ASGNotFoundReason used when the autoscaling group couldn't be retrieved. ASGNotFoundReason = "ASGNotFound" @@ -28,11 +28,11 @@ const ( // ASGDeletionInProgress ASG is in a deletion in progress state. ASGDeletionInProgress = "ASGDeletionInProgress" - // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template + // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template. LaunchTemplateReadyCondition clusterv1.ConditionType = "LaunchTemplateReady" - // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found + // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found. LaunchTemplateNotFoundReason = "LaunchTemplateNotFound" - // LaunchTemplateCreateFailedReason used for failures during Launch Template creation + // LaunchTemplateCreateFailedReason used for failures during Launch Template creation. LaunchTemplateCreateFailedReason = "LaunchTemplateCreateFailed" // InstanceRefreshStartedCondition reports on successfully starting instance refresh. @@ -47,7 +47,7 @@ const ( const ( // EKSNodegroupReadyCondition condition reports on the successful reconciliation of eks control plane. EKSNodegroupReadyCondition clusterv1.ConditionType = "EKSNodegroupReady" - // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSNodegroupReconciliationFailedReason = "EKSNodegroupReconciliationFailed" // WaitingForEKSControlPlaneReason used when the machine pool is waiting for // EKS control plane infrastructure to be ready before proceeding. @@ -58,21 +58,21 @@ const ( // EKSFargateProfileReadyCondition condition reports on the successful reconciliation of eks control plane. EKSFargateProfileReadyCondition clusterv1.ConditionType = "EKSFargateProfileReady" // EKSFargateCreatingCondition condition reports on whether the fargate - // profile is creating + // profile is creating. EKSFargateCreatingCondition clusterv1.ConditionType = "EKSFargateCreating" - // EKSFargateDeletingCondition used to report that the profile is deleting + // EKSFargateDeletingCondition used to report that the profile is deleting. EKSFargateDeletingCondition = "EKSFargateDeleting" - // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSFargateReconciliationFailedReason = "EKSFargateReconciliationFailed" - // EKSFargateDeletingReason used when the profile is deleting + // EKSFargateDeletingReason used when the profile is deleting. EKSFargateDeletingReason = "Deleting" - // EKSFargateCreatingReason used when the profile is creating + // EKSFargateCreatingReason used when the profile is creating. EKSFargateCreatingReason = "Creating" - // EKSFargateCreatedReason used when the profile is created + // EKSFargateCreatedReason used when the profile is created. EKSFargateCreatedReason = "Created" - // EKSFargateDeletedReason used when the profile is deleted + // EKSFargateDeletedReason used when the profile is deleted. EKSFargateDeletedReason = "Deleted" - // EKSFargateFailedReason used when the profile failed + // EKSFargateFailedReason used when the profile failed. EKSFargateFailedReason = "Failed" ) @@ -81,12 +81,12 @@ const ( // reconciliation of EKS nodegroup iam roles. IAMNodegroupRolesReadyCondition clusterv1.ConditionType = "IAMNodegroupRolesReady" // IAMNodegroupRolesReconciliationFailedReason used to report failures while - // reconciling EKS nodegroup iam roles + // reconciling EKS nodegroup iam roles. IAMNodegroupRolesReconciliationFailedReason = "IAMNodegroupRolesReconciliationFailed" // IAMFargateRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. IAMFargateRolesReadyCondition clusterv1.ConditionType = "IAMFargateRolesReady" // IAMFargateRolesReconciliationFailedReason used to report failures while - // reconciling EKS nodegroup iam roles + // reconciling EKS nodegroup iam roles. IAMFargateRolesReconciliationFailedReason = "IAMFargateRolesReconciliationFailed" ) diff --git a/exp/api/v1alpha3/conversion_test.go b/exp/api/v1alpha3/conversion_test.go index b956e6ec09..d72da2843d 100644 --- a/exp/api/v1alpha3/conversion_test.go +++ b/exp/api/v1alpha3/conversion_test.go @@ -34,25 +34,25 @@ func TestFuzzyConversion(t *testing.T) { t.Run("for AWSMachinePool", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.AWSMachinePool{}, - Spoke: &AWSMachinePool{}, + Hub: &v1alpha4.AWSMachinePool{}, + Spoke: &AWSMachinePool{}, })) t.Run("for AWSManagedMachinePool", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.AWSManagedMachinePool{}, - Spoke: &AWSManagedMachinePool{}, + Hub: &v1alpha4.AWSManagedMachinePool{}, + Spoke: &AWSManagedMachinePool{}, })) t.Run("for AWSManagedCluster", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.AWSManagedCluster{}, - Spoke: &AWSManagedCluster{}, + Hub: &v1alpha4.AWSManagedCluster{}, + Spoke: &AWSManagedCluster{}, })) t.Run("for AWSFargateProfile", utilconversion.FuzzTestFunc(utilconversion.FuzzTestFuncInput{ Scheme: scheme, - Hub: &v1alpha4.AWSFargateProfile{}, - Spoke: &AWSFargateProfile{}, + Hub: &v1alpha4.AWSFargateProfile{}, + Spoke: &AWSFargateProfile{}, })) } diff --git a/exp/api/v1alpha3/doc.go b/exp/api/v1alpha3/doc.go index f6a60ab7bd..725979814c 100644 --- a/exp/api/v1alpha3/doc.go +++ b/exp/api/v1alpha3/doc.go @@ -15,4 +15,5 @@ limitations under the License. */ // +k8s:conversion-gen=sigs.k8s.io/cluster-api-provider-aws/exp/api/v1alpha4 + package v1alpha3 diff --git a/exp/api/v1alpha3/groupversion_info.go b/exp/api/v1alpha3/groupversion_info.go index c33933bc1e..209fd92649 100644 --- a/exp/api/v1alpha3/groupversion_info.go +++ b/exp/api/v1alpha3/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1alpha3"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/exp/api/v1alpha3/types.go b/exp/api/v1alpha3/types.go index f3698da505..b446f587d6 100644 --- a/exp/api/v1alpha3/types.go +++ b/exp/api/v1alpha3/types.go @@ -96,7 +96,7 @@ type AWSLaunchTemplate struct { RootVolume *infrav1.Volume `json:"rootVolume,omitempty"` // SSHKeyName is the name of the ssh key to attach to the instance. Valid values are empty string - //(do not use SSH keys), a valid SSH key name, or omitted (use the default SSH key name) + // (do not use SSH keys), a valid SSH key name, or omitted (use the default SSH key name) // +optional SSHKeyName *string `json:"sshKeyName,omitempty"` @@ -125,7 +125,7 @@ type OnDemandAllocationStrategy string var ( // OnDemandAllocationStrategyPrioritized uses the order of instance type overrides - // for the LaunchTemplate to define the launch priority of each instance type + // for the LaunchTemplate to define the launch priority of each instance type. OnDemandAllocationStrategyPrioritized = OnDemandAllocationStrategy("prioritized") ) @@ -135,11 +135,11 @@ type SpotAllocationStrategy string var ( // SpotAllocationStrategyLowestPrice will make the Auto Scaling group launch // instances using the Spot pools with the lowest price, and evenly allocates - // your instances across the number of Spot pools that you specify + // your instances across the number of Spot pools that you specify. SpotAllocationStrategyLowestPrice = SpotAllocationStrategy("lowest-price") // SpotAllocationStrategyCapacityOptimized will make the Auto Scaling group launch - // instances using Spot pools that are optimally chosen based on the available Spot capacity + // instances using Spot pools that are optimally chosen based on the available Spot capacity. SpotAllocationStrategyCapacityOptimized = SpotAllocationStrategy("capacity-optimized") ) @@ -160,7 +160,7 @@ type InstancesDistribution struct { OnDemandPercentageAboveBaseCapacity *int64 `json:"onDemandPercentageAboveBaseCapacity,omitempty"` } -// MixedInstancesPolicy for an Auto Scaling group +// MixedInstancesPolicy for an Auto Scaling group. type MixedInstancesPolicy struct { InstancesDistribution *InstancesDistribution `json:"instancesDistribution,omitempty"` Overrides []Overrides `json:"overrides,omitempty"` @@ -192,6 +192,6 @@ type AutoScalingGroup struct { type ASGStatus string var ( - // ASGStatusDeleteInProgress is the string representing an ASG that is currently deleting + // ASGStatusDeleteInProgress is the string representing an ASG that is currently deleting. ASGStatusDeleteInProgress = ASGStatus("Delete in progress") ) diff --git a/exp/api/v1alpha3/webhook_suite_test.go b/exp/api/v1alpha3/webhook_suite_test.go index e25fc09965..016757b241 100644 --- a/exp/api/v1alpha3/webhook_suite_test.go +++ b/exp/api/v1alpha3/webhook_suite_test.go @@ -63,7 +63,7 @@ func setup() { utilruntime.Must(expv1alpha4.AddToScheme(scheme.Scheme)) testEnvConfig := helpers.NewTestEnvironmentConfiguration([]string{ - path.Join( "config", "crd", "bases"), + path.Join("config", "crd", "bases"), }, ).WithWebhookConfiguration("unmanaged", path.Join("config", "webhook", "manifests.yaml")) var err error diff --git a/exp/api/v1alpha3/webhook_test.go b/exp/api/v1alpha3/webhook_test.go index 8375bb1545..5894fbdc0d 100644 --- a/exp/api/v1alpha3/webhook_test.go +++ b/exp/api/v1alpha3/webhook_test.go @@ -37,8 +37,8 @@ func TestAWSMachinePoolConversion(t *testing.T) { Namespace: ns.Name, }, Spec: AWSMachinePoolSpec{ - MinSize: 1, - MaxSize: 3, + MinSize: 1, + MaxSize: 3, }, } @@ -75,8 +75,8 @@ func TestAWSFargateProfileConversion(t *testing.T) { Namespace: ns.Name, }, Spec: FargateProfileSpec{ - ClusterName: "cluster-name", - ProfileName: "name", + ClusterName: "cluster-name", + ProfileName: "name", }, } diff --git a/exp/api/v1alpha4/awsfargateprofile_types.go b/exp/api/v1alpha4/awsfargateprofile_types.go index 9e3a6cb84d..d140aeb7f5 100644 --- a/exp/api/v1alpha4/awsfargateprofile_types.go +++ b/exp/api/v1alpha4/awsfargateprofile_types.go @@ -27,14 +27,14 @@ import ( ) const ( - // FargateProfileFinalizer allows the controller to clean up resources on delete + // FargateProfileFinalizer allows the controller to clean up resources on delete. FargateProfileFinalizer = "awsfargateprofile.infrastructure.cluster.x-k8s.io" ) var ( // DefaultEKSFargateRole is the name of the default IAM role to use for fargate // profiles if no other role is supplied in the spec and if iam role creation - // is not enabled. The default can be created using clusterawsadm or created manually + // is not enabled. The default can be created using clusterawsadm or created manually. DefaultEKSFargateRole = fmt.Sprintf("eks-fargate%s", infrav1.DefaultNameSuffix) ) @@ -156,7 +156,7 @@ func (r *AWSFargateProfile) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSFargateProfileList contains a list of FargateProfiles +// AWSFargateProfileList contains a list of FargateProfiles. type AWSFargateProfileList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha4/awsfargateprofile_webhook.go b/exp/api/v1alpha4/awsfargateprofile_webhook.go index 5e3a517319..9c66b8e9bc 100644 --- a/exp/api/v1alpha4/awsfargateprofile_webhook.go +++ b/exp/api/v1alpha4/awsfargateprofile_webhook.go @@ -34,7 +34,7 @@ const ( maxProfileNameLength = 100 ) -// SetupWebhookWithManager will setup the webhooks for the AWSFargateProfile +// SetupWebhookWithManager will setup the webhooks for the AWSFargateProfile. func (r *AWSFargateProfile) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -47,7 +47,7 @@ func (r *AWSFargateProfile) SetupWebhookWithManager(mgr ctrl.Manager) error { var _ webhook.Defaulter = &AWSFargateProfile{} var _ webhook.Validator = &AWSFargateProfile{} -// Default will set default values for the AWSFargateProfile +// Default will set default values for the AWSFargateProfile. func (r *AWSFargateProfile) Default() { if r.Labels == nil { r.Labels = make(map[string]string) diff --git a/exp/api/v1alpha4/awsmachinepool_types.go b/exp/api/v1alpha4/awsmachinepool_types.go index 1eb27d3a98..99a327689e 100644 --- a/exp/api/v1alpha4/awsmachinepool_types.go +++ b/exp/api/v1alpha4/awsmachinepool_types.go @@ -24,6 +24,7 @@ import ( "sigs.k8s.io/cluster-api/errors" ) +// Constants block. const ( // MachinePoolFinalizer is the finalizer for the machine pool. MachinePoolFinalizer = "awsmachinepool.infrastructure.cluster.x-k8s.io" @@ -200,7 +201,7 @@ type AWSMachinePool struct { // +kubebuilder:object:root=true -// AWSMachinePoolList contains a list of AWSMachinePool +// AWSMachinePoolList contains a list of AWSMachinePool. type AWSMachinePoolList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha4/awsmachinepool_webhook.go b/exp/api/v1alpha4/awsmachinepool_webhook.go index 066febc4a7..8911f44e45 100644 --- a/exp/api/v1alpha4/awsmachinepool_webhook.go +++ b/exp/api/v1alpha4/awsmachinepool_webhook.go @@ -19,10 +19,11 @@ package v1alpha4 import ( "time" + logf "sigs.k8s.io/controller-runtime/pkg/log" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/util/validation/field" - logf "sigs.k8s.io/controller-runtime/pkg/log" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/webhook" @@ -30,7 +31,7 @@ import ( var log = logf.Log.WithName("awsmachinepool-resource") -// SetupWebhookWithManager will setup the webhooks for the AWSMachinePool +// SetupWebhookWithManager will setup the webhooks for the AWSMachinePool. func (r *AWSMachinePool) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -54,7 +55,7 @@ func (r *AWSMachinePool) validateDefaultCoolDown() field.ErrorList { return allErrs } -// ValidateCreate will do any extra validation when creating a AWSMachinePool +// ValidateCreate will do any extra validation when creating a AWSMachinePool. func (r *AWSMachinePool) ValidateCreate() error { log.Info("AWSMachinePool validate create", "name", r.Name) @@ -75,7 +76,7 @@ func (r *AWSMachinePool) ValidateCreate() error { ) } -// ValidateUpdate will do any extra validation when updating a AWSMachinePool +// ValidateUpdate will do any extra validation when updating a AWSMachinePool. func (r *AWSMachinePool) ValidateUpdate(old runtime.Object) error { var allErrs field.ErrorList if errs := r.validateDefaultCoolDown(); errs != nil || len(errs) == 0 { @@ -93,12 +94,12 @@ func (r *AWSMachinePool) ValidateUpdate(old runtime.Object) error { ) } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *AWSMachinePool) ValidateDelete() error { return nil } -// Default will set default values for the AWSMachinePool +// Default will set default values for the AWSMachinePool. func (r *AWSMachinePool) Default() { if int(r.Spec.DefaultCoolDown.Duration.Seconds()) == 0 { log.Info("DefaultCoolDown is zero, setting 300 seconds as default") diff --git a/exp/api/v1alpha4/awsmanagecluster_webhook.go b/exp/api/v1alpha4/awsmanagecluster_webhook.go index 1e249583f5..a9fb57a0c1 100644 --- a/exp/api/v1alpha4/awsmanagecluster_webhook.go +++ b/exp/api/v1alpha4/awsmanagecluster_webhook.go @@ -22,7 +22,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/webhook" ) -// SetupWebhookWithManager will setup the webhooks for the AWSManagedCluster +// SetupWebhookWithManager will setup the webhooks for the AWSManagedCluster. func (r *AWSManagedCluster) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -35,21 +35,21 @@ func (r *AWSManagedCluster) SetupWebhookWithManager(mgr ctrl.Manager) error { var _ webhook.Defaulter = &AWSManagedCluster{} var _ webhook.Validator = &AWSManagedCluster{} -// Default will set default values for the AWSManagedCluster +// Default will set default values for the AWSManagedCluster. func (r *AWSManagedCluster) Default() { } -// ValidateCreate will do any extra validation when creating a AWSManagedCluster +// ValidateCreate will do any extra validation when creating a AWSManagedCluster. func (r *AWSManagedCluster) ValidateCreate() error { return nil } -// ValidateUpdate will do any extra validation when updating a AWSManagedCluster +// ValidateUpdate will do any extra validation when updating a AWSManagedCluster. func (r *AWSManagedCluster) ValidateUpdate(old runtime.Object) error { return nil } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *AWSManagedCluster) ValidateDelete() error { return nil } diff --git a/exp/api/v1alpha4/awsmanagedcluster_types.go b/exp/api/v1alpha4/awsmanagedcluster_types.go index 16a9b0310d..2bd970201d 100644 --- a/exp/api/v1alpha4/awsmanagedcluster_types.go +++ b/exp/api/v1alpha4/awsmanagedcluster_types.go @@ -59,7 +59,7 @@ type AWSManagedCluster struct { // +kubebuilder:object:root=true -// AWSManagedClusterList contains a list of AWSManagedCluster +// AWSManagedClusterList contains a list of AWSManagedCluster. type AWSManagedClusterList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha4/awsmanagedmachinepool_types.go b/exp/api/v1alpha4/awsmanagedmachinepool_types.go index 5fa2c9bb3d..4291ed901f 100644 --- a/exp/api/v1alpha4/awsmanagedmachinepool_types.go +++ b/exp/api/v1alpha4/awsmanagedmachinepool_types.go @@ -27,26 +27,26 @@ import ( ) const ( - // ManagedMachinePoolFinalizer allows the controller to clean up resources on delete + // ManagedMachinePoolFinalizer allows the controller to clean up resources on delete. ManagedMachinePoolFinalizer = "awsmanagedmachinepools.infrastructure.cluster.x-k8s.io" ) -// ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool +// ManagedMachineAMIType specifies which AWS AMI to use for a managed MachinePool. type ManagedMachineAMIType string const ( - // Al2x86_64 is the default AMI type + // Al2x86_64 is the default AMI type. Al2x86_64 ManagedMachineAMIType = "AL2_x86_64" - // Al2x86_64GPU is the x86-64 GPU AMI type + // Al2x86_64GPU is the x86-64 GPU AMI type. Al2x86_64GPU ManagedMachineAMIType = "AL2_x86_64_GPU" - // Al2Arm64 is the Arm AMI type + // Al2Arm64 is the Arm AMI type. Al2Arm64 ManagedMachineAMIType = "AL2_ARM_64" ) var ( // DefaultEKSNodegroupRole is the name of the default IAM role to use for EKS nodegroups // if no other role is supplied in the spec and if iam role creation is not enabled. The default - // can be created using clusterawsadm or created manually + // can be created using clusterawsadm or created manually. DefaultEKSNodegroupRole = fmt.Sprintf("eks-nodegroup%s", infrav1.DefaultNameSuffix) ) @@ -123,13 +123,13 @@ type AWSManagedMachinePoolSpec struct { ProviderIDList []string `json:"providerIDList,omitempty"` } -// ManagedMachinePoolScaling specifies scaling options +// ManagedMachinePoolScaling specifies scaling options. type ManagedMachinePoolScaling struct { MinSize *int32 `json:"minSize,omitempty"` MaxSize *int32 `json:"maxSize,omitempty"` } -// ManagedRemoteAccess specifies remote access settings for EC2 instances +// ManagedRemoteAccess specifies remote access settings for EC2 instances. type ManagedRemoteAccess struct { // SSHKeyName specifies which EC2 SSH key can be used to access machines. // If left empty, the key from the control plane is used. @@ -224,7 +224,7 @@ func (r *AWSManagedMachinePool) SetConditions(conditions clusterv1.Conditions) { // +kubebuilder:object:root=true -// AWSManagedMachinePoolList contains a list of AWSManagedMachinePools +// AWSManagedMachinePoolList contains a list of AWSManagedMachinePools. type AWSManagedMachinePoolList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` diff --git a/exp/api/v1alpha4/awsmanagedmachinepool_webhook.go b/exp/api/v1alpha4/awsmanagedmachinepool_webhook.go index 1f765e342e..82900a7b7c 100644 --- a/exp/api/v1alpha4/awsmanagedmachinepool_webhook.go +++ b/exp/api/v1alpha4/awsmanagedmachinepool_webhook.go @@ -40,7 +40,7 @@ const ( // log is for logging in this package. var mmpLog = logf.Log.WithName("awsmanagedmachinepool-resource") -// SetupWebhookWithManager will setup the webhooks for the AWSManagedMachinePool +// SetupWebhookWithManager will setup the webhooks for the AWSManagedMachinePool. func (r *AWSManagedMachinePool) SetupWebhookWithManager(mgr ctrl.Manager) error { return ctrl.NewWebhookManagedBy(mgr). For(r). @@ -85,9 +85,8 @@ func (r *AWSManagedMachinePool) validateRemoteAccess() field.ErrorList { } remoteAccessPath := field.NewPath("spec", "remoteAccess") sourceSecurityGroups := r.Spec.RemoteAccess.SourceSecurityGroups - public := r.Spec.RemoteAccess.Public - if public && len(sourceSecurityGroups) > 0 { + if public := r.Spec.RemoteAccess.Public; public && len(sourceSecurityGroups) > 0 { allErrs = append( allErrs, field.Invalid(remoteAccessPath.Child("sourceSecurityGroups"), sourceSecurityGroups, "must be empty if public is set"), @@ -97,7 +96,7 @@ func (r *AWSManagedMachinePool) validateRemoteAccess() field.ErrorList { return allErrs } -// ValidateCreate will do any extra validation when creating a AWSManagedMachinePool +// ValidateCreate will do any extra validation when creating a AWSManagedMachinePool. func (r *AWSManagedMachinePool) ValidateCreate() error { mmpLog.Info("AWSManagedMachinePool validate create", "name", r.Name) @@ -124,7 +123,7 @@ func (r *AWSManagedMachinePool) ValidateCreate() error { ) } -// ValidateUpdate will do any extra validation when updating a AWSManagedMachinePool +// ValidateUpdate will do any extra validation when updating a AWSManagedMachinePool. func (r *AWSManagedMachinePool) ValidateUpdate(old runtime.Object) error { mmpLog.Info("AWSManagedMachinePool validate update", "name", r.Name) oldPool, ok := old.(*AWSManagedMachinePool) @@ -152,7 +151,7 @@ func (r *AWSManagedMachinePool) ValidateUpdate(old runtime.Object) error { ) } -// ValidateDelete allows you to add any extra validation when deleting +// ValidateDelete allows you to add any extra validation when deleting. func (r *AWSManagedMachinePool) ValidateDelete() error { mmpLog.Info("AWSManagedMachinePool validate delete", "name", r.Name) @@ -191,7 +190,7 @@ func (r *AWSManagedMachinePool) validateImmutable(old *AWSManagedMachinePool) fi return allErrs } -// Default will set default values for the AWSManagedMachinePool +// Default will set default values for the AWSManagedMachinePool. func (r *AWSManagedMachinePool) Default() { mmpLog.Info("AWSManagedMachinePool setting defaults", "name", r.Name) diff --git a/exp/api/v1alpha4/conditions_consts.go b/exp/api/v1alpha4/conditions_consts.go index 253669f0ca..9efb66c048 100644 --- a/exp/api/v1alpha4/conditions_consts.go +++ b/exp/api/v1alpha4/conditions_consts.go @@ -19,7 +19,7 @@ package v1alpha4 import clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" const ( - // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned + // ASGReadyCondition reports on current status of the autoscaling group. Ready indicates the group is provisioned. ASGReadyCondition clusterv1.ConditionType = "ASGReady" // ASGNotFoundReason used when the autoscaling group couldn't be retrieved. ASGNotFoundReason = "ASGNotFound" @@ -28,11 +28,11 @@ const ( // ASGDeletionInProgress ASG is in a deletion in progress state. ASGDeletionInProgress = "ASGDeletionInProgress" - // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template + // LaunchTemplateReadyCondition represents the status of an AWSMachinePool's associated Launch Template. LaunchTemplateReadyCondition clusterv1.ConditionType = "LaunchTemplateReady" - // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found + // LaunchTemplateNotFoundReason is used when an associated Launch Template can't be found. LaunchTemplateNotFoundReason = "LaunchTemplateNotFound" - // LaunchTemplateCreateFailedReason used for failures during Launch Template creation + // LaunchTemplateCreateFailedReason used for failures during Launch Template creation. LaunchTemplateCreateFailedReason = "LaunchTemplateCreateFailed" // InstanceRefreshStartedCondition reports on successfully starting instance refresh. @@ -47,7 +47,7 @@ const ( const ( // EKSNodegroupReadyCondition condition reports on the successful reconciliation of eks control plane. EKSNodegroupReadyCondition clusterv1.ConditionType = "EKSNodegroupReady" - // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSNodegroupReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSNodegroupReconciliationFailedReason = "EKSNodegroupReconciliationFailed" // WaitingForEKSControlPlaneReason used when the machine pool is waiting for // EKS control plane infrastructure to be ready before proceeding. @@ -58,21 +58,21 @@ const ( // EKSFargateProfileReadyCondition condition reports on the successful reconciliation of eks control plane. EKSFargateProfileReadyCondition clusterv1.ConditionType = "EKSFargateProfileReady" // EKSFargateCreatingCondition condition reports on whether the fargate - // profile is creating + // profile is creating. EKSFargateCreatingCondition clusterv1.ConditionType = "EKSFargateCreating" - // EKSFargateDeletingCondition used to report that the profile is deleting + // EKSFargateDeletingCondition used to report that the profile is deleting. EKSFargateDeletingCondition = "EKSFargateDeleting" - // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane + // EKSFargateReconciliationFailedReason used to report failures while reconciling EKS control plane. EKSFargateReconciliationFailedReason = "EKSFargateReconciliationFailed" - // EKSFargateDeletingReason used when the profile is deleting + // EKSFargateDeletingReason used when the profile is deleting. EKSFargateDeletingReason = "Deleting" - // EKSFargateCreatingReason used when the profile is creating + // EKSFargateCreatingReason used when the profile is creating. EKSFargateCreatingReason = "Creating" - // EKSFargateCreatedReason used when the profile is created + // EKSFargateCreatedReason used when the profile is created. EKSFargateCreatedReason = "Created" - // EKSFargateDeletedReason used when the profile is deleted + // EKSFargateDeletedReason used when the profile is deleted. EKSFargateDeletedReason = "Deleted" - // EKSFargateFailedReason used when the profile failed + // EKSFargateFailedReason used when the profile failed. EKSFargateFailedReason = "Failed" ) @@ -81,12 +81,12 @@ const ( // reconciliation of EKS nodegroup iam roles. IAMNodegroupRolesReadyCondition clusterv1.ConditionType = "IAMNodegroupRolesReady" // IAMNodegroupRolesReconciliationFailedReason used to report failures while - // reconciling EKS nodegroup iam roles + // reconciling EKS nodegroup iam roles. IAMNodegroupRolesReconciliationFailedReason = "IAMNodegroupRolesReconciliationFailed" // IAMFargateRolesReadyCondition condition reports on the successful // reconciliation of EKS nodegroup iam roles. IAMFargateRolesReadyCondition clusterv1.ConditionType = "IAMFargateRolesReady" // IAMFargateRolesReconciliationFailedReason used to report failures while - // reconciling EKS nodegroup iam roles + // reconciling EKS nodegroup iam roles. IAMFargateRolesReconciliationFailedReason = "IAMFargateRolesReconciliationFailed" ) diff --git a/exp/api/v1alpha4/doc.go b/exp/api/v1alpha4/doc.go index 2abdf95598..0ab416e390 100644 --- a/exp/api/v1alpha4/doc.go +++ b/exp/api/v1alpha4/doc.go @@ -16,4 +16,5 @@ limitations under the License. // +gencrdrefdocs:force // +groupName=infrastructure.cluster.x-k8s.io + package v1alpha4 diff --git a/exp/api/v1alpha4/groupversion_info.go b/exp/api/v1alpha4/groupversion_info.go index 48acc97d9c..ddb183e3fe 100644 --- a/exp/api/v1alpha4/groupversion_info.go +++ b/exp/api/v1alpha4/groupversion_info.go @@ -25,10 +25,10 @@ import ( ) var ( - // GroupVersion is group version used to register these objects + // GroupVersion is group version used to register these objects. GroupVersion = schema.GroupVersion{Group: "infrastructure.cluster.x-k8s.io", Version: "v1alpha4"} - // SchemeBuilder is used to add go types to the GroupVersionKind scheme + // SchemeBuilder is used to add go types to the GroupVersionKind scheme. SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} // AddToScheme adds the types in this group-version to the given scheme. diff --git a/exp/api/v1alpha4/types.go b/exp/api/v1alpha4/types.go index 4ba9ba1ba2..b42e1534e9 100644 --- a/exp/api/v1alpha4/types.go +++ b/exp/api/v1alpha4/types.go @@ -96,7 +96,7 @@ type AWSLaunchTemplate struct { RootVolume *infrav1.Volume `json:"rootVolume,omitempty"` // SSHKeyName is the name of the ssh key to attach to the instance. Valid values are empty string - //(do not use SSH keys), a valid SSH key name, or omitted (use the default SSH key name) + // (do not use SSH keys), a valid SSH key name, or omitted (use the default SSH key name) // +optional SSHKeyName *string `json:"sshKeyName,omitempty"` @@ -125,7 +125,7 @@ type OnDemandAllocationStrategy string var ( // OnDemandAllocationStrategyPrioritized uses the order of instance type overrides - // for the LaunchTemplate to define the launch priority of each instance type + // for the LaunchTemplate to define the launch priority of each instance type. OnDemandAllocationStrategyPrioritized = OnDemandAllocationStrategy("prioritized") ) @@ -135,11 +135,11 @@ type SpotAllocationStrategy string var ( // SpotAllocationStrategyLowestPrice will make the Auto Scaling group launch // instances using the Spot pools with the lowest price, and evenly allocates - // your instances across the number of Spot pools that you specify + // your instances across the number of Spot pools that you specify. SpotAllocationStrategyLowestPrice = SpotAllocationStrategy("lowest-price") // SpotAllocationStrategyCapacityOptimized will make the Auto Scaling group launch - // instances using Spot pools that are optimally chosen based on the available Spot capacity + // instances using Spot pools that are optimally chosen based on the available Spot capacity. SpotAllocationStrategyCapacityOptimized = SpotAllocationStrategy("capacity-optimized") ) @@ -160,7 +160,7 @@ type InstancesDistribution struct { OnDemandPercentageAboveBaseCapacity *int64 `json:"onDemandPercentageAboveBaseCapacity,omitempty"` } -// MixedInstancesPolicy for an Auto Scaling group +// MixedInstancesPolicy for an Auto Scaling group. type MixedInstancesPolicy struct { InstancesDistribution *InstancesDistribution `json:"instancesDistribution,omitempty"` Overrides []Overrides `json:"overrides,omitempty"` @@ -192,11 +192,11 @@ type AutoScalingGroup struct { type ASGStatus string var ( - // ASGStatusDeleteInProgress is the string representing an ASG that is currently deleting + // ASGStatusDeleteInProgress is the string representing an ASG that is currently deleting. ASGStatusDeleteInProgress = ASGStatus("Delete in progress") ) -// TaintEffect is the effect for a Kubernetes taint +// TaintEffect is the effect for a Kubernetes taint. type TaintEffect string var ( @@ -226,7 +226,7 @@ type Taint struct { Value string `json:"value"` } -// Equals is used to test if 2 taints are equal +// Equals is used to test if 2 taints are equal. func (t *Taint) Equals(other *Taint) bool { if t == nil || other == nil { return t == other @@ -237,10 +237,10 @@ func (t *Taint) Equals(other *Taint) bool { t.Value == other.Value } -// Taints is an array of Taints +// Taints is an array of Taints. type Taints []Taint -// Contains checks for existence of a matching taint +// Contains checks for existence of a matching taint. func (t *Taints) Contains(taint *Taint) bool { for _, t := range *t { if t.Equals(taint) { diff --git a/exp/controlleridentitycreator/awscontrolleridentity_controller.go b/exp/controlleridentitycreator/awscontrolleridentity_controller.go index 5b017686c6..28bab0978e 100644 --- a/exp/controlleridentitycreator/awscontrolleridentity_controller.go +++ b/exp/controlleridentitycreator/awscontrolleridentity_controller.go @@ -37,7 +37,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSControllerIdentityReconciler reconciles a AWSClusterControllerIdentity object +// AWSControllerIdentityReconciler reconciles a AWSClusterControllerIdentity object. type AWSControllerIdentityReconciler struct { client.Client Log logr.Logger diff --git a/exp/controlleridentitycreator/awscontrolleridentity_controller_test.go b/exp/controlleridentitycreator/awscontrolleridentity_controller_test.go index 1d17a0b4c4..6bd2ab5db6 100644 --- a/exp/controlleridentitycreator/awscontrolleridentity_controller_test.go +++ b/exp/controlleridentitycreator/awscontrolleridentity_controller_test.go @@ -19,8 +19,8 @@ package controlleridentitycreator import ( "context" "reflect" - "time" "testing" + "time" . "github.com/onsi/gomega" @@ -29,7 +29,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) - func TestAWSInstanceStateController(t *testing.T) { t.Run("should maintain list of cluster queue URLs and reconcile failing machines", func(t *testing.T) { g := NewWithT(t) @@ -56,6 +55,5 @@ func TestAWSInstanceStateController(t *testing.T) { } return false }, 10*time.Second).Should(Equal(true)) - }) } diff --git a/exp/controllers/awsfargatepool_controller.go b/exp/controllers/awsfargatepool_controller.go index 237788f901..81459bae45 100644 --- a/exp/controllers/awsfargatepool_controller.go +++ b/exp/controllers/awsfargatepool_controller.go @@ -41,7 +41,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSFargateProfileReconciler reconciles a AWSFargateProfile object +// AWSFargateProfileReconciler reconciles a AWSFargateProfile object. type AWSFargateProfileReconciler struct { client.Client Recorder record.EventRecorder @@ -50,7 +50,7 @@ type AWSFargateProfileReconciler struct { WatchFilterValue string } -// SetupWithManager is used to setup the controller +// SetupWithManager is used to setup the controller. func (r *AWSFargateProfileReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error { managedControlPlaneToFargateProfileMap := managedControlPlaneToFargateProfileMapFunc(r.Client, ctrl.LoggerFrom(ctx)) return ctrl.NewControllerManagedBy(mgr). @@ -70,7 +70,7 @@ func (r *AWSFargateProfileReconciler) SetupWithManager(ctx context.Context, mgr // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=awsfargateprofiles,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=awsfargateprofiles/status,verbs=get;update;patch -// Reconcile reconciles AWSFargateProfiles +// Reconcile reconciles AWSFargateProfiles. func (r *AWSFargateProfileReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) { log := ctrl.LoggerFrom(ctx) diff --git a/exp/controllers/awsmachinepool_controller.go b/exp/controllers/awsmachinepool_controller.go index f3a75e1ec2..a75832bec8 100644 --- a/exp/controllers/awsmachinepool_controller.go +++ b/exp/controllers/awsmachinepool_controller.go @@ -51,7 +51,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSMachinePoolReconciler reconciles a AWSMachinePool object +// AWSMachinePoolReconciler reconciles a AWSMachinePool object. type AWSMachinePoolReconciler struct { client.Client Recorder record.EventRecorder @@ -82,7 +82,7 @@ func (r *AWSMachinePoolReconciler) getEC2Service(scope scope.EC2Scope) services. // +kubebuilder:rbac:groups="",resources=secrets;,verbs=get;list;watch // +kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch -// Reconcile is the reconciliation loop for AWSMachinePool +// Reconcile is the reconciliation loop for AWSMachinePool. func (r *AWSMachinePoolReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) { log := ctrl.LoggerFrom(ctx) @@ -500,7 +500,7 @@ func (r *AWSMachinePoolReconciler) reconcileTags(machinePoolScope *scope.Machine return nil } -// asgNeedsUpdates compares incoming AWSMachinePool and compares against existing ASG +// asgNeedsUpdates compares incoming AWSMachinePool and compares against existing ASG. func asgNeedsUpdates(machinePoolScope *scope.MachinePoolScope, existingASG *infrav1exp.AutoScalingGroup) bool { if machinePoolScope.MachinePool.Spec.Replicas != nil && machinePoolScope.MachinePool.Spec.Replicas != existingASG.DesiredCapacity { return true @@ -594,7 +594,7 @@ func (r *AWSMachinePoolReconciler) getInfraCluster(ctx context.Context, log logr if err := r.Get(ctx, controlPlaneName, controlPlane); err != nil { // AWSManagedControlPlane is not ready - return nil, nil + return nil, nil // nolint:nilerr } managedControlPlaneScope, err = scope.NewManagedControlPlaneScope(scope.ManagedControlPlaneScopeParams{ @@ -620,7 +620,7 @@ func (r *AWSMachinePoolReconciler) getInfraCluster(ctx context.Context, log logr if err := r.Client.Get(ctx, infraClusterName, awsCluster); err != nil { // AWSCluster is not ready - return nil, nil + return nil, nil // nolint:nilerr } // Create the cluster scope diff --git a/exp/controllers/awsmachinepool_controller_test.go b/exp/controllers/awsmachinepool_controller_test.go index c7c8c2e950..bc53da7739 100644 --- a/exp/controllers/awsmachinepool_controller_test.go +++ b/exp/controllers/awsmachinepool_controller_test.go @@ -42,7 +42,8 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" "sigs.k8s.io/cluster-api/controllers/noderefutil" "sigs.k8s.io/controller-runtime/pkg/client/fake" - //"sigs.k8s.io/cluster-api/controllers/noderefutil" + + // "sigs.k8s.io/cluster-api/controllers/noderefutil" //nolint:godot. capierrors "sigs.k8s.io/cluster-api/errors" expclusterv1 "sigs.k8s.io/cluster-api/exp/api/v1alpha4" "sigs.k8s.io/cluster-api/util/conditions" @@ -314,7 +315,6 @@ func TestAWSMachinePoolReconciler(t *testing.T) { g.Expect(ms.AWSMachinePool.Status.Ready).To(Equal(false)) g.Eventually(recorder.Events).Should(Receive(ContainSubstring("DeletionInProgress"))) }) - }) } diff --git a/exp/controllers/awsmanagedcluster_controller.go b/exp/controllers/awsmanagedcluster_controller.go index 5e849a0a57..afde5d13cd 100644 --- a/exp/controllers/awsmanagedcluster_controller.go +++ b/exp/controllers/awsmanagedcluster_controller.go @@ -25,7 +25,6 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/tools/record" - controlplanev1 "sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1alpha4" ekscontrolplanev1 "sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1alpha4" infrav1exp "sigs.k8s.io/cluster-api-provider-aws/exp/api/v1alpha4" clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" @@ -41,7 +40,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSManagedClusterReconciler reconciles AWSManagedCluster +// AWSManagedClusterReconciler reconciles AWSManagedCluster. type AWSManagedClusterReconciler struct { client.Client Log logr.Logger @@ -114,7 +113,6 @@ func (r *AWSManagedClusterReconciler) Reconcile(ctx context.Context, req ctrl.Re log.Info("Successfully reconciled AWSManagedCluster") return reconcile.Result{}, nil - } func (r *AWSManagedClusterReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error { @@ -154,7 +152,7 @@ func (r *AWSManagedClusterReconciler) managedControlPlaneToManagedCluster(o clie ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() - awsManagedControlPlane, ok := o.(*controlplanev1.AWSManagedControlPlane) + awsManagedControlPlane, ok := o.(*ekscontrolplanev1.AWSManagedControlPlane) if !ok { panic(fmt.Sprintf("Expected a managedControlPlane but got a %T", o)) } diff --git a/exp/controllers/awsmanagedmachinepool_controller.go b/exp/controllers/awsmanagedmachinepool_controller.go index 1841f97dbd..27f7064ea6 100644 --- a/exp/controllers/awsmanagedmachinepool_controller.go +++ b/exp/controllers/awsmanagedmachinepool_controller.go @@ -45,7 +45,7 @@ import ( "sigs.k8s.io/controller-runtime/pkg/source" ) -// AWSManagedMachinePoolReconciler reconciles a AWSManagedMachinePool object +// AWSManagedMachinePoolReconciler reconciles a AWSManagedMachinePool object. type AWSManagedMachinePoolReconciler struct { client.Client Recorder record.EventRecorder @@ -54,7 +54,7 @@ type AWSManagedMachinePoolReconciler struct { WatchFilterValue string } -// SetupWithManager is used to setup the controller +// SetupWithManager is used to setup the controller. func (r *AWSManagedMachinePoolReconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, options controller.Options) error { log := ctrl.LoggerFrom(ctx) @@ -84,7 +84,7 @@ func (r *AWSManagedMachinePoolReconciler) SetupWithManager(ctx context.Context, // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=awsmanagedmachinepools,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=awsmanagedmachinepools/status,verbs=get;update;patch -// Reconcile reconciles AWSManagedMachinePools +// Reconcile reconciles AWSManagedMachinePools. func (r *AWSManagedMachinePoolReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) { log := ctrl.LoggerFrom(ctx) @@ -203,7 +203,7 @@ func (r *AWSManagedMachinePoolReconciler) reconcileDelete( return reconcile.Result{}, nil } -// GetOwnerClusterKey returns only the Cluster name and namespace +// GetOwnerClusterKey returns only the Cluster name and namespace. func GetOwnerClusterKey(obj metav1.ObjectMeta) (*client.ObjectKey, error) { for _, ref := range obj.OwnerReferences { if ref.Kind != "Cluster" { diff --git a/exp/controllers/suite_test.go b/exp/controllers/suite_test.go index c7e8304745..85dc3b57e5 100644 --- a/exp/controllers/suite_test.go +++ b/exp/controllers/suite_test.go @@ -22,17 +22,14 @@ import ( "path" "testing" - "github.com/golang/mock/gomock" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" infrav1exp "sigs.k8s.io/cluster-api-provider-aws/exp/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-aws/test/helpers" clusterv1 "sigs.k8s.io/cluster-api/api/v1alpha4" clusterv1exp "sigs.k8s.io/cluster-api/exp/api/v1alpha4" ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/client" // +kubebuilder:scaffold:imports ) @@ -40,11 +37,8 @@ import ( // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. var ( - testEnv *helpers.TestEnvironment - cfg *rest.Config - k8sClient client.Client - mockCtrl *gomock.Controller - ctx = ctrl.SetupSignalHandler() + testEnv *helpers.TestEnvironment + ctx = ctrl.SetupSignalHandler() ) func TestMain(m *testing.M) { diff --git a/exp/instancestate/awsinstancestate_controller.go b/exp/instancestate/awsinstancestate_controller.go index c756a3e31d..ffd6e67bba 100644 --- a/exp/instancestate/awsinstancestate_controller.go +++ b/exp/instancestate/awsinstancestate_controller.go @@ -42,7 +42,7 @@ import ( // Ec2InstanceStateLabelKey defines an ec2 instance state label. const Ec2InstanceStateLabelKey = "ec2-instance-state" -// AwsInstanceStateReconciler reconciles a AwsInstanceState object +// AwsInstanceStateReconciler reconciles a AwsInstanceState object. type AwsInstanceStateReconciler struct { client.Client Log logr.Logger @@ -205,7 +205,7 @@ func (r *AwsInstanceStateReconciler) processMessage(ctx context.Context, msg mes } } -// getQueueURL retrieves the SQS queue URL for a given cluster +// getQueueURL retrieves the SQS queue URL for a given cluster. func (r *AwsInstanceStateReconciler) getQueueURL(cluster *infrav1.AWSCluster) (string, error) { sqsSvs, err := r.getSQSService(cluster.Spec.Region) if err != nil { diff --git a/exp/instancestate/awsinstancestate_controller_test.go b/exp/instancestate/awsinstancestate_controller_test.go index 9555facca9..8d5f289365 100644 --- a/exp/instancestate/awsinstancestate_controller_test.go +++ b/exp/instancestate/awsinstancestate_controller_test.go @@ -116,7 +116,7 @@ func TestAWSInstanceStateController(t *testing.T) { k8sClient = testEnv.GetClient() persistObject(g, createAWSCluster("aws-cluster-1")) - persistObject(g,createAWSCluster("aws-cluster-2")) + persistObject(g, createAWSCluster("aws-cluster-2")) machine1 := &infrav1.AWSMachine{ Spec: infrav1.AWSMachineSpec{ @@ -124,7 +124,7 @@ func TestAWSInstanceStateController(t *testing.T) { }, ObjectMeta: failingMachineMeta, } - persistObject(g,machine1) + persistObject(g, machine1) t.Log("Ensuring queue URLs are up-to-date") g.Eventually(func() bool { @@ -136,7 +136,7 @@ func TestAWSInstanceStateController(t *testing.T) { return exist }, 10*time.Second).Should(Equal(true)) - deleteAWSCluster(g,"aws-cluster-2") + deleteAWSCluster(g, "aws-cluster-2") t.Log("Ensuring we stop tracking deleted queue") g.Eventually(func() bool { _, ok := instanceStateReconciler.queueURLs.Load("aws-cluster-2") diff --git a/exp/instancestate/helpers_test.go b/exp/instancestate/helpers_test.go index 5e1f88606d..a6f7425460 100644 --- a/exp/instancestate/helpers_test.go +++ b/exp/instancestate/helpers_test.go @@ -18,9 +18,10 @@ package instancestate import ( "context" - "sigs.k8s.io/controller-runtime/pkg/client" "time" + "sigs.k8s.io/controller-runtime/pkg/client" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -52,7 +53,7 @@ func persistObject(g *WithT, o client.Object) { }, time.Second*10).Should(BeTrue()) } -func deleteAWSCluster(g *WithT,name string) { +func deleteAWSCluster(g *WithT, name string) { ctx := context.TODO() awsLookupKey := types.NamespacedName{Name: name, Namespace: "default"} awsCluster := &infrav1.AWSCluster{} diff --git a/exp/instancestate/suite_test.go b/exp/instancestate/suite_test.go index 7382b83815..b5a57381c9 100644 --- a/exp/instancestate/suite_test.go +++ b/exp/instancestate/suite_test.go @@ -18,13 +18,13 @@ package instancestate import ( "fmt" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "os" "path" "testing" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/client-go/kubernetes/scheme" - "k8s.io/client-go/rest" infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" infrav1exp "sigs.k8s.io/cluster-api-provider-aws/exp/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/instancestate/mock_sqsiface" @@ -39,7 +39,6 @@ import ( // http://onsi.github.io/ginkgo/ to learn more about Ginkgo. var ( - cfg *rest.Config k8sClient client.Client instanceStateReconciler *AwsInstanceStateReconciler sqsSvs *mock_sqsiface.MockSQSAPI diff --git a/feature/feature.go b/feature/feature.go index efcef52aa9..48928c9207 100644 --- a/feature/feature.go +++ b/feature/feature.go @@ -26,7 +26,7 @@ const ( // // // owner: @username // // alpha: v1.X - // MyFeature featuregate.Feature = "MyFeature" + // MyFeature featuregate.Feature = "MyFeature". // EKS is used to enable EKS support // owner: @richardcase diff --git a/main.go b/main.go index a317908e55..8fa7ad9ba5 100644 --- a/main.go +++ b/main.go @@ -254,7 +254,7 @@ func main() { } } -func enableGates(ctx context.Context, mgr ctrl.Manager, AWSServiceEndpoints []scope.ServiceEndpoint) { +func enableGates(ctx context.Context, mgr ctrl.Manager, awsServiceEndpoints []scope.ServiceEndpoint) { if feature.Gates.Enabled(feature.EKS) { setupLog.Info("enabling EKS controllers") @@ -264,7 +264,7 @@ func enableGates(ctx context.Context, mgr ctrl.Manager, AWSServiceEndpoints []sc Client: mgr.GetClient(), Recorder: mgr.GetEventRecorderFor("awsmanagedmachinepool-reconciler"), EnableIAM: enableIAM, - Endpoints: AWSServiceEndpoints, + Endpoints: awsServiceEndpoints, WatchFilterValue: watchFilterValue, }).SetupWithManager(ctx, mgr, controller.Options{}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSManagedMachinePool") @@ -282,7 +282,7 @@ func enableGates(ctx context.Context, mgr ctrl.Manager, AWSServiceEndpoints []sc Client: mgr.GetClient(), Recorder: mgr.GetEventRecorderFor("awsfargateprofile-reconciler"), EnableIAM: enableIAM, - Endpoints: AWSServiceEndpoints, + Endpoints: awsServiceEndpoints, WatchFilterValue: watchFilterValue, }).SetupWithManager(ctx, mgr, controller.Options{MaxConcurrentReconciles: awsClusterConcurrency}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSFargateProfile") @@ -303,7 +303,7 @@ func enableGates(ctx context.Context, mgr ctrl.Manager, AWSServiceEndpoints []sc if err := (&instancestate.AwsInstanceStateReconciler{ Client: mgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("AWSInstanceStateController"), - Endpoints: AWSServiceEndpoints, + Endpoints: awsServiceEndpoints, WatchFilterValue: watchFilterValue, }).SetupWithManager(ctx, mgr, controller.Options{MaxConcurrentReconciles: instanceStateConcurrency}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSInstanceStateController") @@ -315,7 +315,7 @@ func enableGates(ctx context.Context, mgr ctrl.Manager, AWSServiceEndpoints []sc if err := (&controlleridentitycreator.AWSControllerIdentityReconciler{ Client: mgr.GetClient(), Log: ctrl.Log.WithName("controllers").WithName("AWSControllerIdentity"), - Endpoints: AWSServiceEndpoints, + Endpoints: awsServiceEndpoints, WatchFilterValue: watchFilterValue, }).SetupWithManager(ctx, mgr, controller.Options{}); err != nil { setupLog.Error(err, "unable to create controller", "controller", "AWSControllerIdentity") diff --git a/pkg/cloud/awserrors/errors.go b/pkg/cloud/awserrors/errors.go index 4e20788abe..8713d66460 100644 --- a/pkg/cloud/awserrors/errors.go +++ b/pkg/cloud/awserrors/errors.go @@ -48,7 +48,7 @@ const ( var _ error = &EC2Error{} -// Code returns the AWS error code as a string +// Code returns the AWS error code as a string. func Code(err error) (string, bool) { if awserr, ok := err.(awserr.Error); ok { return awserr.Code(), true @@ -56,7 +56,7 @@ func Code(err error) (string, bool) { return "", false } -// Message returns the AWS error message as a string +// Message returns the AWS error message as a string. func Message(err error) string { if awserr, ok := err.(awserr.Error); ok { return awserr.Message() @@ -100,7 +100,7 @@ func IsResourceExists(err error) bool { return false } -// NewFailedDependency returns an error which indicates that a dependency failure status +// NewFailedDependency returns an error which indicates that a dependency failure status. func NewFailedDependency(msg string) error { return &EC2Error{ msg: msg, @@ -108,7 +108,7 @@ func NewFailedDependency(msg string) error { } } -// IsFailedDependency checks if the error is pf http.StatusFailedDependency +// IsFailedDependency checks if the error is pf http.StatusFailedDependency. func IsFailedDependency(err error) bool { return ReasonForError(err) == http.StatusFailedDependency } @@ -132,7 +132,7 @@ func IsSDKError(err error) (ok bool) { return } -// IsInvalidNotFoundError tests for common aws not found errors +// IsInvalidNotFoundError tests for common aws not found errors. func IsInvalidNotFoundError(err error) bool { if code, ok := Code(err); ok { switch code { diff --git a/pkg/cloud/converters/eks.go b/pkg/cloud/converters/eks.go index f9b19a4fd7..b291385093 100644 --- a/pkg/cloud/converters/eks.go +++ b/pkg/cloud/converters/eks.go @@ -30,11 +30,11 @@ import ( ) var ( - // ErrUnknowTaintEffect is an error when a unknown TaintEffect is used + // ErrUnknowTaintEffect is an error when a unknown TaintEffect is used. ErrUnknowTaintEffect = errors.New("uknown taint effect") ) -// AddonSDKToAddonState is used to convert an AWS SDK Addon to a control plane AddonState +// AddonSDKToAddonState is used to convert an AWS SDK Addon to a control plane AddonState. func AddonSDKToAddonState(eksAddon *eks.Addon) *ekscontrolplanev1.AddonState { addonState := &ekscontrolplanev1.AddonState{ Name: aws.StringValue(eksAddon.AddonName), @@ -70,7 +70,6 @@ func TaintToSDK(taint infrav1exp.Taint) (*eks.Taint, error) { Key: aws.String(taint.Key), Value: aws.String(taint.Value), }, nil - } // TaintsToSDK is used to convert an array of CAPA Taints to AWS SDK taints. @@ -88,7 +87,7 @@ func TaintsToSDK(taints infrav1exp.Taints) ([]*eks.Taint, error) { return converted, nil } -// TaintsFromSDK is used to convert an array of AWS SDK taints to CAPA Taints +// TaintsFromSDK is used to convert an array of AWS SDK taints to CAPA Taints. func TaintsFromSDK(taints []*eks.Taint) (infrav1exp.Taints, error) { converted := infrav1exp.Taints{} for _, taint := range taints { @@ -106,7 +105,7 @@ func TaintsFromSDK(taints []*eks.Taint) (infrav1exp.Taints, error) { return converted, nil } -// TaintEffectToSDK is used to convert a TaintEffect to the AWS SDK taint effect value +// TaintEffectToSDK is used to convert a TaintEffect to the AWS SDK taint effect value. func TaintEffectToSDK(effect infrav1exp.TaintEffect) (string, error) { switch effect { case infrav1exp.TaintEffectNoExecute: @@ -120,7 +119,7 @@ func TaintEffectToSDK(effect infrav1exp.TaintEffect) (string, error) { } } -// TaintEffectFromSDK is used to convert a AWS SDK taint effect value to a TaintEffect +// TaintEffectFromSDK is used to convert a AWS SDK taint effect value to a TaintEffect. func TaintEffectFromSDK(effect string) (infrav1exp.TaintEffect, error) { switch effect { case eks.TaintEffectNoExecute: diff --git a/pkg/cloud/converters/tags.go b/pkg/cloud/converters/tags.go index 9884e82f7f..863d4add9f 100644 --- a/pkg/cloud/converters/tags.go +++ b/pkg/cloud/converters/tags.go @@ -48,7 +48,7 @@ func MapPtrToMap(src map[string]*string) infrav1.Tags { return tags } -// MapToTags converts a infrav1.Tags to a []*ec2.Tag +// MapToTags converts a infrav1.Tags to a []*ec2.Tag. func MapToTags(src infrav1.Tags) []*ec2.Tag { tags := make([]*ec2.Tag, 0, len(src)) @@ -75,7 +75,7 @@ func ELBTagsToMap(src []*elb.Tag) infrav1.Tags { return tags } -// MapToELBTags converts a infrav1.Tags to a []*elb.Tag +// MapToELBTags converts a infrav1.Tags to a []*elb.Tag. func MapToELBTags(src infrav1.Tags) []*elb.Tag { tags := make([]*elb.Tag, 0, len(src)) @@ -91,7 +91,7 @@ func MapToELBTags(src infrav1.Tags) []*elb.Tag { return tags } -// MapToSecretsManagerTags converts a infrav1.Tags to a []*secretsmanager.Tag +// MapToSecretsManagerTags converts a infrav1.Tags to a []*secretsmanager.Tag. func MapToSecretsManagerTags(src infrav1.Tags) []*secretsmanager.Tag { tags := make([]*secretsmanager.Tag, 0, len(src)) @@ -107,7 +107,7 @@ func MapToSecretsManagerTags(src infrav1.Tags) []*secretsmanager.Tag { return tags } -// MapToSSMTags converts a infrav1.Tags to a []*ssm.Tag +// MapToSSMTags converts a infrav1.Tags to a []*ssm.Tag. func MapToSSMTags(src infrav1.Tags) []*ssm.Tag { tags := make([]*ssm.Tag, 0, len(src)) diff --git a/pkg/cloud/endpoints/endpoints.go b/pkg/cloud/endpoints/endpoints.go index 1a0209dc9e..8d102d743d 100644 --- a/pkg/cloud/endpoints/endpoints.go +++ b/pkg/cloud/endpoints/endpoints.go @@ -39,7 +39,7 @@ func serviceEnum() []string { partitions := resolver.(endpoints.EnumPartitions).Partitions() for _, p := range partitions { for id := range p.Services() { - var add bool = true + var add = true for _, s := range serviceIDs { if id == s { add = false @@ -55,10 +55,9 @@ func serviceEnum() []string { } // ParseFlag parses the command line flag of service endponts in the format ${SigningRegion1}:${ServiceID1}=${URL1},${ServiceID2}=${URL2}...;${SigningRegion2}... -// returning a set of ServiceEndpoints +// returning a set of ServiceEndpoints. func ParseFlag(serviceEndpoints string) ([]scope.ServiceEndpoint, error) { if serviceEndpoints == "" { - return nil, nil } serviceIDs := serviceEnum() @@ -67,7 +66,6 @@ func ParseFlag(serviceEndpoints string) ([]scope.ServiceEndpoint, error) { for _, regionConfig := range signingRegionConfigs { components := strings.SplitN(regionConfig, ":", 2) if len(components) != 2 { - return nil, errServiceEndpointSigningRegion } signingRegion := components[0] @@ -76,10 +74,9 @@ func ParseFlag(serviceEndpoints string) ([]scope.ServiceEndpoint, error) { for _, servicePair := range servicePairs { kv := strings.Split(servicePair, "=") if len(kv) != 2 { - return nil, errServiceEndpointFormat } - var serviceID string = "" + var serviceID = "" for _, id := range serviceIDs { if kv[0] == id { serviceID = kv[0] @@ -96,7 +93,6 @@ func ParseFlag(serviceEndpoints string) ([]scope.ServiceEndpoint, error) { seenServices = append(seenServices, serviceID) URL, err := url.ParseRequestURI(kv[1]) if err != nil { - return nil, errServiceEndpointURL } endpoints = append(endpoints, scope.ServiceEndpoint{ @@ -113,7 +109,6 @@ func ParseFlag(serviceEndpoints string) ([]scope.ServiceEndpoint, error) { func containsString(slice []string, s string) bool { for _, item := range slice { if item == s { - return true } } diff --git a/pkg/cloud/endpoints/endpoints_test.go b/pkg/cloud/endpoints/endpoints_test.go index 53d3fbb77c..1ff6c3c68f 100644 --- a/pkg/cloud/endpoints/endpoints_test.go +++ b/pkg/cloud/endpoints/endpoints_test.go @@ -24,7 +24,6 @@ import ( ) func TestParseFlags(t *testing.T) { - testCases := []struct { name string flagToParse string diff --git a/pkg/cloud/filter/ec2.go b/pkg/cloud/filter/ec2.go index d3a070de10..5da3d6ee99 100644 --- a/pkg/cloud/filter/ec2.go +++ b/pkg/cloud/filter/ec2.go @@ -54,7 +54,7 @@ func (ec2Filters) Name(name string) *ec2.Filter { } // ClusterOwned returns a filter using the Cluster API per-cluster tag where -// the resource is owned +// the resource is owned. func (ec2Filters) ClusterOwned(clusterName string) *ec2.Filter { return &ec2.Filter{ Name: aws.String(fmt.Sprintf("tag:%s", infrav1.ClusterTagKey(clusterName))), diff --git a/pkg/cloud/identity/identity_test.go b/pkg/cloud/identity/identity_test.go index ae58978bb3..090ea70512 100644 --- a/pkg/cloud/identity/identity_test.go +++ b/pkg/cloud/identity/identity_test.go @@ -44,9 +44,8 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { "SecretAccessKey": []byte("static-SecretAccessKey"), }, } - var staticProvider AWSPrincipalTypeProvider - staticProvider = NewAWSStaticPrincipalTypeProvider(&infrav1.AWSClusterStaticIdentity{}, secret) + var staticProvider AWSPrincipalTypeProvider = NewAWSStaticPrincipalTypeProvider(&infrav1.AWSClusterStaticIdentity{}, secret) stsMock := mock_stsiface.NewMockSTSAPI(mockCtrl) roleIdentity := &infrav1.AWSClusterRoleIdentity{ @@ -58,8 +57,8 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { }, }, } - var roleProvider AWSPrincipalTypeProvider - roleProvider = &AWSRolePrincipalTypeProvider{ + + var roleProvider AWSPrincipalTypeProvider = &AWSRolePrincipalTypeProvider{ credentials: nil, Principal: roleIdentity, sourceProvider: &staticProvider, @@ -75,8 +74,8 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { }, }, } - var roleProvider2 AWSPrincipalTypeProvider - roleProvider2 = &AWSRolePrincipalTypeProvider{ + + var roleProvider2 AWSPrincipalTypeProvider = &AWSRolePrincipalTypeProvider{ credentials: nil, Principal: roleIdentity2, sourceProvider: &roleProvider, @@ -190,10 +189,10 @@ func TestAWSStaticPrincipalTypeProvider(t *testing.T) { if tc.expectErr { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) + if !reflect.DeepEqual(tc.value, value) { t.Fatal("Did not get expected result") } diff --git a/pkg/cloud/interfaces.go b/pkg/cloud/interfaces.go index e5ae7e4cb8..49d4fd5c0f 100644 --- a/pkg/cloud/interfaces.go +++ b/pkg/cloud/interfaces.go @@ -26,24 +26,24 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" ) -// Session represents an AWS session +// Session represents an AWS session. type Session interface { Session() awsclient.ConfigProvider ServiceLimiter(string) *throttle.ServiceLimiter } -// ScopeUsage is used to indicate which controller is using a scope +// ScopeUsage is used to indicate which controller is using a scope. type ScopeUsage interface { // ControllerName returns the name of the controller that created the scope ControllerName() string } -// ClusterObject represents a AWS cluster object +// ClusterObject represents a AWS cluster object. type ClusterObject interface { conditions.Setter } -// ClusterScoper is the interface for a cluster scope +// ClusterScoper is the interface for a cluster scope. type ClusterScoper interface { logr.Logger Session diff --git a/pkg/cloud/scope/clients.go b/pkg/cloud/scope/clients.go index 44a720e1f9..f3466093ee 100644 --- a/pkg/cloud/scope/clients.go +++ b/pkg/cloud/scope/clients.go @@ -53,7 +53,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/version" ) -// NewASGClient creates a new ASG API client for a given session +// NewASGClient creates a new ASG API client for a given session. func NewASGClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) autoscalingiface.AutoScalingAPI { asgClient := autoscaling.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) asgClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -63,7 +63,7 @@ func NewASGClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return asgClient } -// NewEC2Client creates a new EC2 API client for a given session +// NewEC2Client creates a new EC2 API client for a given session. func NewEC2Client(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) ec2iface.EC2API { ec2Client := ec2.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) ec2Client.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -79,7 +79,7 @@ func NewEC2Client(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return ec2Client } -// NewELBClient creates a new ELB API client for a given session +// NewELBClient creates a new ELB API client for a given session. func NewELBClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) elbiface.ELBAPI { elbClient := elb.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) elbClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -91,7 +91,7 @@ func NewELBClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return elbClient } -// NewEventBridgeClient creates a new EventBridge API client for a given session +// NewEventBridgeClient creates a new EventBridge API client for a given session. func NewEventBridgeClient(scopeUser cloud.ScopeUsage, session cloud.Session, target runtime.Object) eventbridgeiface.EventBridgeAPI { eventBridgeClient := eventbridge.New(session.Session()) eventBridgeClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -101,7 +101,7 @@ func NewEventBridgeClient(scopeUser cloud.ScopeUsage, session cloud.Session, tar return eventBridgeClient } -// NewSQSClient creates a new SQS API client for a given session +// NewSQSClient creates a new SQS API client for a given session. func NewSQSClient(scopeUser cloud.ScopeUsage, session cloud.Session, target runtime.Object) sqsiface.SQSAPI { SQSClient := sqs.New(session.Session()) SQSClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -111,7 +111,7 @@ func NewSQSClient(scopeUser cloud.ScopeUsage, session cloud.Session, target runt return SQSClient } -// NewGlobalSQSClient for creating a new SQS API client that isn't tied to a cluster +// NewGlobalSQSClient for creating a new SQS API client that isn't tied to a cluster. func NewGlobalSQSClient(scopeUser cloud.ScopeUsage, session cloud.Session) sqsiface.SQSAPI { SQSClient := sqs.New(session.Session()) SQSClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -120,7 +120,7 @@ func NewGlobalSQSClient(scopeUser cloud.ScopeUsage, session cloud.Session) sqsif return SQSClient } -// NewResourgeTaggingClient creates a new Resource Tagging API client for a given session +// NewResourgeTaggingClient creates a new Resource Tagging API client for a given session. func NewResourgeTaggingClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) resourcegroupstaggingapiiface.ResourceGroupsTaggingAPIAPI { resourceTagging := resourcegroupstaggingapi.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) resourceTagging.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -132,7 +132,7 @@ func NewResourgeTaggingClient(scopeUser cloud.ScopeUsage, session cloud.Session, return resourceTagging } -// NewSecretsManagerClient creates a new Secrets API client for a given session +// NewSecretsManagerClient creates a new Secrets API client for a given session.. func NewSecretsManagerClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) secretsmanageriface.SecretsManagerAPI { secretsClient := secretsmanager.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) secretsClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -144,7 +144,7 @@ func NewSecretsManagerClient(scopeUser cloud.ScopeUsage, session cloud.Session, return secretsClient } -// NewEKSClient creates a new EKS API client for a given session +// NewEKSClient creates a new EKS API client for a given session. func NewEKSClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) eksiface.EKSAPI { eksClient := eks.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) eksClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -154,7 +154,7 @@ func NewEKSClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return eksClient } -// NewIAMClient creates a new IAM API client for a given session +// NewIAMClient creates a new IAM API client for a given session. func NewIAMClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) iamiface.IAMAPI { iamClient := iam.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) iamClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -164,7 +164,7 @@ func NewIAMClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return iamClient } -// NewSTSClient creates a new STS API client for a given session +// NewSTSClient creates a new STS API client for a given session. func NewSTSClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) stsiface.STSAPI { stsClient := sts.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) stsClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) @@ -174,7 +174,7 @@ func NewSTSClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr return stsClient } -// NewSSMClient creates a new Secrets API client for a given session +// NewSSMClient creates a new Secrets API client for a given session. func NewSSMClient(scopeUser cloud.ScopeUsage, session cloud.Session, logger logr.Logger, target runtime.Object) ssmiface.SSMAPI { ssmClient := ssm.New(session.Session(), aws.NewConfig().WithLogLevel(awslogs.GetAWSLogLevel(logger)).WithLogger(awslogs.NewWrapLogr(logger))) ssmClient.Handlers.Build.PushFrontNamed(getUserAgentHandler()) diff --git a/pkg/cloud/scope/cluster.go b/pkg/cloud/scope/cluster.go index 914e52e390..0224f03bea 100644 --- a/pkg/cloud/scope/cluster.go +++ b/pkg/cloud/scope/cluster.go @@ -130,7 +130,7 @@ func (s *ClusterScope) CNIIngressRules() infrav1.CNIIngressRules { return infrav1.CNIIngressRules{} } -// SecurityGroupOverrides returns the cluster security group overrides +// SecurityGroupOverrides returns the cluster security group overrides. func (s *ClusterScope) SecurityGroupOverrides() map[infrav1.SecurityGroupRole]string { return s.AWSCluster.Spec.NetworkSpec.SecurityGroupOverrides } @@ -140,7 +140,7 @@ func (s *ClusterScope) SecurityGroups() map[infrav1.SecurityGroupRole]infrav1.Se return s.AWSCluster.Status.Network.SecurityGroups } -// SecondaryCidrBlock is currently unimplemented for non-managed clusters +// SecondaryCidrBlock is currently unimplemented for non-managed clusters. func (s *ClusterScope) SecondaryCidrBlock() *string { return nil } @@ -166,17 +166,17 @@ func (s *ClusterScope) Region() string { } // KubernetesClusterName is the name of the Kubernetes cluster. For the cluster -// scope this is the same as the CAPI cluster name +// scope this is the same as the CAPI cluster name. func (s *ClusterScope) KubernetesClusterName() string { return s.Cluster.Name } -// ControlPlaneLoadBalancer returns the AWSLoadBalancerSpec +// ControlPlaneLoadBalancer returns the AWSLoadBalancerSpec. func (s *ClusterScope) ControlPlaneLoadBalancer() *infrav1.AWSLoadBalancerSpec { return s.AWSCluster.Spec.ControlPlaneLoadBalancer } -// ControlPlaneLoadBalancerScheme returns the Classic ELB scheme (public or internal facing) +// ControlPlaneLoadBalancerScheme returns the Classic ELB scheme (public or internal facing). func (s *ClusterScope) ControlPlaneLoadBalancerScheme() infrav1.ClassicELBScheme { if s.ControlPlaneLoadBalancer() != nil && s.ControlPlaneLoadBalancer().Scheme != nil { return *s.ControlPlaneLoadBalancer().Scheme @@ -277,12 +277,12 @@ func (s *ClusterScope) InfraCluster() cloud.ClusterObject { return s.AWSCluster } -// Session returns the AWS SDK session. Used for creating clients +// Session returns the AWS SDK session. Used for creating clients. func (s *ClusterScope) Session() awsclient.ConfigProvider { return s.session } -// ServiceLimiter returns the AWS SDK session. Used for creating clients +// ServiceLimiter returns the AWS SDK session. Used for creating clients. func (s *ClusterScope) ServiceLimiter(service string) *throttle.ServiceLimiter { if sl, ok := s.serviceLimiters[service]; ok { return sl @@ -311,17 +311,17 @@ func (s *ClusterScope) ControllerName() string { return s.controllerName } -// ImageLookupFormat returns the format string to use when looking up AMIs +// ImageLookupFormat returns the format string to use when looking up AMIs. func (s *ClusterScope) ImageLookupFormat() string { return s.AWSCluster.Spec.ImageLookupFormat } -// ImageLookupOrg returns the organization name to use when looking up AMIs +// ImageLookupOrg returns the organization name to use when looking up AMIs. func (s *ClusterScope) ImageLookupOrg() string { return s.AWSCluster.Spec.ImageLookupOrg } -// ImageLookupBaseOS returns the base operating system name to use when looking up AMIs +// ImageLookupBaseOS returns the base operating system name to use when looking up AMIs. func (s *ClusterScope) ImageLookupBaseOS() string { return s.AWSCluster.Spec.ImageLookupBaseOS } diff --git a/pkg/cloud/scope/ec2.go b/pkg/cloud/scope/ec2.go index 9d5dca9989..aea95cbb86 100644 --- a/pkg/cloud/scope/ec2.go +++ b/pkg/cloud/scope/ec2.go @@ -21,7 +21,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud" ) -// EC2Scope is the interface for the scoep to be used with the ec2 service +// EC2Scope is the interface for the scoep to be used with the ec2 service. type EC2Scope interface { cloud.ClusterScoper diff --git a/pkg/cloud/scope/elb.go b/pkg/cloud/scope/elb.go index 0c53843114..132127f674 100644 --- a/pkg/cloud/scope/elb.go +++ b/pkg/cloud/scope/elb.go @@ -21,7 +21,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud" ) -// ELBScope is a scope for use with the ELB reconciling service +// ELBScope is a scope for use with the ELB reconciling service. type ELBScope interface { cloud.ClusterScoper diff --git a/pkg/cloud/scope/fargate.go b/pkg/cloud/scope/fargate.go index 463e5a43cc..6dafd30b0a 100644 --- a/pkg/cloud/scope/fargate.go +++ b/pkg/cloud/scope/fargate.go @@ -114,7 +114,7 @@ func (s *FargateProfileScope) ManagedPoolName() string { return s.FargateProfile.Name } -// ServiceLimiter returns the AWS SDK session. Used for creating clients +// ServiceLimiter returns the AWS SDK session. Used for creating clients. func (s *FargateProfileScope) ServiceLimiter(service string) *throttle.ServiceLimiter { if sl, ok := s.serviceLimiters[service]; ok { return sl @@ -127,7 +127,7 @@ func (s *FargateProfileScope) ClusterName() string { return s.Cluster.Name } -// EnableIAM indicates that reconciliation should create IAM roles +// EnableIAM indicates that reconciliation should create IAM roles. func (s *FargateProfileScope) EnableIAM() bool { return s.enableIAM } @@ -142,7 +142,7 @@ func (s *FargateProfileScope) AdditionalTags() infrav1.Tags { return s.FargateProfile.Spec.AdditionalTags.DeepCopy() } -// RoleName returns the node group role name +// RoleName returns the node group role name. func (s *FargateProfileScope) RoleName() string { return s.FargateProfile.Spec.RoleName } @@ -158,7 +158,7 @@ func (s *FargateProfileScope) SubnetIDs() []string { } // IAMReadyFalse marks the ready condition false using warning if error isn't -// empty +// empty. func (s *FargateProfileScope) IAMReadyFalse(reason string, err string) error { severity := clusterv1.ConditionSeverityWarning if err == "" { @@ -200,7 +200,7 @@ func (s *FargateProfileScope) InfraCluster() cloud.ClusterObject { return s.ControlPlane } -// Session returns the AWS SDK session. Used for creating clients +// Session returns the AWS SDK session. Used for creating clients. func (s *FargateProfileScope) Session() awsclient.ConfigProvider { return s.session } diff --git a/pkg/cloud/scope/global.go b/pkg/cloud/scope/global.go index 65707b6664..903e626ae0 100644 --- a/pkg/cloud/scope/global.go +++ b/pkg/cloud/scope/global.go @@ -55,7 +55,7 @@ type GlobalScope struct { controllerName string } -// Session returns the AWS SDK session. Used for creating clients +// Session returns the AWS SDK session. Used for creating clients. func (s *GlobalScope) Session() awsclient.ConfigProvider { return s.session } @@ -69,7 +69,7 @@ func (s *GlobalScope) ServiceLimiter(service string) *throttle.ServiceLimiter { } // ControllerName returns the name of the controller that -// created the GlobalScope +// created the GlobalScope. func (s *GlobalScope) ControllerName() string { return s.controllerName } diff --git a/pkg/cloud/scope/machine.go b/pkg/cloud/scope/machine.go index 4c6f81a6f1..da530d1707 100644 --- a/pkg/cloud/scope/machine.go +++ b/pkg/cloud/scope/machine.go @@ -160,12 +160,12 @@ func (m *MachineScope) SetInstanceState(v infrav1.InstanceState) { m.AWSMachine.Status.InstanceState = &v } -// SetReady sets the AWSMachine Ready Status +// SetReady sets the AWSMachine Ready Status. func (m *MachineScope) SetReady() { m.AWSMachine.Status.Ready = true } -// SetNotReady sets the AWSMachine Ready Status to false +// SetNotReady sets the AWSMachine Ready Status to false. func (m *MachineScope) SetNotReady() { m.AWSMachine.Status.Ready = false } @@ -206,31 +206,31 @@ func (m *MachineScope) UserDataIsUncompressed() bool { } // GetSecretPrefix returns the prefix for the secrets belonging -// to the AWSMachine in AWS Secrets Manager +// to the AWSMachine in AWS Secrets Manager. func (m *MachineScope) GetSecretPrefix() string { return m.AWSMachine.Spec.CloudInit.SecretPrefix } // SetSecretPrefix sets the prefix for the secrets belonging -// to the AWSMachine in AWS Secrets Manager +// to the AWSMachine in AWS Secrets Manager. func (m *MachineScope) SetSecretPrefix(value string) { m.AWSMachine.Spec.CloudInit.SecretPrefix = value } // DeleteSecretPrefix deletes the prefix for the secret belonging -// to the AWSMachine in AWS Secrets Manager +// to the AWSMachine in AWS Secrets Manager. func (m *MachineScope) DeleteSecretPrefix() { m.AWSMachine.Spec.CloudInit.SecretPrefix = "" } // GetSecretCount returns the number of AWS Secret Manager entries making up -// the complete userdata +// the complete userdata. func (m *MachineScope) GetSecretCount() int32 { return m.AWSMachine.Spec.CloudInit.SecretCount } // SetSecretCount sets the number of AWS Secret Manager entries making up -// the complete userdata +// the complete userdata. func (m *MachineScope) SetSecretCount(i int32) { m.AWSMachine.Spec.CloudInit.SecretCount = i } @@ -355,7 +355,7 @@ func (m *MachineScope) IsExternallyManaged() bool { return annotations.IsExternallyManaged(m.InfraCluster.InfraCluster()) } -// SetInterruptible sets the AWSMachine status Interruptible +// SetInterruptible sets the AWSMachine status Interruptible. func (m *MachineScope) SetInterruptible() { if m.AWSMachine.Spec.SpotMarketOptions != nil { m.AWSMachine.Status.Interruptible = true diff --git a/pkg/cloud/scope/machine_test.go b/pkg/cloud/scope/machine_test.go index 00e78bfda7..369194279a 100644 --- a/pkg/cloud/scope/machine_test.go +++ b/pkg/cloud/scope/machine_test.go @@ -18,9 +18,10 @@ package scope import ( "encoding/base64" - "sigs.k8s.io/controller-runtime/pkg/client" "testing" + "sigs.k8s.io/controller-runtime/pkg/client" + corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" @@ -199,8 +200,7 @@ func TestSetSecretARN(t *testing.T) { } scope.SetSecretPrefix(prefix) - val := scope.GetSecretPrefix() - if val != prefix { + if val := scope.GetSecretPrefix(); val != prefix { t.Fatalf("prefix does not equal %s: %s", prefix, val) } } diff --git a/pkg/cloud/scope/machinepool.go b/pkg/cloud/scope/machinepool.go index 0d598ecb12..748a0d6d25 100644 --- a/pkg/cloud/scope/machinepool.go +++ b/pkg/cloud/scope/machinepool.go @@ -189,12 +189,12 @@ func (m *MachinePoolScope) SetFailureReason(v capierrors.MachineStatusError) { m.AWSMachinePool.Status.FailureReason = &v } -// HasFailed returns true when the AWSMachinePool's Failure reason or Failure message is populated +// HasFailed returns true when the AWSMachinePool's Failure reason or Failure message is populated. func (m *MachinePoolScope) HasFailed() bool { return m.AWSMachinePool.Status.FailureReason != nil || m.AWSMachinePool.Status.FailureMessage != nil } -// SetNotReady sets the AWSMachinePool Ready Status to false +// SetNotReady sets the AWSMachinePool Ready Status to false. func (m *MachinePoolScope) SetNotReady() { m.AWSMachinePool.Status.Ready = false } @@ -239,7 +239,7 @@ func (m *MachinePoolScope) SubnetIDs() ([]string, error) { }) } -// NodeStatus represents the status of a Kubernetes node +// NodeStatus represents the status of a Kubernetes node. type NodeStatus struct { Ready bool Version string @@ -297,7 +297,6 @@ func (m *MachinePoolScope) getNodeStatusByProviderID(ctx context.Context, provid } for _, node := range nodeList.Items { - strList := strings.Split(node.Spec.ProviderID, "/") if status, ok := nodeStatusMap[fmt.Sprintf("aws:////%s", strList[len(strList)-1])]; ok { diff --git a/pkg/cloud/scope/managedcontrolplane.go b/pkg/cloud/scope/managedcontrolplane.go index 505359e5c0..24fa0161fb 100644 --- a/pkg/cloud/scope/managedcontrolplane.go +++ b/pkg/cloud/scope/managedcontrolplane.go @@ -148,7 +148,7 @@ func (s *ManagedControlPlaneScope) VPC() *infrav1.VPCSpec { return &s.ControlPlane.Spec.NetworkSpec.VPC } -// ServiceLimiter returns the AWS SDK session. Used for creating clients +// ServiceLimiter returns the AWS SDK session. Used for creating clients. func (s *ManagedControlPlaneScope) ServiceLimiter(service string) *throttle.ServiceLimiter { if sl, ok := s.serviceLimiters[service]; ok { return sl @@ -254,7 +254,7 @@ func (s *ManagedControlPlaneScope) AdditionalTags() infrav1.Tags { return s.ControlPlane.Spec.AdditionalTags.DeepCopy() } -// APIServerPort returns the port to use when communicating with the API server +// APIServerPort returns the port to use when communicating with the API server. func (s *ManagedControlPlaneScope) APIServerPort() int32 { return 443 } @@ -272,7 +272,7 @@ func (s *ManagedControlPlaneScope) InfraCluster() cloud.ClusterObject { return s.ControlPlane } -// Session returns the AWS SDK session. Used for creating clients +// Session returns the AWS SDK session. Used for creating clients. func (s *ManagedControlPlaneScope) Session() awsclient.ConfigProvider { return s.session } @@ -298,7 +298,7 @@ func (s *ManagedControlPlaneScope) ControllerName() string { return s.controllerName } -// TokenMethod returns the token method to use in the kubeconfig +// TokenMethod returns the token method to use in the kubeconfig. func (s *ManagedControlPlaneScope) TokenMethod() ekscontrolplanev1.EKSTokenMethod { if s.ControlPlane.Spec.TokenMethod != nil { return *s.ControlPlane.Spec.TokenMethod @@ -308,32 +308,32 @@ func (s *ManagedControlPlaneScope) TokenMethod() ekscontrolplanev1.EKSTokenMetho } // KubernetesClusterName is the name of the Kubernetes cluster. For the managed -// scope this is the different to the CAPI cluster name and is the EKS cluster name +// scope this is the different to the CAPI cluster name and is the EKS cluster name. func (s *ManagedControlPlaneScope) KubernetesClusterName() string { return s.ControlPlane.Spec.EKSClusterName } -// EnableIAM indicates that reconciliation should create IAM roles +// EnableIAM indicates that reconciliation should create IAM roles. func (s *ManagedControlPlaneScope) EnableIAM() bool { return s.enableIAM } -// AllowAdditionalRoles indicates if additional roles can be added to the created IAM roles +// AllowAdditionalRoles indicates if additional roles can be added to the created IAM roles. func (s *ManagedControlPlaneScope) AllowAdditionalRoles() bool { return s.allowAdditionalRoles } -// ImageLookupFormat returns the format string to use when looking up AMIs +// ImageLookupFormat returns the format string to use when looking up AMIs. func (s *ManagedControlPlaneScope) ImageLookupFormat() string { return s.ControlPlane.Spec.ImageLookupFormat } -// ImageLookupOrg returns the organization name to use when looking up AMIs +// ImageLookupOrg returns the organization name to use when looking up AMIs. func (s *ManagedControlPlaneScope) ImageLookupOrg() string { return s.ControlPlane.Spec.ImageLookupOrg } -// ImageLookupBaseOS returns the base operating system name to use when looking up AMIs +// ImageLookupBaseOS returns the base operating system name to use when looking up AMIs. func (s *ManagedControlPlaneScope) ImageLookupBaseOS() string { return s.ControlPlane.Spec.ImageLookupBaseOS } @@ -346,7 +346,7 @@ func (s *ManagedControlPlaneScope) IAMAuthConfig() *ekscontrolplanev1.IAMAuthent return s.ControlPlane.Spec.IAMAuthenticatorConfig } -// Addons returns the list of addons for a EKS cluster +// Addons returns the list of addons for a EKS cluster. func (s *ManagedControlPlaneScope) Addons() []ekscontrolplanev1.Addon { if s.ControlPlane.Spec.Addons == nil { return []ekscontrolplanev1.Addon{} @@ -354,7 +354,7 @@ func (s *ManagedControlPlaneScope) Addons() []ekscontrolplanev1.Addon { return *s.ControlPlane.Spec.Addons } -// DisableVPCCNI returns whether the AWS VPC CNI should be disabled +// DisableVPCCNI returns whether the AWS VPC CNI should be disabled. func (s *ManagedControlPlaneScope) DisableVPCCNI() bool { return s.ControlPlane.Spec.DisableVPCCNI } diff --git a/pkg/cloud/scope/managednodegroup.go b/pkg/cloud/scope/managednodegroup.go index d9f40b72c4..9a0561788e 100644 --- a/pkg/cloud/scope/managednodegroup.go +++ b/pkg/cloud/scope/managednodegroup.go @@ -121,7 +121,7 @@ func (s *ManagedMachinePoolScope) ManagedPoolName() string { return s.ManagedMachinePool.Name } -// ServiceLimiter returns the AWS SDK session. Used for creating clients +// ServiceLimiter returns the AWS SDK session. Used for creating clients. func (s *ManagedMachinePoolScope) ServiceLimiter(service string) *throttle.ServiceLimiter { if sl, ok := s.serviceLimiters[service]; ok { return sl @@ -134,7 +134,7 @@ func (s *ManagedMachinePoolScope) ClusterName() string { return s.Cluster.Name } -// EnableIAM indicates that reconciliation should create IAM roles +// EnableIAM indicates that reconciliation should create IAM roles. func (s *ManagedMachinePoolScope) EnableIAM() bool { return s.enableIAM } @@ -154,12 +154,12 @@ func (s *ManagedMachinePoolScope) AdditionalTags() infrav1.Tags { return s.ManagedMachinePool.Spec.AdditionalTags.DeepCopy() } -// RoleName returns the node group role name +// RoleName returns the node group role name. func (s *ManagedMachinePoolScope) RoleName() string { return s.ManagedMachinePool.Spec.RoleName } -// Version returns the nodegroup Kubernetes version +// Version returns the nodegroup Kubernetes version. func (s *ManagedMachinePoolScope) Version() *string { return s.MachinePool.Spec.Template.Spec.Version } @@ -185,7 +185,7 @@ func (s *ManagedMachinePoolScope) SubnetIDs() ([]string, error) { } // NodegroupReadyFalse marks the ready condition false using warning if error isn't -// empty +// empty. func (s *ManagedMachinePoolScope) NodegroupReadyFalse(reason string, err string) error { severity := clusterv1.ConditionSeverityWarning if err == "" { @@ -205,7 +205,7 @@ func (s *ManagedMachinePoolScope) NodegroupReadyFalse(reason string, err string) } // IAMReadyFalse marks the ready condition false using warning if error isn't -// empty +// empty. func (s *ManagedMachinePoolScope) IAMReadyFalse(reason string, err string) error { severity := clusterv1.ConditionSeverityWarning if err == "" { @@ -245,7 +245,7 @@ func (s *ManagedMachinePoolScope) InfraCluster() cloud.ClusterObject { return s.ControlPlane } -// Session returns the AWS SDK session. Used for creating clients +// Session returns the AWS SDK session. Used for creating clients. func (s *ManagedMachinePoolScope) Session() awsclient.ConfigProvider { return s.session } @@ -261,7 +261,7 @@ func (s *ManagedMachinePoolScope) KubernetesClusterName() string { return s.ControlPlane.Spec.EKSClusterName } -// NodegroupName is the name of the EKS nodegroup +// NodegroupName is the name of the EKS nodegroup. func (s *ManagedMachinePoolScope) NodegroupName() string { return s.ManagedMachinePool.Spec.EKSNodegroupName } diff --git a/pkg/cloud/scope/session.go b/pkg/cloud/scope/session.go index 4676c3232e..b9b59b0659 100644 --- a/pkg/cloud/scope/session.go +++ b/pkg/cloud/scope/session.go @@ -50,7 +50,7 @@ const ( notPermittedError = "Namespace is not permitted to use %s: %s" ) -// ServiceEndpoint defines a tuple containing AWS Service resolution information +// ServiceEndpoint defines a tuple containing AWS Service resolution information. type ServiceEndpoint struct { ServiceID string URL string @@ -123,7 +123,6 @@ func sessionForClusterWithRegion(k8sClient client.Client, clusterScoper cloud.Cl // could not get providers and retrieve the credentials conditions.MarkFalse(clusterScoper.InfraCluster(), infrav1.PrincipalCredentialRetrievedCondition, infrav1.PrincipalCredentialRetrievalFailedReason, clusterv1.ConditionSeverityError, err.Error()) return nil, nil, errors.Wrap(err, "Failed to get providers for cluster") - } isChanged := false @@ -423,7 +422,7 @@ func isClusterPermittedToUsePrincipal(k8sClient client.Client, allowedNs *infrav return true, nil } - for _, v := range (*allowedNs).NamespaceList { + for _, v := range allowedNs.NamespaceList { if v == clusterNamespace { return true, nil } diff --git a/pkg/cloud/scope/session_test.go b/pkg/cloud/scope/session_test.go index 34239702fc..5496129519 100644 --- a/pkg/cloud/scope/session_test.go +++ b/pkg/cloud/scope/session_test.go @@ -200,7 +200,6 @@ func TestIsClusterPermittedToUsePrincipal(t *testing.T) { if tc.expectedResult != result { t.Fatal("Did not get expected result") } - }) } } @@ -463,6 +462,7 @@ func TestPrincipalParsing(t *testing.T) { } for _, tc := range testCases { + tc := tc t.Run(tc.name, func(t *testing.T) { scheme, err := setupScheme() if err != nil { diff --git a/pkg/cloud/scope/shared.go b/pkg/cloud/scope/shared.go index c8379f3818..dfbd0cec97 100644 --- a/pkg/cloud/scope/shared.go +++ b/pkg/cloud/scope/shared.go @@ -27,11 +27,11 @@ import ( var ( // ErrAZSubnetsNotFound is an error when a availability zone is specified but there are - // no matching subnets for that availability zone (a.k.a. fault domain) + // no matching subnets for that availability zone (a.k.a. fault domain). ErrAZSubnetsNotFound = errors.New("no subnets found for supplied availability zone") - // ErrLoggerRequired is an error if a logger isn't specified + // ErrLoggerRequired is an error if a logger isn't specified. ErrLoggerRequired = errors.New("logger is required") - // ErrNotPlaced is an error if there is no placement determined + // ErrNotPlaced is an error if there is no placement determined. ErrNotPlaced = errors.New("placement not determined") ) @@ -56,7 +56,7 @@ func newDefaultSubnetPlacementStrategy(logger logr.Logger) (subnetsPlacementStra }, nil } -// defaultSubnetPlacementStrategy is the default strategy for subnet placement +// defaultSubnetPlacementStrategy is the default strategy for subnet placement. type defaultSubnetPlacementStrategy struct { logger logr.Logger } @@ -66,7 +66,7 @@ type defaultSubnetPlacementStrategy struct { // 2. If the spec has Availability Zones then get the subnets for these AZs // 3. If the parent resource has Availability Zones then get the subnets for these AZs // 4. All the private subnets from the control plane are used -// In Cluster API Availability Zone can also be referred to by the name `Failure Domain` +// In Cluster API Availability Zone can also be referred to by the name `Failure Domain`. func (p *defaultSubnetPlacementStrategy) Place(input *placementInput) ([]string, error) { if len(input.SpecSubnetIDs) > 0 { p.logger.V(2).Info("using subnets from the spec") diff --git a/pkg/cloud/scope/shared_test.go b/pkg/cloud/scope/shared_test.go index d764669596..ade3d452b4 100644 --- a/pkg/cloud/scope/shared_test.go +++ b/pkg/cloud/scope/shared_test.go @@ -162,12 +162,10 @@ func TestSubnetPlacement(t *testing.T) { if tc.expectError { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) g.Expect(actualSubnetIDs).To(Equal(tc.expectedSubnetIDs)) - }) } } diff --git a/pkg/cloud/services/autoscaling/autoscalinggroup.go b/pkg/cloud/services/autoscaling/autoscalinggroup.go index 387e7bc974..4b2d38d2c5 100644 --- a/pkg/cloud/services/autoscaling/autoscalinggroup.go +++ b/pkg/cloud/services/autoscaling/autoscalinggroup.go @@ -114,7 +114,6 @@ func (s *Service) ASGIfExists(name *string) (*expinfrav1.AutoScalingGroup, error } //TODO: double check if you're handling nil vals return s.SDKToAutoScalingGroup(out.AutoScalingGroups[0]) - } // GetASGByName returns the existing ASG or nothing if it doesn't exist. @@ -222,8 +221,7 @@ func (s *Service) runPool(i *expinfrav1.AutoScalingGroup, launchTemplateID strin input.Tags = BuildTagsFromMap(i.Name, i.Tags) } - _, err := s.ASGClient.CreateAutoScalingGroup(input) - if err != nil { + if _, err := s.ASGClient.CreateAutoScalingGroup(input); err != nil { return errors.Wrap(err, "failed to create autoscaling group") } @@ -391,7 +389,7 @@ func createSDKMixedInstancesPolicy(name string, i *expinfrav1.MixedInstancesPoli } // BuildTags takes the tag configuration from the resources and returns a slice of autoscaling Tags -// usable in autoscaling API calls +// usable in autoscaling API calls. func BuildTags(name string, params infrav1.BuildParams) []*autoscaling.Tag { tags := make([]*autoscaling.Tag, 0) resourceName := aws.String(name) @@ -442,7 +440,7 @@ func BuildTags(name string, params infrav1.BuildParams) []*autoscaling.Tag { return tags } -// BuildTagsFromMap takes a map of keys and values and returns them as autoscaling group tags +// BuildTagsFromMap takes a map of keys and values and returns them as autoscaling group tags. func BuildTagsFromMap(asgName string, inTags map[string]string) []*autoscaling.Tag { if inTags == nil { return nil diff --git a/pkg/cloud/services/autoscaling/autoscalinggroup_test.go b/pkg/cloud/services/autoscaling/autoscalinggroup_test.go index f3dac25b81..eb0a5f7464 100644 --- a/pkg/cloud/services/autoscaling/autoscalinggroup_test.go +++ b/pkg/cloud/services/autoscaling/autoscalinggroup_test.go @@ -17,11 +17,12 @@ limitations under the License. package asg import ( - "k8s.io/apimachinery/pkg/runtime" "reflect" - "sigs.k8s.io/controller-runtime/pkg/client/fake" "testing" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/autoscaling" "github.com/golang/mock/gomock" @@ -103,7 +104,7 @@ func TestService_GetASGByName(t *testing.T) { client := fake.NewClientBuilder().WithScheme(scheme).Build() cs, err := scope.NewClusterScope(scope.ClusterScopeParams{ - Client: client, + Client: client, Cluster: &clusterv1.Cluster{}, AWSCluster: &infrav1.AWSCluster{}, }) diff --git a/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go b/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go index 900b27e723..7d735e9148 100644 --- a/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go +++ b/pkg/cloud/services/autoscaling/mock_autoscalingiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination autoscalingapi_mock.go -package mock_autoscalingiface github.com/aws/aws-sdk-go/service/autoscaling/autoscalingiface AutoScalingAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt autoscalingapi_mock.go > _autoscalingapi_mock.go && mv _autoscalingapi_mock.go autoscalingapi_mock.go" -package mock_autoscalingiface //nolint + +package mock_autoscalingiface // nolint:stylecheck diff --git a/pkg/cloud/services/awsnode/cni.go b/pkg/cloud/services/awsnode/cni.go index 76876d6570..1b44226ab2 100644 --- a/pkg/cloud/services/awsnode/cni.go +++ b/pkg/cloud/services/awsnode/cni.go @@ -24,8 +24,8 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/errors" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" @@ -56,7 +56,7 @@ func (s *Service) ReconcileCNI(ctx context.Context) error { var ds appsv1.DaemonSet if err := s.client.Get(ctx, types.NamespacedName{Namespace: awsNodeNamespace, Name: awsNodeName}, &ds); err != nil { - if !errors.IsNotFound(err) { + if !apierrors.IsNotFound(err) { return err } return ErrCNIMissing @@ -75,14 +75,14 @@ func (s *Service) ReconcileCNI(ctx context.Context) error { s.scope.Info("for each subnet", "cluster-name", s.scope.Name(), "cluster-namespace", s.scope.Namespace()) for _, subnet := range s.secondarySubnets() { var eniConfig amazoncni.ENIConfig - if err := s.client.Get(ctx, types.NamespacedName{Namespace: v1.NamespaceSystem, Name: subnet.AvailabilityZone}, &eniConfig); err != nil { - if !errors.IsNotFound(err) { + if err := s.client.Get(ctx, types.NamespacedName{Namespace: metav1.NamespaceSystem, Name: subnet.AvailabilityZone}, &eniConfig); err != nil { + if !apierrors.IsNotFound(err) { return err } s.scope.Info("Creating ENIConfig", "cluster-name", s.scope.Name(), "cluster-namespace", s.scope.Namespace(), "subnet", subnet.ID, "availability-zone", subnet.AvailabilityZone) eniConfig = amazoncni.ENIConfig{ - ObjectMeta: v1.ObjectMeta{ - Namespace: v1.NamespaceSystem, + ObjectMeta: metav1.ObjectMeta{ + Namespace: metav1.NamespaceSystem, Name: subnet.AvailabilityZone, Labels: metaLabels, }, @@ -111,7 +111,7 @@ func (s *Service) ReconcileCNI(ctx context.Context) error { // Removing any ENIConfig no longer needed var eniConfigs amazoncni.ENIConfigList err = s.client.List(ctx, &eniConfigs, &client.ListOptions{ - Namespace: v1.NamespaceSystem, + Namespace: metav1.NamespaceSystem, LabelSelector: labels.SelectorFromSet(metaLabels), }) if err != nil { @@ -187,7 +187,7 @@ func (s *Service) deleteCNI(ctx context.Context) error { ds := &appsv1.DaemonSet{} if err := s.client.Get(ctx, types.NamespacedName{Namespace: awsNodeNamespace, Name: awsNodeName}, ds); err != nil { - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { s.scope.V(2).Info("The aws-node DaemonSet is not found, not action") return nil } @@ -196,7 +196,7 @@ func (s *Service) deleteCNI(ctx context.Context) error { s.scope.V(2).Info("The aws-node DaemonSet found, deleting") if err := s.client.Delete(ctx, ds, &client.DeleteOptions{}); err != nil { - if errors.IsNotFound(err) { + if apierrors.IsNotFound(err) { s.scope.V(2).Info("The aws-node DaemonSet is not found, not deleted") return nil } diff --git a/pkg/cloud/services/awsnode/service.go b/pkg/cloud/services/awsnode/service.go index d24d14bf90..e0593122f0 100644 --- a/pkg/cloud/services/awsnode/service.go +++ b/pkg/cloud/services/awsnode/service.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud" ) -// Scope is a scope for use with the awsnode reconciling service +// Scope is a scope for use with the awsnode reconciling service. type Scope interface { cloud.ClusterScoper diff --git a/pkg/cloud/services/ec2/ami.go b/pkg/cloud/services/ec2/ami.go index 82d69034ab..598c8c3a90 100644 --- a/pkg/cloud/services/ec2/ami.go +++ b/pkg/cloud/services/ec2/ami.go @@ -39,7 +39,7 @@ const ( DefaultMachineAMIOwnerID = "258751437250" // defaultMachineAMILookupBaseOS is the default base operating system to use - // when looking up machine AMIs + // when looking up machine AMIs. defaultMachineAMILookupBaseOS = "ubuntu-18.04" // DefaultAmiNameFormat is defined in the build/ directory of this project. @@ -47,13 +47,13 @@ const ( // 1. the string value `capa-ami-` // 2. the baseOS of the AMI, for example: ubuntu-18.04, centos-7, amazon-2 // 3. the kubernetes version as defined by the packages produced by kubernetes/release with or without v as a prefix, for example: 1.13.0, 1.12.5-mybuild.1, v1.17.3 - // 4. a `-` followed by any additional characters + // 4. a `-` followed by any additional characters. DefaultAmiNameFormat = "capa-ami-{{.BaseOS}}-?{{.K8sVersion}}-*" - // Amazon's AMI timestamp format + // Amazon's AMI timestamp format. createDateTimestampFormat = "2006-01-02T15:04:05.000Z" - // EKS AMI ID SSM Parameter name + // EKS AMI ID SSM Parameter name. eksAmiSSMParameterFormat = "/aws/service/eks/optimized-ami/%s/amazon-linux-2/recommended/image_id" ) @@ -138,7 +138,7 @@ func DefaultAMILookup(ec2Client ec2iface.EC2API, ownerID, baseOS, kubernetesVers return latestImage, nil } -// defaultAMIIDLookup returns the default AMI based on region +// defaultAMIIDLookup returns the default AMI based on region. func (s *Service) defaultAMIIDLookup(amiNameFormat, ownerID, baseOS, kubernetesVersion string) (string, error) { latestImage, err := DefaultAMILookup(s.EC2Client, ownerID, baseOS, kubernetesVersion, amiNameFormat) if err != nil { diff --git a/pkg/cloud/services/ec2/bastion.go b/pkg/cloud/services/ec2/bastion.go index a92895abc6..248caab470 100644 --- a/pkg/cloud/services/ec2/bastion.go +++ b/pkg/cloud/services/ec2/bastion.go @@ -43,7 +43,7 @@ var ( fallbackBastionUsEast1InstanceType = "t2.micro" ) -// ReconcileBastion ensures a bastion is created for the cluster +// ReconcileBastion ensures a bastion is created for the cluster. func (s *Service) ReconcileBastion() error { if !s.scope.Bastion().Enabled { s.scope.V(4).Info("Skipping bastion reconcile") @@ -84,7 +84,6 @@ func (s *Service) ReconcileBastion() error { record.Eventf(s.scope.InfraCluster(), "SuccessfulCreateBastion", "Created bastion instance %q", instance.ID) s.scope.V(2).Info("Created new bastion host", "instance", instance) - } else if err != nil { return err } @@ -98,7 +97,7 @@ func (s *Service) ReconcileBastion() error { return nil } -// DeleteBastion deletes the Bastion instance +// DeleteBastion deletes the Bastion instance. func (s *Service) DeleteBastion() error { instance, err := s.describeBastionInstance() if err != nil { diff --git a/pkg/cloud/services/ec2/console.go b/pkg/cloud/services/ec2/console.go index 8449192cfb..b0d5c9f641 100644 --- a/pkg/cloud/services/ec2/console.go +++ b/pkg/cloud/services/ec2/console.go @@ -25,7 +25,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/record" ) -// GetConsoleOutput returns the latest console output of an instance +// GetConsoleOutput returns the latest console output of an instance. func (s *Service) GetConsoleOutput(instanceID string) (string, error) { input := &ec2.GetConsoleOutputInput{ InstanceId: aws.String(instanceID), diff --git a/pkg/cloud/services/ec2/instances.go b/pkg/cloud/services/ec2/instances.go index 39bac1ee5d..190bcd9b3d 100644 --- a/pkg/cloud/services/ec2/instances.go +++ b/pkg/cloud/services/ec2/instances.go @@ -347,7 +347,7 @@ func (s *Service) findSubnet(scope *scope.MachineScope) (string, error) { } } -// getFilteredSubnets fetches subnets filtered based on the criteria passed +// getFilteredSubnets fetches subnets filtered based on the criteria passed. func (s *Service) getFilteredSubnets(criteria ...*ec2.Filter) ([]*ec2.Subnet, error) { out, err := s.EC2Client.DescribeSubnets(&ec2.DescribeSubnetsInput{Filters: criteria}) if err != nil { @@ -357,7 +357,7 @@ func (s *Service) getFilteredSubnets(criteria ...*ec2.Filter) ([]*ec2.Subnet, er } // GetCoreSecurityGroups looks up the security group IDs managed by this actuator -// They are considered "core" to its proper functioning +// They are considered "core" to its proper functioning. func (s *Service) GetCoreSecurityGroups(scope *scope.MachineScope) ([]string, error) { if scope.IsExternallyManaged() { return nil, nil @@ -394,7 +394,7 @@ func (s *Service) GetCoreSecurityGroups(scope *scope.MachineScope) ([]string, er } // GetCoreNodeSecurityGroups looks up the security group IDs managed by this actuator -// They are considered "core" to its proper functioning +// They are considered "core" to its proper functioning. func (s *Service) GetCoreNodeSecurityGroups(scope *scope.MachinePoolScope) ([]string, error) { // These are common across both controlplane and node machines sgRoles := []infrav1.SecurityGroupRole{ @@ -903,7 +903,7 @@ func (s *Service) DetachSecurityGroupsFromNetworkInterface(groups []string, inte } // checkRootVolume checks the input root volume options against the requested AMI's defaults -// and returns the AMI's root device name +// and returns the AMI's root device name. func (s *Service) checkRootVolume(rootVolume *infrav1.Volume, imageID string) (*string, error) { rootDeviceName, err := s.getImageRootDevice(imageID) if err != nil { @@ -972,7 +972,7 @@ func getInstanceMarketOptionsRequest(spotMarketOptions *infrav1.SpotMarketOption return instanceMarketOptionsRequest } -// GetFilteredSecurityGroupID get security group ID using filters +// GetFilteredSecurityGroupID get security group ID using filters. func (s *Service) GetFilteredSecurityGroupID(securityGroup infrav1.AWSResourceReference) (string, error) { if securityGroup.Filters == nil { return "", nil diff --git a/pkg/cloud/services/ec2/instances_test.go b/pkg/cloud/services/ec2/instances_test.go index e060396c46..f1dcff2056 100644 --- a/pkg/cloud/services/ec2/instances_test.go +++ b/pkg/cloud/services/ec2/instances_test.go @@ -171,7 +171,7 @@ func TestInstanceIfExists(t *testing.T) { client := fake.NewClientBuilder().WithScheme(scheme).Build() scope, err := scope.NewClusterScope(scope.ClusterScopeParams{ - Client: client, + Client: client, Cluster: &clusterv1.Cluster{}, AWSCluster: &infrav1.AWSCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, @@ -251,7 +251,7 @@ func TestTerminateInstance(t *testing.T) { _ = infrav1.AddToScheme(scheme) client := fake.NewClientBuilder().WithScheme(scheme).Build() scope, err := scope.NewClusterScope(scope.ClusterScopeParams{ - Client: client, + Client: client, Cluster: &clusterv1.Cluster{}, AWSCluster: &infrav1.AWSCluster{}, }) @@ -1451,7 +1451,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { @@ -1562,7 +1561,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { @@ -1674,7 +1672,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { @@ -1783,7 +1780,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { @@ -1892,7 +1888,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { @@ -2001,7 +1996,6 @@ func TestCreateInstance(t *testing.T) { }) m.WaitUntilInstanceRunningWithContext(gomock.Any(), gomock.Any(), gomock.Any()). Return(nil) - }, check: func(instance *infrav1.Instance, err error) { if err != nil { diff --git a/pkg/cloud/services/ec2/launchtemplate.go b/pkg/cloud/services/ec2/launchtemplate.go index 790b8e5fb1..0a4e943179 100644 --- a/pkg/cloud/services/ec2/launchtemplate.go +++ b/pkg/cloud/services/ec2/launchtemplate.go @@ -34,7 +34,7 @@ import ( ) // GetLaunchTemplate returns the existing LaunchTemplate or nothing if it doesn't exist. -// For now by name until we need the input to be something different +// For now by name until we need the input to be something different. func (s *Service) GetLaunchTemplate(launchTemplateName string) (*expinfrav1.AWSLaunchTemplate, string, error) { if launchTemplateName == "" { return nil, "", nil @@ -89,7 +89,7 @@ func (s *Service) GetLaunchTemplateID(launchTemplateName string) (string, error) return aws.StringValue(out.LaunchTemplateVersions[0].LaunchTemplateId), nil } -// CreateLaunchTemplate generates a launch template to be used with the autoscaling group +// CreateLaunchTemplate generates a launch template to be used with the autoscaling group. func (s *Service) CreateLaunchTemplate(scope *scope.MachinePoolScope, imageID *string, userData []byte) (string, error) { s.scope.Info("Create a new launch template") @@ -229,7 +229,7 @@ func (s *Service) createLaunchTemplateData(scope *scope.MachinePoolScope, imageI return data, nil } -// DeleteLaunchTemplate delete a launch template +// DeleteLaunchTemplate delete a launch template. func (s *Service) DeleteLaunchTemplate(id string) error { s.scope.V(2).Info("Deleting launch template", "id", id) @@ -406,7 +406,6 @@ func (s *Service) buildLaunchTemplateTagSpecificationRequest(scope *scope.Machin }) } tagSpecifications = append(tagSpecifications, spec) - } return tagSpecifications } diff --git a/pkg/cloud/services/ec2/mock_ec2iface/doc.go b/pkg/cloud/services/ec2/mock_ec2iface/doc.go index ceb50b0285..256d1be808 100644 --- a/pkg/cloud/services/ec2/mock_ec2iface/doc.go +++ b/pkg/cloud/services/ec2/mock_ec2iface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination ec2api_mock.go -package mock_ec2iface github.com/aws/aws-sdk-go/service/ec2/ec2iface EC2API //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt ec2api_mock.go > _ec2api_mock.go && mv _ec2api_mock.go ec2api_mock.go" -package mock_ec2iface //nolint + +package mock_ec2iface // nolint:stylecheck diff --git a/pkg/cloud/services/eks/cluster.go b/pkg/cloud/services/eks/cluster.go index 5f74dd8a33..c422f7a091 100644 --- a/pkg/cloud/services/eks/cluster.go +++ b/pkg/cloud/services/eks/cluster.go @@ -159,7 +159,7 @@ func (s *Service) setStatus(cluster *eks.Cluster) error { return nil } -// deleteCluster deletes an EKS cluster +// deleteCluster deletes an EKS cluster. func (s *Service) deleteCluster() error { eksClusterName := s.scope.KubernetesClusterName() @@ -559,7 +559,7 @@ func (a *awslog) Log(args ...interface{}) { a.WithName("aws").Info(fmt.Sprintln(args...)) } -// WaitUntilClusterUpdating is adapted from aws-sdk-go/service/eks/waiters.go +// WaitUntilClusterUpdating is adapted from aws-sdk-go/service/eks/waiters.go. func (c EKSClient) WaitUntilClusterUpdating(input *eks.DescribeClusterInput, opts ...request.WaiterOption) error { ctx := aws.BackgroundContext() statusPath := "cluster.status" diff --git a/pkg/cloud/services/eks/cluster_test.go b/pkg/cloud/services/eks/cluster_test.go index e5bb0be1c3..a1908acf3f 100644 --- a/pkg/cloud/services/eks/cluster_test.go +++ b/pkg/cloud/services/eks/cluster_test.go @@ -17,9 +17,10 @@ limitations under the License. package eks import ( + "testing" + "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client/fake" - "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/eks" @@ -242,7 +243,6 @@ func TestMakeVPCConfig(t *testing.T) { } }) } - } func TestPublicAccessCIDRsEqual(t *testing.T) { @@ -395,7 +395,7 @@ func TestReconcileClusterVersion(t *testing.T) { scheme := runtime.NewScheme() _ = infrav1.AddToScheme(scheme) - _= ekscontrolplanev1.AddToScheme(scheme) + _ = ekscontrolplanev1.AddToScheme(scheme) client := fake.NewClientBuilder().WithScheme(scheme).Build() scope, err := scope.NewManagedControlPlaneScope(scope.ManagedControlPlaneScopeParams{ Client: client, diff --git a/pkg/cloud/services/eks/eks.go b/pkg/cloud/services/eks/eks.go index 322bca97f3..02a5573960 100644 --- a/pkg/cloud/services/eks/eks.go +++ b/pkg/cloud/services/eks/eks.go @@ -29,7 +29,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/record" ) -// ReconcileControlPlane reconciles a EKS control plane +// ReconcileControlPlane reconciles a EKS control plane. func (s *Service) ReconcileControlPlane(ctx context.Context) error { s.scope.V(2).Info("Reconciling EKS control plane", "cluster-name", s.scope.Cluster.Name, "cluster-namespace", s.scope.Cluster.Namespace) @@ -81,7 +81,7 @@ func (s *Service) DeleteControlPlane() (err error) { return nil } -// ReconcilePool is the entrypoint for ManagedMachinePool reconciliation +// ReconcilePool is the entrypoint for ManagedMachinePool reconciliation. func (s *NodegroupService) ReconcilePool() error { s.scope.V(2).Info("Reconciling EKS nodegroup") @@ -113,7 +113,7 @@ func (s *NodegroupService) ReconcilePool() error { } // ReconcilePoolDelete is the entrypoint for ManagedMachinePool deletion -// reconciliation +// reconciliation. func (s *NodegroupService) ReconcilePoolDelete() error { s.scope.V(2).Info("Reconciling deletion of EKS nodegroup") diff --git a/pkg/cloud/services/eks/errors.go b/pkg/cloud/services/eks/errors.go index 639106700d..1e34f17b7b 100644 --- a/pkg/cloud/services/eks/errors.go +++ b/pkg/cloud/services/eks/errors.go @@ -20,21 +20,21 @@ import "github.com/pkg/errors" var ( // ErrClusterExists is an error if a EKS cluster already exists with - // the same name in the spec but that isn't owned by the CAPI cluster + // the same name in the spec but that isn't owned by the CAPI cluster. ErrClusterExists = errors.New("an EKS cluster already exists with same name but isn't owned by cluster") - // ErrUnknownTokenMethod defines an error if a unsupported token generation method is supplied + // ErrUnknownTokenMethod defines an error if a unsupported token generation method is supplied. ErrUnknownTokenMethod = errors.New("unknown token method") - // ErrClusterRoleNameMissing if no role name is specified + // ErrClusterRoleNameMissing if no role name is specified. ErrClusterRoleNameMissing = errors.New("a cluster role name must be specified") - // ErrClusterRoleNotFound is an error if the specified role couldn't be founbd in AWS + // ErrClusterRoleNotFound is an error if the specified role couldn't be founbd in AWS. ErrClusterRoleNotFound = errors.New("the specified cluster role couldn't be found") - // ErrNodegroupRoleNotFound is an error if the specified role couldn't be founbd in AWS + // ErrNodegroupRoleNotFound is an error if the specified role couldn't be founbd in AWS. ErrNodegroupRoleNotFound = errors.New("the specified nodegroup role couldn't be found") - // ErrFargateRoleNotFound is an error if the specified role couldn't be founbd in AWS + // ErrFargateRoleNotFound is an error if the specified role couldn't be founbd in AWS. ErrFargateRoleNotFound = errors.New("the specified fargate role couldn't be found") // ErrCannotUseAdditionalRoles is an error if the spec contains additional role and the - // EKSAllowAddRoles feature flag isn't enabled + // EKSAllowAddRoles feature flag isn't enabled. ErrCannotUseAdditionalRoles = errors.New("additional rules cannot be added as this has been disabled") - // ErrNoSecurityGroup is an error when no security group is found for an EKS cluster + // ErrNoSecurityGroup is an error when no security group is found for an EKS cluster. ErrNoSecurityGroup = errors.New("no security group for EKS cluster") ) diff --git a/pkg/cloud/services/eks/fargate.go b/pkg/cloud/services/eks/fargate.go index 741e9256a6..6acc098a1d 100644 --- a/pkg/cloud/services/eks/fargate.go +++ b/pkg/cloud/services/eks/fargate.go @@ -42,7 +42,7 @@ func requeueRoleUpdating() reconcile.Result { return reconcile.Result{RequeueAfter: 10 * time.Second} } -// Reconcile is the entrypoint for FargateProfile reconciliation +// Reconcile is the entrypoint for FargateProfile reconciliation. func (s *FargateService) Reconcile() (reconcile.Result, error) { s.scope.V(2).Info("Reconciling EKS fargate profile") @@ -84,7 +84,6 @@ func (s *FargateService) Reconcile() (reconcile.Result, error) { } func (s *FargateService) reconcileFargateProfile() (requeue bool, err error) { - eksClusterName := s.scope.KubernetesClusterName() profileName := s.scope.FargateProfile.Spec.ProfileName profile, err := s.describeFargateProfile() @@ -92,7 +91,7 @@ func (s *FargateService) reconcileFargateProfile() (requeue bool, err error) { return false, errors.Wrap(err, "failed to describe profile") } - if profile == nil { + if eksClusterName := s.scope.KubernetesClusterName(); profile == nil { profile, err = s.createFargateProfile() if err != nil { return false, errors.Wrap(err, "failed to create profile") @@ -154,7 +153,7 @@ func (s *FargateService) handleStatus(profile *eks.FargateProfile) (requeue bool } } -// ReconcileDelete is the entrypoint for FargateProfile reconciliation +// ReconcileDelete is the entrypoint for FargateProfile reconciliation. func (s *FargateService) ReconcileDelete() (reconcile.Result, error) { s.scope.V(2).Info("Reconciling EKS fargate profile deletion") diff --git a/pkg/cloud/services/eks/iam/iam.go b/pkg/cloud/services/eks/iam/iam.go index ed8c69a9c2..c98535704a 100644 --- a/pkg/cloud/services/eks/iam/iam.go +++ b/pkg/cloud/services/eks/iam/iam.go @@ -36,7 +36,7 @@ import ( ) const ( - // EKSFargateService is the service to trust for fargate pod execution roles + // EKSFargateService is the service to trust for fargate pod execution roles. EKSFargateService = "eks-fargate-pods.amazonaws.com" ) @@ -97,8 +97,7 @@ func (s *IAMService) detachIAMRolePolicy(roleName string, policyARN string) erro PolicyArn: aws.String(policyARN), } - _, err := s.IAMClient.DetachRolePolicy(input) - if err != nil { + if _, err := s.IAMClient.DetachRolePolicy(input); err != nil { return errors.Wrapf(err, "error detaching policy %s from role %s", policyARN, roleName) } @@ -111,8 +110,7 @@ func (s *IAMService) attachIAMRolePolicy(roleName string, policyARN string) erro PolicyArn: aws.String(policyARN), } - _, err := s.IAMClient.AttachRolePolicy(input) - if err != nil { + if _, err := s.IAMClient.AttachRolePolicy(input); err != nil { return errors.Wrapf(err, "error attaching policy %s to role %s", policyARN, roleName) } @@ -238,7 +236,6 @@ func (s *IAMService) EnsureTagsAndPolicy( if _, err := s.IAMClient.UpdateAssumeRolePolicy(policyInput); err != nil { return updated, err } - } tagInput := &iam.TagRoleInput{ @@ -313,8 +310,7 @@ func (s *IAMService) DeleteRole(name string) error { RoleName: aws.String(name), } - _, err := s.IAMClient.DeleteRole(input) - if err != nil { + if _, err := s.IAMClient.DeleteRole(input); err != nil { return errors.Wrapf(err, "error deleting role %s", name) } diff --git a/pkg/cloud/services/eks/mock.go b/pkg/cloud/services/eks/mock.go index a0891002b9..36b610a6d4 100644 --- a/pkg/cloud/services/eks/mock.go +++ b/pkg/cloud/services/eks/mock.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../hack/tools/bin/mockgen -destination mock_eksiface/eksapi_mock.go -package mock_eksiface . EKSAPI //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt mock_eksiface/eksapi_mock.go > mock_eksiface/_eksapi_mock.go && mv mock_eksiface/_eksapi_mock.go mock_eksiface/eksapi_mock.go" + package eks diff --git a/pkg/cloud/services/eks/nodegroup.go b/pkg/cloud/services/eks/nodegroup.go index 02581ead33..3f07cb13f9 100644 --- a/pkg/cloud/services/eks/nodegroup.go +++ b/pkg/cloud/services/eks/nodegroup.go @@ -377,7 +377,6 @@ func (s *NodegroupService) reconcileNodegroupConfig(ng *eks.Nodegroup) error { eksClusterName := s.scope.KubernetesClusterName() s.V(2).Info("reconciling node group config", "cluster", eksClusterName, "name", *ng.NodegroupName) - machinePool := s.scope.MachinePool.Spec managedPool := s.scope.ManagedMachinePool.Spec input := &eks.UpdateNodegroupConfigInput{ ClusterName: aws.String(eksClusterName), @@ -398,7 +397,7 @@ func (s *NodegroupService) reconcileNodegroupConfig(ng *eks.Nodegroup) error { input.Taints = taintsPayload needsUpdate = true } - if machinePool.Replicas == nil { + if machinePool := s.scope.MachinePool.Spec; machinePool.Replicas == nil { if ng.ScalingConfig.DesiredSize != nil && *ng.ScalingConfig.DesiredSize != 1 { s.V(2).Info("Nodegroup desired size differs from spec, updating scaling configuration", "nodegroup", ng.NodegroupName) input.ScalingConfig = s.scalingConfig() @@ -432,15 +431,12 @@ func (s *NodegroupService) reconcileNodegroupConfig(ng *eks.Nodegroup) error { } func (s *NodegroupService) reconcileNodegroup() error { - eksClusterName := s.scope.KubernetesClusterName() - eksNodegroupName := s.scope.NodegroupName() - ng, err := s.describeNodegroup() if err != nil { return errors.Wrap(err, "failed to describe nodegroup") } - if ng == nil { + if eksClusterName, eksNodegroupName := s.scope.KubernetesClusterName(), s.scope.NodegroupName(); ng == nil { ng, err = s.createNodegroup() if err != nil { return errors.Wrap(err, "failed to create nodegroup") diff --git a/pkg/cloud/services/eks/roles.go b/pkg/cloud/services/eks/roles.go index 57b30f9fad..4bae769204 100644 --- a/pkg/cloud/services/eks/roles.go +++ b/pkg/cloud/services/eks/roles.go @@ -36,7 +36,7 @@ const ( maxIAMRoleNameLength = 64 ) -// NodegroupRolePolicies gives the policies required for a nodegroup role +// NodegroupRolePolicies gives the policies required for a nodegroup role. func NodegroupRolePolicies() []string { return []string{ "arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy", @@ -45,7 +45,7 @@ func NodegroupRolePolicies() []string { } } -// FargateRolePolicies gives the policies required for a fargate role +// FargateRolePolicies gives the policies required for a fargate role. func FargateRolePolicies() []string { return []string{ "arn:aws:iam::aws:policy/AmazonEKSFargatePodExecutionRolePolicy", diff --git a/pkg/cloud/services/elb/loadbalancer.go b/pkg/cloud/services/elb/loadbalancer.go index d3534094cb..f9ab741fdf 100644 --- a/pkg/cloud/services/elb/loadbalancer.go +++ b/pkg/cloud/services/elb/loadbalancer.go @@ -160,7 +160,7 @@ func (s *Service) DeleteLoadbalancers() error { return nil } -// RegisterInstanceWithClassicELB registers an instance with a classic ELB +// RegisterInstanceWithClassicELB registers an instance with a classic ELB. func (s *Service) RegisterInstanceWithClassicELB(instanceID, loadBalancer string) error { input := &elb.RegisterInstancesWithLoadBalancerInput{ Instances: []*elb.Instance{{InstanceId: aws.String(instanceID)}}, @@ -203,7 +203,7 @@ func (s *Service) InstanceIsRegisteredWithAPIServerELB(i *infrav1.Instance) (boo return false, nil } -// RegisterInstanceWithAPIServerELB registers an instance with a classic ELB +// RegisterInstanceWithAPIServerELB registers an instance with a classic ELB. func (s *Service) RegisterInstanceWithAPIServerELB(i *infrav1.Instance) error { name, err := GenerateELBName(s.scope.Name()) if err != nil { @@ -240,7 +240,7 @@ func (s *Service) RegisterInstanceWithAPIServerELB(i *infrav1.Instance) error { return err } -// DeregisterInstanceFromAPIServerELB de-registers an instance from a classic ELB +// DeregisterInstanceFromAPIServerELB de-registers an instance from a classic ELB. func (s *Service) DeregisterInstanceFromAPIServerELB(i *infrav1.Instance) error { name, err := GenerateELBName(s.scope.Name()) if err != nil { @@ -285,14 +285,14 @@ func GenerateELBName(clusterName string) (string, error) { } // generateStandardELBName generates a formatted ELB name based on cluster -// and ELB name +// and ELB name. func generateStandardELBName(clusterName string) string { - elbCompatibleClusterName := strings.Replace(clusterName, ".", "-", -1) + elbCompatibleClusterName := strings.ReplaceAll(clusterName, ".", "-") return fmt.Sprintf("%s-%s", elbCompatibleClusterName, infrav1.APIServerRoleTagValue) } // generateHashedELBName generates a 32-character hashed name based on cluster -// and ELB name +// and ELB name. func generateHashedELBName(clusterName string) (string, error) { // hashSize = 32 - length of "k8s" - length of "-" = 28 shortName, err := hash.Base36TruncatedHash(clusterName, 28) @@ -557,7 +557,7 @@ func (s *Service) listOwnedELBs() ([]string, error) { serviceTag := infrav1.ClusterAWSCloudProviderTagKey(s.scope.Name()) arns, err := s.listByTag(serviceTag) if err != nil { - //retry by listing all ELBs as listByTag will fail in air-gapped environments + // retry by listing all ELBs as listByTag will fail in air-gapped environments arns, err = s.filterByOwnedTag(serviceTag) if err != nil { return nil, err diff --git a/pkg/cloud/services/elb/mock_elbiface/doc.go b/pkg/cloud/services/elb/mock_elbiface/doc.go index a6ead35063..17da838779 100644 --- a/pkg/cloud/services/elb/mock_elbiface/doc.go +++ b/pkg/cloud/services/elb/mock_elbiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination elbapi_mock.go -package mock_elbiface github.com/aws/aws-sdk-go/service/elb/elbiface ELBAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt elbapi_mock.go > _elbapi_mock.go && mv _elbapi_mock.go elbapi_mock.go" -package mock_elbiface //nolint + +package mock_elbiface //nolint:stylecheck diff --git a/pkg/cloud/services/elb/mock_resourcegroupstaggingapiiface/doc.go b/pkg/cloud/services/elb/mock_resourcegroupstaggingapiiface/doc.go index 9387013b6e..fd5d378510 100644 --- a/pkg/cloud/services/elb/mock_resourcegroupstaggingapiiface/doc.go +++ b/pkg/cloud/services/elb/mock_resourcegroupstaggingapiiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination resourcegroupstaggingapiiface_mock.go -package mock_resourcegroupstaggingapiiface github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/resourcegroupstaggingapiiface ResourceGroupsTaggingAPIAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt resourcegroupstaggingapiiface_mock.go > _resourcegroupstaggingapiiface_mock.go && mv _resourcegroupstaggingapiiface_mock.go resourcegroupstaggingapiiface_mock.go" -package mock_resourcegroupstaggingapiiface //nolint + +package mock_resourcegroupstaggingapiiface // nolint:stylecheck diff --git a/pkg/cloud/services/iamauth/configmap.go b/pkg/cloud/services/iamauth/configmap.go index 3dc48eca59..81bec2f704 100644 --- a/pkg/cloud/services/iamauth/configmap.go +++ b/pkg/cloud/services/iamauth/configmap.go @@ -25,7 +25,7 @@ import ( apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - apierr "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" "sigs.k8s.io/yaml" crclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -47,7 +47,7 @@ type configMapBackend struct { func (b *configMapBackend) MapRole(mapping ekscontrolplanev1.RoleMapping) error { if errs := mapping.Validate(); errs != nil { - return apierr.NewAggregate(errs) + return kerrors.NewAggregate(errs) } authConfig, err := b.getAuthConfig() @@ -69,7 +69,7 @@ func (b *configMapBackend) MapRole(mapping ekscontrolplanev1.RoleMapping) error func (b *configMapBackend) MapUser(mapping ekscontrolplanev1.UserMapping) error { if errs := mapping.Validate(); errs != nil { - return apierr.NewAggregate(errs) + return kerrors.NewAggregate(errs) } authConfig, err := b.getAuthConfig() diff --git a/pkg/cloud/services/iamauth/configmap_test.go b/pkg/cloud/services/iamauth/configmap_test.go index 0c27d0080e..180bf8bfcd 100644 --- a/pkg/cloud/services/iamauth/configmap_test.go +++ b/pkg/cloud/services/iamauth/configmap_test.go @@ -24,7 +24,7 @@ import ( . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" crclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -34,7 +34,7 @@ import ( ) var ( - existingNodeRoleMap string = ` + existingNodeRoleMap = ` - groups: - system:bootstrappers - system:nodes @@ -42,7 +42,7 @@ var ( username: system:node:{{EC2PrivateDNSName}} ` - existingUserMap string = ` + existingUserMap = ` - userarn: arn:aws:iam::000000000000:user/Alice username: alice groups: @@ -135,7 +135,7 @@ func TestAddRoleMappingCM(t *testing.T) { var client crclient.Client if tc.existingAuthConfigMap == nil { - client = fake.NewClientBuilder().Build() + client = fake.NewClientBuilder().Build() } else { client = fake.NewClientBuilder().WithObjects(tc.existingAuthConfigMap).Build() } @@ -146,10 +146,10 @@ func TestAddRoleMappingCM(t *testing.T) { if tc.expectError { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) + key := types.NamespacedName{ Name: "aws-auth", Namespace: "kube-system", @@ -279,10 +279,10 @@ func TestAddUserMappingCM(t *testing.T) { if tc.expectError { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) + key := types.NamespacedName{ Name: "aws-auth", Namespace: "kube-system", @@ -312,14 +312,13 @@ func TestAddUserMappingCM(t *testing.T) { _, roleMappingsFound := cm.Data["mapRoles"] g.Expect(roleMappingsFound).To(BeFalse()) - }) } } func createFakeConfigMap(roleMappings string, userMappings string) *corev1.ConfigMap { cm := &corev1.ConfigMap{ - ObjectMeta: v1.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Name: "aws-auth", Namespace: "kube-system", UID: "1234567", diff --git a/pkg/cloud/services/iamauth/crd.go b/pkg/cloud/services/iamauth/crd.go index ba722197f3..e1b21ec376 100644 --- a/pkg/cloud/services/iamauth/crd.go +++ b/pkg/cloud/services/iamauth/crd.go @@ -21,8 +21,7 @@ import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" - apierr "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" iamauthv1 "sigs.k8s.io/aws-iam-authenticator/pkg/mapper/crd/apis/iamauthenticator/v1alpha1" crclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -37,12 +36,12 @@ func (b *crdBackend) MapRole(mapping ekscontrolplanev1.RoleMapping) error { ctx := context.TODO() if errs := mapping.Validate(); errs != nil { - return apierr.NewAggregate(errs) + return kerrors.NewAggregate(errs) } mappingList := iamauthv1.IAMIdentityMappingList{} - err := b.client.List(ctx, &mappingList) - if err != nil { + + if err := b.client.List(ctx, &mappingList); err != nil { return fmt.Errorf("getting list of mappings: %w", err) } @@ -55,7 +54,7 @@ func (b *crdBackend) MapRole(mapping ekscontrolplanev1.RoleMapping) error { } iamMapping := &iamauthv1.IAMIdentityMapping{ - ObjectMeta: v1.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceSystem, GenerateName: "capa-iamauth-", }, @@ -73,12 +72,12 @@ func (b *crdBackend) MapUser(mapping ekscontrolplanev1.UserMapping) error { ctx := context.TODO() if errs := mapping.Validate(); errs != nil { - return apierr.NewAggregate(errs) + return kerrors.NewAggregate(errs) } mappingList := iamauthv1.IAMIdentityMappingList{} - err := b.client.List(ctx, &mappingList) - if err != nil { + + if err := b.client.List(ctx, &mappingList); err != nil { return fmt.Errorf("getting list of mappings: %w", err) } @@ -91,7 +90,7 @@ func (b *crdBackend) MapUser(mapping ekscontrolplanev1.UserMapping) error { } iamMapping := &iamauthv1.IAMIdentityMapping{ - ObjectMeta: v1.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Namespace: metav1.NamespaceSystem, GenerateName: "capa-iamauth-", }, diff --git a/pkg/cloud/services/iamauth/crd_test.go b/pkg/cloud/services/iamauth/crd_test.go index 6725bfe2ed..f5a7ce0b0d 100644 --- a/pkg/cloud/services/iamauth/crd_test.go +++ b/pkg/cloud/services/iamauth/crd_test.go @@ -24,7 +24,7 @@ import ( . "github.com/onsi/gomega" - v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" iamauthv1 "sigs.k8s.io/aws-iam-authenticator/pkg/mapper/crd/apis/iamauthenticator/v1alpha1" crclient "sigs.k8s.io/controller-runtime/pkg/client" @@ -136,10 +136,10 @@ func TestAddRoleMappingCRD(t *testing.T) { if tc.expectError { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) + mappings := &iamauthv1.IAMIdentityMappingList{} err = client.List(context.TODO(), mappings) g.Expect(err).To(BeNil()) @@ -157,7 +157,6 @@ func TestAddRoleMappingCRD(t *testing.T) { g.Expect(actualMapping.Namespace).To(Equal("kube-system")) g.Expect(strings.HasPrefix(actualMapping.Name, "capa-iamauth-")).To(BeTrue()) } - }) } } @@ -264,10 +263,10 @@ func TestAddUserMappingCRD(t *testing.T) { if tc.expectError { g.Expect(err).ToNot(BeNil()) return - } else { - g.Expect(err).To(BeNil()) } + g.Expect(err).To(BeNil()) + mappings := &iamauthv1.IAMIdentityMappingList{} err = client.List(context.TODO(), mappings) g.Expect(err).To(BeNil()) @@ -285,14 +284,13 @@ func TestAddUserMappingCRD(t *testing.T) { g.Expect(actualMapping.Namespace).To(Equal("kube-system")) g.Expect(strings.HasPrefix(actualMapping.Name, "capa-iamauth-")).To(BeTrue()) } - }) } } func createIAMAuthMapping(arn string, username string, groups []string) *iamauthv1.IAMIdentityMapping { return &iamauthv1.IAMIdentityMapping{ - ObjectMeta: v1.ObjectMeta{ + ObjectMeta: metav1.ObjectMeta{ Name: "capa-iamauth-abcd1234", Namespace: "kube-system", UID: "1234567890", diff --git a/pkg/cloud/services/iamauth/iamauth.go b/pkg/cloud/services/iamauth/iamauth.go index fba4f3e2fe..0044b2be81 100644 --- a/pkg/cloud/services/iamauth/iamauth.go +++ b/pkg/cloud/services/iamauth/iamauth.go @@ -23,16 +23,16 @@ import ( ) const ( - // EC2NodeUserName is the username required for EC2 nodes + // EC2NodeUserName is the username required for EC2 nodes. EC2NodeUserName = "system:node:{{EC2PrivateDNSName}}" ) var ( - // NodeGroups is the groups that are required for a node + // NodeGroups is the groups that are required for a node. NodeGroups = []string{"system:bootstrappers", "system:nodes"} ) -// AuthenticatorBackend is the interface that represents an aws-iam-authenticator backend +// AuthenticatorBackend is the interface that represents an aws-iam-authenticator backend. type AuthenticatorBackend interface { // MapRole is used to map a role ARN to a user and set of groups MapRole(mapping ekscontrolplanev1.RoleMapping) error @@ -40,13 +40,13 @@ type AuthenticatorBackend interface { MapUser(mapping ekscontrolplanev1.UserMapping) error } -// BackendType is a type that represents the different aws-iam-authenticator backends +// BackendType is a type that represents the different aws-iam-authenticator backends. type BackendType string var ( - // BackendTypeConfigMap is the Kubernetes config map backend + // BackendTypeConfigMap is the Kubernetes config map backend. BackendTypeConfigMap = BackendType("config-map") - // BackendTypeCRD is the CRD based backend + // BackendTypeCRD is the CRD based backend. BackendTypeCRD = BackendType("crd") ) diff --git a/pkg/cloud/services/iamauth/reconcile.go b/pkg/cloud/services/iamauth/reconcile.go index 1cad8e439f..b45f3e490b 100644 --- a/pkg/cloud/services/iamauth/reconcile.go +++ b/pkg/cloud/services/iamauth/reconcile.go @@ -32,7 +32,7 @@ import ( ekscontrolplanev1 "sigs.k8s.io/cluster-api-provider-aws/controlplane/eks/api/v1alpha4" ) -// ReconcileIAMAuthenticator is used to create the aws-iam-authenticator in a cluster +// ReconcileIAMAuthenticator is used to create the aws-iam-authenticator in a cluster. func (s *Service) ReconcileIAMAuthenticator(ctx context.Context) error { s.scope.Info("Reconciling aws-iam-authenticator configuration", "cluster-name", s.scope.Name()) diff --git a/pkg/cloud/services/iamauth/service.go b/pkg/cloud/services/iamauth/service.go index bac724dec6..659f6f8e78 100644 --- a/pkg/cloud/services/iamauth/service.go +++ b/pkg/cloud/services/iamauth/service.go @@ -26,7 +26,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/scope" ) -// Scope is a scope for use with the iamauth reconciling service +// Scope is a scope for use with the iamauth reconciling service. type Scope interface { cloud.ClusterScoper diff --git a/pkg/cloud/services/instancestate/ec2events.go b/pkg/cloud/services/instancestate/ec2events.go index e534bf5c1f..25fadd0577 100644 --- a/pkg/cloud/services/instancestate/ec2events.go +++ b/pkg/cloud/services/instancestate/ec2events.go @@ -21,11 +21,8 @@ func (s Service) ReconcileEC2Events() error { if err := s.reconcileSQSQueue(); err != nil { return err } - if err := s.reconcileRules(); err != nil { - return err - } - return nil + return s.reconcileRules() } // DeleteEC2Events will delete a Service's EC2 events. @@ -34,9 +31,5 @@ func (s Service) DeleteEC2Events() error { return err } - if err := s.deleteSQSQueue(); err != nil { - return err - } - - return nil + return s.deleteSQSQueue() } diff --git a/pkg/cloud/services/instancestate/helpers_test.go b/pkg/cloud/services/instancestate/helpers_test.go index cd824c9671..65035b1047 100644 --- a/pkg/cloud/services/instancestate/helpers_test.go +++ b/pkg/cloud/services/instancestate/helpers_test.go @@ -30,7 +30,7 @@ func setupCluster(clusterName string) (*scope.ClusterScope, error) { _ = infrav1.AddToScheme(scheme) awsCluster := &infrav1.AWSCluster{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, - Spec: infrav1.AWSClusterSpec{}, + Spec: infrav1.AWSClusterSpec{}, } client := fake.NewClientBuilder().WithScheme(scheme).WithObjects(awsCluster).Build() return scope.NewClusterScope(scope.ClusterScopeParams{ diff --git a/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go b/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go index 510f5a6f0b..14097cb477 100644 --- a/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go +++ b/pkg/cloud/services/instancestate/mock_eventbridgeiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination eventbridgeiface_mock.go -package mock_eventbridgeiface github.com/aws/aws-sdk-go/service/eventbridge/eventbridgeiface EventBridgeAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt eventbridgeiface_mock.go > _eventbridgeiface_mock.go && mv _eventbridgeiface_mock.go eventbridgeiface_mock.go" -package mock_eventbridgeiface //nolint + +package mock_eventbridgeiface // nolint:stylecheck diff --git a/pkg/cloud/services/instancestate/mock_sqsiface/doc.go b/pkg/cloud/services/instancestate/mock_sqsiface/doc.go index b5ddca5a6d..70b8a24262 100644 --- a/pkg/cloud/services/instancestate/mock_sqsiface/doc.go +++ b/pkg/cloud/services/instancestate/mock_sqsiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination sqsiface_mock.go -package mock_sqsiface github.com/aws/aws-sdk-go/service/sqs/sqsiface SQSAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt sqsiface_mock.go > _sqsiface_mock.go && mv _sqsiface_mock.go sqsiface_mock.go" -package mock_sqsiface //nolint + +package mock_sqsiface // nolint:stylecheck diff --git a/pkg/cloud/services/instancestate/queue.go b/pkg/cloud/services/instancestate/queue.go index c3457c5482..a08dfadc7f 100644 --- a/pkg/cloud/services/instancestate/queue.go +++ b/pkg/cloud/services/instancestate/queue.go @@ -98,7 +98,7 @@ func (s *Service) createPolicyForRule(input *createPolicyForRuleInput) error { // GenerateQueueName will generate a queue name. func GenerateQueueName(clusterName string) string { - adjusted := strings.Replace(clusterName, ".", "-", -1) + adjusted := strings.ReplaceAll(clusterName, ".", "-") return fmt.Sprintf("%s-queue", adjusted) } diff --git a/pkg/cloud/services/instancestate/queue_test.go b/pkg/cloud/services/instancestate/queue_test.go index 0b107205a4..8b99bee39c 100644 --- a/pkg/cloud/services/instancestate/queue_test.go +++ b/pkg/cloud/services/instancestate/queue_test.go @@ -19,11 +19,12 @@ package instancestate import ( "bytes" "encoding/json" + "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/sqs" "github.com/pkg/errors" - "testing" "github.com/golang/mock/gomock" . "github.com/onsi/gomega" diff --git a/pkg/cloud/services/instancestate/rule.go b/pkg/cloud/services/instancestate/rule.go index 1aca638fdd..f2a7a5a501 100644 --- a/pkg/cloud/services/instancestate/rule.go +++ b/pkg/cloud/services/instancestate/rule.go @@ -32,7 +32,7 @@ import ( // Ec2StateChangeNotification defines the EC2 instance's state change notification. const Ec2StateChangeNotification = "EC2 Instance State-change Notification" -// reconcileRules creates rules and attaches the queue as a target +// reconcileRules creates rules and attaches the queue as a target. func (s Service) reconcileRules() error { var ruleNotFound bool ruleResp, err := s.EventBridgeClient.DescribeRule(&eventbridge.DescribeRuleInput{ diff --git a/pkg/cloud/services/instancestate/rule_test.go b/pkg/cloud/services/instancestate/rule_test.go index a2671c9783..0a121769aa 100644 --- a/pkg/cloud/services/instancestate/rule_test.go +++ b/pkg/cloud/services/instancestate/rule_test.go @@ -18,6 +18,8 @@ package instancestate import ( "encoding/json" + "testing" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/eventbridge" @@ -28,7 +30,6 @@ import ( infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/instancestate/mock_eventbridgeiface" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/instancestate/mock_sqsiface" - "testing" ) func TestReconcileRules(t *testing.T) { diff --git a/pkg/cloud/services/interfaces.go b/pkg/cloud/services/interfaces.go index a08afaaf44..daea098bba 100644 --- a/pkg/cloud/services/interfaces.go +++ b/pkg/cloud/services/interfaces.go @@ -23,14 +23,14 @@ import ( ) const ( - // TemporaryResourceID is the name used temporarily when creating AWS resources + // TemporaryResourceID is the name used temporarily when creating AWS resources. TemporaryResourceID = "temporary-resource-id" - // AnyIPv4CidrBlock is the CIDR block to match all IPv4 addresses + // AnyIPv4CidrBlock is the CIDR block to match all IPv4 addresses. AnyIPv4CidrBlock = "0.0.0.0/0" ) // ASGInterface encapsulates the methods exposed to the machinepool -// actuator +// actuator. type ASGInterface interface { ASGIfExists(id *string) (*expinfrav1.AutoScalingGroup, error) GetASGByName(scope *scope.MachinePoolScope) (*expinfrav1.AutoScalingGroup, error) @@ -43,7 +43,7 @@ type ASGInterface interface { } // EC2MachineInterface encapsulates the methods exposed to the machine -// actuator +// actuator. type EC2MachineInterface interface { InstanceIfExists(id *string) (*infrav1.Instance, error) TerminateInstance(id string) error @@ -69,7 +69,7 @@ type EC2MachineInterface interface { } // SecretInterface encapsulated the methods exposed to the -// machine actuator +// machine actuator. type SecretInterface interface { Delete(m *scope.MachineScope) error Create(m *scope.MachineScope, data []byte) (string, int32, error) diff --git a/pkg/cloud/services/mock_services/doc.go b/pkg/cloud/services/mock_services/doc.go index 2b80c58b13..cbc7841e88 100644 --- a/pkg/cloud/services/mock_services/doc.go +++ b/pkg/cloud/services/mock_services/doc.go @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Run go generate to regenerate this mock. +// Run go generate to regenerate this mock. //nolint:revive //go:generate ../../../../hack/tools/bin/mockgen -destination ec2_machine_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services EC2MachineInterface //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt ec2_machine_interface_mock.go > _ec2_machine_interface_mock.go && mv _ec2_machine_interface_mock.go ec2_machine_interface_mock.go" //go:generate ../../../../hack/tools/bin/mockgen -destination secretsmanager_machine_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services SecretInterface //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt secretsmanager_machine_interface_mock.go > _secretsmanager_machine_interface_mock.go && mv _secretsmanager_machine_interface_mock.go secretsmanager_machine_interface_mock.go" //go:generate ../../../../hack/tools/bin/mockgen -destination autoscaling_interface_mock.go -package mock_services sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services ASGInterface //go:generate /usr/bin/env bash -c "cat ../../../../hack/boilerplate/boilerplate.generatego.txt autoscaling_interface_mock.go > _autoscaling_interface_mock.go && mv _autoscaling_interface_mock.go autoscaling_interface_mock.go" -package mock_services //nolint + +package mock_services // nolint:stylecheck diff --git a/pkg/cloud/services/network/gateways_test.go b/pkg/cloud/services/network/gateways_test.go index 5c45091996..922c2a3510 100644 --- a/pkg/cloud/services/network/gateways_test.go +++ b/pkg/cloud/services/network/gateways_test.go @@ -17,9 +17,10 @@ limitations under the License. package network import ( + "testing" + "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client/fake" - "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" diff --git a/pkg/cloud/services/network/routetables_test.go b/pkg/cloud/services/network/routetables_test.go index 1422f382b7..46d6d99dfe 100644 --- a/pkg/cloud/services/network/routetables_test.go +++ b/pkg/cloud/services/network/routetables_test.go @@ -18,11 +18,12 @@ package network import ( "fmt" - "k8s.io/apimachinery/pkg/runtime" - "sigs.k8s.io/controller-runtime/pkg/client/fake" "strings" "testing" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/golang/mock/gomock" @@ -274,7 +275,6 @@ func TestReconcileRouteTables(t *testing.T) { } }) } - } type routeTableInputMatcher struct { diff --git a/pkg/cloud/services/network/service.go b/pkg/cloud/services/network/service.go index 2ac36a1a50..7d83276e23 100644 --- a/pkg/cloud/services/network/service.go +++ b/pkg/cloud/services/network/service.go @@ -24,7 +24,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/scope" ) -// Scope is scope for use with the network service +// Scope is scope for use with the network service. type Scope interface { cloud.ClusterScoper diff --git a/pkg/cloud/services/network/subnets.go b/pkg/cloud/services/network/subnets.go index 6577f1c642..9a6ebea080 100644 --- a/pkg/cloud/services/network/subnets.go +++ b/pkg/cloud/services/network/subnets.go @@ -131,7 +131,7 @@ func (s *Service) reconcileSubnets() error { } else if unmanagedVPC { // If there is no existing subnet and we have an umanaged vpc report an error record.Warnf(s.scope.InfraCluster(), "FailedMatchSubnet", "Using unmanaged VPC and failed to find existing subnet for specified subnet id %d, cidr %q", sub.ID, sub.CidrBlock) - return errors.New(fmt.Sprintf("usign unmanaged vpc and subnet %s (cidr %s) specified but it doesn't exist in vpc %s", sub.ID, sub.CidrBlock, s.scope.VPC().ID)) + return errors.New(fmt.Errorf("usign unmanaged vpc and subnet %s (cidr %s) specified but it doesn't exist in vpc %s", sub.ID, sub.CidrBlock, s.scope.VPC().ID).Error()) } } diff --git a/pkg/cloud/services/network/subnets_test.go b/pkg/cloud/services/network/subnets_test.go index 319fd7e77c..c43e3a056c 100644 --- a/pkg/cloud/services/network/subnets_test.go +++ b/pkg/cloud/services/network/subnets_test.go @@ -18,11 +18,12 @@ package network import ( "encoding/json" - "k8s.io/apimachinery/pkg/runtime" "reflect" - "sigs.k8s.io/controller-runtime/pkg/client/fake" "testing" + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/golang/mock/gomock" diff --git a/pkg/cloud/services/network/vpc.go b/pkg/cloud/services/network/vpc.go index 723ef92084..063b9e2a88 100644 --- a/pkg/cloud/services/network/vpc.go +++ b/pkg/cloud/services/network/vpc.go @@ -56,7 +56,6 @@ func (s *Service) reconcileVPC() error { if err != nil { return errors.Wrap(err, "failed to create new vpc") } - } else if err != nil { return errors.Wrap(err, "failed to describe VPCs") } diff --git a/pkg/cloud/services/secretsmanager/cloudinit.go b/pkg/cloud/services/secretsmanager/cloudinit.go index 45a6ad53d3..9c1834ffaf 100644 --- a/pkg/cloud/services/secretsmanager/cloudinit.go +++ b/pkg/cloud/services/secretsmanager/cloudinit.go @@ -27,7 +27,7 @@ const ( // UserData creates a multi-part MIME document including a script boothook to // download userdata from AWS Secrets Manager and then restart cloud-init, and an include part -// specifying the on disk location of the new userdata +// specifying the on disk location of the new userdata. func (s *Service) UserData(secretPrefix string, chunks int32, region string, endpoints []scope.ServiceEndpoint) ([]byte, error) { serviceEndpoint := "" for _, v := range endpoints { diff --git a/pkg/cloud/services/secretsmanager/secret.go b/pkg/cloud/services/secretsmanager/secret.go index ff6251d70c..f62772e5fe 100644 --- a/pkg/cloud/services/secretsmanager/secret.go +++ b/pkg/cloud/services/secretsmanager/secret.go @@ -83,7 +83,7 @@ func (s *Service) Create(m *scope.MachineScope, data []byte) (string, int32, err return prefix, chunks, err } -// retryableCreateSecret is a function to be passed into a waiter. In a separate function for ease of reading +// retryableCreateSecret is a function to be passed into a waiter. In a separate function for ease of reading. func (s *Service) retryableCreateSecret(name string, chunk []byte, tags infrav1.Tags) (bool, error) { _, err := s.SecretsManagerClient.CreateSecret(&secretsmanager.CreateSecretInput{ Name: aws.String(name), @@ -100,7 +100,7 @@ func (s *Service) retryableCreateSecret(name string, chunk []byte, tags infrav1. return true, err } -// forceDeleteSecretEntry deletes a single secret, ignoring if it is absent +// forceDeleteSecretEntry deletes a single secret, ignoring if it is absent. func (s *Service) forceDeleteSecretEntry(name string) error { _, err := s.SecretsManagerClient.DeleteSecret(&secretsmanager.DeleteSecretInput{ SecretId: aws.String(name), @@ -112,7 +112,7 @@ func (s *Service) forceDeleteSecretEntry(name string) error { return err } -// Delete the secret belonging to a machine from AWS Secrets Manager +// Delete the secret belonging to a machine from AWS Secrets Manager. func (s *Service) Delete(m *scope.MachineScope) error { var errs []error for i := int32(0); i < m.GetSecretCount(); i++ { diff --git a/pkg/cloud/services/secretsmanager/secret_fetch_script.go b/pkg/cloud/services/secretsmanager/secret_fetch_script.go index f1dd05202e..d6ab23c77c 100644 --- a/pkg/cloud/services/secretsmanager/secret_fetch_script.go +++ b/pkg/cloud/services/secretsmanager/secret_fetch_script.go @@ -16,6 +16,7 @@ limitations under the License. package secretsmanager +// nolint: gosec const secretFetchScript = `#cloud-boothook #!/bin/bash diff --git a/pkg/cloud/services/secretsmanager/service_test.go b/pkg/cloud/services/secretsmanager/service_test.go index 1a426e62fc..745198571a 100644 --- a/pkg/cloud/services/secretsmanager/service_test.go +++ b/pkg/cloud/services/secretsmanager/service_test.go @@ -29,8 +29,7 @@ func TestUserData(t *testing.T) { endpoints := []scope.ServiceEndpoint{} doc, _ := service.UserData("secretARN", 1, "eu-west-1", endpoints) - _, err := mail.ReadMessage(bytes.NewBuffer(doc)) - if err != nil { + if _, err := mail.ReadMessage(bytes.NewBuffer(doc)); err != nil { t.Fatalf("Cannot parse MIME doc: %+v\n%s", err, string(doc)) } } @@ -38,7 +37,7 @@ func TestUserData(t *testing.T) { func TestUserDataEndpoints(t *testing.T) { service := Service{} endpoints := []scope.ServiceEndpoint{ - scope.ServiceEndpoint{ + { URL: "localhost", SigningRegion: "localhost", ServiceID: "secretsmanager", @@ -46,8 +45,7 @@ func TestUserDataEndpoints(t *testing.T) { } doc, _ := service.UserData("secretARN", 1, "eu-west-1", endpoints) - _, err := mail.ReadMessage(bytes.NewBuffer(doc)) - if err != nil { + if _, err := mail.ReadMessage(bytes.NewBuffer(doc)); err != nil { t.Fatalf("Cannot parse MIME doc: %+v\n%s", err, string(doc)) } } diff --git a/pkg/cloud/services/securitygroup/securitygroups.go b/pkg/cloud/services/securitygroup/securitygroups.go index bc0fe3b1f7..a52fd708e2 100644 --- a/pkg/cloud/services/securitygroup/securitygroups.go +++ b/pkg/cloud/services/securitygroup/securitygroups.go @@ -23,7 +23,7 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/pkg/errors" - errlist "k8s.io/apimachinery/pkg/util/errors" + kerrors "k8s.io/apimachinery/pkg/util/errors" infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha4" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/awserrors" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/converters" @@ -37,16 +37,16 @@ import ( ) const ( - // IPProtocolTCP is how EC2 represents the TCP protocol in ingress rules + // IPProtocolTCP is how EC2 represents the TCP protocol in ingress rules. IPProtocolTCP = "tcp" - // IPProtocolUDP is how EC2 represents the UDP protocol in ingress rules + // IPProtocolUDP is how EC2 represents the UDP protocol in ingress rules. IPProtocolUDP = "udp" - // IPProtocolICMP is how EC2 represents the ICMP protocol in ingress rules + // IPProtocolICMP is how EC2 represents the ICMP protocol in ingress rules. IPProtocolICMP = "icmp" - // IPProtocolICMPv6 is how EC2 represents the ICMPv6 protocol in ingress rules + // IPProtocolICMPv6 is how EC2 represents the ICMPv6 protocol in ingress rules. IPProtocolICMPv6 = "58" ) @@ -81,7 +81,6 @@ func (s *Service) ReconcileSecurityGroups() error { // Security group overrides should not be specified for a managed VPC if securityGroupOverrides != nil && s.scope.VPC().IsManaged(s.scope.Name()) { return errors.Errorf("security group overrides provided for managed vpc %q", s.scope.Name()) - } sgs, err := s.describeSecurityGroupsByName() if err != nil { @@ -311,7 +310,7 @@ func (s *Service) DeleteSecurityGroups() error { for i := range clusterGroups { sg := clusterGroups[i] if deleteErr := s.deleteSecurityGroup(&sg, "cluster managed"); deleteErr != nil { - err = errlist.NewAggregate([]error{err, deleteErr}) + err = kerrors.NewAggregate([]error{err, deleteErr}) } } diff --git a/pkg/cloud/services/securitygroup/securitygroups_test.go b/pkg/cloud/services/securitygroup/securitygroups_test.go index 3f064d8dce..0f02fa0e06 100644 --- a/pkg/cloud/services/securitygroup/securitygroups_test.go +++ b/pkg/cloud/services/securitygroup/securitygroups_test.go @@ -17,11 +17,12 @@ limitations under the License. package securitygroup import ( + "strings" + "testing" + "github.com/pkg/errors" "k8s.io/apimachinery/pkg/runtime" "sigs.k8s.io/controller-runtime/pkg/client/fake" - "strings" - "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" @@ -105,8 +106,6 @@ func TestReconcileSecurityGroups(t *testing.T) { Return(&ec2.AuthorizeSecurityGroupIngressOutput{}, nil). After(securityGroupBastion) - //////////////////////// - securityGroupAPIServerLb := m.CreateSecurityGroup(gomock.Eq(&ec2.CreateSecurityGroupInput{ VpcId: aws.String("vpc-securitygroups"), GroupName: aws.String("test-cluster-apiserver-lb"), @@ -139,8 +138,6 @@ func TestReconcileSecurityGroups(t *testing.T) { Return(&ec2.AuthorizeSecurityGroupIngressOutput{}, nil). After(securityGroupAPIServerLb) - //////////////////////// - m.CreateSecurityGroup(gomock.Eq(&ec2.CreateSecurityGroupInput{ VpcId: aws.String("vpc-securitygroups"), GroupName: aws.String("test-cluster-lb"), @@ -171,8 +168,6 @@ func TestReconcileSecurityGroups(t *testing.T) { })). Return(&ec2.CreateSecurityGroupOutput{GroupId: aws.String("sg-lb")}, nil) - //////////////////////// - securityGroupControl := m.CreateSecurityGroup(gomock.Eq(&ec2.CreateSecurityGroupInput{ VpcId: aws.String("vpc-securitygroups"), GroupName: aws.String("test-cluster-controlplane"), @@ -205,8 +200,6 @@ func TestReconcileSecurityGroups(t *testing.T) { Return(&ec2.AuthorizeSecurityGroupIngressOutput{}, nil). After(securityGroupControl) - ////////////////////////////////////////////// - securityGroupNode := m.CreateSecurityGroup(gomock.Eq(&ec2.CreateSecurityGroupInput{ VpcId: aws.String("vpc-securitygroups"), GroupName: aws.String("test-cluster-node"), @@ -279,7 +272,6 @@ func TestReconcileSecurityGroups(t *testing.T) { {GroupId: aws.String("sg-node"), GroupName: aws.String("Node Security Group")}, }, }, nil).AnyTimes() - }, }, { @@ -324,7 +316,6 @@ func TestReconcileSecurityGroups(t *testing.T) { {GroupId: aws.String("sg-node"), GroupName: aws.String("Node Security Group")}, }, }, nil).AnyTimes() - }, err: errors.New(`security group overrides provided for managed vpc "test-cluster"`), }, diff --git a/pkg/cloud/services/securitygroup/service.go b/pkg/cloud/services/securitygroup/service.go index 09f53de17c..c006985e8c 100644 --- a/pkg/cloud/services/securitygroup/service.go +++ b/pkg/cloud/services/securitygroup/service.go @@ -24,7 +24,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/scope" ) -// Scope is a scope for use with the security group reconciling service +// Scope is a scope for use with the security group reconciling service. type Scope interface { cloud.ClusterScoper @@ -66,7 +66,7 @@ func NewService(sgScope Scope) *Service { } // NewServiceWithRoles returns a new service given the api clients with a defined -// set of roles +// set of roles. func NewServiceWithRoles(sgScope Scope, roles []infrav1.SecurityGroupRole) *Service { return &Service{ scope: sgScope, diff --git a/pkg/cloud/services/ssm/cloudinit.go b/pkg/cloud/services/ssm/cloudinit.go index 629f6f1068..1f9664f26a 100644 --- a/pkg/cloud/services/ssm/cloudinit.go +++ b/pkg/cloud/services/ssm/cloudinit.go @@ -27,9 +27,9 @@ const ( // UserData creates a multi-part MIME document including a script boothook to // download userdata from AWS Systems Manager and then restart cloud-init, and an include part -// specifying the on disk location of the new userdata +// specifying the on disk location of the new userdata. func (s *Service) UserData(secretPrefix string, chunks int32, region string, endpoints []scope.ServiceEndpoint) ([]byte, error) { - var serviceEndpoint string = "" + var serviceEndpoint = "" for _, v := range endpoints { if v.ServiceID == serviceID { serviceEndpoint = v.URL diff --git a/pkg/cloud/services/ssm/secret.go b/pkg/cloud/services/ssm/secret.go index f1cdfb8b16..03ad741bcc 100644 --- a/pkg/cloud/services/ssm/secret.go +++ b/pkg/cloud/services/ssm/secret.go @@ -36,7 +36,7 @@ import ( const ( entryPrefix = "aws.cluster.x-k8s.io" - // max byte size for ssm is 4KB else we cross into the advanced-parameter tier + // max byte size for ssm is 4KB else we cross into the advanced-parameter tier. maxSecretSizeBytes = 4000 ) @@ -90,7 +90,7 @@ func (s *Service) Create(m *scope.MachineScope, data []byte) (string, int32, err return prefix, chunks, err } -// retryableCreateSecret is a function to be passed into a waiter. In a separate function for ease of reading +// retryableCreateSecret is a function to be passed into a waiter. In a separate function for ease of reading. func (s *Service) retryableCreateSecret(name string, chunk []byte, tags infrav1.Tags) (bool, error) { _, err := s.SSMClient.PutParameter(&ssm.PutParameterInput{ Name: aws.String(name), @@ -105,7 +105,7 @@ func (s *Service) retryableCreateSecret(name string, chunk []byte, tags infrav1. return true, err } -// forceDeleteSecretEntry deletes a single secret, ignoring if it is absent +// forceDeleteSecretEntry deletes a single secret, ignoring if it is absent. func (s *Service) forceDeleteSecretEntry(name string) error { _, err := s.SSMClient.DeleteParameter(&ssm.DeleteParameterInput{ Name: aws.String(name), @@ -116,7 +116,7 @@ func (s *Service) forceDeleteSecretEntry(name string) error { return err } -// Delete the secret belonging to a machine from AWS SSM +// Delete the secret belonging to a machine from AWS SSM. func (s *Service) Delete(m *scope.MachineScope) error { var errs []error for i := int32(0); i < m.GetSecretCount(); i++ { diff --git a/pkg/cloud/services/ssm/secret_fetch_script.go b/pkg/cloud/services/ssm/secret_fetch_script.go index 49107a3e6f..199c85e196 100644 --- a/pkg/cloud/services/ssm/secret_fetch_script.go +++ b/pkg/cloud/services/ssm/secret_fetch_script.go @@ -16,7 +16,8 @@ limitations under the License. package ssm -const secretFetchScript = `#cloud-boothook +// nolint: gosec +const secretFetchScript = `#cloud-boothook #!/bin/bash # Copyright 2020 The Kubernetes Authors. diff --git a/pkg/cloud/services/ssm/service_test.go b/pkg/cloud/services/ssm/service_test.go index b0b1b27c99..504651bee6 100644 --- a/pkg/cloud/services/ssm/service_test.go +++ b/pkg/cloud/services/ssm/service_test.go @@ -29,8 +29,7 @@ func TestUserData(t *testing.T) { endpoints := []scope.ServiceEndpoint{} doc, _ := service.UserData("secretARN", 1, "eu-west-1", endpoints) - _, err := mail.ReadMessage(bytes.NewBuffer(doc)) - if err != nil { + if _, err := mail.ReadMessage(bytes.NewBuffer(doc)); err != nil { t.Fatalf("Cannot parse MIME doc: %+v\n%s", err, string(doc)) } } @@ -38,7 +37,7 @@ func TestUserData(t *testing.T) { func TestUserDataEndpoints(t *testing.T) { service := Service{} endpoints := []scope.ServiceEndpoint{ - scope.ServiceEndpoint{ + { URL: "localhost", SigningRegion: "localhost", ServiceID: "ssm", @@ -46,8 +45,7 @@ func TestUserDataEndpoints(t *testing.T) { } doc, _ := service.UserData("secretARN", 1, "eu-west-1", endpoints) - _, err := mail.ReadMessage(bytes.NewBuffer(doc)) - if err != nil { + if _, err := mail.ReadMessage(bytes.NewBuffer(doc)); err != nil { t.Fatalf("Cannot parse MIME doc: %+v\n%s", err, string(doc)) } } diff --git a/pkg/cloud/services/sts/identity.go b/pkg/cloud/services/sts/identity.go index bf86086809..3c378aec12 100644 --- a/pkg/cloud/services/sts/identity.go +++ b/pkg/cloud/services/sts/identity.go @@ -26,7 +26,7 @@ import ( var reAccountID = regexp.MustCompile(`[0-9]{12}`) -// AccountID gets the current account ID +// AccountID gets the current account ID. func (s *Service) AccountID() (string, error) { input := &sts.GetCallerIdentityInput{} @@ -38,7 +38,7 @@ func (s *Service) AccountID() (string, error) { return aws.StringValue(out.Account), nil } -// ValidateAccountID checks an account ID is valid +// ValidateAccountID checks an account ID is valid. func ValidateAccountID(str string) bool { return reAccountID.MatchString(str) && len(str) == 12 } diff --git a/pkg/cloud/services/sts/mock_stsiface/doc.go b/pkg/cloud/services/sts/mock_stsiface/doc.go index 2570c18e78..625436ba8c 100644 --- a/pkg/cloud/services/sts/mock_stsiface/doc.go +++ b/pkg/cloud/services/sts/mock_stsiface/doc.go @@ -17,4 +17,5 @@ limitations under the License. // Run go generate to regenerate this mock. //go:generate ../../../../../hack/tools/bin/mockgen -destination stsiface_mock.go -package mock_stsiface github.com/aws/aws-sdk-go/service/sts/stsiface STSAPI //go:generate /usr/bin/env bash -c "cat ../../../../../hack/boilerplate/boilerplate.generatego.txt stsiface_mock.go > _stsiface_mock.go && mv _stsiface_mock.go stsiface_mock.go" -package mock_stsiface //nolint + +package mock_stsiface // nolint:stylecheck diff --git a/pkg/cloud/services/userdata/utils.go b/pkg/cloud/services/userdata/utils.go index 333065d2c5..ef0a1c199f 100644 --- a/pkg/cloud/services/userdata/utils.go +++ b/pkg/cloud/services/userdata/utils.go @@ -43,7 +43,7 @@ func templateYAMLIndent(i int, input string) string { return strings.Repeat(" ", i) + strings.Join(split, ident) } -// GzipBytes will gzip a byte array +// GzipBytes will gzip a byte array. func GzipBytes(dat []byte) ([]byte, error) { var buf bytes.Buffer gz := gzip.NewWriter(&buf) diff --git a/pkg/cloud/tags/tags.go b/pkg/cloud/tags/tags.go index a852bf7216..0f3b4eddef 100644 --- a/pkg/cloud/tags/tags.go +++ b/pkg/cloud/tags/tags.go @@ -38,17 +38,17 @@ var ( ErrApplyFuncRequired = errors.New("no tags apply function supplied") ) -// BuilderOption represents an option when creating a tags builder +// BuilderOption represents an option when creating a tags builder. type BuilderOption func(*Builder) -// Builder is the interface for a tags builder +// Builder is the interface for a tags builder. type Builder struct { params *infrav1.BuildParams applyFunc func(params *infrav1.BuildParams) error } // New creates a new TagsBuilder with the specified build parameters -// and with optional configuration +// and with optional configuration. func New(params *infrav1.BuildParams, opts ...BuilderOption) *Builder { builder := &Builder{ params: params, @@ -85,7 +85,7 @@ func (b *Builder) Ensure(current infrav1.Tags) error { return nil } -// WithEC2 is used to denote that the tags builder will be using EC2 +// WithEC2 is used to denote that the tags builder will be using EC2. func WithEC2(ec2client ec2iface.EC2API) BuilderOption { return func(b *Builder) { b.applyFunc = func(params *infrav1.BuildParams) error { @@ -111,7 +111,7 @@ func WithEC2(ec2client ec2iface.EC2API) BuilderOption { } } -// WithEKS is used to specify that the tags builder will be targeting EKS +// WithEKS is used to specify that the tags builder will be targeting EKS. func WithEKS(eksclient eksiface.EKSAPI) BuilderOption { return func(b *Builder) { b.applyFunc = func(params *infrav1.BuildParams) error { @@ -149,7 +149,7 @@ func computeDiff(current infrav1.Tags, buildParams infrav1.BuildParams) infrav1. return want.Difference(current) } -// BuildParamsToTagSpecification builds a TagSpecification for the specified resource type +// BuildParamsToTagSpecification builds a TagSpecification for the specified resource type. func BuildParamsToTagSpecification(ec2ResourceType string, params infrav1.BuildParams) *ec2.TagSpecification { tags := infrav1.Build(params) diff --git a/pkg/eks/addons/plan.go b/pkg/eks/addons/plan.go index 32d2b70716..793b55481c 100644 --- a/pkg/eks/addons/plan.go +++ b/pkg/eks/addons/plan.go @@ -26,7 +26,7 @@ import ( "sigs.k8s.io/cluster-api-provider-aws/pkg/planner" ) -// NewPlan creates a new Plan to manage EKS addons +// NewPlan creates a new Plan to manage EKS addons. func NewPlan(clusterName string, desiredAddons, installedAddons []*EKSAddon, client eksiface.EKSAPI) planner.Plan { return &plan{ installedAddons: installedAddons, @@ -36,7 +36,7 @@ func NewPlan(clusterName string, desiredAddons, installedAddons []*EKSAddon, cli } } -// Plan is a plan that will manage EKS addons +// Plan is a plan that will manage EKS addons. type plan struct { installedAddons []*EKSAddon desiredAddons []*EKSAddon @@ -44,7 +44,7 @@ type plan struct { clusterName string } -// Create will create the plan (i.e. list of procedures) for managing EKS addons +// Create will create the plan (i.e. list of procedures) for managing EKS addons. func (a *plan) Create(ctx context.Context) ([]planner.Procedure, error) { procedures := []planner.Procedure{} diff --git a/pkg/eks/addons/procedures.go b/pkg/eks/addons/procedures.go index ec06c69583..10074223dd 100644 --- a/pkg/eks/addons/procedures.go +++ b/pkg/eks/addons/procedures.go @@ -34,39 +34,38 @@ var ( ErrAddonAlreadyExists = errors.New("addon already exists") ) -// DeleteAddonProcedure is a procedure that will delete an EKS addon +// DeleteAddonProcedure is a procedure that will delete an EKS addon. type DeleteAddonProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *DeleteAddonProcedure) Do(ctx context.Context) error { input := &eks.DeleteAddonInput{ AddonName: aws.String(p.name), ClusterName: aws.String(p.plan.clusterName), } - _, err := p.plan.eksClient.DeleteAddon(input) - if err != nil { + if _, err := p.plan.eksClient.DeleteAddon(input); err != nil { return fmt.Errorf("deleting eks addon %s: %w", p.name, err) } return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *DeleteAddonProcedure) Name() string { return "addon_delete" } -// UpdateAddonProcedure is a procedure that will update an EKS addon +// UpdateAddonProcedure is a procedure that will update an EKS addon. type UpdateAddonProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *UpdateAddonProcedure) Do(ctx context.Context) error { desired := p.plan.getDesired(p.name) @@ -81,26 +80,26 @@ func (p *UpdateAddonProcedure) Do(ctx context.Context) error { ResolveConflicts: desired.ResolveConflict, ServiceAccountRoleArn: desired.ServiceAccountRoleARN, } - _, err := p.plan.eksClient.UpdateAddon(input) - if err != nil { + + if _, err := p.plan.eksClient.UpdateAddon(input); err != nil { return fmt.Errorf("updating eks addon %s: %w", p.name, err) } return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *UpdateAddonProcedure) Name() string { return "addon_update" } -// UpdateAddonTagsProcedure is a procedure that will update an EKS addon tags +// UpdateAddonTagsProcedure is a procedure that will update an EKS addon tags. type UpdateAddonTagsProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *UpdateAddonTagsProcedure) Do(ctx context.Context) error { desired := p.plan.getDesired(p.name) installed := p.plan.getInstalled(p.name) @@ -116,26 +115,26 @@ func (p *UpdateAddonTagsProcedure) Do(ctx context.Context) error { ResourceArn: installed.ARN, Tags: convertTags(desired.Tags), } - _, err := p.plan.eksClient.TagResource(input) - if err != nil { + + if _, err := p.plan.eksClient.TagResource(input); err != nil { return fmt.Errorf("updating eks addon tags %s: %w", p.name, err) } return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *UpdateAddonTagsProcedure) Name() string { return "addon_tags_update" } -// CreateAddonProcedure is a procedure that will create an EKS addon for a cluster +// CreateAddonProcedure is a procedure that will create an EKS addon for a cluster. type CreateAddonProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *CreateAddonProcedure) Do(ctx context.Context) error { desired := p.plan.getDesired(p.name) if desired == nil { @@ -163,19 +162,19 @@ func (p *CreateAddonProcedure) Do(ctx context.Context) error { return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *CreateAddonProcedure) Name() string { return "addon_create" } // WaitAddonActiveProcedure is a procedure that will wait for an EKS addon -// to be active in a cluster +// to be active in a cluster. type WaitAddonActiveProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *WaitAddonActiveProcedure) Do(ctx context.Context) error { input := &eks.DescribeAddonInput{ AddonName: aws.String(p.name), @@ -189,19 +188,19 @@ func (p *WaitAddonActiveProcedure) Do(ctx context.Context) error { return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *WaitAddonActiveProcedure) Name() string { return "addon_wait_active" } // WaitAddonDeleteProcedure is a procedure that will wait for an EKS addon -// to be deleted from a cluster +// to be deleted from a cluster. type WaitAddonDeleteProcedure struct { plan *plan name string } -// Do implements the logic for the procedure +// Do implements the logic for the procedure. func (p *WaitAddonDeleteProcedure) Do(ctx context.Context) error { input := &eks.DescribeAddonInput{ AddonName: aws.String(p.name), @@ -215,7 +214,7 @@ func (p *WaitAddonDeleteProcedure) Do(ctx context.Context) error { return nil } -// Name is the name of the procedure +// Name is the name of the procedure. func (p *WaitAddonDeleteProcedure) Name() string { return "addon_wait_delete" } diff --git a/pkg/eks/addons/types.go b/pkg/eks/addons/types.go index 3833bfe8ea..72cce15462 100644 --- a/pkg/eks/addons/types.go +++ b/pkg/eks/addons/types.go @@ -33,7 +33,7 @@ type EKSAddon struct { Status *string } -// IsEqual determines if 2 EKSAddon are equal +// IsEqual determines if 2 EKSAddon are equal. func (e *EKSAddon) IsEqual(other *EKSAddon, includeTags bool) bool { //NOTE: we don't compare the ARN as thats only for existing addons if e == other { diff --git a/pkg/eks/eks.go b/pkg/eks/eks.go index 706a97982f..94a1de6866 100644 --- a/pkg/eks/eks.go +++ b/pkg/eks/eks.go @@ -28,9 +28,9 @@ const ( resourcePrefix = "capa_" ) -// GenerateEKSName generates a name of an EKS resources +// GenerateEKSName generates a name of an EKS resources. func GenerateEKSName(resourceName, namespace string, maxLength int) (string, error) { - escapedName := strings.Replace(resourceName, ".", "_", -1) + escapedName := strings.ReplaceAll(resourceName, ".", "_") eksName := fmt.Sprintf("%s_%s", namespace, escapedName) if len(eksName) < maxLength { diff --git a/pkg/hash/base36.go b/pkg/hash/base36.go index 6fa514e4bb..e94b8b340b 100644 --- a/pkg/hash/base36.go +++ b/pkg/hash/base36.go @@ -19,6 +19,8 @@ package hash import ( "github.com/pkg/errors" "golang.org/x/crypto/blake2b" + + // keep the blank import to include intstr. _ "k8s.io/apimachinery/pkg/util/intstr" ) @@ -41,7 +43,7 @@ func Base36TruncatedHash(str string, len int) (string, error) { // base36Truncate returns a string that is base36 compliant // It is not an encoding since it returns a same-length string -// for any byte value +// for any byte value. func base36Truncate(bytes []byte) string { var chars string for _, bite := range bytes { diff --git a/pkg/internal/mime/mime.go b/pkg/internal/mime/mime.go index 68e84b7b38..72bcc36c63 100644 --- a/pkg/internal/mime/mime.go +++ b/pkg/internal/mime/mime.go @@ -54,7 +54,7 @@ type scriptVariables struct { // GenerateInitDocument renders a given template, applies MIME properties // and returns a series of byte chunks which put together represent a UserData -// script +// script. func GenerateInitDocument(secretPrefix string, chunks int32, region string, endpoint string, secretFetchScript string) ([]byte, error) { var secretFetchTemplate = template.Must(template.New("secret-fetch-script").Parse(secretFetchScript)) diff --git a/pkg/internal/mime/mime_test.go b/pkg/internal/mime/mime_test.go index 1d1b62fed4..0cb5ddb7f3 100644 --- a/pkg/internal/mime/mime_test.go +++ b/pkg/internal/mime/mime_test.go @@ -26,8 +26,7 @@ func TestGenerateInitDocument(t *testing.T) { secretARN := "secretARN" doc, _ := GenerateInitDocument(secretARN, 1, "eu-west-1", "localhost", "abc123") - _, err := mail.ReadMessage(bytes.NewBuffer(doc)) - if err != nil { + if _, err := mail.ReadMessage(bytes.NewBuffer(doc)); err != nil { t.Fatalf("Cannot parse MIME doc: %+v\n%s", err, string(doc)) } } diff --git a/pkg/internal/rate/rate.go b/pkg/internal/rate/rate.go index 5458fc6d30..16faa59d94 100644 --- a/pkg/internal/rate/rate.go +++ b/pkg/internal/rate/rate.go @@ -241,7 +241,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) { lim.mu.Unlock() if n > burst && limit != Inf { - return errors.New(fmt.Sprintf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst)) + return errors.New(fmt.Errorf("rate: Wait(n=%d) exceeds limiter's burst %d", n, burst).Error()) } // Check if ctx is already cancelled select { @@ -258,7 +258,7 @@ func (lim *Limiter) WaitN(ctx context.Context, n int) (err error) { // Reserve r := lim.reserveN(now, n, waitLimit) if !r.ok { - return errors.New(fmt.Sprintf("rate: Wait(n=%d) would exceed context deadline", n)) + return errors.New(fmt.Errorf("rate: Wait(n=%d) would exceed context deadline", n).Error()) } // Wait if necessary delay := r.DelayFrom(now) diff --git a/pkg/internal/tristate/tristate.go b/pkg/internal/tristate/tristate.go index c8b75a40b0..923ed1fe60 100644 --- a/pkg/internal/tristate/tristate.go +++ b/pkg/internal/tristate/tristate.go @@ -16,7 +16,7 @@ limitations under the License. package tristate -// withDefault evaluates a pointer to a bool with a default value +// withDefault evaluates a pointer to a bool with a default value. func withDefault(def bool, b *bool) bool { if b == nil { return def @@ -24,7 +24,7 @@ func withDefault(def bool, b *bool) bool { return *b } -// EqualWithDefault compares two bool pointers using a default value +// EqualWithDefault compares two bool pointers using a default value. func EqualWithDefault(def bool, a *bool, b *bool) bool { return withDefault(def, a) == withDefault(def, b) } diff --git a/pkg/planner/planner.go b/pkg/planner/planner.go index f6b4465ec3..d370b94b16 100644 --- a/pkg/planner/planner.go +++ b/pkg/planner/planner.go @@ -29,7 +29,7 @@ type Plan interface { } // Procedure represents a procedure/operation that will be carried out -// as part of executing a plan +// as part of executing a plan. type Procedure interface { // Name is the name of the procedure/operation Name() string diff --git a/test/helpers/envtest.go b/test/helpers/envtest.go index 30e456de5b..b0d62e03da 100644 --- a/test/helpers/envtest.go +++ b/test/helpers/envtest.go @@ -81,9 +81,6 @@ func init() { // Get the root of the current file to use in CRD paths. _, filename, _, _ := goruntime.Caller(0) //nolint root = path.Join(path.Dir(filename), "..", "..") - - // Create the test environment. - } type webhookConfiguration struct { @@ -91,7 +88,7 @@ type webhookConfiguration struct { relativeFilePath string } -// TestEnvironmentConfiguration encapsulates the interim, mutable configuration of the Kubernetes local test environment +// TestEnvironmentConfiguration encapsulates the interim, mutable configuration of the Kubernetes local test environment. type TestEnvironmentConfiguration struct { env *envtest.Environment webhookConfigurations []webhookConfiguration @@ -136,7 +133,7 @@ func (t *TestEnvironment) CreateNamespace(ctx context.Context, generateName stri return ns, nil } -// NewTestEnvironmentConfiguration creates a new test environment configuration for running tests +// NewTestEnvironmentConfiguration creates a new test environment configuration for running tests. func NewTestEnvironmentConfiguration(crdDirectoryPaths []string) *TestEnvironmentConfiguration { resolvedCrdDirectoryPaths := make([]string, len(crdDirectoryPaths)) @@ -154,10 +151,9 @@ func NewTestEnvironmentConfiguration(crdDirectoryPaths []string) *TestEnvironmen }, }, } - } -// WithWebhookConfiguration adds the CRD webhook configuration given a named tag and file path for the webhook manifest +// WithWebhookConfiguration adds the CRD webhook configuration given a named tag and file path for the webhook manifest. func (t *TestEnvironmentConfiguration) WithWebhookConfiguration(tag string, relativeFilePath string) *TestEnvironmentConfiguration { t.webhookConfigurations = append(t.webhookConfigurations, webhookConfiguration{tag: tag, relativeFilePath: relativeFilePath}) return t @@ -208,13 +204,12 @@ func (t *TestEnvironmentConfiguration) Build() (*TestEnvironment, error) { Config: mgr.GetConfig(), env: t.env, }, nil - } func buildModifiedWebhook(tag string, relativeFilePath string) (client.Object, client.Object, error) { var mutatingWebhook client.Object var validatingWebhook client.Object - data, err := ioutil.ReadFile(filepath.Join(root, relativeFilePath)) + data, err := ioutil.ReadFile(filepath.Clean(filepath.Join(root, relativeFilePath))) if err != nil { return nil, nil, errors.Wrap(err, "failed to read webhook configuration file") } @@ -242,14 +237,14 @@ func buildModifiedWebhook(tag string, relativeFilePath string) (client.Object, c return mutatingWebhook, validatingWebhook, nil } -// StartManager starts the test controller against the local API server +// StartManager starts the test controller against the local API server. func (t *TestEnvironment) StartManager(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) t.cancel = cancel return t.Manager.Start(ctx) } -// WaitForWebhooks will not return until the webhook port is open +// WaitForWebhooks will not return until the webhook port is open. func (t *TestEnvironment) WaitForWebhooks() { port := t.env.WebhookInstallOptions.LocalServingPort klog.V(2).Infof("Waiting for webhook port %d to be open prior to running tests", port) @@ -267,7 +262,7 @@ func (t *TestEnvironment) WaitForWebhooks() { } } -// Stop stops the test environment +// Stop stops the test environment. func (t *TestEnvironment) Stop() error { t.cancel() return t.env.Stop() diff --git a/util/system/util.go b/util/system/util.go index ac35aac536..d388ebf6f1 100644 --- a/util/system/util.go +++ b/util/system/util.go @@ -20,20 +20,21 @@ import ( "fmt" "io/ioutil" "os" + "path/filepath" "github.com/pkg/errors" ) const ( - // namespaceEnvVarName is the env var coming from DownwardAPI in the manager manifest + // namespaceEnvVarName is the env var coming from DownwardAPI in the manager manifest. namespaceEnvVarName = "POD_NAMESPACE" - // defaultNamespace is the default value from manifest + // defaultNamespace is the default value from manifest. defaultNamespace = "capa-system" - // inClusterNamespacePath is the file the default namespace to be used for namespaced API operations is placed at + // inClusterNamespacePath is the file the default namespace to be used for namespaced API operations is placed at. inClusterNamespacePath = "/var/run/secrets/kubernetes.io/serviceaccount/namespace" ) -// GetManagerNamespace return the namespace where the controller is running +// GetManagerNamespace return the namespace where the controller is running. func GetManagerNamespace() string { ns, err := GetNamespaceFromFile(inClusterNamespacePath) if err == nil { @@ -54,15 +55,15 @@ func GetManagerNamespace() string { func GetNamespaceFromFile(nsFilePath string) (string, error) { // Check whether the namespace file exists. // If not, we are not running in cluster so can't guess the namespace. - _, err := os.Stat(nsFilePath) - if os.IsNotExist(err) { + + if _, err := os.Stat(nsFilePath); os.IsNotExist(err) { return "", errors.Wrapf(err, "not running in-cluster, please specify LeaderElectionNamespace") } else if err != nil { return "", errors.Wrapf(err, "error checking namespace file: %s", nsFilePath) } // Load the namespace file and return its content - namespace, err := ioutil.ReadFile(nsFilePath) + namespace, err := ioutil.ReadFile(filepath.Clean(nsFilePath)) if err != nil { return "", fmt.Errorf("error reading namespace file: %w", err) } diff --git a/util/system/util_test.go b/util/system/util_test.go index 349d2fe4d4..34108d5094 100644 --- a/util/system/util_test.go +++ b/util/system/util_test.go @@ -17,6 +17,8 @@ limitations under the License. package system import ( + "path/filepath" + . "github.com/onsi/gomega" "io/ioutil" @@ -61,10 +63,10 @@ func TestGetNamespaceFromFile(t *testing.T) { path, err := os.Getwd() g.Expect(err).NotTo(HaveOccurred()) nsPath := path + "namespace" - _, err = os.OpenFile(nsPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm) + _, err = os.OpenFile(filepath.Clean(nsPath), os.O_APPEND|os.O_CREATE|os.O_WRONLY, os.ModePerm) g.Expect(err).NotTo(HaveOccurred()) ns := []byte("different-ns") - g.Expect(ioutil.WriteFile(nsPath, ns, 0644)).NotTo(HaveOccurred()) + g.Expect(ioutil.WriteFile(nsPath, ns, 0644)).NotTo(HaveOccurred()) //nolint:gosec g.Expect(GetNamespaceFromFile(nsPath)).To(Equal("different-ns")) g.Expect(os.Remove(nsPath)).NotTo(HaveOccurred()) }