From 0ce2fd66204d67f7dc6ee001ed9b22926acd7ea4 Mon Sep 17 00:00:00 2001 From: Abhay Krishna Arunachalam Date: Wed, 15 Mar 2023 10:45:32 -0700 Subject: [PATCH] Improve Go formatting in CAPI codebase --- .golangci.yml | 1 + Makefile | 2 +- api/v1alpha4/common_types.go | 6 +- api/v1beta1/common_types.go | 6 +- api/v1beta1/machine_webhook.go | 6 +- api/v1beta1/machinedeployment_webhook.go | 8 +- api/v1beta1/machinedeployment_webhook_test.go | 1 - api/v1beta1/machinehealthcheck_webhook.go | 6 +- api/v1beta1/machineset_webhook.go | 6 +- .../kubeadm/api/v1alpha4/kubeadm_types.go | 4 +- .../api/v1alpha4/kubeadm_types_test.go | 10 +- .../kubeadm/api/v1beta1/kubeadm_types.go | 4 +- .../kubeadm/api/v1beta1/kubeadm_types_test.go | 12 +- .../kubeadm/internal/cloudinit/cloudinit.go | 8 +- bootstrap/kubeadm/internal/cloudinit/utils.go | 8 +- .../kubeadmconfig_controller_test.go | 3 +- .../locking/control_plane_init_mutex_test.go | 16 +- .../bootstraptokenstring_test.go | 12 +- .../kubeadm/types/upstreamv1beta1/types.go | 4 +- .../bootstraptokenstring_test.go | 12 +- .../kubeadm/types/upstreamv1beta2/types.go | 4 +- .../bootstraptokenstring_test.go | 12 +- .../kubeadm/types/upstreamv1beta3/types.go | 4 +- cmd/clusterctl/client/alpha/client.go | 4 +- cmd/clusterctl/client/client_test.go | 2 +- cmd/clusterctl/client/cluster/cert_manager.go | 6 +- cmd/clusterctl/client/cluster/client.go | 4 +- .../client/cluster/internal/dryrun/client.go | 4 +- cmd/clusterctl/client/cluster/mover.go | 15 +- cmd/clusterctl/client/cluster/mover_test.go | 1 - cmd/clusterctl/client/cluster/objectgraph.go | 6 +- .../client/cluster/objectgraph_test.go | 4 +- cmd/clusterctl/client/cluster/proxy.go | 4 +- cmd/clusterctl/client/cluster/proxy_test.go | 10 +- cmd/clusterctl/client/cluster/template.go | 4 +- .../client/cluster/template_test.go | 4 +- .../client/cluster/workload_cluster.go | 4 +- cmd/clusterctl/client/common.go | 2 +- cmd/clusterctl/client/config/provider.go | 2 +- cmd/clusterctl/client/config/reader_viper.go | 2 +- .../client/config/reader_viper_test.go | 10 +- cmd/clusterctl/client/config_test.go | 7 +- cmd/clusterctl/client/init_test.go | 18 +- cmd/clusterctl/client/move_test.go | 4 +- cmd/clusterctl/client/repository/client.go | 2 +- .../client/repository/components_test.go | 3 +- .../client/repository/metadata_client.go | 2 +- .../client/repository/repository_github.go | 2 +- .../repository/repository_local_test.go | 4 +- .../client/repository/repository_memory.go | 4 +- cmd/clusterctl/client/tree/discovery.go | 2 +- cmd/clusterctl/client/tree/tree.go | 6 +- .../client/yamlprocessor/simple_processor.go | 6 +- cmd/clusterctl/cmd/config_repositories.go | 6 +- .../cmd/config_repositories_test.go | 4 +- cmd/clusterctl/cmd/describe_cluster.go | 6 +- cmd/clusterctl/cmd/generate_yaml_test.go | 2 +- cmd/clusterctl/cmd/topology_plan.go | 12 +- cmd/clusterctl/cmd/upgrade_plan.go | 1 - cmd/clusterctl/cmd/util.go | 2 +- cmd/clusterctl/cmd/version_checker.go | 10 +- cmd/clusterctl/internal/scheme/scheme.go | 6 +- cmd/clusterctl/internal/test/fake_objects.go | 6 +- cmd/clusterctl/internal/test/fake_proxy.go | 4 +- controllers/external/tracker_test.go | 4 +- controllers/external/util_test.go | 4 +- controllers/noderefutil/providerid_test.go | 6 +- controllers/noderefutil/util_test.go | 162 ++++--- .../remote/cluster_cache_healthcheck_test.go | 6 +- .../remote/cluster_cache_reconciler.go | 1 - .../kubeadm/api/v1alpha3/conversion_test.go | 1 + .../v1beta1/kubeadm_control_plane_webhook.go | 6 +- .../kubeadm_control_plane_webhook_test.go | 1 + .../internal/controllers/controller_test.go | 3 +- .../internal/controllers/fakes_test.go | 2 +- .../internal/controllers/remediation_test.go | 4 +- .../internal/controllers/upgrade_test.go | 6 +- .../kubeadm/internal/etcd/etcd_test.go | 4 +- .../kubeadm/internal/etcd/fake/client.go | 3 + .../internal/etcd_client_generator_test.go | 19 +- controlplane/kubeadm/internal/proxy/dial.go | 2 +- controlplane/kubeadm/internal/proxy/proxy.go | 1 - .../kubeadm/internal/webhooks/scale_test.go | 4 +- .../kubeadm/internal/workload_cluster.go | 2 +- .../internal/workload_cluster_coredns.go | 40 +- .../kubeadm/internal/workload_cluster_etcd.go | 2 +- .../kubeadm/internal/workload_cluster_test.go | 15 +- controlplane/kubeadm/main.go | 1 + .../api/v1beta1/clusterresourceset_webhook.go | 6 +- exp/api/v1beta1/machinepool_webhook.go | 6 +- .../machinepool_controller_noderef.go | 4 +- .../machinepool_controller_phases.go | 4 +- .../machinepool_controller_test.go | 1 - exp/ipam/internal/webhooks/ipaddressclaim.go | 3 +- exp/ipam/webhooks/alias.go | 3 +- exp/runtime/catalog/catalog.go | 2 +- exp/runtime/internal/controllers/warmup.go | 1 - exp/runtime/topologymutation/walker.go | 3 +- exp/runtime/topologymutation/walker_test.go | 4 +- hack/tools/log-push/main_test.go | 1 - hack/tools/runtime-openapi-gen/main.go | 2 +- hack/tools/tilt-prepare/main.go | 6 +- internal/contract/bootstrap.go | 6 +- .../contract/bootstrap_config_template.go | 6 +- internal/contract/controlplane.go | 6 +- internal/contract/controlplane_template.go | 6 +- internal/contract/infrastructure_cluster.go | 6 +- .../infrastructure_cluster_template.go | 6 +- internal/contract/infrastructure_machine.go | 6 +- .../infrastructure_machine_template.go | 6 +- .../controllers/cluster/cluster_controller.go | 1 - .../clusterclass/clusterclass_controller.go | 4 +- .../clusterclass_controller_test.go | 9 +- .../controllers/clusterclass/suite_test.go | 1 + .../controllers/machine/machine_controller.go | 2 +- .../machine/machine_controller_noderef.go | 6 +- .../machine/machine_controller_phases.go | 4 +- .../machine/machine_controller_test.go | 12 +- .../machinedeployment_controller.go | 6 +- .../machinedeployment_rolling.go | 4 +- .../machinedeployment_rollout_ondelete.go | 2 +- .../machinedeployment_sync_test.go | 4 +- .../machinedeployment/mdutil/util.go | 2 +- .../machinedeployment/mdutil/util_test.go | 2 +- .../machinehealthcheck_targets.go | 6 +- .../machinehealthcheck_targets_test.go | 2 +- .../machineset/machineset_controller_test.go | 17 +- .../topology/cluster/blueprint_test.go | 3 +- .../topology/cluster/cluster_controller.go | 1 - .../cluster/cluster_controller_test.go | 7 +- .../topology/cluster/current_state_test.go | 3 +- .../topology/cluster/desired_state.go | 9 +- .../topology/cluster/desired_state_test.go | 9 +- .../topology/cluster/patches/engine_test.go | 15 +- .../inline/json_patch_generator_test.go | 12 +- .../topology/cluster/reconcile_state_test.go | 38 +- .../topology/cluster/suite_test.go | 1 + internal/runtime/client/client_test.go | 3 +- internal/runtime/metrics/metrics.go | 6 +- .../runtime/test/v1alpha1/conversion_test.go | 2 +- internal/test/builder/bootstrap.go | 18 +- internal/test/builder/controlplane.go | 82 ++-- internal/test/envtest/environment.go | 16 +- .../cluster_variable_defaulting_test.go | 15 - .../cluster_variable_validation_test.go | 1 - internal/topology/variables/utils.go | 1 + internal/util/taints/taints_test.go | 9 +- internal/webhooks/cluster.go | 6 +- internal/webhooks/cluster_test.go | 409 +++++++++--------- internal/webhooks/clusterclass.go | 9 +- internal/webhooks/clusterclass_test.go | 25 +- internal/webhooks/patch_validation_test.go | 15 - .../runtime/extensionconfig_webhook.go | 6 +- .../runtime/extensionconfig_webhook_test.go | 3 +- test/e2e/cluster_upgrade.go | 2 +- test/e2e/cluster_upgrade_runtimesdk.go | 17 +- test/e2e/clusterclass_changes.go | 4 +- test/e2e/clusterclass_rollout.go | 2 +- test/e2e/clusterctl_upgrade.go | 10 +- test/e2e/e2e_suite_test.go | 2 +- test/e2e/k8s_conformance.go | 2 +- test/e2e/kcp_adoption.go | 2 +- test/e2e/kcp_remediations.go | 2 +- test/e2e/machine_pool.go | 2 +- test/e2e/md_remediations.go | 2 +- test/e2e/md_rollout.go | 2 +- test/e2e/md_scale.go | 2 +- test/e2e/node_drain_timeout.go | 2 +- test/e2e/quick_start.go | 2 +- test/e2e/self_hosted.go | 2 +- .../handlers/topologymutation/handler_test.go | 4 +- test/framework/alltypes_helpers.go | 6 +- test/framework/cluster_helpers.go | 2 +- test/framework/cluster_proxy.go | 6 +- test/framework/clusterctl/client.go | 6 +- .../framework/clusterctl/clusterctl_config.go | 2 +- .../clusterctl/clusterctl_helpers.go | 4 +- test/framework/clusterctl/e2e_config.go | 2 +- test/framework/clusterctl/logger/log_file.go | 4 +- test/framework/clusterctl/repository.go | 16 +- test/framework/deployment_helpers.go | 15 +- test/framework/docker_logcollector.go | 2 +- test/framework/kubetest/run.go | 2 +- test/framework/namespace_helpers.go | 6 +- test/framework/ownerreference_helpers.go | 4 +- test/framework/suite_helpers.go | 2 +- test/infrastructure/container/fake.go | 13 +- .../v1beta1/dockermachinetemplate_webhook.go | 2 +- .../docker/internal/docker/loadbalancer.go | 2 +- .../docker/internal/docker/machine.go | 2 +- .../docker/internal/docker/types/node.go | 2 +- .../provisioning/cloudinit/runcmd_test.go | 2 +- .../provisioning/cloudinit/writefiles_test.go | 4 +- util/annotations/helpers_test.go | 2 +- util/collections/machine_collection_test.go | 10 +- util/conditions/matchers.go | 1 + util/conditions/patch.go | 2 +- util/conditions/setter.go | 2 +- util/conditions/setter_test.go | 1 + util/container/image.go | 4 +- util/conversion/conversion.go | 6 +- util/conversion/conversion_test.go | 12 +- util/kubeconfig/kubeconfig.go | 6 +- util/labels/helpers_test.go | 2 +- util/patch/utils.go | 12 +- util/secret/consts.go | 6 +- util/suite_test.go | 4 +- util/version/version.go | 2 +- util/version/version_test.go | 4 +- util/yaml/yaml.go | 4 +- util/yaml/yaml_test.go | 4 +- 211 files changed, 927 insertions(+), 887 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 799403e5cb81..cc49faa33eb1 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -30,6 +30,7 @@ linters: - gocritic - godot - gofmt + - gofumpt - goimports - goprintffuncname - gosec diff --git a/Makefile b/Makefile index 2fb191ed8946..c93d6d4e5141 100644 --- a/Makefile +++ b/Makefile @@ -455,7 +455,7 @@ generate-go-conversions-docker-infrastructure: $(CONVERSION_GEN) ## Generate con generate-go-openapi: $(OPENAPI_GEN) $(CONTROLLER_GEN) ## Generate openapi go code for runtime SDK @mkdir -p ./tmp/sigs.k8s.io; ln -s $(ROOT_DIR) ./tmp/sigs.k8s.io/; cd ./tmp; \ for pkg in "api/v1beta1" "$(EXP_DIR)/runtime/hooks/api/v1alpha1"; do \ - $(MAKE) clean-generated-openapi-definitions SRC_DIRS="./$${pkg}"; \ + $(MAKE) clean-generated-openapi-definitions -C sigs.k8s.io/cluster-api SRC_DIRS="./$${pkg}"; \ echo "** Generating openapi schema for types in ./$${pkg} **"; \ $(OPENAPI_GEN) \ --input-dirs=sigs.k8s.io/cluster-api/$${pkg} \ diff --git a/api/v1alpha4/common_types.go b/api/v1alpha4/common_types.go index 6893544c3eb9..27c2a89ec312 100644 --- a/api/v1alpha4/common_types.go +++ b/api/v1alpha4/common_types.go @@ -111,10 +111,8 @@ const ( TemplateSuffix = "Template" ) -var ( - // ZeroDuration is a zero value of the metav1.Duration type. - ZeroDuration = metav1.Duration{} -) +// ZeroDuration is a zero value of the metav1.Duration type. +var ZeroDuration = metav1.Duration{} const ( // MachineNodeNameIndex is used by the Machine Controller to index Machines by Node name, and add a watch on Nodes. diff --git a/api/v1beta1/common_types.go b/api/v1beta1/common_types.go index db826ba0c1f6..960065ffb47a 100644 --- a/api/v1beta1/common_types.go +++ b/api/v1beta1/common_types.go @@ -164,10 +164,8 @@ const ( TemplateSuffix = "Template" ) -var ( - // ZeroDuration is a zero value of the metav1.Duration type. - ZeroDuration = metav1.Duration{} -) +// ZeroDuration is a zero value of the metav1.Duration type. +var ZeroDuration = metav1.Duration{} // MachineAddressType describes a valid MachineAddress type. type MachineAddressType string diff --git a/api/v1beta1/machine_webhook.go b/api/v1beta1/machine_webhook.go index 4a21872eaa51..b4114f2cad3c 100644 --- a/api/v1beta1/machine_webhook.go +++ b/api/v1beta1/machine_webhook.go @@ -42,8 +42,10 @@ func (m *Machine) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-cluster-x-k8s-io-v1beta1-machine,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machines,versions=v1beta1,name=validation.machine.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-machine,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machines,versions=v1beta1,name=default.machine.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Validator = &Machine{} -var _ webhook.Defaulter = &Machine{} +var ( + _ webhook.Validator = &Machine{} + _ webhook.Defaulter = &Machine{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (m *Machine) Default() { diff --git a/api/v1beta1/machinedeployment_webhook.go b/api/v1beta1/machinedeployment_webhook.go index 882fe9fcce22..4bc5a3ccd6ba 100644 --- a/api/v1beta1/machinedeployment_webhook.go +++ b/api/v1beta1/machinedeployment_webhook.go @@ -52,8 +52,10 @@ func (m *MachineDeployment) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-cluster-x-k8s-io-v1beta1-machinedeployment,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinedeployments,versions=v1beta1,name=validation.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-machinedeployment,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinedeployments,versions=v1beta1,name=default.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} -var _ webhook.Validator = &MachineDeployment{} +var ( + _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} + _ webhook.Validator = &MachineDeployment{} +) // MachineDeploymentDefaulter creates a new CustomDefaulter for MachineDeployments. func MachineDeploymentDefaulter(scheme *runtime.Scheme) webhook.CustomDefaulter { @@ -304,7 +306,7 @@ const ( // Notes: // - While the min size and max size annotations of the autoscaler provide the best UX, other autoscalers can use the // DefaultReplicasAnnotation if they have similar use cases. -func calculateMachineDeploymentReplicas(ctx context.Context, oldMD *MachineDeployment, newMD *MachineDeployment, dryRun bool) (int32, error) { +func calculateMachineDeploymentReplicas(ctx context.Context, oldMD, newMD *MachineDeployment, dryRun bool) (int32, error) { // If replicas is already set => Keep the current value. if newMD.Spec.Replicas != nil { return *newMD.Spec.Replicas, nil diff --git a/api/v1beta1/machinedeployment_webhook_test.go b/api/v1beta1/machinedeployment_webhook_test.go index 23d3b9124c19..487f04ec69d3 100644 --- a/api/v1beta1/machinedeployment_webhook_test.go +++ b/api/v1beta1/machinedeployment_webhook_test.go @@ -442,7 +442,6 @@ func TestMachineDeploymentVersionValidation(t *testing.T) { md := &MachineDeployment{ Spec: MachineDeploymentSpec{ - Template: MachineTemplateSpec{ Spec: MachineSpec{ Version: pointer.String(tt.version), diff --git a/api/v1beta1/machinehealthcheck_webhook.go b/api/v1beta1/machinehealthcheck_webhook.go index d50510eaa2cd..a12fe31f43b5 100644 --- a/api/v1beta1/machinehealthcheck_webhook.go +++ b/api/v1beta1/machinehealthcheck_webhook.go @@ -59,8 +59,10 @@ func (m *MachineHealthCheck) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-cluster-x-k8s-io-v1beta1-machinehealthcheck,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinehealthchecks,versions=v1beta1,name=validation.machinehealthcheck.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-machinehealthcheck,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinehealthchecks,versions=v1beta1,name=default.machinehealthcheck.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Defaulter = &MachineHealthCheck{} -var _ webhook.Validator = &MachineHealthCheck{} +var ( + _ webhook.Defaulter = &MachineHealthCheck{} + _ webhook.Validator = &MachineHealthCheck{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (m *MachineHealthCheck) Default() { diff --git a/api/v1beta1/machineset_webhook.go b/api/v1beta1/machineset_webhook.go index 75dbfe9d34b8..fd43b55e423e 100644 --- a/api/v1beta1/machineset_webhook.go +++ b/api/v1beta1/machineset_webhook.go @@ -41,8 +41,10 @@ func (m *MachineSet) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-cluster-x-k8s-io-v1beta1-machineset,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinesets,versions=v1beta1,name=validation.machineset.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-machineset,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinesets,versions=v1beta1,name=default.machineset.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Defaulter = &MachineSet{} -var _ webhook.Validator = &MachineSet{} +var ( + _ webhook.Defaulter = &MachineSet{} + _ webhook.Validator = &MachineSet{} +) // Default sets default MachineSet field values. func (m *MachineSet) Default() { diff --git a/bootstrap/kubeadm/api/v1alpha4/kubeadm_types.go b/bootstrap/kubeadm/api/v1alpha4/kubeadm_types.go index 6e91e00ae28d..695391046868 100644 --- a/bootstrap/kubeadm/api/v1alpha4/kubeadm_types.go +++ b/bootstrap/kubeadm/api/v1alpha4/kubeadm_types.go @@ -173,7 +173,7 @@ type ImageMeta struct { // +optional ImageTag string `json:"imageTag,omitempty"` - //TODO: evaluate if we need also a ImageName based on user feedbacks + // TODO: evaluate if we need also a ImageName based on user feedbacks } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -205,7 +205,6 @@ type APIEndpoint struct { // NodeRegistrationOptions holds fields that relate to registering a new control-plane or node to the cluster, either via "kubeadm init" or "kubeadm join". type NodeRegistrationOptions struct { - // Name is the `.Metadata.Name` field of the Node API object that will be created in this `kubeadm init` or `kubeadm join` operation. // This field is also used in the CommonName field of the kubelet's client certificate to the API server. // Defaults to the hostname of the node if not provided. @@ -278,7 +277,6 @@ type BootstrapToken struct { // Etcd contains elements describing Etcd configuration. type Etcd struct { - // Local provides configuration knobs for configuring the local etcd instance // Local and External are mutually exclusive // +optional diff --git a/bootstrap/kubeadm/api/v1alpha4/kubeadm_types_test.go b/bootstrap/kubeadm/api/v1alpha4/kubeadm_types_test.go index 0173e0d6e111..3a57f78fdb94 100644 --- a/bootstrap/kubeadm/api/v1alpha4/kubeadm_types_test.go +++ b/bootstrap/kubeadm/api/v1alpha4/kubeadm_types_test.go @@ -26,7 +26,7 @@ import ( ) func TestMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -46,7 +46,7 @@ func TestMarshalJSON(t *testing.T) { } func TestUnmarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString expectedError bool @@ -77,7 +77,7 @@ func TestUnmarshalJSON(t *testing.T) { } func TestJSONRoundtrip(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString }{ @@ -132,7 +132,7 @@ func roundtrip(input string, bts *BootstrapTokenString) error { } func TestTokenFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -150,7 +150,7 @@ func TestTokenFromIDAndSecret(t *testing.T) { } func TestNewBootstrapTokenString(t *testing.T) { - var tests = []struct { + tests := []struct { token string expectedError bool bts *BootstrapTokenString diff --git a/bootstrap/kubeadm/api/v1beta1/kubeadm_types.go b/bootstrap/kubeadm/api/v1beta1/kubeadm_types.go index 653b4da552e8..8f5152a3fc5e 100644 --- a/bootstrap/kubeadm/api/v1beta1/kubeadm_types.go +++ b/bootstrap/kubeadm/api/v1beta1/kubeadm_types.go @@ -192,7 +192,7 @@ type ImageMeta struct { // +optional ImageTag string `json:"imageTag,omitempty"` - //TODO: evaluate if we need also a ImageName based on user feedbacks + // TODO: evaluate if we need also a ImageName based on user feedbacks } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -225,7 +225,6 @@ type APIEndpoint struct { // NodeRegistrationOptions holds fields that relate to registering a new control-plane or node to the cluster, either via "kubeadm init" or "kubeadm join". // Note: The NodeRegistrationOptions struct has to be kept in sync with the structs in MarshalJSON. type NodeRegistrationOptions struct { - // Name is the `.Metadata.Name` field of the Node API object that will be created in this `kubeadm init` or `kubeadm join` operation. // This field is also used in the CommonName field of the kubelet's client certificate to the API server. // Defaults to the hostname of the node if not provided. @@ -355,7 +354,6 @@ type BootstrapToken struct { // Etcd contains elements describing Etcd configuration. type Etcd struct { - // Local provides configuration knobs for configuring the local etcd instance // Local and External are mutually exclusive // +optional diff --git a/bootstrap/kubeadm/api/v1beta1/kubeadm_types_test.go b/bootstrap/kubeadm/api/v1beta1/kubeadm_types_test.go index 8a0d6f197093..a6acd9fb4a63 100644 --- a/bootstrap/kubeadm/api/v1beta1/kubeadm_types_test.go +++ b/bootstrap/kubeadm/api/v1beta1/kubeadm_types_test.go @@ -27,7 +27,7 @@ import ( ) func TestNodeRegistrationOptionsMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { name string opts NodeRegistrationOptions expected string @@ -84,7 +84,7 @@ func TestNodeRegistrationOptionsMarshalJSON(t *testing.T) { } func TestBootstrapTokenStringMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -104,7 +104,7 @@ func TestBootstrapTokenStringMarshalJSON(t *testing.T) { } func TestBootstrapTokenStringUnmarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString expectedError bool @@ -135,7 +135,7 @@ func TestBootstrapTokenStringUnmarshalJSON(t *testing.T) { } func TestBootstrapTokenStringJSONRoundtrip(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString }{ @@ -190,7 +190,7 @@ func roundtrip(input string, bts *BootstrapTokenString) error { } func TestBootstrapTokenStringTokenFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -208,7 +208,7 @@ func TestBootstrapTokenStringTokenFromIDAndSecret(t *testing.T) { } func TestNewBootstrapTokenString(t *testing.T) { - var tests = []struct { + tests := []struct { token string expectedError bool bts *BootstrapTokenString diff --git a/bootstrap/kubeadm/internal/cloudinit/cloudinit.go b/bootstrap/kubeadm/internal/cloudinit/cloudinit.go index c2f158f7c5c7..00790a786c21 100644 --- a/bootstrap/kubeadm/internal/cloudinit/cloudinit.go +++ b/bootstrap/kubeadm/internal/cloudinit/cloudinit.go @@ -74,7 +74,7 @@ func (input *BaseUserData) prepare() error { return nil } -func generate(kind string, tpl string, data interface{}) ([]byte, error) { +func generate(kind, tpl string, data interface{}) ([]byte, error) { tm := template.New(kind).Funcs(defaultTemplateFuncMap) if _, err := tm.Parse(filesTemplate); err != nil { return nil, errors.Wrap(err, "failed to parse files template") @@ -117,10 +117,8 @@ func generate(kind string, tpl string, data interface{}) ([]byte, error) { return out.Bytes(), nil } -var ( - //go:embed kubeadm-bootstrap-script.sh - kubeadmBootstrapScript string -) +//go:embed kubeadm-bootstrap-script.sh +var kubeadmBootstrapScript string func generateBootstrapScript(input interface{}) (*bootstrapv1.File, error) { joinScript, err := generate("JoinScript", kubeadmBootstrapScript, input) diff --git a/bootstrap/kubeadm/internal/cloudinit/utils.go b/bootstrap/kubeadm/internal/cloudinit/utils.go index 628c5957000b..dd7933cc33fd 100644 --- a/bootstrap/kubeadm/internal/cloudinit/utils.go +++ b/bootstrap/kubeadm/internal/cloudinit/utils.go @@ -21,11 +21,9 @@ import ( "text/template" ) -var ( - defaultTemplateFuncMap = template.FuncMap{ - "Indent": templateYAMLIndent, - } -) +var defaultTemplateFuncMap = template.FuncMap{ + "Indent": templateYAMLIndent, +} func templateYAMLIndent(i int, input string) string { split := strings.Split(input, "\n") diff --git a/bootstrap/kubeadm/internal/controllers/kubeadmconfig_controller_test.go b/bootstrap/kubeadm/internal/controllers/kubeadmconfig_controller_test.go index 4038c3a16f88..b7306e49fb05 100644 --- a/bootstrap/kubeadm/internal/controllers/kubeadmconfig_controller_test.go +++ b/bootstrap/kubeadm/internal/controllers/kubeadmconfig_controller_test.go @@ -207,7 +207,8 @@ func TestKubeadmConfigReconciler_TestSecretOwnerReferenceReconciliation(t *testi Name: machine.Name, UID: machine.UID, Controller: pointer.Bool(true), - }}) + }, + }) g.Expect(myclient.Update(ctx, actual)).To(Succeed()) _, err = k.Reconcile(ctx, request) diff --git a/bootstrap/kubeadm/internal/locking/control_plane_init_mutex_test.go b/bootstrap/kubeadm/internal/locking/control_plane_init_mutex_test.go index 636afbfc934c..0eda4399b5b4 100644 --- a/bootstrap/kubeadm/internal/locking/control_plane_init_mutex_test.go +++ b/bootstrap/kubeadm/internal/locking/control_plane_init_mutex_test.go @@ -41,9 +41,7 @@ const ( clusterNamespace = "test-namespace" ) -var ( - ctx = ctrl.SetupSignalHandler() -) +var ctx = ctrl.SetupSignalHandler() func TestControlPlaneInitMutex_Lock(t *testing.T) { g := NewWithT(t) @@ -145,10 +143,12 @@ func TestControlPlaneInitMutex_LockWithMachineDeletion(t *testing.T) { &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: configMapName(clusterName), - Namespace: clusterNamespace}, + Namespace: clusterNamespace, + }, Data: map[string]string{ "lock-information": "{\"machineName\":\"existent-machine\"}", - }}, + }, + }, &clusterv1.Machine{ ObjectMeta: metav1.ObjectMeta{ Name: "existent-machine", @@ -166,10 +166,12 @@ func TestControlPlaneInitMutex_LockWithMachineDeletion(t *testing.T) { &corev1.ConfigMap{ ObjectMeta: metav1.ObjectMeta{ Name: configMapName(clusterName), - Namespace: clusterNamespace}, + Namespace: clusterNamespace, + }, Data: map[string]string{ "lock-information": "{\"machineName\":\"non-existent-machine\"}", - }}, + }, + }, ).Build(), }, expectedMachineName: newMachineName, diff --git a/bootstrap/kubeadm/types/upstreamv1beta1/bootstraptokenstring_test.go b/bootstrap/kubeadm/types/upstreamv1beta1/bootstraptokenstring_test.go index ce7f45252321..d90eaba86c21 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta1/bootstraptokenstring_test.go +++ b/bootstrap/kubeadm/types/upstreamv1beta1/bootstraptokenstring_test.go @@ -26,7 +26,7 @@ import ( ) func TestMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -46,7 +46,7 @@ func TestMarshalJSON(t *testing.T) { } func TestUnmarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString expectedError bool @@ -77,7 +77,7 @@ func TestUnmarshalJSON(t *testing.T) { } func TestJSONRoundtrip(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString }{ @@ -132,7 +132,7 @@ func roundtrip(input string, bts *BootstrapTokenString) error { } func TestTokenFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -150,7 +150,7 @@ func TestTokenFromIDAndSecret(t *testing.T) { } func TestNewBootstrapTokenString(t *testing.T) { - var tests = []struct { + tests := []struct { token string expectedError bool bts *BootstrapTokenString @@ -188,7 +188,7 @@ func TestNewBootstrapTokenString(t *testing.T) { } func TestNewBootstrapTokenStringFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { id, secret string expectedError bool bts *BootstrapTokenString diff --git a/bootstrap/kubeadm/types/upstreamv1beta1/types.go b/bootstrap/kubeadm/types/upstreamv1beta1/types.go index 3f90b4611fcc..e5e403004b2c 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta1/types.go +++ b/bootstrap/kubeadm/types/upstreamv1beta1/types.go @@ -180,7 +180,7 @@ type ImageMeta struct { // In case this value is set, kubeadm does not change automatically the version of the above components during upgrades. ImageTag string `json:"imageTag,omitempty"` - //TODO: evaluate if we need also a ImageName based on user feedbacks + // TODO: evaluate if we need also a ImageName based on user feedbacks } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -207,7 +207,6 @@ type APIEndpoint struct { // NodeRegistrationOptions holds fields that relate to registering a new control-plane or node to the cluster, either via "kubeadm init" or "kubeadm join". type NodeRegistrationOptions struct { - // Name is the `.Metadata.Name` field of the Node API object that will be created in this `kubeadm init` or `kubeadm join` operation. // This field is also used in the CommonName field of the kubelet's client certificate to the API server. // Defaults to the hostname of the node if not provided. @@ -272,7 +271,6 @@ type BootstrapToken struct { // Etcd contains elements describing Etcd configuration. type Etcd struct { - // Local provides configuration knobs for configuring the local etcd instance // Local and External are mutually exclusive Local *LocalEtcd `json:"local,omitempty"` diff --git a/bootstrap/kubeadm/types/upstreamv1beta2/bootstraptokenstring_test.go b/bootstrap/kubeadm/types/upstreamv1beta2/bootstraptokenstring_test.go index 3a0d1b5331ba..9f891e917f79 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta2/bootstraptokenstring_test.go +++ b/bootstrap/kubeadm/types/upstreamv1beta2/bootstraptokenstring_test.go @@ -26,7 +26,7 @@ import ( ) func TestMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -46,7 +46,7 @@ func TestMarshalJSON(t *testing.T) { } func TestUnmarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString expectedError bool @@ -77,7 +77,7 @@ func TestUnmarshalJSON(t *testing.T) { } func TestJSONRoundtrip(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString }{ @@ -132,7 +132,7 @@ func roundtrip(input string, bts *BootstrapTokenString) error { } func TestTokenFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -150,7 +150,7 @@ func TestTokenFromIDAndSecret(t *testing.T) { } func TestNewBootstrapTokenString(t *testing.T) { - var tests = []struct { + tests := []struct { token string expectedError bool bts *BootstrapTokenString @@ -188,7 +188,7 @@ func TestNewBootstrapTokenString(t *testing.T) { } func TestNewBootstrapTokenStringFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { id, secret string expectedError bool bts *BootstrapTokenString diff --git a/bootstrap/kubeadm/types/upstreamv1beta2/types.go b/bootstrap/kubeadm/types/upstreamv1beta2/types.go index 413f6fe9b5b0..1a25976c8350 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta2/types.go +++ b/bootstrap/kubeadm/types/upstreamv1beta2/types.go @@ -194,7 +194,7 @@ type ImageMeta struct { // In case this value is set, kubeadm does not change automatically the version of the above components during upgrades. ImageTag string `json:"imageTag,omitempty"` - //TODO: evaluate if we need also a ImageName based on user feedbacks + // TODO: evaluate if we need also a ImageName based on user feedbacks } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object @@ -221,7 +221,6 @@ type APIEndpoint struct { // NodeRegistrationOptions holds fields that relate to registering a new control-plane or node to the cluster, either via "kubeadm init" or "kubeadm join". type NodeRegistrationOptions struct { - // Name is the `.Metadata.Name` field of the Node API object that will be created in this `kubeadm init` or `kubeadm join` operation. // This field is also used in the CommonName field of the kubelet's client certificate to the API server. // Defaults to the hostname of the node if not provided. @@ -292,7 +291,6 @@ type BootstrapToken struct { // Etcd contains elements describing Etcd configuration. type Etcd struct { - // Local provides configuration knobs for configuring the local etcd instance // Local and External are mutually exclusive Local *LocalEtcd `json:"local,omitempty"` diff --git a/bootstrap/kubeadm/types/upstreamv1beta3/bootstraptokenstring_test.go b/bootstrap/kubeadm/types/upstreamv1beta3/bootstraptokenstring_test.go index 640c581a6dea..5927283e8155 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta3/bootstraptokenstring_test.go +++ b/bootstrap/kubeadm/types/upstreamv1beta3/bootstraptokenstring_test.go @@ -25,7 +25,7 @@ import ( ) func TestMarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -51,7 +51,7 @@ func TestMarshalJSON(t *testing.T) { } func TestUnmarshalJSON(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString expectedError bool @@ -84,7 +84,7 @@ func TestUnmarshalJSON(t *testing.T) { } func TestJSONRoundtrip(t *testing.T) { - var tests = []struct { + tests := []struct { input string bts *BootstrapTokenString }{ @@ -139,7 +139,7 @@ func roundtrip(input string, bts *BootstrapTokenString) error { } func TestTokenFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { bts BootstrapTokenString expected string }{ @@ -162,7 +162,7 @@ func TestTokenFromIDAndSecret(t *testing.T) { } func TestNewBootstrapTokenString(t *testing.T) { - var tests = []struct { + tests := []struct { token string expectedError bool bts *BootstrapTokenString @@ -208,7 +208,7 @@ func TestNewBootstrapTokenString(t *testing.T) { } func TestNewBootstrapTokenStringFromIDAndSecret(t *testing.T) { - var tests = []struct { + tests := []struct { id, secret string expectedError bool bts *BootstrapTokenString diff --git a/bootstrap/kubeadm/types/upstreamv1beta3/types.go b/bootstrap/kubeadm/types/upstreamv1beta3/types.go index abc993a88a31..3106d73b8158 100644 --- a/bootstrap/kubeadm/types/upstreamv1beta3/types.go +++ b/bootstrap/kubeadm/types/upstreamv1beta3/types.go @@ -183,7 +183,7 @@ type ImageMeta struct { // +optional ImageTag string `json:"imageTag,omitempty"` - //TODO: evaluate if we need also a ImageName based on user feedbacks + // TODO: evaluate if we need also a ImageName based on user feedbacks } // APIEndpoint struct contains elements of API server instance deployed on a node. @@ -200,7 +200,6 @@ type APIEndpoint struct { // NodeRegistrationOptions holds fields that relate to registering a new control-plane or node to the cluster, either via "kubeadm init" or "kubeadm join". type NodeRegistrationOptions struct { - // Name is the `.Metadata.Name` field of the Node API object that will be created in this `kubeadm init` or `kubeadm join` operation. // This field is also used in the CommonName field of the kubelet's client certificate to the API server. // Defaults to the hostname of the node if not provided. @@ -276,7 +275,6 @@ type BootstrapToken struct { // Etcd contains elements describing Etcd configuration. type Etcd struct { - // Local provides configuration knobs for configuring the local etcd instance // Local and External are mutually exclusive // +optional diff --git a/cmd/clusterctl/client/alpha/client.go b/cmd/clusterctl/client/alpha/client.go index c72386b650dc..518f0450ffe8 100644 --- a/cmd/clusterctl/client/alpha/client.go +++ b/cmd/clusterctl/client/alpha/client.go @@ -18,9 +18,7 @@ package alpha import "context" -var ( - ctx = context.TODO() -) +var ctx = context.TODO() // Client is the alpha client. type Client interface { diff --git a/cmd/clusterctl/client/client_test.go b/cmd/clusterctl/client/client_test.go index b1374b805255..bd0498a65d9b 100644 --- a/cmd/clusterctl/client/client_test.go +++ b/cmd/clusterctl/client/client_test.go @@ -161,7 +161,7 @@ func newFakeClient(configClient config.Client) *fakeClient { fake.configClient = newFakeConfig() } - var clusterClientFactory = func(i ClusterClientFactoryInput) (cluster.Client, error) { + clusterClientFactory := func(i ClusterClientFactoryInput) (cluster.Client, error) { // converting the client.Kubeconfig to cluster.Kubeconfig alias k := cluster.Kubeconfig(i.Kubeconfig) if _, ok := fake.clusters[k]; !ok { diff --git a/cmd/clusterctl/client/cluster/cert_manager.go b/cmd/clusterctl/client/cluster/cert_manager.go index dc1d3a91984b..cdbc11114ff3 100644 --- a/cmd/clusterctl/client/cluster/cert_manager.go +++ b/cmd/clusterctl/client/cluster/cert_manager.go @@ -50,10 +50,8 @@ const ( certManagerVersionAnnotation = "certmanager.clusterctl.cluster.x-k8s.io/version" ) -var ( - //go:embed assets/cert-manager-test-resources.yaml - certManagerTestManifest []byte -) +//go:embed assets/cert-manager-test-resources.yaml +var certManagerTestManifest []byte // CertManagerUpgradePlan defines the upgrade plan if cert-manager needs to be // upgraded to a different version. diff --git a/cmd/clusterctl/client/cluster/client.go b/cmd/clusterctl/client/cluster/client.go index bd34d912581b..d95ce2005029 100644 --- a/cmd/clusterctl/client/cluster/client.go +++ b/cmd/clusterctl/client/cluster/client.go @@ -29,9 +29,7 @@ import ( logf "sigs.k8s.io/cluster-api/cmd/clusterctl/log" ) -var ( - ctx = context.TODO() -) +var ctx = context.TODO() // Kubeconfig is a type that specifies inputs related to the actual // kubeconfig. diff --git a/cmd/clusterctl/client/cluster/internal/dryrun/client.go b/cmd/clusterctl/client/cluster/internal/dryrun/client.go index aa08f8e6d53b..a6d0e3486384 100644 --- a/cmd/clusterctl/client/cluster/internal/dryrun/client.go +++ b/cmd/clusterctl/client/cluster/internal/dryrun/client.go @@ -33,9 +33,7 @@ import ( "sigs.k8s.io/cluster-api/cmd/clusterctl/internal/scheme" ) -var ( - localScheme = scheme.Scheme -) +var localScheme = scheme.Scheme // changeTrackerID represents a unique identifier of an object. type changeTrackerID struct { diff --git a/cmd/clusterctl/client/cluster/mover.go b/cmd/clusterctl/client/cluster/mover.go index 6d88b589197d..ccd5bb2b3b2a 100644 --- a/cmd/clusterctl/client/cluster/mover.go +++ b/cmd/clusterctl/client/cluster/mover.go @@ -47,7 +47,7 @@ type ObjectMover interface { Move(namespace string, toCluster Client, dryRun bool) error // ToDirectory writes all the Cluster API objects existing in a namespace (or from all the namespaces if empty) to a target directory. - ToDirectory(namespace string, directory string) error + ToDirectory(namespace, directory string) error // FromDirectory reads all the Cluster API objects existing in a configured directory to a target management cluster. FromDirectory(toCluster Client, directory string) error @@ -94,7 +94,7 @@ func (o *objectMover) Move(namespace string, toCluster Client, dryRun bool) erro return o.move(objectGraph, proxy) } -func (o *objectMover) ToDirectory(namespace string, directory string) error { +func (o *objectMover) ToDirectory(namespace, directory string) error { log := logf.Log log.Info("Moving to directory...") @@ -532,7 +532,7 @@ func getMoveSequence(graph *objectGraph) *moveSequence { } // setClusterPause sets the paused field on nodes referring to Cluster objects. -func setClusterPause(proxy Proxy, clusters []*node, value bool, dryRun bool) error { +func setClusterPause(proxy Proxy, clusters []*node, value, dryRun bool) error { if dryRun { return nil } @@ -562,7 +562,7 @@ func setClusterPause(proxy Proxy, clusters []*node, value bool, dryRun bool) err } // setClusterClassPause sets the paused annotation on nodes referring to ClusterClass objects. -func setClusterClassPause(proxy Proxy, clusterclasses []*node, pause bool, dryRun bool) error { +func setClusterClassPause(proxy Proxy, clusterclasses []*node, pause, dryRun bool) error { if dryRun { return nil } @@ -953,7 +953,7 @@ func (o *objectMover) backupTargetObject(nodeToCreate *node, directory string) e } } - err = os.WriteFile(objectFile, byObj, 0600) + err = os.WriteFile(objectFile, byObj, 0o600) if err != nil { return err } @@ -1054,7 +1054,6 @@ func (o *objectMover) deleteGroup(group moveGroup) error { err := retryWithExponentialBackoff(deleteSourceObjectBackoff, func() error { return o.deleteSourceObject(nodeToDelete) }) - if err != nil { errList = append(errList, err) } @@ -1063,9 +1062,7 @@ func (o *objectMover) deleteGroup(group moveGroup) error { return kerrors.NewAggregate(errList) } -var ( - removeFinalizersPatch = client.RawPatch(types.MergePatchType, []byte("{\"metadata\":{\"finalizers\":[]}}")) -) +var removeFinalizersPatch = client.RawPatch(types.MergePatchType, []byte("{\"metadata\":{\"finalizers\":[]}}")) // deleteSourceObject deletes the Kubernetes object corresponding to the node from the source management cluster, taking care of removing all the finalizers so // the objects gets immediately deleted (force delete). diff --git a/cmd/clusterctl/client/cluster/mover_test.go b/cmd/clusterctl/client/cluster/mover_test.go index 56b10250d441..9349d8ee9181 100644 --- a/cmd/clusterctl/client/cluster/mover_test.go +++ b/cmd/clusterctl/client/cluster/mover_test.go @@ -1654,7 +1654,6 @@ func Test_objectMoverService_ensureNamespaces(t *testing.T) { expectedNamespaces: []string{"namespace-1", "namespace-2"}, }, { - name: "ensureNamespaces moves namespace-2 to target which already has namespace-1", fields: fields{ objs: cluster2.Objs(), diff --git a/cmd/clusterctl/client/cluster/objectgraph.go b/cmd/clusterctl/client/cluster/objectgraph.go index b0934b45c7dc..b947ea1e8a94 100644 --- a/cmd/clusterctl/client/cluster/objectgraph.go +++ b/cmd/clusterctl/client/cluster/objectgraph.go @@ -36,8 +36,10 @@ import ( secretutil "sigs.k8s.io/cluster-api/util/secret" ) -const clusterTopologyNameKey = "cluster.spec.topology.class" -const clusterResourceSetBindingClusterNameKey = "clusterresourcesetbinding.spec.clustername" +const ( + clusterTopologyNameKey = "cluster.spec.topology.class" + clusterResourceSetBindingClusterNameKey = "clusterresourcesetbinding.spec.clustername" +) type empty struct{} diff --git a/cmd/clusterctl/client/cluster/objectgraph_test.go b/cmd/clusterctl/client/cluster/objectgraph_test.go index dcd856f48521..18d5a2bfde22 100644 --- a/cmd/clusterctl/client/cluster/objectgraph_test.go +++ b/cmd/clusterctl/client/cluster/objectgraph_test.go @@ -963,7 +963,6 @@ var objectGraphsTests = []struct { }, want: wantGraph{ nodes: map[string]wantGraphItem{ - "infrastructure.cluster.x-k8s.io/v1beta1, Kind=GenericInfrastructureMachineTemplate, ns1/shared": { owners: []string{ "cluster.x-k8s.io/v1beta1, Kind=Cluster, ns1/cluster1", @@ -1558,7 +1557,6 @@ var objectGraphsTests = []struct { // We need to deduplicate objects here as the clusterclasses share objects and // setting up the test server panics if we try to create it with duplicate objects. return deduplicateObjects(objs) - }(), }, want: wantGraph{ @@ -1737,7 +1735,7 @@ func TestObjectGraph_DiscoveryByNamespace(t *testing.T) { namespace string objs []client.Object } - var tests = []struct { + tests := []struct { name string args args want wantGraph diff --git a/cmd/clusterctl/client/cluster/proxy.go b/cmd/clusterctl/client/cluster/proxy.go index 5c114beac458..c41f45ce3984 100644 --- a/cmd/clusterctl/client/cluster/proxy.go +++ b/cmd/clusterctl/client/cluster/proxy.go @@ -41,9 +41,7 @@ import ( "sigs.k8s.io/cluster-api/version" ) -var ( - localScheme = scheme.Scheme -) +var localScheme = scheme.Scheme // Proxy defines a client proxy interface. type Proxy interface { diff --git a/cmd/clusterctl/client/cluster/proxy_test.go b/cmd/clusterctl/client/cluster/proxy_test.go index dfa55f029512..ffbd185379e5 100644 --- a/cmd/clusterctl/client/cluster/proxy_test.go +++ b/cmd/clusterctl/client/cluster/proxy_test.go @@ -67,7 +67,7 @@ func TestProxyGetConfig(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) defer os.RemoveAll(dir) configFile := filepath.Join(dir, ".test-kubeconfig.yaml") - g.Expect(os.WriteFile(configFile, []byte(tt.kubeconfigContents), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte(tt.kubeconfigContents), 0o600)).To(Succeed()) proxy := newProxy(Kubeconfig{Path: configFile, Context: tt.context}) conf, err := proxy.GetConfig() @@ -94,7 +94,7 @@ func TestProxyGetConfig(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) defer os.RemoveAll(dir) configFile := filepath.Join(dir, ".test-kubeconfig.yaml") - g.Expect(os.WriteFile(configFile, []byte(kubeconfig("management", "default")), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte(kubeconfig("management", "default")), 0o600)).To(Succeed()) proxy := newProxy(Kubeconfig{Path: configFile, Context: "management"}, InjectProxyTimeout(23*time.Second)) conf, err := proxy.GetConfig() @@ -121,7 +121,7 @@ func TestKUBECONFIGEnvVar(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) defer os.RemoveAll(dir) configFile := filepath.Join(dir, ".test-kubeconfig.yaml") - g.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0o600)).To(Succeed()) proxy := newProxy( // dont't give an explicit path but rather define the file in the @@ -149,7 +149,7 @@ func TestKUBECONFIGEnvVar(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) defer os.RemoveAll(dir) configFile := filepath.Join(dir, ".test-kubeconfig.yaml") - g.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte(kubeconfigContents), 0o600)).To(Succeed()) proxy := newProxy( // dont't give an explicit path but rather define the file in the @@ -226,7 +226,7 @@ func TestProxyCurrentNamespace(t *testing.T) { g.Expect(err).NotTo(HaveOccurred()) defer os.RemoveAll(dir) configFile = filepath.Join(dir, ".test-kubeconfig.yaml") - g.Expect(os.WriteFile(configFile, []byte(tt.kubeconfigContents), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte(tt.kubeconfigContents), 0o600)).To(Succeed()) } proxy := newProxy(Kubeconfig{Path: configFile, Context: tt.kubeconfigContext}) diff --git a/cmd/clusterctl/client/cluster/template.go b/cmd/clusterctl/client/cluster/template.go index f6cffbf56f30..02612a87e685 100644 --- a/cmd/clusterctl/client/cluster/template.go +++ b/cmd/clusterctl/client/cluster/template.go @@ -219,7 +219,7 @@ func (t *templateClient) getGitHubFileContent(rURL *url.URL) ([]byte, error) { return nil, fmt.Errorf("unknown github URL: %v", rURL) } -func getGithubFileContentFromCode(ghClient *github.Client, fullPath string, owner string, repo string, path string, branch string) ([]byte, error) { +func getGithubFileContentFromCode(ghClient *github.Client, fullPath, owner, repo, path, branch string) ([]byte, error) { fileContent, _, _, err := ghClient.Repositories.GetContents(ctx, owner, repo, path, &github.RepositoryContentGetOptions{Ref: branch}) if err != nil { return nil, handleGithubErr(err, "failed to get %q", fullPath) @@ -261,7 +261,7 @@ func (t *templateClient) getRawURLFileContent(rURL string) ([]byte, error) { return content, nil } -func getGithubAssetFromRelease(ghClient *github.Client, path string, owner string, repo string, tag string, assetName string) ([]byte, error) { +func getGithubAssetFromRelease(ghClient *github.Client, path, owner, repo, tag, assetName string) ([]byte, error) { release, _, err := ghClient.Repositories.GetReleaseByTag(ctx, owner, repo, tag) if err != nil { return nil, handleGithubErr(err, "failed to get release '%s' from %s/%s repository", tag, owner, repo) diff --git a/cmd/clusterctl/client/cluster/template_test.go b/cmd/clusterctl/client/cluster/template_test.go index 7f32862e48ea..cb4dbc27ac48 100644 --- a/cmd/clusterctl/client/cluster/template_test.go +++ b/cmd/clusterctl/client/cluster/template_test.go @@ -277,7 +277,7 @@ func Test_templateClient_getLocalFileContent(t *testing.T) { defer os.RemoveAll(tmpDir) path := filepath.Join(tmpDir, "cluster-template.yaml") - g.Expect(os.WriteFile(path, []byte(template), 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, []byte(template), 0o600)).To(Succeed()) type args struct { rURL *url.URL @@ -395,7 +395,7 @@ func Test_templateClient_GetFromURL(t *testing.T) { }) path := filepath.Join(tmpDir, "cluster-template.yaml") - g.Expect(os.WriteFile(path, []byte(template), 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, []byte(template), 0o600)).To(Succeed()) // redirect stdin saveStdin := os.Stdin diff --git a/cmd/clusterctl/client/cluster/workload_cluster.go b/cmd/clusterctl/client/cluster/workload_cluster.go index a5e085dae2c9..38ba2ea10d8d 100644 --- a/cmd/clusterctl/client/cluster/workload_cluster.go +++ b/cmd/clusterctl/client/cluster/workload_cluster.go @@ -26,7 +26,7 @@ import ( // WorkloadCluster has methods for fetching kubeconfig of workload cluster from management cluster. type WorkloadCluster interface { // GetKubeconfig returns the kubeconfig of the workload cluster. - GetKubeconfig(workloadClusterName string, namespace string) (string, error) + GetKubeconfig(workloadClusterName, namespace string) (string, error) } // workloadCluster implements WorkloadCluster. @@ -41,7 +41,7 @@ func newWorkloadCluster(proxy Proxy) *workloadCluster { } } -func (p *workloadCluster) GetKubeconfig(workloadClusterName string, namespace string) (string, error) { +func (p *workloadCluster) GetKubeconfig(workloadClusterName, namespace string) (string, error) { cs, err := p.proxy.NewClient() if err != nil { return "", err diff --git a/cmd/clusterctl/client/common.go b/cmd/clusterctl/client/common.go index be299a7307c7..9b6d32934a23 100644 --- a/cmd/clusterctl/client/common.go +++ b/cmd/clusterctl/client/common.go @@ -60,7 +60,7 @@ func (c *clusterctlClient) getComponentsByName(provider string, providerType clu } // parseProviderName defines a utility function that parses the abbreviated syntax for name[:version]. -func parseProviderName(provider string) (name string, version string, err error) { +func parseProviderName(provider string) (name, version string, err error) { t := strings.Split(strings.ToLower(provider), ":") if len(t) > 2 { return "", "", errors.Errorf("invalid provider name %q. Provider name should be in the form name[:version]", provider) diff --git a/cmd/clusterctl/client/config/provider.go b/cmd/clusterctl/client/config/provider.go index 2066155f4636..6f50d7ac6a81 100644 --- a/cmd/clusterctl/client/config/provider.go +++ b/cmd/clusterctl/client/config/provider.go @@ -84,7 +84,7 @@ func (p *provider) Less(other Provider) bool { } // NewProvider creates a new Provider with the given input. -func NewProvider(name string, url string, ttype clusterctlv1.ProviderType) Provider { +func NewProvider(name, url string, ttype clusterctlv1.ProviderType) Provider { return &provider{ name: name, url: url, diff --git a/cmd/clusterctl/client/config/reader_viper.go b/cmd/clusterctl/client/config/reader_viper.go index 113423100efe..651903d4f78a 100644 --- a/cmd/clusterctl/client/config/reader_viper.go +++ b/cmd/clusterctl/client/config/reader_viper.go @@ -133,7 +133,7 @@ func (v *viperReader) Init(path string) error { return nil } -func downloadFile(url string, filepath string) error { +func downloadFile(url, filepath string) error { ctx := context.TODO() // Create the file diff --git a/cmd/clusterctl/client/config/reader_viper_test.go b/cmd/clusterctl/client/config/reader_viper_test.go index 8e0b5b209821..fe0104964d73 100644 --- a/cmd/clusterctl/client/config/reader_viper_test.go +++ b/cmd/clusterctl/client/config/reader_viper_test.go @@ -42,10 +42,10 @@ func Test_viperReader_Init(t *testing.T) { defer os.RemoveAll(dir) configFile := filepath.Join(dir, "clusterctl.yaml") - g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0o600)).To(Succeed()) configFileBadContents := filepath.Join(dir, "clusterctl-bad.yaml") - g.Expect(os.WriteFile(configFileBadContents, []byte("bad-contents"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFileBadContents, []byte("bad-contents"), 0o600)).To(Succeed()) // To test the remote config file ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -128,7 +128,7 @@ func Test_viperReader_Get(t *testing.T) { _ = os.Setenv("FOO", "foo") configFile := filepath.Join(dir, "clusterctl.yaml") - g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0o600)).To(Succeed()) type args struct { key string @@ -211,7 +211,7 @@ func Test_viperReader_Set(t *testing.T) { configFile := filepath.Join(dir, "clusterctl.yaml") - g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0o600)).To(Succeed()) type args struct { key string @@ -256,7 +256,7 @@ func Test_viperReader_checkDefaultConfig(t *testing.T) { dir = strings.TrimSuffix(dir, "/") configFile := filepath.Join(dir, "clusterctl.yaml") - g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(configFile, []byte("bar: bar"), 0o600)).To(Succeed()) type fields struct { configPaths []string diff --git a/cmd/clusterctl/client/config_test.go b/cmd/clusterctl/client/config_test.go index 690ab55af094..79c44a7a8d8e 100644 --- a/cmd/clusterctl/client/config_test.go +++ b/cmd/clusterctl/client/config_test.go @@ -474,7 +474,7 @@ func Test_clusterctlClient_GetClusterTemplate(t *testing.T) { defer os.RemoveAll(tmpDir) path := filepath.Join(tmpDir, "cluster-template.yaml") - g.Expect(os.WriteFile(path, rawTemplate, 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, rawTemplate, 0o600)).To(Succeed()) // Template on a repository & in a ConfigMap configMap := &corev1.ConfigMap{ @@ -681,6 +681,7 @@ func Test_clusterctlClient_GetClusterTemplate_withClusterClass(t *testing.T) { g.Expect(got.TargetNamespace()).To(Equal("ns1")) g.Expect(got.Objs()).To(ContainElement(MatchClusterClass("dev", "ns1"))) } + func Test_clusterctlClient_GetClusterTemplate_onEmptyCluster(t *testing.T) { g := NewWithT(t) @@ -692,7 +693,7 @@ func Test_clusterctlClient_GetClusterTemplate_onEmptyCluster(t *testing.T) { defer os.RemoveAll(tmpDir) path := filepath.Join(tmpDir, "cluster-template.yaml") - g.Expect(os.WriteFile(path, rawTemplate, 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, rawTemplate, 0o600)).To(Succeed()) // Template in a ConfigMap in a cluster not initialized configMap := &corev1.ConfigMap{ @@ -959,7 +960,7 @@ v3: ${VAR3:-default3}` defer os.RemoveAll(dir) templateFile := filepath.Join(dir, "template.yaml") - g.Expect(os.WriteFile(templateFile, []byte(template), 0600)).To(Succeed()) + g.Expect(os.WriteFile(templateFile, []byte(template), 0o600)).To(Succeed()) inputReader := strings.NewReader(template) diff --git a/cmd/clusterctl/client/init_test.go b/cmd/clusterctl/client/init_test.go index 8b3e72c55e27..cd42adf9ceee 100644 --- a/cmd/clusterctl/client/init_test.go +++ b/cmd/clusterctl/client/init_test.go @@ -32,9 +32,7 @@ import ( utilyaml "sigs.k8s.io/cluster-api/util/yaml" ) -var ( - ctx = ctrl.SetupSignalHandler() -) +var ctx = ctrl.SetupSignalHandler() func Test_clusterctlClient_InitImages(t *testing.T) { type field struct { @@ -729,7 +727,7 @@ func fakeRepositories(config *fakeConfigClient, providers []Provider) []*fakeRep }). WithFile("v3.0.0", "cluster-template.yaml", templateYAML("ns4", "test")) - var providerRepositories = []*fakeRepositoryClient{repository1, repository2, repository3, repository4} + providerRepositories := []*fakeRepositoryClient{repository1, repository2, repository3, repository4} for _, provider := range providers { providerRepositories = append(providerRepositories, @@ -792,12 +790,12 @@ func fakeClusterWithCoreProvider() *fakeClient { } func componentsYAML(ns string) []byte { - var namespaceYaml = []byte("apiVersion: v1\n" + + namespaceYaml := []byte("apiVersion: v1\n" + "kind: Namespace\n" + "metadata:\n" + fmt.Sprintf(" name: %s", ns)) - var podYaml = []byte("apiVersion: v1\n" + + podYaml := []byte("apiVersion: v1\n" + "kind: Pod\n" + "metadata:\n" + " name: manager") @@ -805,8 +803,8 @@ func componentsYAML(ns string) []byte { return utilyaml.JoinYaml(namespaceYaml, podYaml) } -func templateYAML(ns string, clusterName string) []byte { - var podYaml = []byte("apiVersion: v1\n" + +func templateYAML(ns, clusterName string) []byte { + podYaml := []byte("apiVersion: v1\n" + "kind: Cluster\n" + "metadata:\n" + fmt.Sprintf(" name: %s\n", clusterName) + @@ -827,7 +825,7 @@ func mangedTopologyTemplateYAML(ns, clusterName, clusterClassName string) []byte } func clusterClassYAML(ns, clusterClassName string) []byte { - var podYaml = []byte(fmt.Sprintf("apiVersion: %s\n", clusterv1.GroupVersion.String()) + + podYaml := []byte(fmt.Sprintf("apiVersion: %s\n", clusterv1.GroupVersion.String()) + "kind: ClusterClass\n" + "metadata:\n" + fmt.Sprintf(" name: %s\n", clusterClassName) + @@ -839,7 +837,7 @@ func clusterClassYAML(ns, clusterClassName string) []byte { // infraComponentsYAML defines a namespace and deployment with container // images and a variable. func infraComponentsYAML(namespace string) []byte { - var infraComponentsYAML = `--- + infraComponentsYAML := `--- apiVersion: v1 kind: Namespace metadata: diff --git a/cmd/clusterctl/client/move_test.go b/cmd/clusterctl/client/move_test.go index a34ba55cc31b..407056e26925 100644 --- a/cmd/clusterctl/client/move_test.go +++ b/cmd/clusterctl/client/move_test.go @@ -302,11 +302,11 @@ func (f *fakeObjectMover) Move(_ string, _ cluster.Client, _ bool) error { return f.moveErr } -func (f *fakeObjectMover) ToDirectory(_ string, _ string) error { +func (f *fakeObjectMover) ToDirectory(_, _ string) error { return f.toDirectoryErr } -func (f *fakeObjectMover) Backup(_ string, _ string) error { +func (f *fakeObjectMover) Backup(_, _ string) error { return f.toDirectoryErr } diff --git a/cmd/clusterctl/client/repository/client.go b/cmd/clusterctl/client/repository/client.go index 915936880ec0..cf00acbdbbaa 100644 --- a/cmd/clusterctl/client/repository/client.go +++ b/cmd/clusterctl/client/repository/client.go @@ -160,7 +160,7 @@ type Repository interface { ComponentsPath() string // GetFile return a file for a given provider version. - GetFile(version string, path string) ([]byte, error) + GetFile(version, path string) ([]byte, error) // GetVersions return the list of versions that are available in a provider repository GetVersions() ([]string, error) diff --git a/cmd/clusterctl/client/repository/components_test.go b/cmd/clusterctl/client/repository/components_test.go index 1d78fbf5bb44..0f3c6c43d477 100644 --- a/cmd/clusterctl/client/repository/components_test.go +++ b/cmd/clusterctl/client/repository/components_test.go @@ -291,7 +291,8 @@ func Test_fixTargetNamespace(t *testing.T) { }, targetNamespace: "bar", wantErr: true, - }, { + }, + { name: "fix v1 webhook configs", objs: []unstructured.Unstructured{ { diff --git a/cmd/clusterctl/client/repository/metadata_client.go b/cmd/clusterctl/client/repository/metadata_client.go index 6a75e0580e4b..5bc5f902b6b3 100644 --- a/cmd/clusterctl/client/repository/metadata_client.go +++ b/cmd/clusterctl/client/repository/metadata_client.go @@ -90,7 +90,7 @@ func (f *metadataClient) Get() (*clusterctlv1.Metadata, error) { return nil, errors.Wrapf(err, "error decoding %q for provider %q", metadataFile, f.provider.ManifestLabel()) } - //TODO: consider if to add metadata validation (TBD) + // TODO: consider if to add metadata validation (TBD) return obj, nil } diff --git a/cmd/clusterctl/client/repository/repository_github.go b/cmd/clusterctl/client/repository/repository_github.go index 1632abd0cbfa..1da52a1ffeb2 100644 --- a/cmd/clusterctl/client/repository/repository_github.go +++ b/cmd/clusterctl/client/repository/repository_github.go @@ -235,7 +235,7 @@ func NewGitHubRepository(providerConfig config.Provider, configVariablesClient c } // getComponentsPath returns the file name. -func getComponentsPath(path string, rootPath string) string { +func getComponentsPath(path, rootPath string) string { filePath := strings.TrimPrefix(path, rootPath) componentsPath := strings.TrimPrefix(filePath, "/") return componentsPath diff --git a/cmd/clusterctl/client/repository/repository_local_test.go b/cmd/clusterctl/client/repository/repository_local_test.go index 18f41b6caa5c..77a229a5e79b 100644 --- a/cmd/clusterctl/client/repository/repository_local_test.go +++ b/cmd/clusterctl/client/repository/repository_local_test.go @@ -141,8 +141,8 @@ func createLocalTestProviderFile(t *testing.T, tmpDir, path, msg string) string dst := filepath.Join(tmpDir, path) // Create all directories in the standard layout - g.Expect(os.MkdirAll(filepath.Dir(dst), 0750)).To(Succeed()) - g.Expect(os.WriteFile(dst, []byte(msg), 0600)).To(Succeed()) + g.Expect(os.MkdirAll(filepath.Dir(dst), 0o750)).To(Succeed()) + g.Expect(os.WriteFile(dst, []byte(msg), 0o600)).To(Succeed()) return dst } diff --git a/cmd/clusterctl/client/repository/repository_memory.go b/cmd/clusterctl/client/repository/repository_memory.go index 2d340a7e7c1f..201670036e17 100644 --- a/cmd/clusterctl/client/repository/repository_memory.go +++ b/cmd/clusterctl/client/repository/repository_memory.go @@ -73,7 +73,7 @@ func (f *MemoryRepository) ComponentsPath() string { // GetFile returns a file for a given provider version. // NOTE: If the provided version is missing, the default version is used. -func (f *MemoryRepository) GetFile(version string, path string) ([]byte, error) { +func (f *MemoryRepository) GetFile(version, path string) ([]byte, error) { if version == "" { version = f.DefaultVersion() } @@ -168,6 +168,6 @@ func (f *MemoryRepository) WithMetadata(version string, metadata *clusterctlv1.M return f.WithFile(version, "metadata.yaml", data) } -func vpath(version string, path string) string { +func vpath(version, path string) string { return fmt.Sprintf("%s/%s", version, path) } diff --git a/cmd/clusterctl/client/tree/discovery.go b/cmd/clusterctl/client/tree/discovery.go index e16b250ac9bc..b25807cfc40a 100644 --- a/cmd/clusterctl/client/tree/discovery.go +++ b/cmd/clusterctl/client/tree/discovery.go @@ -280,7 +280,7 @@ func addMachinePoolsToObjectTree(ctx context.Context, c client.Client, namespace } } -func getResourceSetBindingInCluster(ctx context.Context, c client.Client, namespace string, name string) (*addonsv1.ClusterResourceSetBinding, error) { +func getResourceSetBindingInCluster(ctx context.Context, c client.Client, namespace, name string) (*addonsv1.ClusterResourceSetBinding, error) { if name == "" { return nil, nil } diff --git a/cmd/clusterctl/client/tree/tree.go b/cmd/clusterctl/client/tree/tree.go index 36e037f21aec..51c1682e1568 100644 --- a/cmd/clusterctl/client/tree/tree.go +++ b/cmd/clusterctl/client/tree/tree.go @@ -84,7 +84,7 @@ func NewObjectTree(root client.Object, options ObjectTreeOptions) *ObjectTree { } // Add a object to the object tree. -func (od ObjectTree) Add(parent, obj client.Object, opts ...AddObjectOption) (added bool, visible bool) { +func (od ObjectTree) Add(parent, obj client.Object, opts ...AddObjectOption) (added, visible bool) { if parent == nil || obj == nil { return false, false } @@ -180,7 +180,7 @@ func (od ObjectTree) Add(parent, obj client.Object, opts ...AddObjectOption) (ad return true, true } -func (od ObjectTree) remove(parent client.Object, s client.Object) { +func (od ObjectTree) remove(parent, s client.Object) { for _, child := range od.GetObjectsByParent(s.GetUID()) { od.remove(s, child) } @@ -188,7 +188,7 @@ func (od ObjectTree) remove(parent client.Object, s client.Object) { delete(od.ownership[parent.GetUID()], s.GetUID()) } -func (od ObjectTree) addInner(parent client.Object, obj client.Object) { +func (od ObjectTree) addInner(parent, obj client.Object) { od.items[obj.GetUID()] = obj if od.ownership[parent.GetUID()] == nil { od.ownership[parent.GetUID()] = make(map[types.UID]bool) diff --git a/cmd/clusterctl/client/yamlprocessor/simple_processor.go b/cmd/clusterctl/client/yamlprocessor/simple_processor.go index ebfaf5de1c23..c787edb02d66 100644 --- a/cmd/clusterctl/client/yamlprocessor/simple_processor.go +++ b/cmd/clusterctl/client/yamlprocessor/simple_processor.go @@ -185,8 +185,10 @@ func traverse(root parse.Node, variables map[string]string) { // legacyVariableRegEx defines the regexp used for searching variables inside a YAML. // It searches for variables with the format ${ VAR}, ${ VAR }, ${VAR }. -var legacyVariableRegEx = regexp.MustCompile(`(\${(\s+([A-Za-z0-9_$]+)\s+)})|(\${(\s+([A-Za-z0-9_$]+))})|(\${(([A-Za-z0-9_$]+)\s+)})`) -var whitespaceRegEx = regexp.MustCompile(`\s`) +var ( + legacyVariableRegEx = regexp.MustCompile(`(\${(\s+([A-Za-z0-9_$]+)\s+)})|(\${(\s+([A-Za-z0-9_$]+))})|(\${(([A-Za-z0-9_$]+)\s+)})`) + whitespaceRegEx = regexp.MustCompile(`\s`) +) // convertLegacyVars parses through the yaml string and modifies it replacing // variables with the format ${ VAR}, ${ VAR }, ${VAR } to ${VAR}. This is diff --git a/cmd/clusterctl/cmd/config_repositories.go b/cmd/clusterctl/cmd/config_repositories.go index 48e189d18771..16aca8ad05f9 100644 --- a/cmd/clusterctl/cmd/config_repositories.go +++ b/cmd/clusterctl/cmd/config_repositories.go @@ -37,10 +37,8 @@ const ( RepositoriesOutputText = "text" ) -var ( - // RepositoriesOutputs is a list of valid repository list outputs. - RepositoriesOutputs = []string{RepositoriesOutputYaml, RepositoriesOutputText} -) +// RepositoriesOutputs is a list of valid repository list outputs. +var RepositoriesOutputs = []string{RepositoriesOutputYaml, RepositoriesOutputText} type configRepositoriesOptions struct { output string diff --git a/cmd/clusterctl/cmd/config_repositories_test.go b/cmd/clusterctl/cmd/config_repositories_test.go index 079737bad555..12868a9b16dd 100644 --- a/cmd/clusterctl/cmd/config_repositories_test.go +++ b/cmd/clusterctl/cmd/config_repositories_test.go @@ -35,7 +35,7 @@ func Test_runGetRepositories(t *testing.T) { defer os.RemoveAll(tmpDir) path := filepath.Join(tmpDir, "clusterctl.yaml") - g.Expect(os.WriteFile(path, []byte(template), 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, []byte(template), 0o600)).To(Succeed()) buf := bytes.NewBufferString("") @@ -72,7 +72,7 @@ func Test_runGetRepositories(t *testing.T) { defer os.RemoveAll(tmpDir) path := filepath.Join(tmpDir, "clusterctl.yaml") - g.Expect(os.WriteFile(path, []byte("providers: foobar"), 0600)).To(Succeed()) + g.Expect(os.WriteFile(path, []byte("providers: foobar"), 0o600)).To(Succeed()) buf := bytes.NewBufferString("") g.Expect(runGetRepositories(path, buf)).ToNot(Succeed()) diff --git a/cmd/clusterctl/cmd/describe_cluster.go b/cmd/clusterctl/cmd/describe_cluster.go index b73cdf3e75d0..f5089c7df39b 100644 --- a/cmd/clusterctl/cmd/describe_cluster.go +++ b/cmd/clusterctl/cmd/describe_cluster.go @@ -237,7 +237,8 @@ func addObjectRow(prefix string, tbl *tablewriter.Table, objectTree *tree.Object readyDescriptor.readyColor.Sprint(readyDescriptor.severity), readyDescriptor.readyColor.Sprint(readyDescriptor.reason), readyDescriptor.age, - readyDescriptor.message}) + readyDescriptor.message, + }) // If it is required to show all the conditions for the object, add a row for each object's conditions. if tree.IsShowConditionsObject(obj) { @@ -287,7 +288,8 @@ func addOtherConditions(prefix string, tbl *tablewriter.Table, objectTree *tree. otherDescriptor.readyColor.Sprint(otherDescriptor.severity), otherDescriptor.readyColor.Sprint(otherDescriptor.reason), otherDescriptor.age, - otherDescriptor.message}) + otherDescriptor.message, + }) } } diff --git a/cmd/clusterctl/cmd/generate_yaml_test.go b/cmd/clusterctl/cmd/generate_yaml_test.go index ccab5a914002..664d7e3e4f06 100644 --- a/cmd/clusterctl/cmd/generate_yaml_test.go +++ b/cmd/clusterctl/cmd/generate_yaml_test.go @@ -121,7 +121,7 @@ func createTempFile(g *WithT, contents string) (string, func()) { g.Expect(err).NotTo(HaveOccurred()) templateFile := filepath.Join(dir, "templ.yaml") - g.Expect(os.WriteFile(templateFile, []byte(contents), 0600)).To(Succeed()) + g.Expect(os.WriteFile(templateFile, []byte(contents), 0o600)).To(Succeed()) return templateFile, func() { // We don't want to fail if the deletion of the temp file fails, so we ignore the error here diff --git a/cmd/clusterctl/cmd/topology_plan.go b/cmd/clusterctl/cmd/topology_plan.go index 8a8ede41bfe5..55057098df12 100644 --- a/cmd/clusterctl/cmd/topology_plan.go +++ b/cmd/clusterctl/cmd/topology_plan.go @@ -229,7 +229,7 @@ func writeOutputFiles(out *cluster.TopologyPlanOutput, outDir string) error { // Write created files createdDir := path.Join(outDir, "created") - if err := os.MkdirAll(createdDir, 0750); err != nil { + if err := os.MkdirAll(createdDir, 0o750); err != nil { return errors.Wrapf(err, "failed to create %q directory", createdDir) } for _, c := range out.Created { @@ -239,7 +239,7 @@ func writeOutputFiles(out *cluster.TopologyPlanOutput, outDir string) error { } fileName := fmt.Sprintf("%s_%s_%s.yaml", c.GetKind(), c.GetNamespace(), c.GetName()) filePath := path.Join(createdDir, fileName) - if err := os.WriteFile(filePath, yaml, 0600); err != nil { + if err := os.WriteFile(filePath, yaml, 0o600); err != nil { return errors.Wrapf(err, "failed to write yaml to file %q", filePath) } } @@ -249,7 +249,7 @@ func writeOutputFiles(out *cluster.TopologyPlanOutput, outDir string) error { // Write modified files modifiedDir := path.Join(outDir, "modified") - if err := os.MkdirAll(modifiedDir, 0750); err != nil { + if err := os.MkdirAll(modifiedDir, 0o750); err != nil { return errors.Wrapf(err, "failed to create %q directory", modifiedDir) } for _, m := range out.Modified { @@ -275,14 +275,14 @@ func writeOutputFiles(out *cluster.TopologyPlanOutput, outDir string) error { } patchFileName := fmt.Sprintf("%s_%s_%s.jsonpatch", m.After.GetKind(), m.After.GetNamespace(), m.After.GetName()) patchFilePath := path.Join(modifiedDir, patchFileName) - if err := os.WriteFile(patchFilePath, jsonPatch, 0600); err != nil { + if err := os.WriteFile(patchFilePath, jsonPatch, 0o600); err != nil { return errors.Wrapf(err, "failed to write jsonpatch to file %q", patchFilePath) } // Calculate the diff and write to a file. diffFileName := fmt.Sprintf("%s_%s_%s.diff", m.After.GetKind(), m.After.GetNamespace(), m.After.GetName()) diffFilePath := path.Join(modifiedDir, diffFileName) - diffFile, err := os.OpenFile(filepath.Clean(diffFilePath), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + diffFile, err := os.OpenFile(filepath.Clean(diffFilePath), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600) if err != nil { return errors.Wrapf(err, "unable to open file %q", diffFilePath) } @@ -302,7 +302,7 @@ func writeObjectToFile(filePath string, obj *unstructured.Unstructured) error { if err != nil { return errors.Wrap(err, "failed to convert object to yaml") } - if err := os.WriteFile(filePath, yaml, 0600); err != nil { + if err := os.WriteFile(filePath, yaml, 0o600); err != nil { return errors.Wrapf(err, "failed to write yaml to file %q", filePath) } return nil diff --git a/cmd/clusterctl/cmd/upgrade_plan.go b/cmd/clusterctl/cmd/upgrade_plan.go index 00f711e8a53c..a0dfae87aec8 100644 --- a/cmd/clusterctl/cmd/upgrade_plan.go +++ b/cmd/clusterctl/cmd/upgrade_plan.go @@ -87,7 +87,6 @@ func runUpgradePlan() error { upgradePlans, err := c.PlanUpgrade(client.PlanUpgradeOptions{ Kubeconfig: client.Kubeconfig{Path: up.kubeconfig, Context: up.kubeconfigContext}, }) - if err != nil { return err } diff --git a/cmd/clusterctl/cmd/util.go b/cmd/clusterctl/cmd/util.go index 2ab45cbb653c..1087101af0fe 100644 --- a/cmd/clusterctl/cmd/util.go +++ b/cmd/clusterctl/cmd/util.go @@ -47,7 +47,7 @@ func printYamlOutput(printer client.YamlPrinter, outputFile string) error { return nil } outputFile = filepath.Clean(outputFile) - if err := os.WriteFile(outputFile, yaml, 0600); err != nil { + if err := os.WriteFile(outputFile, yaml, 0o600); err != nil { return errors.Wrap(err, "failed to write to destination file") } return nil diff --git a/cmd/clusterctl/cmd/version_checker.go b/cmd/clusterctl/cmd/version_checker.go index 8aee0ef0607c..651aaa06a1f5 100644 --- a/cmd/clusterctl/cmd/version_checker.go +++ b/cmd/clusterctl/cmd/version_checker.go @@ -37,11 +37,9 @@ import ( "sigs.k8s.io/cluster-api/version" ) -var ( - // gitVersionRegEx matches git versions of style 0.3.7-45-c1aeccb679cd56 - // see ./hack/version.sh for more info. - gitVersionRegEx = regexp.MustCompile(`(.*)-(\d+)-([0-9,a-f]{14})`) -) +// gitVersionRegEx matches git versions of style 0.3.7-45-c1aeccb679cd56 +// see ./hack/version.sh for more info. +var gitVersionRegEx = regexp.MustCompile(`(.*)-(\d+)-([0-9,a-f]{14})`) type versionChecker struct { versionFilePath string @@ -173,7 +171,7 @@ func writeStateFile(path string, vs *VersionState) error { if err := os.MkdirAll(filepath.Dir(path), os.ModePerm); err != nil { return err } - return os.WriteFile(path, vsb, 0600) + return os.WriteFile(path, vsb, 0o600) } func readStateFile(filepath string) (*VersionState, error) { diff --git a/cmd/clusterctl/internal/scheme/scheme.go b/cmd/clusterctl/internal/scheme/scheme.go index bf171813ab75..b601e37fe9a0 100644 --- a/cmd/clusterctl/internal/scheme/scheme.go +++ b/cmd/clusterctl/internal/scheme/scheme.go @@ -32,10 +32,8 @@ import ( expv1 "sigs.k8s.io/cluster-api/exp/api/v1beta1" ) -var ( - // Scheme contains a set of API resources used by clusterctl. - Scheme = runtime.NewScheme() -) +// Scheme contains a set of API resources used by clusterctl. +var Scheme = runtime.NewScheme() func init() { _ = clientgoscheme.AddToScheme(Scheme) diff --git a/cmd/clusterctl/internal/test/fake_objects.go b/cmd/clusterctl/internal/test/fake_objects.go index 71c9661bff3f..b0f658ed5881 100644 --- a/cmd/clusterctl/internal/test/fake_objects.go +++ b/cmd/clusterctl/internal/test/fake_objects.go @@ -1304,20 +1304,20 @@ func setUID(obj client.Object) { } // FakeClusterCustomResourceDefinition returns a fake CRD object for the given group/versions/kind. -func FakeClusterCustomResourceDefinition(group string, kind string, versions ...string) *apiextensionsv1.CustomResourceDefinition { +func FakeClusterCustomResourceDefinition(group, kind string, versions ...string) *apiextensionsv1.CustomResourceDefinition { crd := fakeCRD(group, kind, versions) crd.Spec.Scope = apiextensionsv1.ClusterScoped return crd } // FakeNamespacedCustomResourceDefinition returns a fake CRD object for the given group/versions/kind. -func FakeNamespacedCustomResourceDefinition(group string, kind string, versions ...string) *apiextensionsv1.CustomResourceDefinition { +func FakeNamespacedCustomResourceDefinition(group, kind string, versions ...string) *apiextensionsv1.CustomResourceDefinition { crd := fakeCRD(group, kind, versions) crd.Spec.Scope = apiextensionsv1.NamespaceScoped return crd } -func fakeCRD(group string, kind string, versions []string) *apiextensionsv1.CustomResourceDefinition { +func fakeCRD(group, kind string, versions []string) *apiextensionsv1.CustomResourceDefinition { crd := &apiextensionsv1.CustomResourceDefinition{ TypeMeta: metav1.TypeMeta{ Kind: apiextensionsv1.SchemeGroupVersion.String(), diff --git a/cmd/clusterctl/internal/test/fake_proxy.go b/cmd/clusterctl/internal/test/fake_proxy.go index f1524f477c8c..f01b96a0bb49 100644 --- a/cmd/clusterctl/internal/test/fake_proxy.go +++ b/cmd/clusterctl/internal/test/fake_proxy.go @@ -47,9 +47,7 @@ type FakeProxy struct { available *bool } -var ( - FakeScheme = runtime.NewScheme() //nolint:revive -) +var FakeScheme = runtime.NewScheme() //nolint:revive func init() { _ = clientgoscheme.AddToScheme(FakeScheme) diff --git a/controllers/external/tracker_test.go b/controllers/external/tracker_test.go index fd4c7d2dd9cf..23cc39202003 100644 --- a/controllers/external/tracker_test.go +++ b/controllers/external/tracker_test.go @@ -32,9 +32,7 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) -var ( - logger = logr.New(log.NullLogSink{}) -) +var logger = logr.New(log.NullLogSink{}) type fakeController struct { controller.Controller diff --git a/controllers/external/util_test.go b/controllers/external/util_test.go index 9d9e94d85f82..9cb410db3a8c 100644 --- a/controllers/external/util_test.go +++ b/controllers/external/util_test.go @@ -32,9 +32,7 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) -var ( - ctx = ctrl.SetupSignalHandler() -) +var ctx = ctrl.SetupSignalHandler() const ( testClusterName = "test-cluster" diff --git a/controllers/noderefutil/providerid_test.go b/controllers/noderefutil/providerid_test.go index 77a77a831a4f..f795c33a10f0 100644 --- a/controllers/noderefutil/providerid_test.go +++ b/controllers/noderefutil/providerid_test.go @@ -22,8 +22,10 @@ import ( . "github.com/onsi/gomega" ) -const aws = "aws" -const azure = "azure" +const ( + aws = "aws" + azure = "azure" +) func TestNewProviderID(t *testing.T) { tests := []struct { diff --git a/controllers/noderefutil/util_test.go b/controllers/noderefutil/util_test.go index a071e27efb4d..3b2735745e6f 100644 --- a/controllers/noderefutil/util_test.go +++ b/controllers/noderefutil/util_test.go @@ -48,91 +48,105 @@ func TestIsNodeAvaialble(t *testing.T) { }, { name: "no ready condition", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeDiskPressure, - Status: corev1.ConditionTrue, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeDiskPressure, + Status: corev1.ConditionTrue, + }, }, - }}, + }, }, expectedAvailable: false, }, { name: "ready condition true, minReadySeconds = 0, lastTransitionTime now", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionTrue, - LastTransitionTime: metav1.Now(), + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionTrue, + LastTransitionTime: metav1.Now(), + }, }, - }}, + }, }, expectedAvailable: true, }, { name: "ready condition true, minReadySeconds = 0, lastTransitionTime past", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionTrue, - LastTransitionTime: metav1.Time{Time: time.Now().Add(time.Duration(-700) * time.Second)}, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionTrue, + LastTransitionTime: metav1.Time{Time: time.Now().Add(time.Duration(-700) * time.Second)}, + }, }, - }}, + }, }, expectedAvailable: true, }, { name: "ready condition true, minReadySeconds = 300, lastTransitionTime now", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionTrue, - LastTransitionTime: metav1.Now(), + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionTrue, + LastTransitionTime: metav1.Now(), + }, }, - }}, + }, }, minReadySeconds: 300, expectedAvailable: false, }, { name: "ready condition true, minReadySeconds = 300, lastTransitionTime past", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionTrue, - LastTransitionTime: metav1.Time{Time: time.Now().Add(time.Duration(-700) * time.Second)}, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionTrue, + LastTransitionTime: metav1.Time{Time: time.Now().Add(time.Duration(-700) * time.Second)}, + }, }, - }}, + }, }, minReadySeconds: 300, expectedAvailable: true, }, { name: "ready condition false", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionFalse, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionFalse, + }, }, - }}, + }, }, expectedAvailable: false, }, { name: "ready condition unknown", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionUnknown, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionUnknown, + }, }, - }}, + }, }, expectedAvailable: false, }, @@ -249,49 +263,57 @@ func TestIsNodeReady(t *testing.T) { }, { name: "no ready condition", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeDiskPressure, - Status: corev1.ConditionTrue, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeDiskPressure, + Status: corev1.ConditionTrue, + }, }, - }}, + }, }, expectedReady: false, }, { name: "ready condition true", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionTrue, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionTrue, + }, }, - }}, + }, }, expectedReady: true, }, { name: "ready condition false", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionFalse, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionFalse, + }, }, - }}, + }, }, expectedReady: false, }, { name: "ready condition unknown", - node: &corev1.Node{Status: corev1.NodeStatus{ - Conditions: []corev1.NodeCondition{ - { - Type: corev1.NodeReady, - Status: corev1.ConditionUnknown, + node: &corev1.Node{ + Status: corev1.NodeStatus{ + Conditions: []corev1.NodeCondition{ + { + Type: corev1.NodeReady, + Status: corev1.ConditionUnknown, + }, }, - }}, + }, }, expectedReady: false, }, diff --git a/controllers/remote/cluster_cache_healthcheck_test.go b/controllers/remote/cluster_cache_healthcheck_test.go index 0ab126dea72b..d5ae96e94d85 100644 --- a/controllers/remote/cluster_cache_healthcheck_test.go +++ b/controllers/remote/cluster_cache_healthcheck_test.go @@ -48,9 +48,9 @@ func TestClusterCacheHealthCheck(t *testing.T) { var cct *ClusterCacheTracker var cc *stoppableCache - var testPollInterval = 250 * time.Millisecond - var testPollTimeout = 1 * time.Second - var testUnhealthyThreshold = 3 + testPollInterval := 250 * time.Millisecond + testPollTimeout := 1 * time.Second + testUnhealthyThreshold := 3 setup := func(t *testing.T, g *WithT) *corev1.Namespace { t.Helper() diff --git a/controllers/remote/cluster_cache_reconciler.go b/controllers/remote/cluster_cache_reconciler.go index 748778c63021..f1a1a9ad2e6b 100644 --- a/controllers/remote/cluster_cache_reconciler.go +++ b/controllers/remote/cluster_cache_reconciler.go @@ -47,7 +47,6 @@ func (r *ClusterCacheReconciler) SetupWithManager(ctx context.Context, mgr ctrl. WithOptions(options). WithEventFilter(predicates.ResourceHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)). Complete(r) - if err != nil { return errors.Wrap(err, "failed setting up with a controller manager") } diff --git a/controlplane/kubeadm/api/v1alpha3/conversion_test.go b/controlplane/kubeadm/api/v1alpha3/conversion_test.go index 2d8217c19da4..3b346a339e50 100644 --- a/controlplane/kubeadm/api/v1alpha3/conversion_test.go +++ b/controlplane/kubeadm/api/v1alpha3/conversion_test.go @@ -60,6 +60,7 @@ func kubeadmBootstrapTokenStringFuzzer(in *upstreamv1beta1.BootstrapTokenString, in.ID = "abcdef" in.Secret = "abcdef0123456789" } + func cabpkBootstrapTokenStringFuzzer(in *bootstrapv1.BootstrapTokenString, _ fuzz.Continue) { in.ID = "abcdef" in.Secret = "abcdef0123456789" diff --git a/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook.go b/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook.go index 50cce2e0456e..22cdbb777bbf 100644 --- a/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook.go +++ b/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook.go @@ -47,8 +47,10 @@ func (in *KubeadmControlPlane) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/mutate-controlplane-cluster-x-k8s-io-v1beta1-kubeadmcontrolplane,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=controlplane.cluster.x-k8s.io,resources=kubeadmcontrolplanes,versions=v1beta1,name=default.kubeadmcontrolplane.controlplane.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/validate-controlplane-cluster-x-k8s-io-v1beta1-kubeadmcontrolplane,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=controlplane.cluster.x-k8s.io,resources=kubeadmcontrolplanes,versions=v1beta1,name=validation.kubeadmcontrolplane.controlplane.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Defaulter = &KubeadmControlPlane{} -var _ webhook.Validator = &KubeadmControlPlane{} +var ( + _ webhook.Defaulter = &KubeadmControlPlane{} + _ webhook.Validator = &KubeadmControlPlane{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (in *KubeadmControlPlane) Default() { diff --git a/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook_test.go b/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook_test.go index 6ae774051a0f..3035d307cd3e 100644 --- a/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook_test.go +++ b/controlplane/kubeadm/api/v1beta1/kubeadm_control_plane_webhook_test.go @@ -1192,6 +1192,7 @@ func TestValidateVersion(t *testing.T) { }) } } + func TestKubeadmControlPlaneValidateUpdateAfterDefaulting(t *testing.T) { before := &KubeadmControlPlane{ ObjectMeta: metav1.ObjectMeta{ diff --git a/controlplane/kubeadm/internal/controllers/controller_test.go b/controlplane/kubeadm/internal/controllers/controller_test.go index 05218bb48cbb..1b5af5a2772e 100644 --- a/controlplane/kubeadm/internal/controllers/controller_test.go +++ b/controlplane/kubeadm/internal/controllers/controller_test.go @@ -82,7 +82,8 @@ func TestClusterToKubeadmControlPlane(t *testing.T) { { NamespacedName: client.ObjectKey{ Namespace: cluster.Spec.ControlPlaneRef.Namespace, - Name: cluster.Spec.ControlPlaneRef.Name}, + Name: cluster.Spec.ControlPlaneRef.Name, + }, }, } diff --git a/controlplane/kubeadm/internal/controllers/fakes_test.go b/controlplane/kubeadm/internal/controllers/fakes_test.go index 7f5a962e2db8..aa3a0abe71cb 100644 --- a/controlplane/kubeadm/internal/controllers/fakes_test.go +++ b/controlplane/kubeadm/internal/controllers/fakes_test.go @@ -73,7 +73,7 @@ type fakeWorkloadCluster struct { APIServerCertificateExpiry *time.Time } -func (f fakeWorkloadCluster) ForwardEtcdLeadership(_ context.Context, _ *clusterv1.Machine, leaderCandidate *clusterv1.Machine) error { +func (f fakeWorkloadCluster) ForwardEtcdLeadership(_ context.Context, _, leaderCandidate *clusterv1.Machine) error { if leaderCandidate == nil { return errors.New("leaderCandidate is nil") } diff --git a/controlplane/kubeadm/internal/controllers/remediation_test.go b/controlplane/kubeadm/internal/controllers/remediation_test.go index 26183baa1cc7..9dc338d87add 100644 --- a/controlplane/kubeadm/internal/controllers/remediation_test.go +++ b/controlplane/kubeadm/internal/controllers/remediation_test.go @@ -53,7 +53,7 @@ func TestReconcileUnhealthyMachines(t *testing.T) { g.Expect(env.Cleanup(ctx, ns)).To(Succeed()) }() - var removeFinalizer = func(g *WithT, m *clusterv1.Machine) { + removeFinalizer := func(g *WithT, m *clusterv1.Machine) { patchHelper, err := patch.NewHelper(m, env.GetClient()) g.Expect(err).ToNot(HaveOccurred()) m.ObjectMeta.Finalizers = nil @@ -945,7 +945,7 @@ func TestReconcileUnhealthyMachines(t *testing.T) { } func TestReconcileUnhealthyMachinesSequences(t *testing.T) { - var removeFinalizer = func(g *WithT, m *clusterv1.Machine) { + removeFinalizer := func(g *WithT, m *clusterv1.Machine) { patchHelper, err := patch.NewHelper(m, env.GetClient()) g.Expect(err).ToNot(HaveOccurred()) m.ObjectMeta.Finalizers = nil diff --git a/controlplane/kubeadm/internal/controllers/upgrade_test.go b/controlplane/kubeadm/internal/controllers/upgrade_test.go index 75f26fe3d860..ab46b95b8d82 100644 --- a/controlplane/kubeadm/internal/controllers/upgrade_test.go +++ b/controlplane/kubeadm/internal/controllers/upgrade_test.go @@ -39,8 +39,10 @@ import ( "sigs.k8s.io/cluster-api/util/collections" ) -const UpdatedVersion string = "v1.17.4" -const Host string = "nodomain.example.com" +const ( + UpdatedVersion string = "v1.17.4" + Host string = "nodomain.example.com" +) func TestKubeadmControlPlaneReconciler_RolloutStrategy_ScaleUp(t *testing.T) { setup := func(t *testing.T, g *WithT) *corev1.Namespace { diff --git a/controlplane/kubeadm/internal/etcd/etcd_test.go b/controlplane/kubeadm/internal/etcd/etcd_test.go index d5699d64f82f..2cd1f08c3d59 100644 --- a/controlplane/kubeadm/internal/etcd/etcd_test.go +++ b/controlplane/kubeadm/internal/etcd/etcd_test.go @@ -28,9 +28,7 @@ import ( etcdfake "sigs.k8s.io/cluster-api/controlplane/kubeadm/internal/etcd/fake" ) -var ( - ctx = ctrl.SetupSignalHandler() -) +var ctx = ctrl.SetupSignalHandler() func TestEtcdMembers_WithErrors(t *testing.T) { g := NewWithT(t) diff --git a/controlplane/kubeadm/internal/etcd/fake/client.go b/controlplane/kubeadm/internal/etcd/fake/client.go index a8eeb24c2b49..a552eebf5d09 100644 --- a/controlplane/kubeadm/internal/etcd/fake/client.go +++ b/controlplane/kubeadm/internal/etcd/fake/client.go @@ -56,13 +56,16 @@ func (c *FakeEtcdClient) AlarmList(_ context.Context) (*clientv3.AlarmResponse, func (c *FakeEtcdClient) MemberList(_ context.Context) (*clientv3.MemberListResponse, error) { return c.MemberListResponse, c.ErrorResponse } + func (c *FakeEtcdClient) MemberRemove(_ context.Context, i uint64) (*clientv3.MemberRemoveResponse, error) { c.RemovedMember = i return c.MemberRemoveResponse, c.ErrorResponse } + func (c *FakeEtcdClient) MemberUpdate(_ context.Context, _ uint64, _ []string) (*clientv3.MemberUpdateResponse, error) { return c.MemberUpdateResponse, c.ErrorResponse } + func (c *FakeEtcdClient) Status(_ context.Context, _ string) (*clientv3.StatusResponse, error) { return c.StatusResponse, nil } diff --git a/controlplane/kubeadm/internal/etcd_client_generator_test.go b/controlplane/kubeadm/internal/etcd_client_generator_test.go index eff3879ec2d6..933af983f531 100644 --- a/controlplane/kubeadm/internal/etcd_client_generator_test.go +++ b/controlplane/kubeadm/internal/etcd_client_generator_test.go @@ -32,9 +32,7 @@ import ( etcdfake "sigs.k8s.io/cluster-api/controlplane/kubeadm/internal/etcd/fake" ) -var ( - subject *EtcdClientGenerator -) +var subject *EtcdClientGenerator func TestNewEtcdClientGenerator(t *testing.T) { g := NewWithT(t) @@ -129,7 +127,8 @@ func TestForLeader(t *testing.T) { }, }, AlarmResponse: &clientv3.AlarmResponse{}, - }}, nil + }, + }, nil }, expectedClient: etcd.Client{ Endpoint: "etcd-node-leader", @@ -141,7 +140,8 @@ func TestForLeader(t *testing.T) { }, }, AlarmResponse: &clientv3.AlarmResponse{}, - }}, + }, + }, }, { name: "Returns client for leader even when one or more nodes are down", @@ -160,7 +160,8 @@ func TestForLeader(t *testing.T) { }, }, AlarmResponse: &clientv3.AlarmResponse{}, - }}, nil + }, + }, nil }, expectedClient: etcd.Client{ Endpoint: "etcd-node-leader", @@ -171,7 +172,8 @@ func TestForLeader(t *testing.T) { }, }, AlarmResponse: &clientv3.AlarmResponse{}, - }}, + }, + }, }, { name: "Fails when called with an empty node list", @@ -194,7 +196,8 @@ func TestForLeader(t *testing.T) { }, }, AlarmResponse: &clientv3.AlarmResponse{}, - }}, nil + }, + }, nil }, expectedErr: "etcd leader is reported as 6c1 with name \"node-leader\", but we couldn't find a corresponding Node in the cluster", }, diff --git a/controlplane/kubeadm/internal/proxy/dial.go b/controlplane/kubeadm/internal/proxy/dial.go index e4c1024ff527..0a872adea6d0 100644 --- a/controlplane/kubeadm/internal/proxy/dial.go +++ b/controlplane/kubeadm/internal/proxy/dial.go @@ -84,7 +84,7 @@ func (d *Dialer) DialContextWithAddr(ctx context.Context, addr string) (net.Conn // DialContext creates proxied port-forwarded connections. // ctx is currently unused, but fulfils the type signature used by GRPC. -func (d *Dialer) DialContext(_ context.Context, _ string, addr string) (net.Conn, error) { +func (d *Dialer) DialContext(_ context.Context, _, addr string) (net.Conn, error) { req := d.clientset.CoreV1().RESTClient(). Post(). Resource(d.proxy.Kind). diff --git a/controlplane/kubeadm/internal/proxy/proxy.go b/controlplane/kubeadm/internal/proxy/proxy.go index 381f7780ab33..1eb1d1c924b9 100644 --- a/controlplane/kubeadm/internal/proxy/proxy.go +++ b/controlplane/kubeadm/internal/proxy/proxy.go @@ -24,7 +24,6 @@ import ( // Proxy defines the API server port-forwarded proxy. type Proxy struct { - // Kind is the kind of Kubernetes resource Kind string diff --git a/controlplane/kubeadm/internal/webhooks/scale_test.go b/controlplane/kubeadm/internal/webhooks/scale_test.go index f074dcf20a3c..607761696b0e 100644 --- a/controlplane/kubeadm/internal/webhooks/scale_test.go +++ b/controlplane/kubeadm/internal/webhooks/scale_test.go @@ -42,9 +42,7 @@ func init() { _ = admissionv1.AddToScheme(scheme) } -var ( - scheme *runtime.Scheme -) +var scheme *runtime.Scheme func TestKubeadmControlPlaneValidateScale(t *testing.T) { kcpManagedEtcd := &controlplanev1.KubeadmControlPlane{ diff --git a/controlplane/kubeadm/internal/workload_cluster.go b/controlplane/kubeadm/internal/workload_cluster.go index 7ffacda66193..d2e77da15dfb 100644 --- a/controlplane/kubeadm/internal/workload_cluster.go +++ b/controlplane/kubeadm/internal/workload_cluster.go @@ -118,7 +118,7 @@ type WorkloadCluster interface { RemoveEtcdMemberForMachine(ctx context.Context, machine *clusterv1.Machine) error RemoveMachineFromKubeadmConfigMap(ctx context.Context, machine *clusterv1.Machine, version semver.Version) error RemoveNodeFromKubeadmConfigMap(ctx context.Context, nodeName string, version semver.Version) error - ForwardEtcdLeadership(ctx context.Context, machine *clusterv1.Machine, leaderCandidate *clusterv1.Machine) error + ForwardEtcdLeadership(ctx context.Context, machine, leaderCandidate *clusterv1.Machine) error AllowBootstrapTokensToGetNodes(ctx context.Context) error // State recovery tasks. diff --git a/controlplane/kubeadm/internal/workload_cluster_coredns.go b/controlplane/kubeadm/internal/workload_cluster_coredns.go index 9ebf7eda9950..0e67da5e83e9 100644 --- a/controlplane/kubeadm/internal/workload_cluster_coredns.go +++ b/controlplane/kubeadm/internal/workload_cluster_coredns.go @@ -55,29 +55,27 @@ const ( controlPlaneTaint = "node-role.kubernetes.io/control-plane" ) -var ( - // Source: https://github.com/kubernetes/kubernetes/blob/v1.22.0-beta.1/cmd/kubeadm/app/phases/addons/dns/manifests.go#L178-L207 - coreDNS181PolicyRules = []rbacv1.PolicyRule{ - { - Verbs: []string{"list", "watch"}, - APIGroups: []string{""}, - Resources: []string{"endpoints", "services", "pods", "namespaces"}, - }, - { - Verbs: []string{"get"}, - APIGroups: []string{""}, - Resources: []string{"nodes"}, - }, - { - Verbs: []string{"list", "watch"}, - APIGroups: []string{"discovery.k8s.io"}, - Resources: []string{"endpointslices"}, - }, - } -) +// Source: https://github.com/kubernetes/kubernetes/blob/v1.22.0-beta.1/cmd/kubeadm/app/phases/addons/dns/manifests.go#L178-L207 +var coreDNS181PolicyRules = []rbacv1.PolicyRule{ + { + Verbs: []string{"list", "watch"}, + APIGroups: []string{""}, + Resources: []string{"endpoints", "services", "pods", "namespaces"}, + }, + { + Verbs: []string{"get"}, + APIGroups: []string{""}, + Resources: []string{"nodes"}, + }, + { + Verbs: []string{"list", "watch"}, + APIGroups: []string{"discovery.k8s.io"}, + Resources: []string{"endpointslices"}, + }, +} type coreDNSMigrator interface { - Migrate(currentVersion string, toVersion string, corefile string, deprecations bool) (string, error) + Migrate(currentVersion, toVersion, corefile string, deprecations bool) (string, error) } // CoreDNSMigrator is a shim that can be used to migrate CoreDNS files from one version to another. diff --git a/controlplane/kubeadm/internal/workload_cluster_etcd.go b/controlplane/kubeadm/internal/workload_cluster_etcd.go index 3b3662a29f01..5204b1912fd7 100644 --- a/controlplane/kubeadm/internal/workload_cluster_etcd.go +++ b/controlplane/kubeadm/internal/workload_cluster_etcd.go @@ -163,7 +163,7 @@ func (w *Workload) removeMemberForNode(ctx context.Context, name string) error { } // ForwardEtcdLeadership forwards etcd leadership to the first follower. -func (w *Workload) ForwardEtcdLeadership(ctx context.Context, machine *clusterv1.Machine, leaderCandidate *clusterv1.Machine) error { +func (w *Workload) ForwardEtcdLeadership(ctx context.Context, machine, leaderCandidate *clusterv1.Machine) error { if machine == nil || machine.Status.NodeRef == nil { return nil } diff --git a/controlplane/kubeadm/internal/workload_cluster_test.go b/controlplane/kubeadm/internal/workload_cluster_test.go index 63bbea586df2..3e6883f6b4f4 100644 --- a/controlplane/kubeadm/internal/workload_cluster_test.go +++ b/controlplane/kubeadm/internal/workload_cluster_test.go @@ -160,7 +160,8 @@ func TestUpdateKubeProxyImageInfo(t *testing.T) { ImageRepository: "foo.bar.example/baz/qux", }, }, - }}, + }, + }, }, { name: "does not update image repository if it is blank", @@ -175,7 +176,8 @@ func TestUpdateKubeProxyImageInfo(t *testing.T) { ImageRepository: "", }, }, - }}, + }, + }, }, { name: "does update image repository to new default registry for v1.25 updates", @@ -185,7 +187,8 @@ func TestUpdateKubeProxyImageInfo(t *testing.T) { KCP: &controlplanev1.KubeadmControlPlane{ Spec: controlplanev1.KubeadmControlPlaneSpec{ Version: "v1.25.0-alpha.1", - }}, + }, + }, }, { name: "returns error if image repository is invalid", @@ -199,7 +202,8 @@ func TestUpdateKubeProxyImageInfo(t *testing.T) { ImageRepository: "%%%", }, }, - }}, + }, + }, }, { name: "does not update image repository when no kube-proxy update is requested", @@ -214,7 +218,8 @@ func TestUpdateKubeProxyImageInfo(t *testing.T) { }, Spec: controlplanev1.KubeadmControlPlaneSpec{ Version: "v1.16.3", - }}, + }, + }, }, } diff --git a/controlplane/kubeadm/main.go b/controlplane/kubeadm/main.go index 107d9050c3ab..38eca8d32b67 100644 --- a/controlplane/kubeadm/main.go +++ b/controlplane/kubeadm/main.go @@ -152,6 +152,7 @@ func InitFlags(fs *pflag.FlagSet) { feature.MutableGates.AddFlag(fs) } + func main() { rand.Seed(time.Now().UnixNano()) diff --git a/exp/addons/api/v1beta1/clusterresourceset_webhook.go b/exp/addons/api/v1beta1/clusterresourceset_webhook.go index e33cba7faadd..f830872a7f7c 100644 --- a/exp/addons/api/v1beta1/clusterresourceset_webhook.go +++ b/exp/addons/api/v1beta1/clusterresourceset_webhook.go @@ -39,8 +39,10 @@ func (m *ClusterResourceSet) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-addons-cluster-x-k8s-io-v1beta1-clusterresourceset,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=addons.cluster.x-k8s.io,resources=clusterresourcesets,versions=v1beta1,name=validation.clusterresourceset.addons.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-addons-cluster-x-k8s-io-v1beta1-clusterresourceset,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=addons.cluster.x-k8s.io,resources=clusterresourcesets,versions=v1beta1,name=default.clusterresourceset.addons.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Defaulter = &ClusterResourceSet{} -var _ webhook.Validator = &ClusterResourceSet{} +var ( + _ webhook.Defaulter = &ClusterResourceSet{} + _ webhook.Validator = &ClusterResourceSet{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (m *ClusterResourceSet) Default() { diff --git a/exp/api/v1beta1/machinepool_webhook.go b/exp/api/v1beta1/machinepool_webhook.go index 10a3db671ba3..88992ebe4b1e 100644 --- a/exp/api/v1beta1/machinepool_webhook.go +++ b/exp/api/v1beta1/machinepool_webhook.go @@ -41,8 +41,10 @@ func (m *MachinePool) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update,path=/validate-cluster-x-k8s-io-v1beta1-machinepool,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinepools,versions=v1beta1,name=validation.machinepool.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-cluster-x-k8s-io-v1beta1-machinepool,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=cluster.x-k8s.io,resources=machinepools,versions=v1beta1,name=default.machinepool.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.Defaulter = &MachinePool{} -var _ webhook.Validator = &MachinePool{} +var ( + _ webhook.Defaulter = &MachinePool{} + _ webhook.Validator = &MachinePool{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (m *MachinePool) Default() { diff --git a/exp/internal/controllers/machinepool_controller_noderef.go b/exp/internal/controllers/machinepool_controller_noderef.go index 6b8f953b1a17..2b04c5a7f1c3 100644 --- a/exp/internal/controllers/machinepool_controller_noderef.go +++ b/exp/internal/controllers/machinepool_controller_noderef.go @@ -37,9 +37,7 @@ import ( "sigs.k8s.io/cluster-api/util/patch" ) -var ( - errNoAvailableNodes = errors.New("cannot find nodes with matching ProviderIDs in ProviderIDList") -) +var errNoAvailableNodes = errors.New("cannot find nodes with matching ProviderIDs in ProviderIDList") type getNodeReferencesResult struct { references []corev1.ObjectReference diff --git a/exp/internal/controllers/machinepool_controller_phases.go b/exp/internal/controllers/machinepool_controller_phases.go index cb60b4429569..44225f91efc1 100644 --- a/exp/internal/controllers/machinepool_controller_phases.go +++ b/exp/internal/controllers/machinepool_controller_phases.go @@ -43,9 +43,7 @@ import ( "sigs.k8s.io/cluster-api/util/patch" ) -var ( - externalReadyWait = 30 * time.Second -) +var externalReadyWait = 30 * time.Second func (r *MachinePoolReconciler) reconcilePhase(mp *expv1.MachinePool) { // Set the phase to "pending" if nil. diff --git a/exp/internal/controllers/machinepool_controller_test.go b/exp/internal/controllers/machinepool_controller_test.go index a771d25c3bcd..eb768fb9ceac 100644 --- a/exp/internal/controllers/machinepool_controller_test.go +++ b/exp/internal/controllers/machinepool_controller_test.go @@ -316,7 +316,6 @@ func TestReconcileMachinePoolRequest(t *testing.T) { Replicas: pointer.Int32(1), Template: clusterv1.MachineTemplateSpec{ Spec: clusterv1.MachineSpec{ - InfrastructureRef: corev1.ObjectReference{ APIVersion: builder.InfrastructureGroupVersion.String(), Kind: builder.TestInfrastructureMachineTemplateKind, diff --git a/exp/ipam/internal/webhooks/ipaddressclaim.go b/exp/ipam/internal/webhooks/ipaddressclaim.go index c009eb2398a1..510bac37bd61 100644 --- a/exp/ipam/internal/webhooks/ipaddressclaim.go +++ b/exp/ipam/internal/webhooks/ipaddressclaim.go @@ -41,8 +41,7 @@ func (webhook *IPAddressClaim) SetupWebhookWithManager(mgr ctrl.Manager) error { // +kubebuilder:webhook:verbs=create;update;delete,path=/validate-ipam-cluster-x-k8s-io-v1alpha1-ipaddressclaim,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=ipam.cluster.x-k8s.io,resources=ipaddressclaims,versions=v1alpha1,name=validation.ipaddressclaim.ipam.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // IPAddressClaim implements a validating webhook for IPAddressClaim. -type IPAddressClaim struct { -} +type IPAddressClaim struct{} var _ webhook.CustomValidator = &IPAddressClaim{} diff --git a/exp/ipam/webhooks/alias.go b/exp/ipam/webhooks/alias.go index 092347cf72f2..edf4d7165462 100644 --- a/exp/ipam/webhooks/alias.go +++ b/exp/ipam/webhooks/alias.go @@ -36,8 +36,7 @@ func (webhook *IPAddress) SetupWebhookWithManager(mgr ctrl.Manager) error { } // IPAddressClaim implements a validating and defaulting webhook for IPAddressClaim. -type IPAddressClaim struct { -} +type IPAddressClaim struct{} // SetupWebhookWithManager sets up IPAddressClaim webhooks. func (webhook *IPAddressClaim) SetupWebhookWithManager(mgr ctrl.Manager) error { diff --git a/exp/runtime/catalog/catalog.go b/exp/runtime/catalog/catalog.go index 6e20a27a5976..05a9d9c510d9 100644 --- a/exp/runtime/catalog/catalog.go +++ b/exp/runtime/catalog/catalog.go @@ -192,7 +192,7 @@ func (c *Catalog) AddOpenAPIDefinitions(getter OpenAPIDefinitionsGetter) { // Convert will attempt to convert in into out. Both must be pointers. // Returns an error if the conversion isn't possible. -func (c *Catalog) Convert(in, out interface{}, context interface{}) error { +func (c *Catalog) Convert(in, out, context interface{}) error { return c.scheme.Convert(in, out, context) } diff --git a/exp/runtime/internal/controllers/warmup.go b/exp/runtime/internal/controllers/warmup.go index 72b2860bd5cb..d8a1786d96b1 100644 --- a/exp/runtime/internal/controllers/warmup.go +++ b/exp/runtime/internal/controllers/warmup.go @@ -79,7 +79,6 @@ func (r *warmupRunnable) Start(ctx context.Context) error { } return true, nil }) - if err != nil { return errors.Wrapf(err, "ExtensionConfig registry warmup timed out after %s", r.warmupTimeout.String()) } diff --git a/exp/runtime/topologymutation/walker.go b/exp/runtime/topologymutation/walker.go index 1f66d83bff56..5f756838aab2 100644 --- a/exp/runtime/topologymutation/walker.go +++ b/exp/runtime/topologymutation/walker.go @@ -80,7 +80,8 @@ func (d PatchFormat) ApplyToWalkTemplates(in *WalkTemplatesOptions) { // and GeneratePatchesResponse messages format and focus on writing patches/modifying the templates. func WalkTemplates(ctx context.Context, decoder runtime.Decoder, req *runtimehooksv1.GeneratePatchesRequest, resp *runtimehooksv1.GeneratePatchesResponse, mutateFunc func(ctx context.Context, obj runtime.Object, - variables map[string]apiextensionsv1.JSON, holderRef runtimehooksv1.HolderReference) error, opts ...WalkTemplatesOption) { + variables map[string]apiextensionsv1.JSON, holderRef runtimehooksv1.HolderReference) error, opts ...WalkTemplatesOption, +) { log := ctrl.LoggerFrom(ctx) globalVariables := patchvariables.ToMap(req.Variables) diff --git a/exp/runtime/topologymutation/walker_test.go b/exp/runtime/topologymutation/walker_test.go index 52c0e60fb7b5..8d428f3cb7db 100644 --- a/exp/runtime/topologymutation/walker_test.go +++ b/exp/runtime/topologymutation/walker_test.go @@ -35,9 +35,7 @@ import ( "sigs.k8s.io/cluster-api/internal/controllers/topology/cluster/patches/variables" ) -var ( - testScheme = runtime.NewScheme() -) +var testScheme = runtime.NewScheme() func init() { _ = controlplanev1.AddToScheme(testScheme) diff --git a/hack/tools/log-push/main_test.go b/hack/tools/log-push/main_test.go index 3d102d69cb5e..7b6fc484dda5 100644 --- a/hack/tools/log-push/main_test.go +++ b/hack/tools/log-push/main_test.go @@ -46,7 +46,6 @@ func Test_calculateGCSLogLocation(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotBucket, gotFolder, err := calculateGCSLogLocation(tt.logPath) - if err != nil { t.Errorf("calculateGCSLogLocation() unexpected error: %v", err) } diff --git a/hack/tools/runtime-openapi-gen/main.go b/hack/tools/runtime-openapi-gen/main.go index 82ff98b7483e..b4f7d4ecbc57 100644 --- a/hack/tools/runtime-openapi-gen/main.go +++ b/hack/tools/runtime-openapi-gen/main.go @@ -72,7 +72,7 @@ func main() { klog.Exitf("Failed to marshal OpenAPI specification: %v", err) } - err = os.WriteFile(*outputFile, openAPIBytes, 0600) + err = os.WriteFile(*outputFile, openAPIBytes, 0o600) if err != nil { klog.Exitf("Failed to write OpenAPI specification to file %q: %v", outputFile, err) } diff --git a/hack/tools/tilt-prepare/main.go b/hack/tools/tilt-prepare/main.go index 9869aa3c3660..e18c21432e9f 100644 --- a/hack/tools/tilt-prepare/main.go +++ b/hack/tools/tilt-prepare/main.go @@ -760,7 +760,7 @@ func workloadTask(name, workloadType, binaryName, containerName string, ts *tilt // writeIfChanged writes yaml to a file if the file does not exist or if the content has changed. // NOTE: Skipping write in case the content is not changed avoids unnecessary Tiltfile reload. -func writeIfChanged(prefix string, path string, yaml []byte) error { +func writeIfChanged(prefix, path string, yaml []byte) error { _, err := os.Stat(path) if err != nil && !errors.Is(err, os.ErrNotExist) { return errors.Wrapf(err, "[%s] failed to check if %s exists", prefix, path) @@ -777,12 +777,12 @@ func writeIfChanged(prefix string, path string, yaml []byte) error { } } - err = os.MkdirAll(filepath.Dir(path), 0750) + err = os.MkdirAll(filepath.Dir(path), 0o750) if err != nil { return errors.Wrapf(err, "[%s] failed to create dir %s", prefix, filepath.Dir(path)) } - if err := os.WriteFile(path, yaml, 0600); err != nil { + if err := os.WriteFile(path, yaml, 0o600); err != nil { return errors.Wrapf(err, "[%s] failed to write %s", prefix, path) } return nil diff --git a/internal/contract/bootstrap.go b/internal/contract/bootstrap.go index d042d1a5e16c..fc672d7c8378 100644 --- a/internal/contract/bootstrap.go +++ b/internal/contract/bootstrap.go @@ -21,8 +21,10 @@ import "sync" // BootstrapContract encodes information about the Cluster API contract for bootstrap objects. type BootstrapContract struct{} -var bootstrap *BootstrapContract -var onceBootstrap sync.Once +var ( + bootstrap *BootstrapContract + onceBootstrap sync.Once +) // Bootstrap provide access to the information about the Cluster API contract for bootstrap objects. func Bootstrap() *BootstrapContract { diff --git a/internal/contract/bootstrap_config_template.go b/internal/contract/bootstrap_config_template.go index a49834c3308f..c594198c4da6 100644 --- a/internal/contract/bootstrap_config_template.go +++ b/internal/contract/bootstrap_config_template.go @@ -24,8 +24,10 @@ import ( // like KubeadmConfigTemplate, etc. type BootstrapConfigTemplateContract struct{} -var bootstrapConfigTemplate *BootstrapConfigTemplateContract -var onceBootstrapConfigTemplate sync.Once +var ( + bootstrapConfigTemplate *BootstrapConfigTemplateContract + onceBootstrapConfigTemplate sync.Once +) // BootstrapConfigTemplate provide access to the information about the Cluster API contract for BootstrapConfigTemplate objects. func BootstrapConfigTemplate() *BootstrapConfigTemplateContract { diff --git a/internal/contract/controlplane.go b/internal/contract/controlplane.go index 3148477af309..6cbad76b7ad0 100644 --- a/internal/contract/controlplane.go +++ b/internal/contract/controlplane.go @@ -31,8 +31,10 @@ import ( // like e.g the KubeadmControlPlane etc. type ControlPlaneContract struct{} -var controlPlane *ControlPlaneContract -var onceControlPlane sync.Once +var ( + controlPlane *ControlPlaneContract + onceControlPlane sync.Once +) // ControlPlane provide access to the information about the Cluster API contract for ControlPlane objects. func ControlPlane() *ControlPlaneContract { diff --git a/internal/contract/controlplane_template.go b/internal/contract/controlplane_template.go index a5168d2b77ba..3e85399f6f49 100644 --- a/internal/contract/controlplane_template.go +++ b/internal/contract/controlplane_template.go @@ -22,8 +22,10 @@ import "sync" // like e.g. the KubeadmControlPlane etc. type ControlPlaneTemplateContract struct{} -var controlPlaneTemplate *ControlPlaneTemplateContract -var onceControlPlaneTemplate sync.Once +var ( + controlPlaneTemplate *ControlPlaneTemplateContract + onceControlPlaneTemplate sync.Once +) // ControlPlaneTemplate provide access to the information about the Cluster API contract for ControlPlaneTemplate objects. func ControlPlaneTemplate() *ControlPlaneTemplateContract { diff --git a/internal/contract/infrastructure_cluster.go b/internal/contract/infrastructure_cluster.go index e1055fea3577..6d8366e970b6 100644 --- a/internal/contract/infrastructure_cluster.go +++ b/internal/contract/infrastructure_cluster.go @@ -31,8 +31,10 @@ import ( // like DockerClusters, AWS Clusters, etc. type InfrastructureClusterContract struct{} -var infrastructureCluster *InfrastructureClusterContract -var onceInfrastructureCluster sync.Once +var ( + infrastructureCluster *InfrastructureClusterContract + onceInfrastructureCluster sync.Once +) // InfrastructureCluster provide access to the information about the Cluster API contract for InfrastructureCluster objects. func InfrastructureCluster() *InfrastructureClusterContract { diff --git a/internal/contract/infrastructure_cluster_template.go b/internal/contract/infrastructure_cluster_template.go index 5da12e0014ed..f783ad13a17c 100644 --- a/internal/contract/infrastructure_cluster_template.go +++ b/internal/contract/infrastructure_cluster_template.go @@ -24,8 +24,10 @@ import ( // like DockerClusterTemplates, AWSClusterTemplates, etc. type InfrastructureClusterTemplateContract struct{} -var infrastructureClusterTemplate *InfrastructureClusterTemplateContract -var onceInfrastructureClusterTemplate sync.Once +var ( + infrastructureClusterTemplate *InfrastructureClusterTemplateContract + onceInfrastructureClusterTemplate sync.Once +) // InfrastructureClusterTemplate provides access to the information about the Cluster API contract for InfrastructureClusterTemplate objects. func InfrastructureClusterTemplate() *InfrastructureClusterTemplateContract { diff --git a/internal/contract/infrastructure_machine.go b/internal/contract/infrastructure_machine.go index ac63f5a96a93..edd1f717d5c4 100644 --- a/internal/contract/infrastructure_machine.go +++ b/internal/contract/infrastructure_machine.go @@ -31,8 +31,10 @@ import ( // like DockerMachines, AWS Machines, etc. type InfrastructureMachineContract struct{} -var infrastructureMachine *InfrastructureMachineContract -var onceInfrastructureMachine sync.Once +var ( + infrastructureMachine *InfrastructureMachineContract + onceInfrastructureMachine sync.Once +) // InfrastructureMachine provide access to the information about the Cluster API contract for InfrastructureMachine objects. func InfrastructureMachine() *InfrastructureMachineContract { diff --git a/internal/contract/infrastructure_machine_template.go b/internal/contract/infrastructure_machine_template.go index dcdca2351c0f..6ef4eee6b4bc 100644 --- a/internal/contract/infrastructure_machine_template.go +++ b/internal/contract/infrastructure_machine_template.go @@ -24,8 +24,10 @@ import ( // like DockerMachineTemplates, AWSMachineTemplates, etc. type InfrastructureMachineTemplateContract struct{} -var infrastructureMachineTemplate *InfrastructureMachineTemplateContract -var onceInfrastructureMachineTemplate sync.Once +var ( + infrastructureMachineTemplate *InfrastructureMachineTemplateContract + onceInfrastructureMachineTemplate sync.Once +) // InfrastructureMachineTemplate provide access to the information about the Cluster API contract for InfrastructureMachineTemplate objects. func InfrastructureMachineTemplate() *InfrastructureMachineTemplateContract { diff --git a/internal/controllers/cluster/cluster_controller.go b/internal/controllers/cluster/cluster_controller.go index ae61275377f6..eb737ea6f02d 100644 --- a/internal/controllers/cluster/cluster_controller.go +++ b/internal/controllers/cluster/cluster_controller.go @@ -86,7 +86,6 @@ func (r *Reconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, opt WithOptions(options). WithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)). Build(r) - if err != nil { return errors.Wrap(err, "failed setting up with a controller manager") } diff --git a/internal/controllers/clusterclass/clusterclass_controller.go b/internal/controllers/clusterclass/clusterclass_controller.go index 9f8b483d357a..b28a0c0e206b 100644 --- a/internal/controllers/clusterclass/clusterclass_controller.go +++ b/internal/controllers/clusterclass/clusterclass_controller.go @@ -84,7 +84,6 @@ func (r *Reconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, opt ). WithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)). Complete(r) - if err != nil { return errors.Wrap(err, "failed setting up with a controller manager") } @@ -319,7 +318,8 @@ func addNewStatusVariable(variable clusterv1.ClusterClassVariable, from string) Required: variable.Required, Schema: variable.Schema, }, - }} + }, + } } func addDefinitionToExistingStatusVariable(variable clusterv1.ClusterClassVariable, from string, existingVariable *clusterv1.ClusterClassStatusVariable) *clusterv1.ClusterClassStatusVariable { diff --git a/internal/controllers/clusterclass/clusterclass_controller_test.go b/internal/controllers/clusterclass/clusterclass_controller_test.go index 15fbe79573ee..edda7defa6a7 100644 --- a/internal/controllers/clusterclass/clusterclass_controller_test.go +++ b/internal/controllers/clusterclass/clusterclass_controller_test.go @@ -171,6 +171,7 @@ func assertStatusVariables(actualClusterClass *clusterv1.ClusterClass) error { } return nil } + func assertInfrastructureClusterTemplate(ctx context.Context, actualClusterClass *clusterv1.ClusterClass, ns *corev1.Namespace) error { // Assert the infrastructure cluster template has the correct owner reference. actualInfraClusterTemplate := builder.InfrastructureClusterTemplate("", "").Build() @@ -391,7 +392,9 @@ func TestReconciler_reconcileVariables(t *testing.T) { Name: "patch1", External: &clusterv1.ExternalPatchDefinition{ DiscoverVariablesExtension: pointer.String("variables-one"), - }}}). + }, + }, + }). Build(), patchResponse: &runtimehooksv1.DiscoverVariablesResponse{ CommonResponse: runtimehooksv1.CommonResponse{ @@ -494,7 +497,9 @@ func TestReconciler_reconcileVariables(t *testing.T) { Name: "patch1", External: &clusterv1.ExternalPatchDefinition{ DiscoverVariablesExtension: pointer.String("variables-one"), - }}}). + }, + }, + }). Build(), patchResponse: &runtimehooksv1.DiscoverVariablesResponse{ CommonResponse: runtimehooksv1.CommonResponse{ diff --git a/internal/controllers/clusterclass/suite_test.go b/internal/controllers/clusterclass/suite_test.go index 484c0d3bb81c..759ed81d37e4 100644 --- a/internal/controllers/clusterclass/suite_test.go +++ b/internal/controllers/clusterclass/suite_test.go @@ -52,6 +52,7 @@ func init() { _ = clusterv1.AddToScheme(fakeScheme) _ = apiextensionsv1.AddToScheme(fakeScheme) } + func TestMain(m *testing.M) { if err := feature.Gates.(featuregate.MutableFeatureGate).Set(fmt.Sprintf("%s=%v", feature.ClusterTopology, true)); err != nil { panic(fmt.Sprintf("unable to set ClusterTopology feature gate: %v", err)) diff --git a/internal/controllers/machine/machine_controller.go b/internal/controllers/machine/machine_controller.go index 4335bac6c2d4..1c08083af078 100644 --- a/internal/controllers/machine/machine_controller.go +++ b/internal/controllers/machine/machine_controller.go @@ -311,7 +311,7 @@ func (r *Reconciler) reconcileDelete(ctx context.Context, cluster *clusterv1.Clu if err != nil { switch err { case errNoControlPlaneNodes, errLastControlPlaneNode, errNilNodeRef, errClusterIsBeingDeleted, errControlPlaneIsBeingDeleted: - var nodeName = "" + nodeName := "" if m.Status.NodeRef != nil { nodeName = m.Status.NodeRef.Name } diff --git a/internal/controllers/machine/machine_controller_noderef.go b/internal/controllers/machine/machine_controller_noderef.go index 796b6c764791..d6b12cdecaba 100644 --- a/internal/controllers/machine/machine_controller_noderef.go +++ b/internal/controllers/machine/machine_controller_noderef.go @@ -37,10 +37,8 @@ import ( "sigs.k8s.io/cluster-api/util/conditions" ) -var ( - // ErrNodeNotFound signals that a corev1.Node could not be found for the given provider id. - ErrNodeNotFound = errors.New("cannot find node with matching ProviderID") -) +// ErrNodeNotFound signals that a corev1.Node could not be found for the given provider id. +var ErrNodeNotFound = errors.New("cannot find node with matching ProviderID") func (r *Reconciler) reconcileNode(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) (ctrl.Result, error) { log := ctrl.LoggerFrom(ctx) diff --git a/internal/controllers/machine/machine_controller_phases.go b/internal/controllers/machine/machine_controller_phases.go index 83c493afc0c4..5edfdc3dad2a 100644 --- a/internal/controllers/machine/machine_controller_phases.go +++ b/internal/controllers/machine/machine_controller_phases.go @@ -43,9 +43,7 @@ import ( "sigs.k8s.io/cluster-api/util/patch" ) -var ( - externalReadyWait = 30 * time.Second -) +var externalReadyWait = 30 * time.Second func (r *Reconciler) reconcilePhase(_ context.Context, m *clusterv1.Machine) { originalPhase := m.Status.Phase diff --git a/internal/controllers/machine/machine_controller_test.go b/internal/controllers/machine/machine_controller_test.go index 4464f21f66cc..92c002dad0db 100644 --- a/internal/controllers/machine/machine_controller_test.go +++ b/internal/controllers/machine/machine_controller_test.go @@ -150,7 +150,8 @@ func TestWatches(t *testing.T) { Kind: "GenericBootstrapConfig", Name: "bootstrap-config-machinereconcile", }, - }}, + }, + }, } g.Expect(env.Create(ctx, machine)).To(BeNil()) @@ -250,7 +251,8 @@ func TestMachine_Reconcile(t *testing.T) { Kind: "GenericBootstrapConfig", Name: "bootstrap-config-machinereconcile", }, - }}, + }, + }, Status: clusterv1.MachineStatus{ NodeRef: &corev1.ObjectReference{ Name: "test", @@ -1869,7 +1871,8 @@ func TestNodeToMachine(t *testing.T) { Kind: "GenericBootstrapConfig", Name: "bootstrap-config-machinereconcile", }, - }}, + }, + }, } g.Expect(env.Create(ctx, expectedMachine)).To(BeNil()) @@ -1908,7 +1911,8 @@ func TestNodeToMachine(t *testing.T) { Kind: "GenericBootstrapConfig", Name: "bootstrap-config-machinereconcile", }, - }}, + }, + }, } g.Expect(env.Create(ctx, randomMachine)).To(BeNil()) diff --git a/internal/controllers/machinedeployment/machinedeployment_controller.go b/internal/controllers/machinedeployment/machinedeployment_controller.go index ce19faef945f..9125a315b3c9 100644 --- a/internal/controllers/machinedeployment/machinedeployment_controller.go +++ b/internal/controllers/machinedeployment/machinedeployment_controller.go @@ -47,10 +47,8 @@ import ( "sigs.k8s.io/cluster-api/util/predicates" ) -var ( - // machineDeploymentKind contains the schema.GroupVersionKind for the MachineDeployment type. - machineDeploymentKind = clusterv1.GroupVersion.WithKind("MachineDeployment") -) +// machineDeploymentKind contains the schema.GroupVersionKind for the MachineDeployment type. +var machineDeploymentKind = clusterv1.GroupVersion.WithKind("MachineDeployment") // machineDeploymentManagerName is the manager name used for Server-Side-Apply (SSA) operations // in the MachineDeployment controller. diff --git a/internal/controllers/machinedeployment/machinedeployment_rolling.go b/internal/controllers/machinedeployment/machinedeployment_rolling.go index ffc7acc19943..15c2ea59cfc6 100644 --- a/internal/controllers/machinedeployment/machinedeployment_rolling.go +++ b/internal/controllers/machinedeployment/machinedeployment_rolling.go @@ -98,7 +98,7 @@ func (r *Reconciler) reconcileNewMachineSet(ctx context.Context, allMSs []*clust return r.scaleMachineSet(ctx, newMS, newReplicasCount, deployment) } -func (r *Reconciler) reconcileOldMachineSets(ctx context.Context, allMSs []*clusterv1.MachineSet, oldMSs []*clusterv1.MachineSet, newMS *clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) error { +func (r *Reconciler) reconcileOldMachineSets(ctx context.Context, allMSs, oldMSs []*clusterv1.MachineSet, newMS *clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) error { log := ctrl.LoggerFrom(ctx) if deployment.Spec.Replicas == nil { @@ -237,7 +237,7 @@ func (r *Reconciler) cleanupUnhealthyReplicas(ctx context.Context, oldMSs []*clu // scaleDownOldMachineSetsForRollingUpdate scales down old MachineSets when deployment strategy is "RollingUpdate". // Need check maxUnavailable to ensure availability. -func (r *Reconciler) scaleDownOldMachineSetsForRollingUpdate(ctx context.Context, allMSs []*clusterv1.MachineSet, oldMSs []*clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) (int32, error) { +func (r *Reconciler) scaleDownOldMachineSetsForRollingUpdate(ctx context.Context, allMSs, oldMSs []*clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) (int32, error) { log := ctrl.LoggerFrom(ctx) if deployment.Spec.Replicas == nil { diff --git a/internal/controllers/machinedeployment/machinedeployment_rollout_ondelete.go b/internal/controllers/machinedeployment/machinedeployment_rollout_ondelete.go index 107d65e506d9..130fee20620a 100644 --- a/internal/controllers/machinedeployment/machinedeployment_rollout_ondelete.go +++ b/internal/controllers/machinedeployment/machinedeployment_rollout_ondelete.go @@ -75,7 +75,7 @@ func (r *Reconciler) rolloutOnDelete(ctx context.Context, md *clusterv1.MachineD } // reconcileOldMachineSetsOnDelete handles reconciliation of Old MachineSets associated with the MachineDeployment in the OnDelete MachineDeploymentStrategyType. -func (r *Reconciler) reconcileOldMachineSetsOnDelete(ctx context.Context, oldMSs []*clusterv1.MachineSet, allMSs []*clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) error { +func (r *Reconciler) reconcileOldMachineSetsOnDelete(ctx context.Context, oldMSs, allMSs []*clusterv1.MachineSet, deployment *clusterv1.MachineDeployment) error { log := ctrl.LoggerFrom(ctx) if deployment.Spec.Replicas == nil { return errors.Errorf("spec replicas for MachineDeployment %q/%q is nil, this is unexpected", diff --git a/internal/controllers/machinedeployment/machinedeployment_sync_test.go b/internal/controllers/machinedeployment/machinedeployment_sync_test.go index f5be0ed01a7d..0d58ee573364 100644 --- a/internal/controllers/machinedeployment/machinedeployment_sync_test.go +++ b/internal/controllers/machinedeployment/machinedeployment_sync_test.go @@ -43,7 +43,7 @@ import ( func TestCalculateStatus(t *testing.T) { msStatusError := capierrors.MachineSetStatusError("some failure") - var tests = map[string]struct { + tests := map[string]struct { machineSets []*clusterv1.MachineSet newMachineSet *clusterv1.MachineSet deployment *clusterv1.MachineDeployment @@ -719,7 +719,7 @@ func TestComputeDesiredMachineSet(t *testing.T) { }) } -func assertMachineSet(g *WithT, actualMS *clusterv1.MachineSet, expectedMS *clusterv1.MachineSet) { +func assertMachineSet(g *WithT, actualMS, expectedMS *clusterv1.MachineSet) { // check UID if expectedMS.UID != "" { g.Expect(actualMS.UID).Should(Equal(expectedMS.UID)) diff --git a/internal/controllers/machinedeployment/mdutil/util.go b/internal/controllers/machinedeployment/mdutil/util.go index b6f99693ecb2..144c8b4b1488 100644 --- a/internal/controllers/machinedeployment/mdutil/util.go +++ b/internal/controllers/machinedeployment/mdutil/util.go @@ -428,7 +428,7 @@ func FindNewMachineSet(deployment *clusterv1.MachineDeployment, msList []*cluste return nil } -func shouldRolloutAfter(ms *clusterv1.MachineSet, reconciliationTime *metav1.Time, rolloutAfter *metav1.Time) bool { +func shouldRolloutAfter(ms *clusterv1.MachineSet, reconciliationTime, rolloutAfter *metav1.Time) bool { if ms == nil { return false } diff --git a/internal/controllers/machinedeployment/mdutil/util_test.go b/internal/controllers/machinedeployment/mdutil/util_test.go index 8feed22a63aa..fdee8405280e 100644 --- a/internal/controllers/machinedeployment/mdutil/util_test.go +++ b/internal/controllers/machinedeployment/mdutil/util_test.go @@ -961,7 +961,7 @@ func TestComputeMachineSetAnnotations(t *testing.T) { } } -func machineSetWithRevisionAndHistory(revision string, revisionHistory string) *clusterv1.MachineSet { +func machineSetWithRevisionAndHistory(revision, revisionHistory string) *clusterv1.MachineSet { ms := &clusterv1.MachineSet{ ObjectMeta: metav1.ObjectMeta{ Annotations: map[string]string{ diff --git a/internal/controllers/machinehealthcheck/machinehealthcheck_targets.go b/internal/controllers/machinehealthcheck/machinehealthcheck_targets.go index 5d174fb63155..10965fb644a7 100644 --- a/internal/controllers/machinehealthcheck/machinehealthcheck_targets.go +++ b/internal/controllers/machinehealthcheck/machinehealthcheck_targets.go @@ -47,10 +47,8 @@ const ( EventDetectedUnhealthy string = "DetectedUnhealthy" ) -var ( - // We allow users to disable the nodeStartupTimeout by setting the duration to 0. - disabledNodeStartupTimeout = clusterv1.ZeroDuration -) +// We allow users to disable the nodeStartupTimeout by setting the duration to 0. +var disabledNodeStartupTimeout = clusterv1.ZeroDuration // healthCheckTarget contains the information required to perform a health check // on the node to determine if any remediation is required. diff --git a/internal/controllers/machinehealthcheck/machinehealthcheck_targets_test.go b/internal/controllers/machinehealthcheck/machinehealthcheck_targets_test.go index da94b56d157e..5505a7322630 100644 --- a/internal/controllers/machinehealthcheck/machinehealthcheck_targets_test.go +++ b/internal/controllers/machinehealthcheck/machinehealthcheck_targets_test.go @@ -543,6 +543,6 @@ func newTestUnhealthyNode(name string, condition corev1.NodeConditionType, statu } } -func newFailedHealthCheckCondition(reason string, messageFormat string, messageArgs ...interface{}) clusterv1.Condition { +func newFailedHealthCheckCondition(reason, messageFormat string, messageArgs ...interface{}) clusterv1.Condition { return *conditions.FalseCondition(clusterv1.MachineHealthCheckSucceededCondition, reason, clusterv1.ConditionSeverityWarning, messageFormat, messageArgs...) } diff --git a/internal/controllers/machineset/machineset_controller_test.go b/internal/controllers/machineset/machineset_controller_test.go index 01e55825ecd0..438a0be0cbe0 100644 --- a/internal/controllers/machineset/machineset_controller_test.go +++ b/internal/controllers/machineset/machineset_controller_test.go @@ -919,16 +919,17 @@ func TestMachineSetReconciler_updateStatusResizedCondition(t *testing.T) { { name: "MachineSet should have ResizedCondition=false on scale down", machineSet: newMachineSet("ms-scale-down", cluster.Name, int32(0)), - machines: []*clusterv1.Machine{{ - ObjectMeta: metav1.ObjectMeta{ - Name: "machine-a", - Namespace: metav1.NamespaceDefault, - Labels: map[string]string{ - clusterv1.ClusterNameLabel: cluster.Name, + machines: []*clusterv1.Machine{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "machine-a", + Namespace: metav1.NamespaceDefault, + Labels: map[string]string{ + clusterv1.ClusterNameLabel: cluster.Name, + }, }, }, }, - }, expectedReason: clusterv1.ScalingDownReason, expectedMessage: "Scaling down MachineSet to 0 replicas (actual 1)", }, @@ -1448,7 +1449,7 @@ func TestComputeDesiredMachine(t *testing.T) { } } -func assertMachine(g *WithT, actualMachine *clusterv1.Machine, expectedMachine *clusterv1.Machine) { +func assertMachine(g *WithT, actualMachine, expectedMachine *clusterv1.Machine) { // Check Name if expectedMachine.Name != "" { g.Expect(actualMachine.Name).Should(Equal(expectedMachine.Name)) diff --git a/internal/controllers/topology/cluster/blueprint_test.go b/internal/controllers/topology/cluster/blueprint_test.go index ecf900a6322e..7d39bd301a62 100644 --- a/internal/controllers/topology/cluster/blueprint_test.go +++ b/internal/controllers/topology/cluster/blueprint_test.go @@ -60,7 +60,8 @@ func TestGetBlueprint(t *testing.T) { Build() machineHealthCheck := &clusterv1.MachineHealthCheckClass{ NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(1)}, + Duration: time.Duration(1), + }, } machineDeployment := builder.MachineDeploymentClass("workerclass1"). diff --git a/internal/controllers/topology/cluster/cluster_controller.go b/internal/controllers/topology/cluster/cluster_controller.go index b600e6e56dcb..aeea270ef8bc 100644 --- a/internal/controllers/topology/cluster/cluster_controller.go +++ b/internal/controllers/topology/cluster/cluster_controller.go @@ -107,7 +107,6 @@ func (r *Reconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, opt WithOptions(options). WithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)). Build(r) - if err != nil { return errors.Wrap(err, "failed setting up with a controller manager") } diff --git a/internal/controllers/topology/cluster/cluster_controller_test.go b/internal/controllers/topology/cluster/cluster_controller_test.go index 646725d5affe..a6cdeaf36660 100644 --- a/internal/controllers/topology/cluster/cluster_controller_test.go +++ b/internal/controllers/topology/cluster/cluster_controller_test.go @@ -1189,7 +1189,8 @@ func TestReconciler_DefaultCluster(t *testing.T) { }, }, }, - }}...). + }, + }...). Build(), initialCluster: clusterBuilder.DeepCopy(). WithTopology(topologyBase.DeepCopy(). @@ -1231,7 +1232,7 @@ func TestReconciler_DefaultCluster(t *testing.T) { APIReader: fakeClient, } // Ignore the error here as we expect the ClusterClass to fail in reconciliation as its references do not exist. - var _, _ = r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKey{Name: tt.initialCluster.Name, Namespace: tt.initialCluster.Namespace}}) + _, _ = r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKey{Name: tt.initialCluster.Name, Namespace: tt.initialCluster.Namespace}}) got := &clusterv1.Cluster{} g.Expect(fakeClient.Get(ctx, client.ObjectKey{Name: tt.initialCluster.Name, Namespace: tt.initialCluster.Namespace}, got)).To(Succeed()) // Compare the spec of the two clusters to ensure that variables are defaulted correctly. @@ -1319,7 +1320,7 @@ func TestReconciler_ValidateCluster(t *testing.T) { Client: fakeClient, APIReader: fakeClient, } - var _, err = r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKey{Name: tt.cluster.Name, Namespace: tt.cluster.Namespace}}) + _, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: client.ObjectKey{Name: tt.cluster.Name, Namespace: tt.cluster.Namespace}}) // Reconcile will always return an error here as the topology is incomplete. This test checks specifically for // validation errors. validationErrMessage := fmt.Sprintf("Cluster.cluster.x-k8s.io %q is invalid:", tt.cluster.Name) diff --git a/internal/controllers/topology/cluster/current_state_test.go b/internal/controllers/topology/cluster/current_state_test.go index d30c3ef42078..e8d62f796525 100644 --- a/internal/controllers/topology/cluster/current_state_test.go +++ b/internal/controllers/topology/cluster/current_state_test.go @@ -400,7 +400,8 @@ func TestGetCurrentState(t *testing.T) { ControlPlane: &scope.ControlPlaneState{}, InfrastructureCluster: nil, MachineDeployments: map[string]*scope.MachineDeploymentState{ - "md1": {Object: machineDeployment, BootstrapTemplate: machineDeploymentBootstrap, InfrastructureMachineTemplate: machineDeploymentInfrastructure}}, + "md1": {Object: machineDeployment, BootstrapTemplate: machineDeploymentBootstrap, InfrastructureMachineTemplate: machineDeploymentInfrastructure}, + }, }, }, { diff --git a/internal/controllers/topology/cluster/desired_state.go b/internal/controllers/topology/cluster/desired_state.go index 78587e828517..778eab0b28af 100644 --- a/internal/controllers/topology/cluster/desired_state.go +++ b/internal/controllers/topology/cluster/desired_state.go @@ -1055,9 +1055,10 @@ func selectorForControlPlaneMHC() *metav1.LabelSelector { func selectorForMachineDeploymentMHC(md *clusterv1.MachineDeployment) *metav1.LabelSelector { // The selector returned here is the minimal common selector for all MachineSets belonging to a MachineDeployment. // It does not include any labels set in ClusterClass, Cluster Topology or elsewhere. - return &metav1.LabelSelector{MatchLabels: map[string]string{ - clusterv1.ClusterTopologyOwnedLabel: "", - clusterv1.ClusterTopologyMachineDeploymentNameLabel: md.Spec.Selector.MatchLabels[clusterv1.ClusterTopologyMachineDeploymentNameLabel], - }, + return &metav1.LabelSelector{ + MatchLabels: map[string]string{ + clusterv1.ClusterTopologyOwnedLabel: "", + clusterv1.ClusterTopologyMachineDeploymentNameLabel: md.Spec.Selector.MatchLabels[clusterv1.ClusterTopologyMachineDeploymentNameLabel], + }, } } diff --git a/internal/controllers/topology/cluster/desired_state_test.go b/internal/controllers/topology/cluster/desired_state_test.go index 05f889f2133f..0fcc39984601 100644 --- a/internal/controllers/topology/cluster/desired_state_test.go +++ b/internal/controllers/topology/cluster/desired_state_test.go @@ -1414,7 +1414,8 @@ func TestComputeMachineDeployment(t *testing.T) { MachineHealthCheck: &clusterv1.MachineHealthCheckClass{ UnhealthyConditions: unhealthyConditions, NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(1)}, + Duration: time.Duration(1), + }, }, }, }, @@ -2305,7 +2306,8 @@ func Test_computeMachineHealthCheck(t *testing.T) { }, }, NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(1)}, + Duration: time.Duration(1), + }, } selector := &metav1.LabelSelector{MatchLabels: map[string]string{ "foo": "bar", @@ -2343,7 +2345,8 @@ func Test_computeMachineHealthCheck(t *testing.T) { }, }, NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(1)}, + Duration: time.Duration(1), + }, }, } diff --git a/internal/controllers/topology/cluster/patches/engine_test.go b/internal/controllers/topology/cluster/patches/engine_test.go index 4db0384d909d..05fdb6c89914 100644 --- a/internal/controllers/topology/cluster/patches/engine_test.go +++ b/internal/controllers/topology/cluster/patches/engine_test.go @@ -374,7 +374,8 @@ func TestApply(t *testing.T) { Patch: bytesPatch([]jsonPatchRFC6902{{ Op: "add", Path: "/spec/template/spec/resource", - Value: &apiextensionsv1.JSON{Raw: []byte(`"infraCluster"`)}}}), + Value: &apiextensionsv1.JSON{Raw: []byte(`"infraCluster"`)}, + }}), }, }, }, @@ -410,7 +411,8 @@ func TestApply(t *testing.T) { Patch: bytesPatch([]jsonPatchRFC6902{{ Op: "add", Path: "/spec/template/spec/resource", - Value: &apiextensionsv1.JSON{Raw: []byte(`"invalid-infraCluster"`)}}}), + Value: &apiextensionsv1.JSON{Raw: []byte(`"invalid-infraCluster"`)}, + }}), }, }, }, @@ -449,7 +451,8 @@ func TestApply(t *testing.T) { Patch: bytesPatch([]jsonPatchRFC6902{{ Op: "add", Path: "/spec/template/spec/resource", - Value: &apiextensionsv1.JSON{Raw: []byte(`"infraCluster"`)}}}), + Value: &apiextensionsv1.JSON{Raw: []byte(`"infraCluster"`)}, + }}), }, { UID: "1", @@ -457,7 +460,8 @@ func TestApply(t *testing.T) { Patch: bytesPatch([]jsonPatchRFC6902{{ Op: "add", Path: "/spec/template/spec/another", - Value: &apiextensionsv1.JSON{Raw: []byte(`"resource"`)}}}), + Value: &apiextensionsv1.JSON{Raw: []byte(`"resource"`)}, + }}), }, }, }, @@ -466,7 +470,8 @@ func TestApply(t *testing.T) { { UID: "2", PatchType: runtimehooksv1.JSONMergePatchType, - Patch: []byte(`{"spec":{"template":{"spec":{"resource": "controlPlane"}}}}`)}, + Patch: []byte(`{"spec":{"template":{"spec":{"resource": "controlPlane"}}}}`), + }, }, }, }, diff --git a/internal/controllers/topology/cluster/patches/inline/json_patch_generator_test.go b/internal/controllers/topology/cluster/patches/inline/json_patch_generator_test.go index 072cd1593b57..484c82b788c9 100644 --- a/internal/controllers/topology/cluster/patches/inline/json_patch_generator_test.go +++ b/internal/controllers/topology/cluster/patches/inline/json_patch_generator_test.go @@ -1601,7 +1601,8 @@ func TestRenderValueTemplate(t *testing.T) { variables: map[string]apiextensionsv1.JSON{ patchvariables.BuiltinsName: {Raw: []byte(`{"cluster":{"name":"cluster1"}}`)}, }, - want: &apiextensionsv1.JSON{Raw: []byte(` + want: &apiextensionsv1.JSON{ + Raw: []byte(` [{ "contentFrom":{ "secret":{ @@ -1625,7 +1626,8 @@ owner: root:root variables: map[string]apiextensionsv1.JSON{ patchvariables.BuiltinsName: {Raw: []byte(`{"cluster":{"name":"cluster1"}}`)}, }, - want: &apiextensionsv1.JSON{Raw: []byte(` + want: &apiextensionsv1.JSON{ + Raw: []byte(` { "contentFrom":{ "secret":{ @@ -1653,7 +1655,8 @@ owner: root:root variables: map[string]apiextensionsv1.JSON{ patchvariables.BuiltinsName: {Raw: []byte(`{"cluster":{"name":"cluster1"}}`)}, }, - want: &apiextensionsv1.JSON{Raw: []byte(` + want: &apiextensionsv1.JSON{ + Raw: []byte(` [{ "contentFrom":{ "secret":{ @@ -1680,7 +1683,8 @@ owner: root:root variables: map[string]apiextensionsv1.JSON{ patchvariables.BuiltinsName: {Raw: []byte(`{"cluster":{"name":"cluster1"}}`)}, }, - want: &apiextensionsv1.JSON{Raw: []byte(` + want: &apiextensionsv1.JSON{ + Raw: []byte(` { "contentFrom":{ "secret":{ diff --git a/internal/controllers/topology/cluster/reconcile_state_test.go b/internal/controllers/topology/cluster/reconcile_state_test.go index 7feb3e2be1a1..5a66e2562026 100644 --- a/internal/controllers/topology/cluster/reconcile_state_test.go +++ b/internal/controllers/topology/cluster/reconcile_state_test.go @@ -50,11 +50,9 @@ import ( "sigs.k8s.io/cluster-api/internal/util/ssa" ) -var ( - IgnoreNameGenerated = IgnorePaths{ - "metadata.name", - } -) +var IgnoreNameGenerated = IgnorePaths{ + "metadata.name", +} func TestReconcileShim(t *testing.T) { infrastructureCluster := builder.TestInfrastructureCluster(metav1.NamespaceDefault, "infrastructure-cluster1").Build() @@ -292,7 +290,6 @@ func TestReconcile_callAfterControlPlaneInitialized(t *testing.T) { } successResponse := &runtimehooksv1.AfterControlPlaneInitializedResponse{ - CommonResponse: runtimehooksv1.CommonResponse{ Status: runtimehooksv1.ResponseStatusSuccess, }, @@ -480,7 +477,6 @@ func TestReconcile_callAfterClusterUpgrade(t *testing.T) { } successResponse := &runtimehooksv1.AfterClusterUpgradeResponse{ - CommonResponse: runtimehooksv1.CommonResponse{ Status: runtimehooksv1.ResponseStatusSuccess, }, @@ -1500,7 +1496,8 @@ func TestReconcileControlPlaneMachineHealthCheck(t *testing.T) { desired: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), InfrastructureMachineTemplate: infrastructureMachineTemplate.DeepCopy(), - MachineHealthCheck: mhcBuilder.Build()}, + MachineHealthCheck: mhcBuilder.Build(), + }, want: mhcBuilder.DeepCopy(). WithDefaulter(true). Build(), @@ -1511,7 +1508,8 @@ func TestReconcileControlPlaneMachineHealthCheck(t *testing.T) { current: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), // Note this creation would be blocked by the validation Webhook. MHC with no MachineInfrastructure is not allowed. - MachineHealthCheck: mhcBuilder.Build()}, + MachineHealthCheck: mhcBuilder.Build(), + }, desired: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), // ControlPlane does not have defined MachineInfrastructure. @@ -1525,7 +1523,8 @@ func TestReconcileControlPlaneMachineHealthCheck(t *testing.T) { current: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), InfrastructureMachineTemplate: infrastructureMachineTemplate.DeepCopy(), - MachineHealthCheck: mhcBuilder.Build()}, + MachineHealthCheck: mhcBuilder.Build(), + }, desired: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), InfrastructureMachineTemplate: infrastructureMachineTemplate.DeepCopy(), @@ -1542,7 +1541,8 @@ func TestReconcileControlPlaneMachineHealthCheck(t *testing.T) { current: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), InfrastructureMachineTemplate: infrastructureMachineTemplate.DeepCopy(), - MachineHealthCheck: mhcBuilder.Build()}, + MachineHealthCheck: mhcBuilder.Build(), + }, desired: &scope.ControlPlaneState{ Object: controlPlane1.DeepCopy(), InfrastructureMachineTemplate: infrastructureMachineTemplate.DeepCopy(), @@ -2478,20 +2478,24 @@ func TestReconcileMachineDeploymentMachineHealthCheck(t *testing.T) { mhcBuilder.DeepCopy().Build()), }, want: []*clusterv1.MachineHealthCheck{ - mhcBuilder.DeepCopy().WithDefaulter(true).Build()}, + mhcBuilder.DeepCopy().WithDefaulter(true).Build(), + }, }, { name: "Create a new MachineHealthCheck if the MachineDeployment is modified to include one", current: []*scope.MachineDeploymentState{ newFakeMachineDeploymentTopologyState("md-1", infrastructureMachineTemplate, bootstrapTemplate, - nil)}, + nil), + }, // MHC is added in the desired state of the MachineDeployment desired: []*scope.MachineDeploymentState{ newFakeMachineDeploymentTopologyState("md-1", infrastructureMachineTemplate, bootstrapTemplate, mhcBuilder.DeepCopy().Build()), }, want: []*clusterv1.MachineHealthCheck{ - mhcBuilder.DeepCopy().WithDefaulter(true).Build()}}, + mhcBuilder.DeepCopy().WithDefaulter(true).Build(), + }, + }, { name: "Update MachineHealthCheck spec adding a field if the spec adds a field", current: []*scope.MachineDeploymentState{ @@ -2500,12 +2504,14 @@ func TestReconcileMachineDeploymentMachineHealthCheck(t *testing.T) { }, desired: []*scope.MachineDeploymentState{ newFakeMachineDeploymentTopologyState("md-1", infrastructureMachineTemplate, bootstrapTemplate, - mhcBuilder.DeepCopy().WithMaxUnhealthy(&maxUnhealthy).Build())}, + mhcBuilder.DeepCopy().WithMaxUnhealthy(&maxUnhealthy).Build()), + }, want: []*clusterv1.MachineHealthCheck{ mhcBuilder.DeepCopy(). WithMaxUnhealthy(&maxUnhealthy). WithDefaulter(true). - Build()}, + Build(), + }, }, { name: "Update MachineHealthCheck spec removing a field if the spec removes a field", diff --git a/internal/controllers/topology/cluster/suite_test.go b/internal/controllers/topology/cluster/suite_test.go index fec64edd3b35..0416b41c1550 100644 --- a/internal/controllers/topology/cluster/suite_test.go +++ b/internal/controllers/topology/cluster/suite_test.go @@ -48,6 +48,7 @@ func init() { _ = clusterv1.AddToScheme(fakeScheme) _ = apiextensionsv1.AddToScheme(fakeScheme) } + func TestMain(m *testing.M) { setupIndexes := func(ctx context.Context, mgr ctrl.Manager) { if err := index.AddDefaultIndexes(ctx, mgr); err != nil { diff --git a/internal/runtime/client/client_test.go b/internal/runtime/client/client_test.go index 27c46536cd94..9734a6683607 100644 --- a/internal/runtime/client/client_test.go +++ b/internal/runtime/client/client_test.go @@ -572,7 +572,8 @@ func TestClient_CallExtension(t *testing.T) { URL: pointer.String("https://127.0.0.1/"), CABundle: testcerts.CACert, }, - NamespaceSelector: &metav1.LabelSelector{}}, + NamespaceSelector: &metav1.LabelSelector{}, + }, Status: runtimev1.ExtensionConfigStatus{ Handlers: []runtimev1.ExtensionHandler{ { diff --git a/internal/runtime/metrics/metrics.go b/internal/runtime/metrics/metrics.go index e7fd72373c9f..e2c9139f4902 100644 --- a/internal/runtime/metrics/metrics.go +++ b/internal/runtime/metrics/metrics.go @@ -58,8 +58,10 @@ var ( Subsystem: runtimeSDKSubsystem, Name: "request_duration_seconds", Help: "Request duration in seconds, broken down by hook and host.", - Buckets: []float64{0.005, 0.025, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.25, 1.5, 2, 3, - 4, 5, 6, 8, 10, 15, 20, 30, 45, 60}, + Buckets: []float64{ + 0.005, 0.025, 0.05, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.25, 1.5, 2, 3, + 4, 5, 6, 8, 10, 15, 20, 30, 45, 60, + }, }, []string{"host", "group", "version", "hook"}), } ) diff --git a/internal/runtime/test/v1alpha1/conversion_test.go b/internal/runtime/test/v1alpha1/conversion_test.go index 289bc00b2851..9b643f382e50 100644 --- a/internal/runtime/test/v1alpha1/conversion_test.go +++ b/internal/runtime/test/v1alpha1/conversion_test.go @@ -31,7 +31,7 @@ import ( func TestConversion(t *testing.T) { g := NewWithT(t) - var c = runtimecatalog.New() + c := runtimecatalog.New() _ = AddToCatalog(c) _ = v1alpha2.AddToCatalog(c) diff --git a/internal/test/builder/bootstrap.go b/internal/test/builder/bootstrap.go index 1daf6fa394d6..6f8962b27720 100644 --- a/internal/test/builder/bootstrap.go +++ b/internal/test/builder/bootstrap.go @@ -92,13 +92,11 @@ func testBootstrapConfigCRD(gvk schema.GroupVersionKind) *apiextensionsv1.Custom }) } -var ( - bootstrapConfigSpecSchema = apiextensionsv1.JSONSchemaProps{ - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - // General purpose fields to be used in different test scenario. - "foo": {Type: "string"}, - "bar": {Type: "string"}, - }, - } -) +var bootstrapConfigSpecSchema = apiextensionsv1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + // General purpose fields to be used in different test scenario. + "foo": {Type: "string"}, + "bar": {Type: "string"}, + }, +} diff --git a/internal/test/builder/controlplane.go b/internal/test/builder/controlplane.go index e715fcd02bf9..02a073c1cc5d 100644 --- a/internal/test/builder/controlplane.go +++ b/internal/test/builder/controlplane.go @@ -99,47 +99,45 @@ func testControlPlaneCRD(gvk schema.GroupVersionKind) *apiextensionsv1.CustomRes }) } -var ( - controPlaneSpecSchema = apiextensionsv1.JSONSchemaProps{ - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - // Mandatory field from the Cluster API contract - version support - "version": { - Type: "string", - }, - // mandatory field from the Cluster API contract - replicas support - "replicas": { - Type: "integer", - Format: "int32", - }, - // mandatory field from the Cluster API contract - using Machines support - "machineTemplate": { - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - "metadata": metadataSchema, - "infrastructureRef": refSchema, - "nodeDeletionTimeout": {Type: "string"}, - "nodeDrainTimeout": {Type: "string"}, - }, +var controPlaneSpecSchema = apiextensionsv1.JSONSchemaProps{ + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + // Mandatory field from the Cluster API contract - version support + "version": { + Type: "string", + }, + // mandatory field from the Cluster API contract - replicas support + "replicas": { + Type: "integer", + Format: "int32", + }, + // mandatory field from the Cluster API contract - using Machines support + "machineTemplate": { + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "metadata": metadataSchema, + "infrastructureRef": refSchema, + "nodeDeletionTimeout": {Type: "string"}, + "nodeDrainTimeout": {Type: "string"}, }, - // General purpose fields to be used in different test scenario. - "foo": {Type: "string"}, - "bar": {Type: "string"}, - // Copy of a subset of KCP spec fields to test server side apply on deep nested structs - "kubeadmConfigSpec": { - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - "clusterConfiguration": { - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - "controllerManager": { - Type: "object", - Properties: map[string]apiextensionsv1.JSONSchemaProps{ - "extraArgs": { - Type: "object", - AdditionalProperties: &apiextensionsv1.JSONSchemaPropsOrBool{ - Schema: &apiextensionsv1.JSONSchemaProps{Type: "string"}, - }, + }, + // General purpose fields to be used in different test scenario. + "foo": {Type: "string"}, + "bar": {Type: "string"}, + // Copy of a subset of KCP spec fields to test server side apply on deep nested structs + "kubeadmConfigSpec": { + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "clusterConfiguration": { + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "controllerManager": { + Type: "object", + Properties: map[string]apiextensionsv1.JSONSchemaProps{ + "extraArgs": { + Type: "object", + AdditionalProperties: &apiextensionsv1.JSONSchemaPropsOrBool{ + Schema: &apiextensionsv1.JSONSchemaProps{Type: "string"}, }, }, }, @@ -148,5 +146,5 @@ var ( }, }, }, - } -) + }, +} diff --git a/internal/test/envtest/environment.go b/internal/test/envtest/environment.go index 38d62a356179..2cbc249c0f86 100644 --- a/internal/test/envtest/environment.go +++ b/internal/test/envtest/environment.go @@ -135,7 +135,7 @@ func Run(ctx context.Context, input RunInput) int { config := kubeconfig.FromEnvTestConfig(env.Config, &clusterv1.Cluster{ ObjectMeta: metav1.ObjectMeta{Name: "test"}, }) - if err := os.WriteFile(kubeconfigPath, config, 0600); err != nil { + if err := os.WriteFile(kubeconfigPath, config, 0o600); err != nil { panic(errors.Wrapf(err, "failed to write the test env kubeconfig")) } } @@ -168,14 +168,12 @@ func Run(ctx context.Context, input RunInput) int { return code } -var ( - cacheSyncBackoff = wait.Backoff{ - Duration: 100 * time.Millisecond, - Factor: 1.5, - Steps: 8, - Jitter: 0.4, - } -) +var cacheSyncBackoff = wait.Backoff{ + Duration: 100 * time.Millisecond, + Factor: 1.5, + Steps: 8, + Jitter: 0.4, +} // Environment encapsulates a Kubernetes local test environment. type Environment struct { diff --git a/internal/topology/variables/cluster_variable_defaulting_test.go b/internal/topology/variables/cluster_variable_defaulting_test.go index ba4b068d0cc4..72b6809fb6b0 100644 --- a/internal/topology/variables/cluster_variable_defaulting_test.go +++ b/internal/topology/variables/cluster_variable_defaulting_test.go @@ -56,7 +56,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "cpu", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -72,7 +71,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "location", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -89,7 +87,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "count", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -105,7 +102,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "correct", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -154,7 +150,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "cpu", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -178,7 +173,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "cpu", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -194,7 +188,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "correct", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -239,7 +232,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "cpu", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -334,7 +326,6 @@ func Test_DefaultClusterVariables(t *testing.T) { Name: "cpu", Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -345,7 +336,6 @@ func Test_DefaultClusterVariables(t *testing.T) { }, }, { - Required: true, From: "somepatch", Schema: clusterv1.VariableSchema{ @@ -356,7 +346,6 @@ func Test_DefaultClusterVariables(t *testing.T) { }, }, { - Required: true, From: "otherpatch", Schema: clusterv1.VariableSchema{ @@ -449,7 +438,6 @@ func Test_DefaultClusterVariables(t *testing.T) { DefinitionsConflict: true, Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -502,7 +490,6 @@ func Test_DefaultClusterVariables(t *testing.T) { DefinitionsConflict: true, Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Required: true, From: clusterv1.VariableDefinitionFromInline, Schema: clusterv1.VariableSchema{ @@ -993,7 +980,6 @@ func Test_DefaultClusterVariable(t *testing.T) { clusterClassVariable: &statusVariableDefinition{ Name: "httpProxy", ClusterClassStatusVariableDefinition: &clusterv1.ClusterClassStatusVariableDefinition{ - Required: true, Schema: clusterv1.VariableSchema{ OpenAPIV3Schema: clusterv1.JSONSchemaProps{ @@ -1146,7 +1132,6 @@ func Test_DefaultClusterVariable(t *testing.T) { clusterClassVariable: &statusVariableDefinition{ Name: "testVariable", ClusterClassStatusVariableDefinition: &clusterv1.ClusterClassStatusVariableDefinition{ - Required: true, Schema: clusterv1.VariableSchema{ OpenAPIV3Schema: clusterv1.JSONSchemaProps{ diff --git a/internal/topology/variables/cluster_variable_validation_test.go b/internal/topology/variables/cluster_variable_validation_test.go index c9abc2a24016..2ec9bac3ed3e 100644 --- a/internal/topology/variables/cluster_variable_validation_test.go +++ b/internal/topology/variables/cluster_variable_validation_test.go @@ -592,7 +592,6 @@ func Test_ValidateClusterVariables(t *testing.T) { // There are conflicting definitions which means values should include a `definitionFrom` field. Definitions: []clusterv1.ClusterClassStatusVariableDefinition{ { - Schema: clusterv1.VariableSchema{ OpenAPIV3Schema: clusterv1.JSONSchemaProps{ Type: "string", diff --git a/internal/topology/variables/utils.go b/internal/topology/variables/utils.go index 600c03f58e52..dd4f63e248b3 100644 --- a/internal/topology/variables/utils.go +++ b/internal/topology/variables/utils.go @@ -97,6 +97,7 @@ func newDefinitionsIndex(definitions []clusterv1.ClusterClassStatusVariable) def } return i } + func (i definitionsIndex) store(definition clusterv1.ClusterClassStatusVariable) { for _, d := range definition.Definitions { if _, ok := i[definition.Name]; !ok { diff --git a/internal/util/taints/taints_test.go b/internal/util/taints/taints_test.go index 2777a79e30dd..8db9b47b5bc8 100644 --- a/internal/util/taints/taints_test.go +++ b/internal/util/taints/taints_test.go @@ -40,7 +40,8 @@ func TestRemoveNodeTaint(t *testing.T) { Taints: []corev1.Taint{ taint1, taint2, - }}}, + }, + }}, dropTaint: taint1, wantTaints: []corev1.Taint{taint2}, wantModified: true, @@ -50,7 +51,8 @@ func TestRemoveNodeTaint(t *testing.T) { node: &corev1.Node{Spec: corev1.NodeSpec{ Taints: []corev1.Taint{ taint2, - }}}, + }, + }}, dropTaint: taint1, wantTaints: []corev1.Taint{taint2}, wantModified: false, @@ -60,7 +62,8 @@ func TestRemoveNodeTaint(t *testing.T) { node: &corev1.Node{Spec: corev1.NodeSpec{ Taints: []corev1.Taint{ taint1, - }}}, + }, + }}, dropTaint: taint1, wantTaints: []corev1.Taint{}, wantModified: true, diff --git a/internal/webhooks/cluster.go b/internal/webhooks/cluster.go index 0a3f255c1593..610df69a2580 100644 --- a/internal/webhooks/cluster.go +++ b/internal/webhooks/cluster.go @@ -59,8 +59,10 @@ type Cluster struct { Client client.Reader } -var _ webhook.CustomDefaulter = &Cluster{} -var _ webhook.CustomValidator = &Cluster{} +var ( + _ webhook.CustomDefaulter = &Cluster{} + _ webhook.CustomValidator = &Cluster{} +) var errClusterClassNotReconciled = errors.New("ClusterClass is not up to date") diff --git a/internal/webhooks/cluster_test.go b/internal/webhooks/cluster_test.go index 9e9a2f8fd214..4971cedf1500 100644 --- a/internal/webhooks/cluster_test.go +++ b/internal/webhooks/cluster_test.go @@ -564,7 +564,8 @@ func TestClusterDefaultAndValidateVariables(t *testing.T) { }, }, }, - }}, + }, + }, ).Build(), topology: builder.ClusterTopology(). WithVariables(clusterv1.ClusterVariable{ @@ -590,7 +591,8 @@ func TestClusterDefaultAndValidateVariables(t *testing.T) { }, }, }, - }}).Build(), + }, + }).Build(), topology: builder.ClusterTopology(). WithVariables(clusterv1.ClusterVariable{ Name: "cpu", @@ -622,7 +624,8 @@ func TestClusterDefaultAndValidateVariables(t *testing.T) { }, }, }, - }}).Build(), + }, + }).Build(), topology: builder.ClusterTopology(). WithClass("foo"). WithVersion("v1.19.1"). @@ -658,7 +661,8 @@ func TestClusterDefaultAndValidateVariables(t *testing.T) { }, }, }, - }}).Build(), + }, + }).Build(), topology: builder.ClusterTopology(). WithClass("foo"). WithVersion("v1.19.1"). @@ -706,7 +710,8 @@ func TestClusterDefaultAndValidateVariables(t *testing.T) { }, }, }, - }}).Build(), + }, + }).Build(), topology: builder.ClusterTopology(). WithClass("foo"). WithVersion("v1.19.1"). @@ -808,195 +813,211 @@ func TestClusterDefaultTopologyVersion(t *testing.T) { func TestClusterValidation(t *testing.T) { // NOTE: ClusterTopology feature flag is disabled by default, thus preventing to set Cluster.Topologies. - var ( - tests = []struct { - name string - in *clusterv1.Cluster - old *clusterv1.Cluster - expectErr bool - }{ - { - name: "should return error when cluster namespace and infrastructure ref namespace mismatch", - expectErr: true, - in: builder.Cluster("fooNamespace", "cluster1"). - WithInfrastructureCluster( - builder.InfrastructureClusterTemplate("barNamespace", "infra1").Build()). - WithControlPlane( - builder.ControlPlane("fooNamespace", "cp1").Build()). - Build(), - }, - { - name: "should return error when cluster namespace and controlPlane ref namespace mismatch", - expectErr: true, - in: builder.Cluster("fooNamespace", "cluster1"). - WithInfrastructureCluster( - builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). - WithControlPlane( - builder.ControlPlane("barNamespace", "cp1").Build()). - Build(), - }, - { - name: "should succeed when namespaces match", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithInfrastructureCluster( - builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). - WithControlPlane( - builder.ControlPlane("fooNamespace", "cp1").Build()). - Build(), - }, - { - name: "fails if topology is set but feature flag is disabled", - expectErr: true, - in: builder.Cluster("fooNamespace", "cluster1"). - WithInfrastructureCluster( - builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). - WithControlPlane( - builder.ControlPlane("fooNamespace", "cp1").Build()). - WithTopology(&clusterv1.Topology{}). - Build(), - }, - { - name: "pass with undefined CIDR ranges", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{}}, - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{}}, - }). - Build(), - }, - { - name: "pass with nil CIDR ranges", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: nil}, - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: nil}, - }). - Build(), - }, - { - name: "pass with valid IPv4 CIDR ranges", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"10.10.10.10/24"}}, - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"10.10.10.10/24"}}, - }). - Build(), - }, - { - name: "pass with valid IPv6 CIDR ranges", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64"}}, - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64"}}, - }). - Build(), - }, - { - name: "pass with valid dualstack CIDR ranges", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64", "10.10.10.10/24"}}, - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64", "10.10.10.10/24"}}, - }). - Build(), - }, - { - name: "pass if multiple CIDR ranges of IPv4 are passed", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"10.10.10.10/24", "11.11.11.11/24"}}, - }). - Build(), - }, - { - name: "pass if multiple CIDR ranges of IPv6 are passed", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"2002::1234:abcd:ffff:c0a8:101/64", "2004::1234:abcd:ffff:c0a8:101/64"}}, - }). - Build(), - }, - { - name: "pass if too many cidr ranges are specified in the clusterNetwork pods field", - expectErr: false, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Pods: &clusterv1.NetworkRanges{ - CIDRBlocks: []string{"10.10.10.10/24", "11.11.11.11/24", "12.12.12.12/24"}}}). - Build(), - }, - { - name: "fails if service cidr ranges are not valid", - expectErr: true, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Services: &clusterv1.NetworkRanges{ - // Invalid ranges: missing network suffix - CIDRBlocks: []string{"10.10.10.10", "11.11.11.11"}}}). - Build(), - }, - { - name: "fails if pod cidr ranges are not valid", - expectErr: true, - in: builder.Cluster("fooNamespace", "cluster1"). - WithClusterNetwork(&clusterv1.ClusterNetwork{ - Pods: &clusterv1.NetworkRanges{ - // Invalid ranges: missing network suffix - CIDRBlocks: []string{"10.10.10.10", "11.11.11.11"}}}). - Build(), - }, - { - name: "pass with name of under 63 characters", - expectErr: false, - in: builder.Cluster("fooNamespace", "short-name").Build(), - }, - { - name: "pass with _, -, . characters in name", - in: builder.Cluster("fooNamespace", "thisNameContains.A_Non-Alphanumeric").Build(), - expectErr: false, - }, - { - name: "fails if cluster name is longer than 63 characters", - in: builder.Cluster("fooNamespace", "thisNameIsReallyMuchLongerThanTheMaximumLengthOfSixtyThreeCharacters").Build(), - expectErr: true, - }, - { - name: "error when name starts with NonAlphanumeric character", - in: builder.Cluster("fooNamespace", "-thisNameStartsWithANonAlphanumeric").Build(), - expectErr: true, - }, - { - name: "error when name ends with NonAlphanumeric character", - in: builder.Cluster("fooNamespace", "thisNameEndsWithANonAlphanumeric.").Build(), - expectErr: true, - }, - { - name: "error when name contains invalid NonAlphanumeric character", - in: builder.Cluster("fooNamespace", "thisNameContainsInvalid!@NonAlphanumerics").Build(), - expectErr: true, - }, - } - ) + tests := []struct { + name string + in *clusterv1.Cluster + old *clusterv1.Cluster + expectErr bool + }{ + { + name: "should return error when cluster namespace and infrastructure ref namespace mismatch", + expectErr: true, + in: builder.Cluster("fooNamespace", "cluster1"). + WithInfrastructureCluster( + builder.InfrastructureClusterTemplate("barNamespace", "infra1").Build()). + WithControlPlane( + builder.ControlPlane("fooNamespace", "cp1").Build()). + Build(), + }, + { + name: "should return error when cluster namespace and controlPlane ref namespace mismatch", + expectErr: true, + in: builder.Cluster("fooNamespace", "cluster1"). + WithInfrastructureCluster( + builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). + WithControlPlane( + builder.ControlPlane("barNamespace", "cp1").Build()). + Build(), + }, + { + name: "should succeed when namespaces match", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithInfrastructureCluster( + builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). + WithControlPlane( + builder.ControlPlane("fooNamespace", "cp1").Build()). + Build(), + }, + { + name: "fails if topology is set but feature flag is disabled", + expectErr: true, + in: builder.Cluster("fooNamespace", "cluster1"). + WithInfrastructureCluster( + builder.InfrastructureClusterTemplate("fooNamespace", "infra1").Build()). + WithControlPlane( + builder.ControlPlane("fooNamespace", "cp1").Build()). + WithTopology(&clusterv1.Topology{}). + Build(), + }, + { + name: "pass with undefined CIDR ranges", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{}, + }, + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{}, + }, + }). + Build(), + }, + { + name: "pass with nil CIDR ranges", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: nil, + }, + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: nil, + }, + }). + Build(), + }, + { + name: "pass with valid IPv4 CIDR ranges", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"10.10.10.10/24"}, + }, + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"10.10.10.10/24"}, + }, + }). + Build(), + }, + { + name: "pass with valid IPv6 CIDR ranges", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64"}, + }, + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64"}, + }, + }). + Build(), + }, + { + name: "pass with valid dualstack CIDR ranges", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64", "10.10.10.10/24"}, + }, + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"2004::1234:abcd:ffff:c0a8:101/64", "10.10.10.10/24"}, + }, + }). + Build(), + }, + { + name: "pass if multiple CIDR ranges of IPv4 are passed", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"10.10.10.10/24", "11.11.11.11/24"}, + }, + }). + Build(), + }, + { + name: "pass if multiple CIDR ranges of IPv6 are passed", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"2002::1234:abcd:ffff:c0a8:101/64", "2004::1234:abcd:ffff:c0a8:101/64"}, + }, + }). + Build(), + }, + { + name: "pass if too many cidr ranges are specified in the clusterNetwork pods field", + expectErr: false, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Pods: &clusterv1.NetworkRanges{ + CIDRBlocks: []string{"10.10.10.10/24", "11.11.11.11/24", "12.12.12.12/24"}, + }, + }). + Build(), + }, + { + name: "fails if service cidr ranges are not valid", + expectErr: true, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Services: &clusterv1.NetworkRanges{ + // Invalid ranges: missing network suffix + CIDRBlocks: []string{"10.10.10.10", "11.11.11.11"}, + }, + }). + Build(), + }, + { + name: "fails if pod cidr ranges are not valid", + expectErr: true, + in: builder.Cluster("fooNamespace", "cluster1"). + WithClusterNetwork(&clusterv1.ClusterNetwork{ + Pods: &clusterv1.NetworkRanges{ + // Invalid ranges: missing network suffix + CIDRBlocks: []string{"10.10.10.10", "11.11.11.11"}, + }, + }). + Build(), + }, + { + name: "pass with name of under 63 characters", + expectErr: false, + in: builder.Cluster("fooNamespace", "short-name").Build(), + }, + { + name: "pass with _, -, . characters in name", + in: builder.Cluster("fooNamespace", "thisNameContains.A_Non-Alphanumeric").Build(), + expectErr: false, + }, + { + name: "fails if cluster name is longer than 63 characters", + in: builder.Cluster("fooNamespace", "thisNameIsReallyMuchLongerThanTheMaximumLengthOfSixtyThreeCharacters").Build(), + expectErr: true, + }, + { + name: "error when name starts with NonAlphanumeric character", + in: builder.Cluster("fooNamespace", "-thisNameStartsWithANonAlphanumeric").Build(), + expectErr: true, + }, + { + name: "error when name ends with NonAlphanumeric character", + in: builder.Cluster("fooNamespace", "thisNameEndsWithANonAlphanumeric.").Build(), + expectErr: true, + }, + { + name: "error when name contains invalid NonAlphanumeric character", + in: builder.Cluster("fooNamespace", "thisNameContainsInvalid!@NonAlphanumerics").Build(), + expectErr: true, + }, + } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { g := NewWithT(t) diff --git a/internal/webhooks/clusterclass.go b/internal/webhooks/clusterclass.go index 0e3b65886d1f..83e309c7d9e1 100644 --- a/internal/webhooks/clusterclass.go +++ b/internal/webhooks/clusterclass.go @@ -55,8 +55,10 @@ type ClusterClass struct { Client client.Reader } -var _ webhook.CustomDefaulter = &ClusterClass{} -var _ webhook.CustomValidator = &ClusterClass{} +var ( + _ webhook.CustomDefaulter = &ClusterClass{} + _ webhook.CustomValidator = &ClusterClass{} +) // Default implements defaulting for ClusterClass create and update. func (webhook *ClusterClass) Default(_ context.Context, obj runtime.Object) error { @@ -360,7 +362,8 @@ func validateMachineHealthCheckClass(fldPath *field.Path, namepace string, m *cl UnhealthyConditions: m.UnhealthyConditions, UnhealthyRange: m.UnhealthyRange, RemediationTemplate: m.RemediationTemplate, - }} + }, + } return mhc.ValidateCommonFields(fldPath) } diff --git a/internal/webhooks/clusterclass_test.go b/internal/webhooks/clusterclass_test.go index 444e9268a058..e3752903be32 100644 --- a/internal/webhooks/clusterclass_test.go +++ b/internal/webhooks/clusterclass_test.go @@ -219,7 +219,6 @@ func TestClusterClassValidation(t *testing.T) { old *clusterv1.ClusterClass expectErr bool }{ - /* CREATE Tests */ @@ -644,7 +643,9 @@ func TestClusterClassValidation(t *testing.T) { }, }, NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(6000000000000)}}). + Duration: time.Duration(6000000000000), + }, + }). Build(), }, { @@ -658,7 +659,9 @@ func TestClusterClassValidation(t *testing.T) { // No ControlPlaneMachineInfrastructure makes this an invalid creation request. WithControlPlaneMachineHealthCheck(&clusterv1.MachineHealthCheckClass{ NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(6000000000000)}}). + Duration: time.Duration(6000000000000), + }, + }). Build(), expectErr: true, }, @@ -675,7 +678,9 @@ func TestClusterClassValidation(t *testing.T) { Build()). WithControlPlaneMachineHealthCheck(&clusterv1.MachineHealthCheckClass{ NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(6000000000000)}}). + Duration: time.Duration(6000000000000), + }, + }). Build(), expectErr: true, }, @@ -702,7 +707,9 @@ func TestClusterClassValidation(t *testing.T) { }, }, NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(6000000000000)}}). + Duration: time.Duration(6000000000000), + }, + }). Build()). Build(), }, @@ -730,7 +737,9 @@ func TestClusterClassValidation(t *testing.T) { }, NodeStartupTimeout: &metav1.Duration{ // nodeStartupTimeout is too short here - 600ns. - Duration: time.Duration(600)}}). + Duration: time.Duration(600), + }, + }). Build()). Build(), expectErr: true, @@ -751,7 +760,9 @@ func TestClusterClassValidation(t *testing.T) { builder.BootstrapTemplate(metav1.NamespaceDefault, "bootstrap1").Build()). WithMachineHealthCheckClass(&clusterv1.MachineHealthCheckClass{ NodeStartupTimeout: &metav1.Duration{ - Duration: time.Duration(6000000000000)}}). + Duration: time.Duration(6000000000000), + }, + }). Build()). Build(), expectErr: true, diff --git a/internal/webhooks/patch_validation_test.go b/internal/webhooks/patch_validation_test.go index a26946edf7d7..fad4e46cc2ab 100644 --- a/internal/webhooks/patch_validation_test.go +++ b/internal/webhooks/patch_validation_test.go @@ -140,7 +140,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "", Definitions: []clusterv1.PatchDefinition{ @@ -194,7 +193,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -328,7 +326,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -371,7 +368,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -464,7 +460,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -518,7 +513,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -572,7 +566,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -626,7 +619,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -682,7 +674,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -722,7 +713,6 @@ func TestValidatePatches(t *testing.T) { }, }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -778,7 +768,6 @@ func TestValidatePatches(t *testing.T) { }, }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -818,7 +807,6 @@ func TestValidatePatches(t *testing.T) { }, }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -861,7 +849,6 @@ func TestValidatePatches(t *testing.T) { }, }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -904,7 +891,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ @@ -1353,7 +1339,6 @@ func TestValidatePatches(t *testing.T) { }, Patches: []clusterv1.ClusterClassPatch{ - { Name: "patch1", Definitions: []clusterv1.PatchDefinition{ diff --git a/internal/webhooks/runtime/extensionconfig_webhook.go b/internal/webhooks/runtime/extensionconfig_webhook.go index 1f852fea09e9..58ff42b6d2ba 100644 --- a/internal/webhooks/runtime/extensionconfig_webhook.go +++ b/internal/webhooks/runtime/extensionconfig_webhook.go @@ -49,8 +49,10 @@ func (webhook *ExtensionConfig) SetupWebhookWithManager(mgr ctrl.Manager) error // +kubebuilder:webhook:verbs=create;update,path=/validate-runtime-cluster-x-k8s-io-v1alpha1-extensionconfig,mutating=false,failurePolicy=fail,matchPolicy=Equivalent,groups=runtime.cluster.x-k8s.io,resources=extensionconfigs,versions=v1alpha1,name=validation.extensionconfig.runtime.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 // +kubebuilder:webhook:verbs=create;update,path=/mutate-runtime-cluster-x-k8s-io-v1alpha1-extensionconfig,mutating=true,failurePolicy=fail,matchPolicy=Equivalent,groups=runtime.cluster.x-k8s.io,resources=extensionconfigs,versions=v1alpha1,name=default.extensionconfig.runtime.addons.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 -var _ webhook.CustomValidator = &ExtensionConfig{} -var _ webhook.CustomDefaulter = &ExtensionConfig{} +var ( + _ webhook.CustomValidator = &ExtensionConfig{} + _ webhook.CustomDefaulter = &ExtensionConfig{} +) // Default implements webhook.Defaulter so a webhook will be registered for the type. func (webhook *ExtensionConfig) Default(_ context.Context, obj runtime.Object) error { diff --git a/internal/webhooks/runtime/extensionconfig_webhook_test.go b/internal/webhooks/runtime/extensionconfig_webhook_test.go index 1fa477cfaefc..8f4ef6f01abf 100644 --- a/internal/webhooks/runtime/extensionconfig_webhook_test.go +++ b/internal/webhooks/runtime/extensionconfig_webhook_test.go @@ -154,7 +154,8 @@ func TestExtensionConfigValidate(t *testing.T) { Port: pointer.Int32(1), Name: "foo", Namespace: "bar", - }}, + }, + }, }, } diff --git a/test/e2e/cluster_upgrade.go b/test/e2e/cluster_upgrade.go index 9971cac69069..9d1c101c3bc0 100644 --- a/test/e2e/cluster_upgrade.go +++ b/test/e2e/cluster_upgrade.go @@ -87,7 +87,7 @@ func ClusterUpgradeConformanceSpec(ctx context.Context, inputGetter func() Clust Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersionUpgradeFrom)) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersionUpgradeTo)) diff --git a/test/e2e/cluster_upgrade_runtimesdk.go b/test/e2e/cluster_upgrade_runtimesdk.go index c5d8c0b8edf4..1c1d08eea40d 100644 --- a/test/e2e/cluster_upgrade_runtimesdk.go +++ b/test/e2e/cluster_upgrade_runtimesdk.go @@ -104,7 +104,7 @@ func clusterUpgradeWithRuntimeSDKSpec(ctx context.Context, inputGetter func() cl Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersionUpgradeFrom)) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersionUpgradeTo)) @@ -358,7 +358,7 @@ func beforeClusterCreateTestHandler(ctx context.Context, c client.Client, cluste func beforeClusterUpgradeTestHandler(ctx context.Context, c client.Client, cluster types.NamespacedName, toVersion string, intervals []interface{}) { hookName := "BeforeClusterUpgrade" runtimeHookTestHandler(ctx, c, cluster, hookName, true, func() bool { - var blocked = true + blocked := true controlPlaneMachines := framework.GetControlPlaneMachinesByCluster(ctx, framework.GetControlPlaneMachinesByClusterInput{Lister: c, ClusterName: cluster.Name, Namespace: cluster.Namespace}) @@ -376,7 +376,7 @@ func beforeClusterUpgradeTestHandler(ctx context.Context, c client.Client, clust func afterControlPlaneUpgradeTestHandler(ctx context.Context, c client.Client, cluster types.NamespacedName, version string, intervals []interface{}) { hookName := "AfterControlPlaneUpgrade" runtimeHookTestHandler(ctx, c, cluster, hookName, true, func() bool { - var blocked = true + blocked := true mds := framework.GetMachineDeploymentsByCluster(ctx, framework.GetMachineDeploymentsByClusterInput{ClusterName: cluster.Name, Namespace: cluster.Namespace, Lister: c}) @@ -395,7 +395,7 @@ func afterControlPlaneUpgradeTestHandler(ctx context.Context, c client.Client, c func beforeClusterDeleteHandler(ctx context.Context, c client.Client, cluster types.NamespacedName, intervals []interface{}) { hookName := "BeforeClusterDelete" runtimeHookTestHandler(ctx, c, cluster, hookName, false, func() bool { - var blocked = true + blocked := true // If the Cluster is not found it has been deleted and the hook is unblocked. if apierrors.IsNotFound(c.Get(ctx, client.ObjectKey{Name: cluster.Name, Namespace: cluster.Namespace}, &clusterv1.Cluster{})) { @@ -425,7 +425,8 @@ func runtimeHookTestHandler(ctx context.Context, c client.Client, cluster types. // Check for the existence of the condition if withTopologyReconciledCondition is true. if withTopologyReconciledCondition { cluster := framework.GetClusterByName(ctx, framework.GetClusterByNameInput{ - Name: cluster.Name, Namespace: cluster.Namespace, Getter: c}) + Name: cluster.Name, Namespace: cluster.Namespace, Getter: c, + }) if !clusterConditionShowsHookBlocking(cluster, hookName) { return errors.Errorf("Blocking condition for %s not found on Cluster object", hookName) @@ -470,7 +471,8 @@ func dumpAndDeleteCluster(ctx context.Context, proxy framework.ClusterProxy, nam By("Deleting the workload cluster") cluster := framework.GetClusterByName(ctx, framework.GetClusterByNameInput{ - Name: clusterName, Namespace: namespace, Getter: proxy.GetClient()}) + Name: clusterName, Namespace: namespace, Getter: proxy.GetClient(), + }) // Dump all the logs from the workload cluster before deleting them. proxy.CollectWorkloadClusterLogs(ctx, @@ -482,7 +484,8 @@ func dumpAndDeleteCluster(ctx context.Context, proxy framework.ClusterProxy, nam framework.DumpAllResources(ctx, framework.DumpAllResourcesInput{ Lister: proxy.GetClient(), Namespace: namespace, - LogPath: filepath.Join(artifactFolder, "clusters-beforeClusterDelete", proxy.GetName(), "resources")}) + LogPath: filepath.Join(artifactFolder, "clusters-beforeClusterDelete", proxy.GetName(), "resources"), + }) By("Deleting the workload cluster") framework.DeleteCluster(ctx, framework.DeleteClusterInput{ diff --git a/test/e2e/clusterclass_changes.go b/test/e2e/clusterclass_changes.go index c94161a259cc..86772a74847b 100644 --- a/test/e2e/clusterclass_changes.go +++ b/test/e2e/clusterclass_changes.go @@ -119,7 +119,7 @@ func ClusterClassChangesSpec(ctx context.Context, inputGetter func() ClusterClas Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveValidVersion(input.E2EConfig.GetVariable(KubernetesVersion))) Expect(input.ModifyControlPlaneFields).ToNot(BeEmpty(), "Invalid argument. input.ModifyControlPlaneFields can't be empty when calling %s spec", specName) @@ -473,7 +473,7 @@ func rebaseClusterClassAndWait(ctx context.Context, input rebaseClusterClassAndW mgmtClient := input.ClusterProxy.GetClient() - var testWorkerLabelName = "rebase-diff" + testWorkerLabelName := "rebase-diff" // Create a new ClusterClass with a new name and the new worker label set. newClusterClass := input.ClusterClass.DeepCopy() diff --git a/test/e2e/clusterclass_rollout.go b/test/e2e/clusterclass_rollout.go index 2ed58f518b6f..4968f9f9e863 100644 --- a/test/e2e/clusterclass_rollout.go +++ b/test/e2e/clusterclass_rollout.go @@ -94,7 +94,7 @@ func ClusterClassRolloutSpec(ctx context.Context, inputGetter func() ClusterClas Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveValidVersion(input.E2EConfig.GetVariable(KubernetesVersion))) diff --git a/test/e2e/clusterctl_upgrade.go b/test/e2e/clusterctl_upgrade.go index 8ef677152763..3b0f7e142823 100644 --- a/test/e2e/clusterctl_upgrade.go +++ b/test/e2e/clusterctl_upgrade.go @@ -94,7 +94,7 @@ type ClusterctlUpgradeSpecInput struct { SkipCleanup bool // PreWaitForCluster is a function that can be used as a hook to apply extra resources (that cannot be part of the template) in the generated namespace hosting the cluster // This function is called after applying the cluster template and before waiting for the cluster resources. - PreWaitForCluster func(managementClusterProxy framework.ClusterProxy, workloadClusterNamespace string, workloadClusterName string) + PreWaitForCluster func(managementClusterProxy framework.ClusterProxy, workloadClusterNamespace, workloadClusterName string) ControlPlaneWaiters clusterctl.ControlPlaneWaiters PreInit func(managementClusterProxy framework.ClusterProxy) PreUpgrade func(managementClusterProxy framework.ClusterProxy) @@ -199,7 +199,7 @@ func ClusterctlUpgradeSpec(ctx context.Context, inputGetter func() ClusterctlUpg } Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) // Setup a Namespace where to host objects for this spec and create a watcher for the namespace events. managementClusterNamespace, managementClusterCancelWatches = setupSpecNamespace(ctx, specName, input.BootstrapClusterProxy, input.ArtifactFolder) @@ -260,7 +260,7 @@ func ClusterctlUpgradeSpec(ctx context.Context, inputGetter func() ClusterctlUpg clusterctlBinaryPath := downloadToTmpFile(ctx, initClusterctlBinaryURL) defer os.Remove(clusterctlBinaryPath) // clean up - err := os.Chmod(clusterctlBinaryPath, 0744) //nolint:gosec + err := os.Chmod(clusterctlBinaryPath, 0o744) //nolint:gosec Expect(err).ToNot(HaveOccurred(), "failed to chmod temporary file") // Adjusts the clusterctlConfigPath in case the clusterctl version <= v1.3 (thus using a config file with only the providers supported in those versions) @@ -713,7 +713,7 @@ func waitForClusterDeletedV1alpha4(ctx context.Context, input waitForClusterDele }, intervals...).Should(BeTrue()) } -func matchUnstructuredLists(l1 *unstructured.UnstructuredList, l2 *unstructured.UnstructuredList) bool { +func matchUnstructuredLists(l1, l2 *unstructured.UnstructuredList) bool { if l1 == nil && l2 == nil { return true } @@ -735,7 +735,7 @@ func matchUnstructuredLists(l1 *unstructured.UnstructuredList, l2 *unstructured. } // getValueOrFallback returns the input value unless it is empty, then it returns the fallback input. -func getValueOrFallback(value []string, fallback []string) []string { +func getValueOrFallback(value, fallback []string) []string { if value != nil { return value } diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go index f0dce8fea018..ea3ce62874e9 100644 --- a/test/e2e/e2e_suite_test.go +++ b/test/e2e/e2e_suite_test.go @@ -104,7 +104,7 @@ func TestE2E(t *testing.T) { } // ensure the artifacts folder exists - g.Expect(os.MkdirAll(artifactFolder, 0755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder) //nolint:gosec + g.Expect(os.MkdirAll(artifactFolder, 0o755)).To(Succeed(), "Invalid test suite argument. Can't create e2e.artifacts-folder %q", artifactFolder) //nolint:gosec RegisterFailHandler(Fail) diff --git a/test/e2e/k8s_conformance.go b/test/e2e/k8s_conformance.go index 675c73745e55..ebbf3865b3cc 100644 --- a/test/e2e/k8s_conformance.go +++ b/test/e2e/k8s_conformance.go @@ -64,7 +64,7 @@ func K8SConformanceSpec(ctx context.Context, inputGetter func() K8SConformanceSp Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveKey(kubetestConfigurationVariable), "% spec requires a %s variable to be defined in the config file", specName, kubetestConfigurationVariable) diff --git a/test/e2e/kcp_adoption.go b/test/e2e/kcp_adoption.go index e71af91149b5..0d46908811a7 100644 --- a/test/e2e/kcp_adoption.go +++ b/test/e2e/kcp_adoption.go @@ -87,7 +87,7 @@ func KCPAdoptionSpec(ctx context.Context, inputGetter func() KCPAdoptionSpecInpu Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) // Setup a Namespace where to host objects for this spec and create a watcher for the namespace events. diff --git a/test/e2e/kcp_remediations.go b/test/e2e/kcp_remediations.go index 64fc229b0b59..a9101229fadb 100644 --- a/test/e2e/kcp_remediations.go +++ b/test/e2e/kcp_remediations.go @@ -92,7 +92,7 @@ func KCPRemediationSpec(ctx context.Context, inputGetter func() KCPRemediationSp Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) // Setup a Namespace where to host objects for this spec and create a watcher for the namespace events. diff --git a/test/e2e/machine_pool.go b/test/e2e/machine_pool.go index 24c074a1ce70..51f95407d5ca 100644 --- a/test/e2e/machine_pool.go +++ b/test/e2e/machine_pool.go @@ -65,7 +65,7 @@ func MachinePoolSpec(ctx context.Context, inputGetter func() MachinePoolInput) { Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0755)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) //nolint:gosec + Expect(os.MkdirAll(input.ArtifactFolder, 0o755)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) //nolint:gosec Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveValidVersion(input.E2EConfig.GetVariable(KubernetesVersion))) diff --git a/test/e2e/md_remediations.go b/test/e2e/md_remediations.go index 7d95a032518f..0c305397db6b 100644 --- a/test/e2e/md_remediations.go +++ b/test/e2e/md_remediations.go @@ -65,7 +65,7 @@ func MachineDeploymentRemediationSpec(ctx context.Context, inputGetter func() Ma Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) // Setup a Namespace where to host objects for this spec and create a watcher for the namespace events. diff --git a/test/e2e/md_rollout.go b/test/e2e/md_rollout.go index 1fb3fa43ed74..4e072e504ce7 100644 --- a/test/e2e/md_rollout.go +++ b/test/e2e/md_rollout.go @@ -59,7 +59,7 @@ func MachineDeploymentRolloutSpec(ctx context.Context, inputGetter func() Machin Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveValidVersion(input.E2EConfig.GetVariable(KubernetesVersion))) diff --git a/test/e2e/md_scale.go b/test/e2e/md_scale.go index 6ab8a81c91d0..496d5ba5accc 100644 --- a/test/e2e/md_scale.go +++ b/test/e2e/md_scale.go @@ -59,7 +59,7 @@ func MachineDeploymentScaleSpec(ctx context.Context, inputGetter func() MachineD Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) Expect(input.E2EConfig.Variables).To(HaveValidVersion(input.E2EConfig.GetVariable(KubernetesVersion))) diff --git a/test/e2e/node_drain_timeout.go b/test/e2e/node_drain_timeout.go index 879a49ab14ac..2c7fa1762da0 100644 --- a/test/e2e/node_drain_timeout.go +++ b/test/e2e/node_drain_timeout.go @@ -70,7 +70,7 @@ func NodeDrainTimeoutSpec(ctx context.Context, inputGetter func() NodeDrainTimeo Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.GetIntervals(specName, "wait-deployment-available")).ToNot(BeNil()) Expect(input.E2EConfig.GetIntervals(specName, "wait-machine-deleted")).ToNot(BeNil()) diff --git a/test/e2e/quick_start.go b/test/e2e/quick_start.go index 983efdf77393..3f4abe2e705b 100644 --- a/test/e2e/quick_start.go +++ b/test/e2e/quick_start.go @@ -86,7 +86,7 @@ func QuickStartSpec(ctx context.Context, inputGetter func() QuickStartSpecInput) Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) Expect(input.E2EConfig.Variables).To(HaveKey(KubernetesVersion)) diff --git a/test/e2e/self_hosted.go b/test/e2e/self_hosted.go index cf3f19d5a346..e466a01c8aa7 100644 --- a/test/e2e/self_hosted.go +++ b/test/e2e/self_hosted.go @@ -92,7 +92,7 @@ func SelfHostedSpec(ctx context.Context, inputGetter func() SelfHostedSpecInput) Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling %s spec", specName) Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling %s spec", specName) Expect(input.BootstrapClusterProxy).ToNot(BeNil(), "Invalid argument. input.BootstrapClusterProxy can't be nil when calling %s spec", specName) - Expect(os.MkdirAll(input.ArtifactFolder, 0750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) + Expect(os.MkdirAll(input.ArtifactFolder, 0o750)).To(Succeed(), "Invalid argument. input.ArtifactFolder can't be created for %s spec", specName) if input.SkipUpgrade { // Use KubernetesVersion if no upgrade step is defined by test input. diff --git a/test/extension/handlers/topologymutation/handler_test.go b/test/extension/handlers/topologymutation/handler_test.go index 7d84842680f4..437390238c4d 100644 --- a/test/extension/handlers/topologymutation/handler_test.go +++ b/test/extension/handlers/topologymutation/handler_test.go @@ -37,9 +37,7 @@ import ( infrav1 "sigs.k8s.io/cluster-api/test/infrastructure/docker/api/v1beta1" ) -var ( - testScheme = runtime.NewScheme() -) +var testScheme = runtime.NewScheme() func init() { _ = infrav1.AddToScheme(testScheme) diff --git a/test/framework/alltypes_helpers.go b/test/framework/alltypes_helpers.go index 6d1bf2dc7f9c..35f8d6f546a5 100644 --- a/test/framework/alltypes_helpers.go +++ b/test/framework/alltypes_helpers.go @@ -141,13 +141,13 @@ func dumpObject(resource runtime.Object, logPath string) { name := metaObj.GetName() resourceFilePath := filepath.Clean(path.Join(logPath, namespace, kind, name+".yaml")) - Expect(os.MkdirAll(filepath.Dir(resourceFilePath), 0750)).To(Succeed(), "Failed to create folder %s", filepath.Dir(resourceFilePath)) + Expect(os.MkdirAll(filepath.Dir(resourceFilePath), 0o750)).To(Succeed(), "Failed to create folder %s", filepath.Dir(resourceFilePath)) - f, err := os.OpenFile(resourceFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + f, err := os.OpenFile(resourceFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) Expect(err).ToNot(HaveOccurred(), "Failed to open %s", resourceFilePath) defer f.Close() - Expect(os.WriteFile(f.Name(), resourceYAML, 0600)).To(Succeed(), "Failed to write %s", resourceFilePath) + Expect(os.WriteFile(f.Name(), resourceYAML, 0o600)).To(Succeed(), "Failed to write %s", resourceFilePath) } // capiProviderOptions returns a set of ListOptions that allows to identify all the objects belonging to Cluster API providers. diff --git a/test/framework/cluster_helpers.go b/test/framework/cluster_helpers.go index 0024274ec7e4..a220acd9f713 100644 --- a/test/framework/cluster_helpers.go +++ b/test/framework/cluster_helpers.go @@ -233,7 +233,7 @@ func DeleteClusterAndWait(ctx context.Context, input DeleteClusterAndWaitInput, Cluster: input.Cluster, }, intervals...) - //TODO: consider if to move in another func (what if there are more than one cluster?) + // TODO: consider if to move in another func (what if there are more than one cluster?) log.Logf("Check for all the Cluster API resources being deleted") Eventually(func() []*unstructured.Unstructured { return GetCAPIResources(ctx, GetCAPIResourcesInput{ diff --git a/test/framework/cluster_proxy.go b/test/framework/cluster_proxy.go index 0c30dbec68da..0b2e8233d92b 100644 --- a/test/framework/cluster_proxy.go +++ b/test/framework/cluster_proxy.go @@ -132,7 +132,7 @@ type clusterProxy struct { // NewClusterProxy returns a clusterProxy given a KubeconfigPath and the scheme defining the types hosted in the cluster. // If a kubeconfig file isn't provided, standard kubeconfig locations will be used (kubectl loading rules apply). -func NewClusterProxy(name string, kubeconfigPath string, scheme *runtime.Scheme, options ...Option) ClusterProxy { +func NewClusterProxy(name, kubeconfigPath string, scheme *runtime.Scheme, options ...Option) ClusterProxy { Expect(scheme).NotTo(BeNil(), "scheme is required for NewClusterProxy") if kubeconfigPath == "" { @@ -347,7 +347,7 @@ func getMachinePoolsInCluster(ctx context.Context, c client.Client, namespace, n return machinePoolList, nil } -func (p *clusterProxy) getKubeconfig(ctx context.Context, namespace string, name string) *api.Config { +func (p *clusterProxy) getKubeconfig(ctx context.Context, namespace, name string) *api.Config { cl := p.GetClient() secret := &corev1.Secret{} @@ -366,7 +366,7 @@ func (p *clusterProxy) getKubeconfig(ctx context.Context, namespace string, name return config } -func (p *clusterProxy) isDockerCluster(ctx context.Context, namespace string, name string) bool { +func (p *clusterProxy) isDockerCluster(ctx context.Context, namespace, name string) bool { cl := p.GetClient() cluster := &clusterv1.Cluster{} diff --git a/test/framework/clusterctl/client.go b/test/framework/clusterctl/client.go index 1fc7c3128036..31cc6359a56c 100644 --- a/test/framework/clusterctl/client.go +++ b/test/framework/clusterctl/client.go @@ -94,7 +94,7 @@ func InitWithBinary(_ context.Context, binary string, input InitInput) { cmd := exec.Command(binary, args...) //nolint:gosec // We don't care about command injection here. out, err := cmd.CombinedOutput() - _ = os.WriteFile(filepath.Join(input.LogFolder, "clusterctl-init.log"), out, 0644) //nolint:gosec // this is a log file to be shared via prow artifacts + _ = os.WriteFile(filepath.Join(input.LogFolder, "clusterctl-init.log"), out, 0o644) //nolint:gosec // this is a log file to be shared via prow artifacts var stdErr string if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { @@ -356,7 +356,7 @@ func ConfigClusterWithBinary(_ context.Context, clusterctlBinaryPath string, inp } out, err = cmd.Output() - _ = os.WriteFile(filepath.Join(input.LogFolder, fmt.Sprintf("%s-cluster-template.yaml", input.ClusterName)), out, 0644) //nolint:gosec // this is a log file to be shared via prow artifacts + _ = os.WriteFile(filepath.Join(input.LogFolder, fmt.Sprintf("%s-cluster-template.yaml", input.ClusterName)), out, 0o644) //nolint:gosec // this is a log file to be shared via prow artifacts var stdErr string if err != nil { if exitErr, ok := err.(*exec.ExitError); ok { @@ -384,7 +384,7 @@ func Move(ctx context.Context, input MoveInput) { Expect(input.FromKubeconfigPath).To(BeAnExistingFile(), "Invalid argument. input.FromKubeconfigPath must be an existing file when calling Move") Expect(input.ToKubeconfigPath).To(BeAnExistingFile(), "Invalid argument. input.ToKubeconfigPath must be an existing file when calling Move") logDir := path.Join(input.LogFolder, "logs", input.Namespace) - Expect(os.MkdirAll(logDir, 0750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for Move") + Expect(os.MkdirAll(logDir, 0o750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for Move") By("Moving workload clusters") log.Logf("clusterctl move --from-kubeconfig %s --to-kubeconfig %s --namespace %s", diff --git a/test/framework/clusterctl/clusterctl_config.go b/test/framework/clusterctl/clusterctl_config.go index 96b6d23322d3..9f492fbdf90a 100644 --- a/test/framework/clusterctl/clusterctl_config.go +++ b/test/framework/clusterctl/clusterctl_config.go @@ -44,7 +44,7 @@ func (c *clusterctlConfig) write() { data, err := yaml.Marshal(c.Values) Expect(err).ToNot(HaveOccurred(), "Failed to marshal the clusterctl config file") - Expect(os.WriteFile(c.Path, data, 0600)).To(Succeed(), "Failed to write the clusterctl config file") + Expect(os.WriteFile(c.Path, data, 0o600)).To(Succeed(), "Failed to write the clusterctl config file") } // read reads a clusterctl config file from disk. diff --git a/test/framework/clusterctl/clusterctl_helpers.go b/test/framework/clusterctl/clusterctl_helpers.go index 677afaa0c745..5407e8983ed1 100644 --- a/test/framework/clusterctl/clusterctl_helpers.go +++ b/test/framework/clusterctl/clusterctl_helpers.go @@ -56,7 +56,7 @@ func InitManagementClusterAndWatchControllerLogs(ctx context.Context, input Init Expect(input.ClusterProxy).ToNot(BeNil(), "Invalid argument. input.ClusterProxy can't be nil when calling InitManagementClusterAndWatchControllerLogs") Expect(input.ClusterctlConfigPath).To(BeAnExistingFile(), "Invalid argument. input.ClusterctlConfigPath must be an existing file when calling InitManagementClusterAndWatchControllerLogs") Expect(input.InfrastructureProviders).ToNot(BeEmpty(), "Invalid argument. input.InfrastructureProviders can't be empty when calling InitManagementClusterAndWatchControllerLogs") - Expect(os.MkdirAll(input.LogFolder, 0750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for InitManagementClusterAndWatchControllerLogs") + Expect(os.MkdirAll(input.LogFolder, 0o750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for InitManagementClusterAndWatchControllerLogs") if input.CoreProvider == "" { input.CoreProvider = config.ClusterAPIProviderName @@ -158,7 +158,7 @@ func UpgradeManagementClusterAndWait(ctx context.Context, input UpgradeManagemen Expect((input.Contract != "" && !isCustomUpgrade) || (input.Contract == "" && isCustomUpgrade)).To(BeTrue(), `Invalid argument. Either the input.Contract parameter or at least one of the following providers has to be set: input.CoreProvider, input.BootstrapProviders, input.ControlPlaneProviders, input.InfrastructureProviders, input.IPAMProviders, input.RuntimeExtensionProviders`) - Expect(os.MkdirAll(input.LogFolder, 0750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for UpgradeManagementClusterAndWait") + Expect(os.MkdirAll(input.LogFolder, 0o750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created for UpgradeManagementClusterAndWait") Upgrade(ctx, UpgradeInput{ ClusterctlConfigPath: input.ClusterctlConfigPath, diff --git a/test/framework/clusterctl/e2e_config.go b/test/framework/clusterctl/e2e_config.go index 3603b1bdf474..e9b5de0303a5 100644 --- a/test/framework/clusterctl/e2e_config.go +++ b/test/framework/clusterctl/e2e_config.go @@ -627,7 +627,7 @@ func (c *E2EConfig) GetProviderLatestVersionsByContract(contract string, provide return ret } -func (c *E2EConfig) getVersions(provider string, contract string) []string { +func (c *E2EConfig) getVersions(provider, contract string) []string { versions := []string{} for _, p := range c.Providers { if p.Name == provider { diff --git a/test/framework/clusterctl/logger/log_file.go b/test/framework/clusterctl/logger/log_file.go index 3ba48dff28d5..00491eb51cd2 100644 --- a/test/framework/clusterctl/logger/log_file.go +++ b/test/framework/clusterctl/logger/log_file.go @@ -34,9 +34,9 @@ type OpenLogFileInput struct { func OpenLogFile(input OpenLogFileInput) *LogFile { filePath := filepath.Join(input.LogFolder, input.Name) - Expect(os.MkdirAll(filepath.Dir(filePath), 0750)).To(Succeed(), "Failed to create log folder %s", filepath.Dir(filePath)) + Expect(os.MkdirAll(filepath.Dir(filePath), 0o750)).To(Succeed(), "Failed to create log folder %s", filepath.Dir(filePath)) - f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) //nolint:gosec // No security issue: filepath is safe. + f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o666) //nolint:gosec // No security issue: filepath is safe. Expect(err).ToNot(HaveOccurred(), "Failed to create log file %s", filePath) return &LogFile{ diff --git a/test/framework/clusterctl/repository.go b/test/framework/clusterctl/repository.go index 92119c1d839e..c0af665efbe2 100644 --- a/test/framework/clusterctl/repository.go +++ b/test/framework/clusterctl/repository.go @@ -75,14 +75,16 @@ func (i *CreateRepositoryInput) RegisterClusterResourceSetConfigMapTransformatio }) } -const clusterctlConfigFileName = "clusterctl-config.yaml" -const clusterctlConfigV1_2FileName = "clusterctl-config.v1.2.yaml" +const ( + clusterctlConfigFileName = "clusterctl-config.yaml" + clusterctlConfigV1_2FileName = "clusterctl-config.v1.2.yaml" +) // CreateRepository creates a clusterctl local repository based on the e2e test config, and the returns the path // to a clusterctl config file to be used for working with such repository. func CreateRepository(ctx context.Context, input CreateRepositoryInput) string { Expect(input.E2EConfig).ToNot(BeNil(), "Invalid argument. input.E2EConfig can't be nil when calling CreateRepository") - Expect(os.MkdirAll(input.RepositoryFolder, 0750)).To(Succeed(), "Failed to create the clusterctl local repository folder %s", input.RepositoryFolder) + Expect(os.MkdirAll(input.RepositoryFolder, 0o750)).To(Succeed(), "Failed to create the clusterctl local repository folder %s", input.RepositoryFolder) providers := []providerConfig{} providersV1_2 := []providerConfig{} @@ -94,10 +96,10 @@ func CreateRepository(ctx context.Context, input CreateRepositoryInput) string { Expect(err).ToNot(HaveOccurred(), "Failed to generate the manifest for %q / %q", providerLabel, version.Name) sourcePath := filepath.Join(input.RepositoryFolder, providerLabel, version.Name) - Expect(os.MkdirAll(sourcePath, 0750)).To(Succeed(), "Failed to create the clusterctl local repository folder for %q / %q", providerLabel, version.Name) + Expect(os.MkdirAll(sourcePath, 0o750)).To(Succeed(), "Failed to create the clusterctl local repository folder for %q / %q", providerLabel, version.Name) filePath := filepath.Join(sourcePath, "components.yaml") - Expect(os.WriteFile(filePath, manifest, 0600)).To(Succeed(), "Failed to write manifest in the clusterctl local repository for %q / %q", providerLabel, version.Name) + Expect(os.WriteFile(filePath, manifest, 0o600)).To(Succeed(), "Failed to write manifest in the clusterctl local repository for %q / %q", providerLabel, version.Name) destinationPath := filepath.Join(input.RepositoryFolder, providerLabel, version.Name, "components.yaml") allFiles := append(provider.Files, version.Files...) @@ -112,7 +114,7 @@ func CreateRepository(ctx context.Context, input CreateRepositoryInput) string { } destinationFile := filepath.Join(filepath.Dir(destinationPath), file.TargetName) - Expect(os.WriteFile(destinationFile, data, 0600)).To(Succeed(), "Failed to write clusterctl local repository file %q / %q", provider.Name, file.TargetName) + Expect(os.WriteFile(destinationFile, data, 0o600)).To(Succeed(), "Failed to write clusterctl local repository file %q / %q", provider.Name, file.TargetName) } } p := providerConfig{ @@ -128,7 +130,7 @@ func CreateRepository(ctx context.Context, input CreateRepositoryInput) string { // set this path to an empty file under the repository path, so test can run in isolation without user's overrides kicking in overridePath := filepath.Join(input.RepositoryFolder, "overrides") - Expect(os.MkdirAll(overridePath, 0750)).To(Succeed(), "Failed to create the clusterctl overrides folder %q", overridePath) + Expect(os.MkdirAll(overridePath, 0o750)).To(Succeed(), "Failed to create the clusterctl overrides folder %q", overridePath) // creates a clusterctl config file to be used for working with such repository clusterctlConfigFile := &clusterctlConfig{ diff --git a/test/framework/deployment_helpers.go b/test/framework/deployment_helpers.go index 8115a3297a99..5ee233b2376f 100644 --- a/test/framework/deployment_helpers.go +++ b/test/framework/deployment_helpers.go @@ -255,7 +255,7 @@ func (eh *watchPodLogsEventHandler) streamPodLogs(pod *corev1.Pod) { // Create log metadata file. logMetadataFile := filepath.Clean(path.Join(eh.input.LogPath, eh.input.DeploymentName, pod.Name, container.Name+"-log-metadata.json")) - Expect(os.MkdirAll(filepath.Dir(logMetadataFile), 0750)).To(Succeed()) + Expect(os.MkdirAll(filepath.Dir(logMetadataFile), 0o750)).To(Succeed()) metadata := logMetadata{ Job: eh.input.Namespace + "/" + eh.input.DeploymentName, @@ -268,16 +268,16 @@ func (eh *watchPodLogsEventHandler) streamPodLogs(pod *corev1.Pod) { } metadataBytes, err := json.Marshal(&metadata) Expect(err).To(BeNil()) - Expect(os.WriteFile(logMetadataFile, metadataBytes, 0600)).To(Succeed()) + Expect(os.WriteFile(logMetadataFile, metadataBytes, 0o600)).To(Succeed()) // Watch each container's logs in a goroutine so we can stream them all concurrently. go func(pod *corev1.Pod, container corev1.Container) { defer GinkgoRecover() logFile := filepath.Clean(path.Join(eh.input.LogPath, eh.input.DeploymentName, pod.Name, container.Name+".log")) - Expect(os.MkdirAll(filepath.Dir(logFile), 0750)).To(Succeed()) + Expect(os.MkdirAll(filepath.Dir(logFile), 0o750)).To(Succeed()) - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) Expect(err).NotTo(HaveOccurred()) defer f.Close() @@ -383,11 +383,11 @@ func WatchPodMetrics(ctx context.Context, input WatchPodMetricsInput) { } // dumpPodMetrics captures metrics from all pods. It expects to find port 8080 open on the controller. -func dumpPodMetrics(ctx context.Context, client *kubernetes.Clientset, metricsPath string, deploymentName string, pods *corev1.PodList) { +func dumpPodMetrics(ctx context.Context, client *kubernetes.Clientset, metricsPath, deploymentName string, pods *corev1.PodList) { for _, pod := range pods.Items { metricsDir := path.Join(metricsPath, deploymentName, pod.Name) metricsFile := path.Join(metricsDir, "metrics.txt") - Expect(os.MkdirAll(metricsDir, 0750)).To(Succeed()) + Expect(os.MkdirAll(metricsDir, 0o750)).To(Succeed()) res := client.CoreV1().RESTClient().Get(). Namespace(pod.Namespace). @@ -397,14 +397,13 @@ func dumpPodMetrics(ctx context.Context, client *kubernetes.Clientset, metricsPa Suffix("metrics"). Do(ctx) data, err := res.Raw() - if err != nil { // Failing to dump metrics should not cause the test to fail data = []byte(fmt.Sprintf("Error retrieving metrics for pod %s: %v\n%s", klog.KRef(pod.Namespace, pod.Name), err, string(data))) metricsFile = path.Join(metricsDir, "metrics-error.txt") } - if err := os.WriteFile(metricsFile, data, 0600); err != nil { + if err := os.WriteFile(metricsFile, data, 0o600); err != nil { // Failing to dump metrics should not cause the test to fail log.Logf("Error writing metrics for pod %s: %v", klog.KRef(pod.Namespace, pod.Name), err) } diff --git a/test/framework/docker_logcollector.go b/test/framework/docker_logcollector.go index 0d3f80ddb332..df2bbf976774 100644 --- a/test/framework/docker_logcollector.go +++ b/test/framework/docker_logcollector.go @@ -75,7 +75,7 @@ func (k DockerLogCollector) CollectMachinePoolLog(ctx context.Context, _ client. return kerrors.NewAggregate(errs) } -func (k DockerLogCollector) collectLogsFromNode(ctx context.Context, outputPath string, containerName string) error { +func (k DockerLogCollector) collectLogsFromNode(ctx context.Context, outputPath, containerName string) error { containerRuntime, err := container.RuntimeFrom(ctx) if err != nil { return errors.Wrap(err, "Failed to collect logs from node") diff --git a/test/framework/kubetest/run.go b/test/framework/kubetest/run.go index 4e233568569c..268266c3459c 100644 --- a/test/framework/kubetest/run.go +++ b/test/framework/kubetest/run.go @@ -235,7 +235,7 @@ func discoverClusterKubernetesVersion(proxy framework.ClusterProxy) (string, err return serverVersionInfo.String(), nil } -func dockeriseKubeconfig(kubetestConfigDir string, kubeConfigPath string) (string, error) { +func dockeriseKubeconfig(kubetestConfigDir, kubeConfigPath string) (string, error) { kubeConfig, err := clientcmd.LoadFromFile(kubeConfigPath) if err != nil { return "", err diff --git a/test/framework/namespace_helpers.go b/test/framework/namespace_helpers.go index 8a6055b00a14..70b2bcd97567 100644 --- a/test/framework/namespace_helpers.go +++ b/test/framework/namespace_helpers.go @@ -132,9 +132,9 @@ func WatchNamespaceEvents(ctx context.Context, input WatchNamespaceEventsInput) Expect(input.Name).NotTo(BeEmpty(), "input.Name is required for WatchNamespaceEvents") logFile := filepath.Clean(path.Join(input.LogFolder, "resources", input.Name, "events.log")) - Expect(os.MkdirAll(filepath.Dir(logFile), 0750)).To(Succeed()) + Expect(os.MkdirAll(filepath.Dir(logFile), 0o750)).To(Succeed()) - f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) + f, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) Expect(err).NotTo(HaveOccurred()) defer f.Close() @@ -180,7 +180,7 @@ func CreateNamespaceAndWatchEvents(ctx context.Context, input CreateNamespaceAnd Expect(input.Creator).ToNot(BeNil(), "Invalid argument. input.Creator can't be nil when calling CreateNamespaceAndWatchEvents") Expect(input.ClientSet).ToNot(BeNil(), "Invalid argument. input.ClientSet can't be nil when calling ClientSet") Expect(input.Name).ToNot(BeEmpty(), "Invalid argument. input.Name can't be empty when calling ClientSet") - Expect(os.MkdirAll(input.LogFolder, 0750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created in CreateNamespaceAndWatchEvents") + Expect(os.MkdirAll(input.LogFolder, 0o750)).To(Succeed(), "Invalid argument. input.LogFolder can't be created in CreateNamespaceAndWatchEvents") namespace := CreateNamespace(ctx, CreateNamespaceInput{Creator: input.Creator, Name: input.Name}, "40s", "10s") Expect(namespace).ToNot(BeNil(), "Failed to create namespace %q", input.Name) diff --git a/test/framework/ownerreference_helpers.go b/test/framework/ownerreference_helpers.go index 2fe596e6290f..ce6e9bd224aa 100644 --- a/test/framework/ownerreference_helpers.go +++ b/test/framework/ownerreference_helpers.go @@ -281,10 +281,10 @@ func hasExactOwnersByGVK(refList []metav1.OwnerReference, wantGVKs []schema.Grou } refGVKs = append(refGVKs, refGVK) } - sort.SliceStable(refGVKs, func(i int, j int) bool { + sort.SliceStable(refGVKs, func(i, j int) bool { return refGVKs[i].String() > refGVKs[j].String() }) - sort.SliceStable(wantGVKs, func(i int, j int) bool { + sort.SliceStable(wantGVKs, func(i, j int) bool { return wantGVKs[i].String() > wantGVKs[j].String() }) if !reflect.DeepEqual(wantGVKs, refGVKs) { diff --git a/test/framework/suite_helpers.go b/test/framework/suite_helpers.go index 4db07dc7f8c0..a1086b06fac6 100644 --- a/test/framework/suite_helpers.go +++ b/test/framework/suite_helpers.go @@ -28,7 +28,7 @@ import ( // GatherJUnitReports will move JUnit files from one directory to another, // renaming them in a format expected by Prow. -func GatherJUnitReports(srcDir string, destDir string) error { +func GatherJUnitReports(srcDir, destDir string) error { if err := os.MkdirAll(srcDir, 0o700); err != nil { return err } diff --git a/test/infrastructure/container/fake.go b/test/infrastructure/container/fake.go index 7b777a759b32..8f8f92b49d8e 100644 --- a/test/infrastructure/container/fake.go +++ b/test/infrastructure/container/fake.go @@ -21,10 +21,12 @@ import ( "io" ) -var runContainerCallLog []RunContainerArgs -var deleteContainerCallLog []string -var killContainerCallLog []KillContainerArgs -var execContainerCallLog []ExecContainerArgs +var ( + runContainerCallLog []RunContainerArgs + deleteContainerCallLog []string + killContainerCallLog []KillContainerArgs + execContainerCallLog []ExecContainerArgs +) // RunContainerArgs contains the arguments passed to calls to RunContainer. type RunContainerArgs struct { @@ -46,8 +48,7 @@ type ExecContainerArgs struct { Args []string } -type FakeRuntime struct { -} +type FakeRuntime struct{} // NewFakeClient gets a client for testing. func NewFakeClient() (Runtime, error) { diff --git a/test/infrastructure/docker/api/v1beta1/dockermachinetemplate_webhook.go b/test/infrastructure/docker/api/v1beta1/dockermachinetemplate_webhook.go index adbbb231c4d7..daf40ca38316 100644 --- a/test/infrastructure/docker/api/v1beta1/dockermachinetemplate_webhook.go +++ b/test/infrastructure/docker/api/v1beta1/dockermachinetemplate_webhook.go @@ -54,7 +54,7 @@ func (*DockerMachineTemplateWebhook) ValidateCreate(_ context.Context, _ runtime } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*DockerMachineTemplateWebhook) ValidateUpdate(ctx context.Context, oldRaw runtime.Object, newRaw runtime.Object) error { +func (*DockerMachineTemplateWebhook) ValidateUpdate(ctx context.Context, oldRaw, newRaw runtime.Object) error { newObj, ok := newRaw.(*DockerMachineTemplate) if !ok { return apierrors.NewBadRequest(fmt.Sprintf("expected a DockerMachineTemplate but got a %T", newRaw)) diff --git a/test/infrastructure/docker/internal/docker/loadbalancer.go b/test/infrastructure/docker/internal/docker/loadbalancer.go index 2126165b1c1b..59f6af7f795f 100644 --- a/test/infrastructure/docker/internal/docker/loadbalancer.go +++ b/test/infrastructure/docker/internal/docker/loadbalancer.go @@ -154,7 +154,7 @@ func (s *LoadBalancer) UpdateConfiguration(ctx context.Context) error { return errors.WithStack(err) } - var backendServers = map[string]string{} + backendServers := map[string]string{} for _, n := range controlPlaneNodes { controlPlaneIPv4, controlPlaneIPv6, err := n.IP(ctx) if err != nil { diff --git a/test/infrastructure/docker/internal/docker/machine.go b/test/infrastructure/docker/internal/docker/machine.go index 054483264a9d..fd4dec0d9a10 100644 --- a/test/infrastructure/docker/internal/docker/machine.go +++ b/test/infrastructure/docker/internal/docker/machine.go @@ -197,7 +197,7 @@ func (m *Machine) ContainerImage() string { } // Create creates a docker container hosting a Kubernetes node. -func (m *Machine) Create(ctx context.Context, image string, role string, version *string, labels map[string]string, mounts []infrav1.Mount) error { +func (m *Machine) Create(ctx context.Context, image, role string, version *string, labels map[string]string, mounts []infrav1.Mount) error { log := ctrl.LoggerFrom(ctx) // Create if not exists. diff --git a/test/infrastructure/docker/internal/docker/types/node.go b/test/infrastructure/docker/internal/docker/types/node.go index 202e9e4ad0e7..ef67f198428a 100644 --- a/test/infrastructure/docker/internal/docker/types/node.go +++ b/test/infrastructure/docker/internal/docker/types/node.go @@ -69,7 +69,7 @@ func (n *Node) Role() (string, error) { } // IP gets the docker ipv4 and ipv6 of the node. -func (n *Node) IP(ctx context.Context) (ipv4 string, ipv6 string, err error) { +func (n *Node) IP(ctx context.Context) (ipv4, ipv6 string, err error) { // retrieve the IP address of the node using docker inspect containerRuntime, err := container.RuntimeFrom(ctx) if err != nil { diff --git a/test/infrastructure/docker/internal/provisioning/cloudinit/runcmd_test.go b/test/infrastructure/docker/internal/provisioning/cloudinit/runcmd_test.go index 1afb666a09e4..b787ea4516c0 100644 --- a/test/infrastructure/docker/internal/provisioning/cloudinit/runcmd_test.go +++ b/test/infrastructure/docker/internal/provisioning/cloudinit/runcmd_test.go @@ -44,7 +44,7 @@ runcmd: } func TestRunCmdRun(t *testing.T) { - var useCases = []struct { + useCases := []struct { name string r runCmd expectedCmds []provisioning.Cmd diff --git a/test/infrastructure/docker/internal/provisioning/cloudinit/writefiles_test.go b/test/infrastructure/docker/internal/provisioning/cloudinit/writefiles_test.go index e3e7fd3c2d91..fc67f5a752d2 100644 --- a/test/infrastructure/docker/internal/provisioning/cloudinit/writefiles_test.go +++ b/test/infrastructure/docker/internal/provisioning/cloudinit/writefiles_test.go @@ -27,7 +27,7 @@ import ( ) func TestWriteFiles(t *testing.T) { - var useCases = []struct { + useCases := []struct { name string w writeFilesAction expectedCmds []provisioning.Cmd @@ -101,7 +101,7 @@ func TestWriteFiles(t *testing.T) { func TestFixContent(t *testing.T) { v := "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" gv, _ := gZipData([]byte(v)) - var useCases = []struct { + useCases := []struct { name string content string encoding string diff --git a/util/annotations/helpers_test.go b/util/annotations/helpers_test.go index 9793fcf87369..fdb20fe051a2 100644 --- a/util/annotations/helpers_test.go +++ b/util/annotations/helpers_test.go @@ -27,7 +27,7 @@ import ( func TestAddAnnotations(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string obj metav1.Object input map[string]string diff --git a/util/collections/machine_collection_test.go b/util/collections/machine_collection_test.go index e3623263d9e5..42ed5505518c 100644 --- a/util/collections/machine_collection_test.go +++ b/util/collections/machine_collection_test.go @@ -166,10 +166,10 @@ func machine(name string, opts ...machineOpt) *clusterv1.Machine { func machines() collections.Machines { return collections.Machines{ - "machine-4": machine("machine-4", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 04, 02, 03, 04, 05, 06, time.UTC)})), - "machine-5": machine("machine-5", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 05, 02, 03, 04, 05, 06, time.UTC)})), - "machine-2": machine("machine-2", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 02, 02, 03, 04, 05, 06, time.UTC)})), - "machine-1": machine("machine-1", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 01, 02, 03, 04, 05, 06, time.UTC)})), - "machine-3": machine("machine-3", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 03, 02, 03, 04, 05, 06, time.UTC)})), + "machine-4": machine("machine-4", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 4, 2, 3, 4, 5, 6, time.UTC)})), + "machine-5": machine("machine-5", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 5, 2, 3, 4, 5, 6, time.UTC)})), + "machine-2": machine("machine-2", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 2, 2, 3, 4, 5, 6, time.UTC)})), + "machine-1": machine("machine-1", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 1, 2, 3, 4, 5, 6, time.UTC)})), + "machine-3": machine("machine-3", withCreationTimestamp(metav1.Time{Time: time.Date(2018, 3, 2, 3, 4, 5, 6, time.UTC)})), } } diff --git a/util/conditions/matchers.go b/util/conditions/matchers.go index a2fd651744ef..531c1377e190 100644 --- a/util/conditions/matchers.go +++ b/util/conditions/matchers.go @@ -48,6 +48,7 @@ func (matcher *conditionMatcher) Match(actual interface{}) (success bool, err er func (matcher *conditionMatcher) FailureMessage(actual interface{}) (message string) { return format.Message(actual, "to have the same state of", matcher.Expected) } + func (matcher *conditionMatcher) NegatedFailureMessage(actual interface{}) (message string) { return format.Message(actual, "not to have the same state of", matcher.Expected) } diff --git a/util/conditions/patch.go b/util/conditions/patch.go index 1724af2f771b..bc526ef03bd4 100644 --- a/util/conditions/patch.go +++ b/util/conditions/patch.go @@ -51,7 +51,7 @@ const ( ) // NewPatch returns the Patch required to align source conditions to after conditions. -func NewPatch(before Getter, after Getter) (Patch, error) { +func NewPatch(before, after Getter) (Patch, error) { var patch Patch if util.IsNil(before) { diff --git a/util/conditions/setter.go b/util/conditions/setter.go index c882b054d062..fc4c33dfa3ac 100644 --- a/util/conditions/setter.go +++ b/util/conditions/setter.go @@ -97,7 +97,7 @@ func FalseCondition(t clusterv1.ConditionType, reason string, severity clusterv1 } // UnknownCondition returns a condition with Status=Unknown and the given type. -func UnknownCondition(t clusterv1.ConditionType, reason string, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { +func UnknownCondition(t clusterv1.ConditionType, reason, messageFormat string, messageArgs ...interface{}) *clusterv1.Condition { return &clusterv1.Condition{ Type: t, Status: corev1.ConditionUnknown, diff --git a/util/conditions/setter_test.go b/util/conditions/setter_test.go index 60a7cba27c7e..1347ae1a8911 100644 --- a/util/conditions/setter_test.go +++ b/util/conditions/setter_test.go @@ -297,6 +297,7 @@ func (matcher *ConditionsMatcher) Match(actual interface{}) (success bool, err e func (matcher *ConditionsMatcher) FailureMessage(actual interface{}) (message string) { return format.Message(actual, "to have the same conditions of", matcher.Expected) } + func (matcher *ConditionsMatcher) NegatedFailureMessage(actual interface{}) (message string) { return format.Message(actual, "not to have the same conditions of", matcher.Expected) } diff --git a/util/container/image.go b/util/container/image.go index 41ae708800da..5aa08333a779 100644 --- a/util/container/image.go +++ b/util/container/image.go @@ -28,9 +28,7 @@ import ( "github.com/pkg/errors" ) -var ( - ociTagAllowedChars = regexp.MustCompile(`[^-a-zA-Z0-9_\.]`) -) +var ociTagAllowedChars = regexp.MustCompile(`[^-a-zA-Z0-9_\.]`) // Image type represents the container image details. type Image struct { diff --git a/util/conversion/conversion.go b/util/conversion/conversion.go index af1dff3c4a34..d522e9912a2d 100644 --- a/util/conversion/conversion.go +++ b/util/conversion/conversion.go @@ -50,9 +50,7 @@ const ( DataAnnotation = "cluster.x-k8s.io/conversion-data" ) -var ( - contract = clusterv1.GroupVersion.String() -) +var contract = clusterv1.GroupVersion.String() // UpdateReferenceAPIContract takes a client and object reference, queries the API Server for // the Custom Resource Definition and looks which one is the stored version available. @@ -98,7 +96,7 @@ func getLatestAPIVersionFromContract(metadata metav1.Object) (string, error) { // MarshalData stores the source object as json data in the destination object annotations map. // It ignores the metadata of the source object. -func MarshalData(src metav1.Object, dst metav1.Object) error { +func MarshalData(src, dst metav1.Object) error { u, err := runtime.DefaultUnstructuredConverter.ToUnstructured(src) if err != nil { return err diff --git a/util/conversion/conversion_test.go b/util/conversion/conversion_test.go index daa472967506..b1d61a828733 100644 --- a/util/conversion/conversion_test.go +++ b/util/conversion/conversion_test.go @@ -27,13 +27,11 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) -var ( - oldMachineGVK = schema.GroupVersionKind{ - Group: clusterv1.GroupVersion.Group, - Version: "v1old", - Kind: "Machine", - } -) +var oldMachineGVK = schema.GroupVersionKind{ + Group: clusterv1.GroupVersion.Group, + Version: "v1old", + Kind: "Machine", +} func TestMarshalData(t *testing.T) { g := NewWithT(t) diff --git a/util/kubeconfig/kubeconfig.go b/util/kubeconfig/kubeconfig.go index 3c5338f683d9..8237f0336b6e 100644 --- a/util/kubeconfig/kubeconfig.go +++ b/util/kubeconfig/kubeconfig.go @@ -38,10 +38,8 @@ import ( "sigs.k8s.io/cluster-api/util/secret" ) -var ( - // ErrDependentCertificateNotFound signals that a CA secret could not be found. - ErrDependentCertificateNotFound = errors.New("could not find secret ca") -) +// ErrDependentCertificateNotFound signals that a CA secret could not be found. +var ErrDependentCertificateNotFound = errors.New("could not find secret ca") // FromSecret fetches the Kubeconfig for a Cluster. func FromSecret(ctx context.Context, c client.Reader, cluster client.ObjectKey) ([]byte, error) { diff --git a/util/labels/helpers_test.go b/util/labels/helpers_test.go index d627014800f2..8a90bc9be4cc 100644 --- a/util/labels/helpers_test.go +++ b/util/labels/helpers_test.go @@ -29,7 +29,7 @@ import ( func TestHasWatchLabel(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string obj metav1.Object input string diff --git a/util/patch/utils.go b/util/patch/utils.go index 92b362672444..2059a2f77e4b 100644 --- a/util/patch/utils.go +++ b/util/patch/utils.go @@ -34,13 +34,11 @@ const ( statusPatch patchType = "status" ) -var ( - preserveUnstructuredKeys = map[string]bool{ - "kind": true, - "apiVersion": true, - "metadata": true, - } -) +var preserveUnstructuredKeys = map[string]bool{ + "kind": true, + "apiVersion": true, + "metadata": true, +} func unstructuredHasStatus(u *unstructured.Unstructured) bool { _, ok := u.Object["status"] diff --git a/util/secret/consts.go b/util/secret/consts.go index d50062da35bd..a9926a3ec2eb 100644 --- a/util/secret/consts.go +++ b/util/secret/consts.go @@ -50,7 +50,5 @@ const ( APIServerEtcdClient = Purpose("apiserver-etcd-client") ) -var ( - // allSecretPurposes defines a lists with all the secret suffix used by Cluster API. - allSecretPurposes = []Purpose{Kubeconfig, ClusterCA, EtcdCA, ServiceAccount, FrontProxyCA, APIServerEtcdClient} -) +// allSecretPurposes defines a lists with all the secret suffix used by Cluster API. +var allSecretPurposes = []Purpose{Kubeconfig, ClusterCA, EtcdCA, ServiceAccount, FrontProxyCA, APIServerEtcdClient} diff --git a/util/suite_test.go b/util/suite_test.go index b8af09802b44..46347cc604f8 100644 --- a/util/suite_test.go +++ b/util/suite_test.go @@ -24,9 +24,7 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1" ) -var ( - ctx = ctrl.SetupSignalHandler() -) +var ctx = ctrl.SetupSignalHandler() func init() { utilruntime.Must(clusterv1.AddToScheme(scheme.Scheme)) diff --git a/util/version/version.go b/util/version/version.go index 277ed61050ec..8f7b47c6eea3 100644 --- a/util/version/version.go +++ b/util/version/version.go @@ -80,7 +80,7 @@ const ( numbers = "01234567890" ) -func containsOnly(s string, set string) bool { +func containsOnly(s, set string) bool { return strings.IndexFunc(s, func(r rune) bool { return !strings.ContainsRune(set, r) }) == -1 diff --git a/util/version/version_test.go b/util/version/version_test.go index a76ea9d2c7e5..de82c5610b83 100644 --- a/util/version/version_test.go +++ b/util/version/version_test.go @@ -26,7 +26,7 @@ import ( func TestParseMajorMinorPatch(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string input string output semver.Version @@ -79,7 +79,7 @@ func TestParseMajorMinorPatch(t *testing.T) { func TestParseMajorMinorPatchTolerant(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string input string output semver.Version diff --git a/util/yaml/yaml.go b/util/yaml/yaml.go index e539da9acde6..0a0bd46c4d4e 100644 --- a/util/yaml/yaml.go +++ b/util/yaml/yaml.go @@ -237,9 +237,9 @@ func ToUnstructured(rawyaml []byte) ([]unstructured.Unstructured, error) { // JoinYaml takes a list of YAML files and join them ensuring // each YAML that the yaml separator goes on a new line by adding \n where necessary. func JoinYaml(yamls ...[]byte) []byte { - var yamlSeparator = []byte("---") + yamlSeparator := []byte("---") - var cr = []byte("\n") + cr := []byte("\n") var b [][]byte //nolint:prealloc for _, y := range yamls { if !bytes.HasPrefix(y, cr) { diff --git a/util/yaml/yaml_test.go b/util/yaml/yaml_test.go index 7c110ba1dee4..e067aedf6115 100644 --- a/util/yaml/yaml_test.go +++ b/util/yaml/yaml_test.go @@ -178,7 +178,7 @@ func TestParseInvalidFile(t *testing.T) { func TestParseClusterYaml(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string contents string expectedName string @@ -232,7 +232,7 @@ func TestParseClusterYaml(t *testing.T) { func TestParseMachineYaml(t *testing.T) { g := NewWithT(t) - var testcases = []struct { + testcases := []struct { name string contents string expectErr bool