diff --git a/.golangci.yml b/.golangci.yml index e6232ebd2..ae4c816ea 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,21 +18,37 @@ issues: - text: "Unhandled error in call to function fmt.Print*" linters: - revive + - path: cmd/main.go + linters: + - maintidx + - path: test/ + linters: + - perfsprint linters: disable-all: true enable: - asciicheck - bodyclose + - canonicalheader - containedctx - contextcheck - copyloopvar - decorder - dogsled - dupl + - dupword - durationcheck - errcheck + - errchkjson + - errname + - forbidigo - forcetypeassert + - gci + - ginkgolinter + - gocheckcompilerdirectives + - gochecksumtype - goconst + - gocritic - gocyclo - gofmt - gofumpt @@ -41,11 +57,20 @@ linters: - gosimple - govet - ineffassign + - interfacebloat + - intrange + - loggercheck + - maintidx - misspell + - musttag - nakedret + - nilerr + - nilnil - noctx - nolintlint - nosprintfhostport + - paralleltest + - perfsprint - prealloc - predeclared - promlinter @@ -53,8 +78,9 @@ linters: - staticcheck - stylecheck - tenv + - testifylint - thelper - - typecheck + - tparallel - unconvert - unparam - unused @@ -67,6 +93,12 @@ linters-settings: # Tokens count to trigger issue. # Default: 150 threshold: 200 + gci: + sections: + - standard # Standard section: captures all standard packages. + - default # Default section: contains all imports that could not be matched to another section type. + - prefix(github.com/Mirantis/hmc) # Custom section: groups all imports with the specified Prefix. + skip-generated: false gofmt: # Apply the rewrite rules to the source before reformatting. # https://pkg.go.dev/cmd/gofmt @@ -74,8 +106,20 @@ linters-settings: rewrite-rules: - pattern: "interface{}" replacement: "any" - stylecheck: - checks: ["all", "-ST1000", "-ST1001", "-ST1021"] + gofumpt: + extra-rules: true + govet: + enable-all: true + disable: + - fieldalignment + - shadow + loggercheck: + kitlog: false + klog: false + require-string-key: true + no-printf-like: true + paralleltest: + ignore-missing: true revive: enable-all-rules: true rules: @@ -96,4 +140,6 @@ linters-settings: - name: line-length-limit disabled: true - name: package-comments - disabled: true \ No newline at end of file + disabled: true + stylecheck: + checks: ["all", "-ST1000", "-ST1001", "-ST1021"] diff --git a/cmd/main.go b/cmd/main.go index ab2b66de1..702cae6ce 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -19,11 +19,9 @@ import ( "flag" "os" - // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) - // to ensure that exec-entrypoint and run can make use of them. - hcv2 "github.com/fluxcd/helm-controller/api/v2" sourcev1 "github.com/fluxcd/source-controller/api/v1" + sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/dynamic" @@ -37,15 +35,12 @@ import ( metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "sigs.k8s.io/controller-runtime/pkg/webhook" - sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" - hmcmirantiscomv1alpha1 "github.com/Mirantis/hmc/api/v1alpha1" "github.com/Mirantis/hmc/internal/controller" "github.com/Mirantis/hmc/internal/helm" "github.com/Mirantis/hmc/internal/telemetry" "github.com/Mirantis/hmc/internal/utils" hmcwebhook "github.com/Mirantis/hmc/internal/webhook" - // +kubebuilder:scaffold:imports ) var ( diff --git a/internal/controller/managedcluster_controller.go b/internal/controller/managedcluster_controller.go index 97f462c71..b0a6a1b93 100644 --- a/internal/controller/managedcluster_controller.go +++ b/internal/controller/managedcluster_controller.go @@ -169,8 +169,7 @@ func (r *ManagedClusterReconciler) setStatusFromClusterStatus(ctx context.Contex func (r *ManagedClusterReconciler) Update(ctx context.Context, managedCluster *hmc.ManagedCluster) (result ctrl.Result, err error) { l := ctrl.LoggerFrom(ctx) - finalizersUpdated := controllerutil.AddFinalizer(managedCluster, hmc.ManagedClusterFinalizer) - if finalizersUpdated { + if controllerutil.AddFinalizer(managedCluster, hmc.ManagedClusterFinalizer) { if err := r.Client.Update(ctx, managedCluster); err != nil { return ctrl.Result{}, fmt.Errorf("failed to update managedCluster %s/%s: %w", managedCluster.Namespace, managedCluster.Name, err) } @@ -460,7 +459,7 @@ func (r *ManagedClusterReconciler) updateStatus(ctx context.Context, managedClus func (r *ManagedClusterReconciler) getSource(ctx context.Context, ref *hcv2.CrossNamespaceSourceReference) (sourcev1.Source, error) { if ref == nil { - return nil, fmt.Errorf("helm chart source is not provided") + return nil, errors.New("helm chart source is not provided") } chartRef := client.ObjectKey{Namespace: ref.Namespace, Name: ref.Name} hc := sourcev1.HelmChart{} @@ -481,8 +480,7 @@ func (r *ManagedClusterReconciler) Delete(ctx context.Context, managedCluster *h if err != nil { if apierrors.IsNotFound(err) { l.Info("Removing Finalizer", "finalizer", hmc.ManagedClusterFinalizer) - finalizersUpdated := controllerutil.RemoveFinalizer(managedCluster, hmc.ManagedClusterFinalizer) - if finalizersUpdated { + if controllerutil.RemoveFinalizer(managedCluster, hmc.ManagedClusterFinalizer) { if err := r.Client.Update(ctx, managedCluster); err != nil { return ctrl.Result{}, fmt.Errorf("failed to update managedCluster %s/%s: %w", managedCluster.Namespace, managedCluster.Name, err) } @@ -618,8 +616,7 @@ func (r *ManagedClusterReconciler) getCluster(ctx context.Context, namespace, na func (r *ManagedClusterReconciler) removeClusterFinalizer(ctx context.Context, cluster *metav1.PartialObjectMetadata) error { originalCluster := *cluster - finalizersUpdated := controllerutil.RemoveFinalizer(cluster, hmc.BlockingFinalizer) - if finalizersUpdated { + if controllerutil.RemoveFinalizer(cluster, hmc.BlockingFinalizer) { ctrl.LoggerFrom(ctx).Info("Allow to stop cluster", "finalizer", hmc.BlockingFinalizer) if err := r.Client.Patch(ctx, cluster, client.MergeFrom(&originalCluster)); err != nil { return fmt.Errorf("failed to patch cluster %s/%s: %w", cluster.Namespace, cluster.Name, err) @@ -654,7 +651,7 @@ func (r *ManagedClusterReconciler) reconcileCredentialPropagation(ctx context.Co kubeconfSecret := &corev1.Secret{} if err := r.Client.Get(ctx, client.ObjectKey{ - Name: fmt.Sprintf("%s-kubeconfig", managedCluster.Name), + Name: managedCluster.Name + "-kubeconfig", Namespace: managedCluster.Namespace, }, kubeconfSecret); err != nil { return fmt.Errorf("failed to get kubeconfig secret for cluster %s/%s: %s", managedCluster.Namespace, managedCluster.Name, err) @@ -708,7 +705,7 @@ func (r *ManagedClusterReconciler) reconcileCredentialPropagation(ctx context.Co Type: hmc.CredentialsPropagatedCondition, Status: metav1.ConditionFalse, Reason: hmc.FailedReason, - Message: fmt.Sprintf("unsupported infrastructure provider %s", provider), + Message: "unsupported infrastructure provider " + provider, }) } } @@ -845,8 +842,8 @@ func (r *ManagedClusterReconciler) propagateVSphereSecrets(ctx context.Context, func generateVSphereCCMConfigs(vCl *capv.VSphereCluster, vScrt *corev1.Secret, vMa *capv.VSphereMachine) (*corev1.Secret, *corev1.ConfigMap, error) { secretName := "vsphere-cloud-secret" secretData := map[string][]byte{ - fmt.Sprintf("%s.username", vCl.Spec.Server): vScrt.Data["username"], - fmt.Sprintf("%s.password", vCl.Spec.Server): vScrt.Data["password"], + vCl.Spec.Server + ".username": vScrt.Data["username"], + vCl.Spec.Server + ".password": vScrt.Data["password"], } ccmCfg := map[string]any{ "global": map[string]any{ diff --git a/internal/controller/managedcluster_controller_test.go b/internal/controller/managedcluster_controller_test.go index 4d93fcce9..2182968fe 100644 --- a/internal/controller/managedcluster_controller_test.go +++ b/internal/controller/managedcluster_controller_test.go @@ -166,7 +166,7 @@ var _ = Describe("ManagedCluster Controller", func() { _, err := controllerReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: typeNamespacedName}) Expect(err).NotTo(HaveOccurred()) - Eventually(k8sClient.Get(ctx, typeNamespacedName, managedCluster), 1*time.Minute, 5*time.Second).Should(HaveOccurred()) + Eventually(k8sClient.Get, 1*time.Minute, 5*time.Second).WithArguments(ctx, typeNamespacedName, managedCluster).Should(HaveOccurred()) Expect(k8sClient.Delete(ctx, template)).To(Succeed()) Expect(k8sClient.Delete(ctx, management)).To(Succeed()) diff --git a/internal/controller/management_controller.go b/internal/controller/management_controller.go index 6c9728810..c2b4e2c5b 100644 --- a/internal/controller/management_controller.go +++ b/internal/controller/management_controller.go @@ -85,8 +85,7 @@ func (r *ManagementReconciler) Reconcile(ctx context.Context, req ctrl.Request) func (r *ManagementReconciler) Update(ctx context.Context, management *hmc.Management) (ctrl.Result, error) { l := ctrl.LoggerFrom(ctx) - finalizersUpdated := controllerutil.AddFinalizer(management, hmc.ManagementFinalizer) - if finalizersUpdated { + if controllerutil.AddFinalizer(management, hmc.ManagementFinalizer) { if err := r.Client.Update(ctx, management); err != nil { l.Error(err, "Failed to update Management finalizers") return ctrl.Result{}, err diff --git a/internal/controller/management_controller_test.go b/internal/controller/management_controller_test.go index 23c8c405d..cad5c732a 100644 --- a/internal/controller/management_controller_test.go +++ b/internal/controller/management_controller_test.go @@ -20,11 +20,10 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/reconcile" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - hmcmirantiscomv1alpha1 "github.com/Mirantis/hmc/api/v1alpha1" ) diff --git a/internal/controller/multiclusterservice_controller.go b/internal/controller/multiclusterservice_controller.go index 06077127b..28ba554d0 100644 --- a/internal/controller/multiclusterservice_controller.go +++ b/internal/controller/multiclusterservice_controller.go @@ -18,9 +18,9 @@ import ( "context" "fmt" + sourcev1 "github.com/fluxcd/source-controller/api/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" @@ -28,7 +28,6 @@ import ( hmc "github.com/Mirantis/hmc/api/v1alpha1" "github.com/Mirantis/hmc/internal/sveltos" "github.com/Mirantis/hmc/internal/utils" - sourcev1 "github.com/fluxcd/source-controller/api/v1" ) // MultiClusterServiceReconciler reconciles a MultiClusterService object @@ -111,7 +110,7 @@ func helmChartOpts(ctx context.Context, c client.Client, namespace string, servi // because if the services slice is part of: // 1. ManagedCluster: Then the referred template must be in its own namespace. // 2. MultiClusterService: Then the referred template must be in hmc-system namespace. - tmplRef := types.NamespacedName{Name: svc.Template, Namespace: namespace} + tmplRef := client.ObjectKey{Name: svc.Template, Namespace: namespace} if err := c.Get(ctx, tmplRef, tmpl); err != nil { return nil, fmt.Errorf("failed to get ServiceTemplate %s: %w", tmplRef.String(), err) } @@ -121,7 +120,7 @@ func helmChartOpts(ctx context.Context, c client.Client, namespace string, servi } chart := &sourcev1.HelmChart{} - chartRef := types.NamespacedName{ + chartRef := client.ObjectKey{ Namespace: tmpl.GetCommonStatus().ChartRef.Namespace, Name: tmpl.GetCommonStatus().ChartRef.Name, } @@ -130,7 +129,7 @@ func helmChartOpts(ctx context.Context, c client.Client, namespace string, servi } repo := &sourcev1.HelmRepository{} - repoRef := types.NamespacedName{ + repoRef := client.ObjectKey{ // Using chart's namespace because it's source // should be within the same namespace. Namespace: chart.Namespace, diff --git a/internal/controller/multiclusterservice_controller_test.go b/internal/controller/multiclusterservice_controller_test.go index b5fe5954f..245f5b55e 100644 --- a/internal/controller/multiclusterservice_controller_test.go +++ b/internal/controller/multiclusterservice_controller_test.go @@ -22,17 +22,16 @@ import ( sourcev1 "github.com/fluxcd/source-controller/api/v1" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" "helm.sh/helm/v3/pkg/chart" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/reconcile" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - hmc "github.com/Mirantis/hmc/api/v1alpha1" "github.com/Mirantis/hmc/internal/utils" - sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" ) var _ = Describe("MultiClusterService Controller", func() { @@ -187,7 +186,7 @@ var _ = Describe("MultiClusterService Controller", func() { // Running reconcile to remove the finalizer and delete the MultiClusterService _, err := reconciler.Reconcile(ctx, reconcile.Request{NamespacedName: multiClusterServiceRef}) Expect(err).NotTo(HaveOccurred()) - Eventually(k8sClient.Get(ctx, multiClusterServiceRef, multiClusterService), 1*time.Minute, 5*time.Second).Should(HaveOccurred()) + Eventually(k8sClient.Get, 1*time.Minute, 5*time.Second).WithArguments(ctx, multiClusterServiceRef, multiClusterService).Should(HaveOccurred()) Expect(k8sClient.Get(ctx, clusterProfileRef, &sveltosv1beta1.ClusterProfile{})).To(HaveOccurred()) @@ -220,7 +219,7 @@ var _ = Describe("MultiClusterService Controller", func() { _, err = multiClusterServiceReconciler.Reconcile(ctx, reconcile.Request{NamespacedName: multiClusterServiceRef}) Expect(err).NotTo(HaveOccurred()) - Eventually(k8sClient.Get(ctx, clusterProfileRef, clusterProfile), 1*time.Minute, 5*time.Second).ShouldNot(HaveOccurred()) + Eventually(k8sClient.Get, 1*time.Minute, 5*time.Second).WithArguments(ctx, clusterProfileRef, clusterProfile).ShouldNot(HaveOccurred()) }) }) }) diff --git a/internal/controller/suite_test.go b/internal/controller/suite_test.go index 50f8d66f3..b7dbdbc40 100644 --- a/internal/controller/suite_test.go +++ b/internal/controller/suite_test.go @@ -26,27 +26,25 @@ import ( "testing" "time" + helmcontrollerv2 "github.com/fluxcd/helm-controller/api/v2" + sourcev1 "github.com/fluxcd/source-controller/api/v1" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" admissionv1 "k8s.io/api/admissionregistration/v1" - utilyaml "sigs.k8s.io/cluster-api/util/yaml" - ctrl "sigs.k8s.io/controller-runtime" - metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" - "sigs.k8s.io/controller-runtime/pkg/webhook" - - helmcontrollerv2 "github.com/fluxcd/helm-controller/api/v2" - sourcev1 "github.com/fluxcd/source-controller/api/v1" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" + utilyaml "sigs.k8s.io/cluster-api/util/yaml" + ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/log/zap" + metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" + "sigs.k8s.io/controller-runtime/pkg/webhook" hmcmirantiscomv1alpha1 "github.com/Mirantis/hmc/api/v1alpha1" hmcwebhook "github.com/Mirantis/hmc/internal/webhook" - sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" - // +kubebuilder:scaffold:imports ) // These tests use Ginkgo (BDD-style Go testing framework). Refer to diff --git a/internal/controller/template_controller.go b/internal/controller/template_controller.go index c12a36e8e..ebe3d86be 100644 --- a/internal/controller/template_controller.go +++ b/internal/controller/template_controller.go @@ -157,7 +157,7 @@ func (r *TemplateReconciler) ReconcileTemplate(ctx context.Context, template tem } } else { if helmSpec.ChartName == "" { - err := fmt.Errorf("neither chartName nor chartRef is set") + err := errors.New("neither chartName nor chartRef is set") l.Error(err, "invalid helm chart reference") return ctrl.Result{}, err } @@ -180,7 +180,7 @@ func (r *TemplateReconciler) ReconcileTemplate(ctx context.Context, template tem } } if hcChart == nil { - err := fmt.Errorf("HelmChart is nil") + err := errors.New("HelmChart is nil") l.Error(err, "could not get the helm chart") return ctrl.Result{}, err } @@ -249,7 +249,7 @@ func templateManagedByHMC(template templateCommon) bool { func fillStatusWithProviders(template templateCommon, helmChart *chart.Chart) error { if helmChart.Metadata == nil { - return fmt.Errorf("chart metadata is empty") + return errors.New("chart metadata is empty") } return template.FillStatusWithProviders(helmChart.Metadata.Annotations) diff --git a/internal/controller/templatechain_controller.go b/internal/controller/templatechain_controller.go index 42e3035f7..758a7c36d 100644 --- a/internal/controller/templatechain_controller.go +++ b/internal/controller/templatechain_controller.go @@ -137,7 +137,7 @@ func (r *TemplateChainReconciler) ReconcileTemplateChain(ctx context.Context, te } if err := r.Create(ctx, target); err == nil { - l.Info(fmt.Sprintf("%s was successfully created", templateChain.TemplateKind()), "template namespace", templateChain.GetNamespace(), "template name", supportedTemplate.Name) + l.Info(templateChain.TemplateKind()+" was successfully created", "template namespace", templateChain.GetNamespace(), "template name", supportedTemplate.Name) continue } diff --git a/internal/controller/templatemanagement_controller.go b/internal/controller/templatemanagement_controller.go index 571418563..281a8061c 100644 --- a/internal/controller/templatemanagement_controller.go +++ b/internal/controller/templatemanagement_controller.go @@ -108,8 +108,7 @@ func (r *TemplateManagementReconciler) Reconcile(ctx context.Context, req ctrl.R } } - managedChains := append(managedCtChains, managedStChains...) - for _, managedChain := range managedChains { + for _, managedChain := range append(managedCtChains, managedStChains...) { keep := false templateNamespacedName := getNamespacedName(managedChain.GetNamespace(), managedChain.GetName()) switch managedChain.Kind() { @@ -248,7 +247,7 @@ func (r *TemplateManagementReconciler) createTemplateChain(ctx context.Context, } return err } - l.Info(fmt.Sprintf("%s was successfully created", source.Kind()), "target namespace", targetNamespace, "source name", source.GetName()) + l.Info(source.Kind()+" was successfully created", "target namespace", targetNamespace, "source name", source.GetName()) return nil } @@ -262,7 +261,7 @@ func (r *TemplateManagementReconciler) deleteTemplateChain(ctx context.Context, } return err } - l.Info(fmt.Sprintf("%s was successfully deleted", chain.Kind()), "chain namespace", chain.GetNamespace(), "chain name", chain.GetName()) + l.Info(chain.Kind()+"%s was successfully deleted", "chain namespace", chain.GetNamespace(), "chain name", chain.GetName()) return nil } diff --git a/internal/helm/chart.go b/internal/helm/chart.go index faf7a23ac..5a9543b82 100644 --- a/internal/helm/chart.go +++ b/internal/helm/chart.go @@ -15,6 +15,7 @@ package helm import ( + "errors" "fmt" sourcev1 "github.com/fluxcd/source-controller/api/v1" @@ -25,7 +26,7 @@ func ArtifactReady(chart *sourcev1.HelmChart) (reportStatus bool, _ error) { for _, c := range chart.Status.Conditions { if c.Type == "Ready" { if chart.Generation != c.ObservedGeneration { - return false, fmt.Errorf("HelmChart was not reconciled yet, retrying") + return false, errors.New("HelmChart was not reconciled yet, retrying") } if c.Status != metav1.ConditionTrue { return true, fmt.Errorf("failed to download helm chart artifact: %s", c.Message) @@ -34,7 +35,7 @@ func ArtifactReady(chart *sourcev1.HelmChart) (reportStatus bool, _ error) { } if chart.Status.Artifact == nil || chart.Status.URL == "" { - return false, fmt.Errorf("helm chart artifact is not ready yet") + return false, errors.New("helm chart artifact is not ready yet") } return false, nil diff --git a/internal/helm/release.go b/internal/helm/release.go index dd63a666c..c30f51e7f 100644 --- a/internal/helm/release.go +++ b/internal/helm/release.go @@ -89,7 +89,7 @@ func ReconcileHelmRelease(ctx context.Context, return hr, operation, nil } -func DeleteHelmRelease(ctx context.Context, cl client.Client, name string, namespace string) error { +func DeleteHelmRelease(ctx context.Context, cl client.Client, name, namespace string) error { err := cl.Delete(ctx, &hcv2.HelmRelease{ ObjectMeta: metav1.ObjectMeta{ Name: name, diff --git a/internal/sveltos/profile.go b/internal/sveltos/profile.go index 8bba498b8..2c3dc79d3 100644 --- a/internal/sveltos/profile.go +++ b/internal/sveltos/profile.go @@ -20,7 +20,6 @@ import ( "math" "unsafe" - hmc "github.com/Mirantis/hmc/api/v1alpha1" sveltosv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" @@ -29,6 +28,8 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/yaml" + + hmc "github.com/Mirantis/hmc/api/v1alpha1" ) type ReconcileProfileOpts struct { @@ -126,7 +127,7 @@ func ReconcileProfile( // Spec returns a spec object to be used with // a Sveltos Profile or ClusterProfile object. func Spec(opts *ReconcileProfileOpts) (*sveltosv1beta1.Spec, error) { - tier, err := PriorityToTier(opts.Priority) + tier, err := priorityToTier(opts.Priority) if err != nil { return nil, err } @@ -190,7 +191,7 @@ func objectMeta(owner *metav1.OwnerReference) metav1.ObjectMeta { } // DeleteProfile deletes a Sveltos Profile object. -func DeleteProfile(ctx context.Context, cl client.Client, namespace string, name string) error { +func DeleteProfile(ctx context.Context, cl client.Client, namespace, name string) error { err := cl.Delete(ctx, &sveltosv1beta1.Profile{ ObjectMeta: metav1.ObjectMeta{ Namespace: namespace, @@ -212,8 +213,8 @@ func DeleteClusterProfile(ctx context.Context, cl client.Client, name string) er return client.IgnoreNotFound(err) } -// PriorityToTier converts priority value to Sveltos tier value. -func PriorityToTier(priority int32) (int32, error) { +// priorityToTier converts priority value to Sveltos tier value. +func priorityToTier(priority int32) (int32, error) { var mini int32 = 1 maxi := math.MaxInt32 - mini diff --git a/internal/sveltos/profile_test.go b/internal/sveltos/profile_test.go index bfeee74ef..eb1c924ef 100644 --- a/internal/sveltos/profile_test.go +++ b/internal/sveltos/profile_test.go @@ -19,29 +19,28 @@ import ( "fmt" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) -func TestPriorityToTier(t *testing.T) { +func Test_priorityToTier(t *testing.T) { for _, tc := range []struct { err error priority int32 tier int32 }{ - {priority: 1, tier: 2147483646, err: nil}, - {priority: 2147483646, tier: 1, err: nil}, - {priority: 0, err: errors.New("priority cannot be < 1")}, - {priority: 2147483647, err: errors.New("priority cannot be > 2147483646")}, + {priority: 1, tier: 2147483646}, + {priority: 2147483646, tier: 1}, + {priority: 0, err: errors.New("priority has to be between 1 and 2147483646")}, + {priority: 2147483647, err: errors.New("priority has to be between 1 and 2147483646")}, } { t.Run(fmt.Sprintf("priority=%d", tc.priority), func(t *testing.T) { - tier, err := PriorityToTier(tc.priority) + tier, err := priorityToTier(tc.priority) if tc.err != nil { - assert.NotNil(t, err) - assert.Zero(t, tc.tier) + require.ErrorContains(t, err, tc.err.Error()) } else { - assert.Nil(t, err) - assert.Equal(t, tc.tier, tier) + require.NoError(t, err) } + require.Equal(t, tc.tier, tier) }) } } diff --git a/internal/webhook/managedcluster_webhook.go b/internal/webhook/managedcluster_webhook.go index 672bc10ea..90f286ea4 100644 --- a/internal/webhook/managedcluster_webhook.go +++ b/internal/webhook/managedcluster_webhook.go @@ -16,6 +16,7 @@ package webhook import ( "context" + "errors" "fmt" "strings" @@ -79,7 +80,7 @@ func (v *ManagedClusterValidator) ValidateCreate(ctx context.Context, obj runtim } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (v *ManagedClusterValidator) ValidateUpdate(ctx context.Context, oldObj runtime.Object, newObj runtime.Object) (admission.Warnings, error) { +func (v *ManagedClusterValidator) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) { oldManagedCluster, ok := oldObj.(*hmcv1alpha1.ManagedCluster) if !ok { return nil, apierrors.NewBadRequest(fmt.Sprintf("expected ManagedCluster but got a %T", oldObj)) @@ -235,7 +236,7 @@ func (v *ManagedClusterValidator) validateCredential(ctx context.Context, manage } if cred.Status.State != hmcv1alpha1.CredentialReady { - return fmt.Errorf("credential is not Ready") + return errors.New("credential is not Ready") } return isCredMatchTemplate(cred, template) diff --git a/internal/webhook/management_webhook_test.go b/internal/webhook/management_webhook_test.go index 4987dcf99..98142ed96 100644 --- a/internal/webhook/management_webhook_test.go +++ b/internal/webhook/management_webhook_test.go @@ -88,7 +88,7 @@ func TestManagementValidateUpdate(t *testing.T) { template.WithProviderStatusCAPIContracts(capiVersion, ""), ), }, - err: fmt.Sprintf("the Management is invalid: not valid ProviderTemplate %s", release.DefaultCAPITemplateName), + err: "the Management is invalid: not valid ProviderTemplate " + release.DefaultCAPITemplateName, }, { name: "no providertemplates that declared in mgmt spec.providers, should fail", @@ -139,7 +139,7 @@ func TestManagementValidateUpdate(t *testing.T) { template.WithProviderStatusCAPIContracts(capiVersionOther, someContractVersion), ), }, - err: fmt.Sprintf("the Management is invalid: not valid ProviderTemplate %s", template.DefaultName), + err: "the Management is invalid: not valid ProviderTemplate " + template.DefaultName, }, { name: "providertemplates do not match capi contracts, should fail", diff --git a/internal/webhook/template_webhook.go b/internal/webhook/template_webhook.go index a57343ef7..b2a0dacd8 100644 --- a/internal/webhook/template_webhook.go +++ b/internal/webhook/template_webhook.go @@ -55,7 +55,7 @@ func (*ClusterTemplateValidator) ValidateCreate(_ context.Context, _ runtime.Obj } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*ClusterTemplateValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*ClusterTemplateValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } @@ -110,7 +110,7 @@ func (*ServiceTemplateValidator) ValidateCreate(_ context.Context, _ runtime.Obj } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*ServiceTemplateValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*ServiceTemplateValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } @@ -165,7 +165,7 @@ func (*ProviderTemplateValidator) ValidateCreate(_ context.Context, _ runtime.Ob } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*ProviderTemplateValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*ProviderTemplateValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } diff --git a/internal/webhook/templatechain_webhook.go b/internal/webhook/templatechain_webhook.go index 03a9c2d22..3611ca32e 100644 --- a/internal/webhook/templatechain_webhook.go +++ b/internal/webhook/templatechain_webhook.go @@ -64,7 +64,7 @@ func (*ClusterTemplateChainValidator) ValidateCreate(_ context.Context, obj runt } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*ClusterTemplateChainValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*ClusterTemplateChainValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } @@ -110,7 +110,7 @@ func (*ServiceTemplateChainValidator) ValidateCreate(_ context.Context, obj runt } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*ServiceTemplateChainValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*ServiceTemplateChainValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } diff --git a/internal/webhook/templatemanagement_webhook.go b/internal/webhook/templatemanagement_webhook.go index 9d7470adb..6025522bf 100644 --- a/internal/webhook/templatemanagement_webhook.go +++ b/internal/webhook/templatemanagement_webhook.go @@ -59,13 +59,13 @@ func (v *TemplateManagementValidator) ValidateCreate(ctx context.Context, _ runt return nil, err } if len(itemsList.Items) > 0 { - return nil, fmt.Errorf("TemplateManagement object already exists") + return nil, errors.New("TemplateManagement object already exists") } return nil, nil } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. -func (*TemplateManagementValidator) ValidateUpdate(_ context.Context, _ runtime.Object, _ runtime.Object) (admission.Warnings, error) { +func (*TemplateManagementValidator) ValidateUpdate(_ context.Context, _, _ runtime.Object) (admission.Warnings, error) { return nil, nil } diff --git a/test/e2e/e2e_suite_test.go b/test/e2e/e2e_suite_test.go index 3c61a50bf..e76a4c245 100644 --- a/test/e2e/e2e_suite_test.go +++ b/test/e2e/e2e_suite_test.go @@ -26,15 +26,16 @@ import ( "testing" "time" - internalutils "github.com/Mirantis/hmc/internal/utils" - "github.com/Mirantis/hmc/test/e2e/kubeclient" - "github.com/Mirantis/hmc/test/e2e/managedcluster" - "github.com/Mirantis/hmc/test/utils" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/utils/ptr" + + internalutils "github.com/Mirantis/hmc/internal/utils" + "github.com/Mirantis/hmc/test/e2e/kubeclient" + "github.com/Mirantis/hmc/test/e2e/managedcluster" + "github.com/Mirantis/hmc/test/utils" ) // Run e2e tests using the Ginkgo runner. @@ -104,7 +105,7 @@ func verifyControllersUp(kc *kubeclient.KubeClient) error { return nil } -func validateController(kc *kubeclient.KubeClient, labelSelector string, name string) error { +func validateController(kc *kubeclient.KubeClient, labelSelector, name string) error { controllerItems := 1 if strings.Contains(labelSelector, managedcluster.GetProviderLabel(managedcluster.ProviderAzure)) { // Azure provider has two controllers. diff --git a/test/e2e/kubeclient/kubeclient.go b/test/e2e/kubeclient/kubeclient.go index c5b8fe811..089dce519 100644 --- a/test/e2e/kubeclient/kubeclient.go +++ b/test/e2e/kubeclient/kubeclient.go @@ -21,7 +21,6 @@ import ( "os" "path/filepath" - "github.com/Mirantis/hmc/test/utils" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" @@ -33,6 +32,8 @@ import ( "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" + + "github.com/Mirantis/hmc/test/utils" ) type KubeClient struct { @@ -143,9 +144,7 @@ func newKubeClient(configBytes []byte, namespace string) *KubeClient { } // GetDynamicClient returns a dynamic client for the given GroupVersionResource. -// -//nolint:revive -func (kc *KubeClient) GetDynamicClient(gvr schema.GroupVersionResource, namespaced bool) dynamic.ResourceInterface { +func (kc *KubeClient) GetDynamicClient(gvr schema.GroupVersionResource, namespaced bool) dynamic.ResourceInterface { //nolint:revive GinkgoHelper() client, err := dynamic.NewForConfig(kc.Config) diff --git a/test/e2e/managedcluster/clusteridentity/clusteridentity.go b/test/e2e/managedcluster/clusteridentity/clusteridentity.go index 91e69ea54..dbdc342c4 100644 --- a/test/e2e/managedcluster/clusteridentity/clusteridentity.go +++ b/test/e2e/managedcluster/clusteridentity/clusteridentity.go @@ -20,8 +20,6 @@ import ( "os" "time" - "github.com/Mirantis/hmc/test/e2e/kubeclient" - "github.com/Mirantis/hmc/test/e2e/managedcluster" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" corev1 "k8s.io/api/core/v1" @@ -29,6 +27,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/Mirantis/hmc/test/e2e/kubeclient" + "github.com/Mirantis/hmc/test/e2e/managedcluster" ) type ClusterIdentity struct { diff --git a/test/e2e/managedcluster/common.go b/test/e2e/managedcluster/common.go index f237f855f..5fabf7fde 100644 --- a/test/e2e/managedcluster/common.go +++ b/test/e2e/managedcluster/common.go @@ -20,12 +20,13 @@ import ( "fmt" "time" - "github.com/Mirantis/hmc/test/e2e/kubeclient" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" + + "github.com/Mirantis/hmc/test/e2e/kubeclient" ) // PatchHostedClusterReady patches a hosted clusters' infrastructure resource diff --git a/test/e2e/managedcluster/managedcluster.go b/test/e2e/managedcluster/managedcluster.go index 2b8495719..72efa96f8 100644 --- a/test/e2e/managedcluster/managedcluster.go +++ b/test/e2e/managedcluster/managedcluster.go @@ -20,13 +20,14 @@ import ( "os" "strings" - "github.com/Mirantis/hmc/test/utils" "github.com/a8m/envsubst" "github.com/google/uuid" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "gopkg.in/yaml.v3" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/Mirantis/hmc/test/utils" ) type ProviderType string diff --git a/test/e2e/managedcluster/providervalidator.go b/test/e2e/managedcluster/providervalidator.go index a28dd7cf0..4df0fa84b 100644 --- a/test/e2e/managedcluster/providervalidator.go +++ b/test/e2e/managedcluster/providervalidator.go @@ -18,8 +18,9 @@ import ( "context" "fmt" - "github.com/Mirantis/hmc/test/e2e/kubeclient" . "github.com/onsi/ginkgo/v2" + + "github.com/Mirantis/hmc/test/e2e/kubeclient" ) // ProviderValidator is a struct that contains the necessary information to diff --git a/test/e2e/managedcluster/validate_deleted.go b/test/e2e/managedcluster/validate_deleted.go index dce3211f6..582c27623 100644 --- a/test/e2e/managedcluster/validate_deleted.go +++ b/test/e2e/managedcluster/validate_deleted.go @@ -19,10 +19,11 @@ import ( "errors" "fmt" - "github.com/Mirantis/hmc/test/e2e/kubeclient" - "github.com/Mirantis/hmc/test/utils" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + "github.com/Mirantis/hmc/test/e2e/kubeclient" + "github.com/Mirantis/hmc/test/utils" ) // validateClusterDeleted validates that the Cluster resource has been deleted. diff --git a/test/e2e/managedcluster/validate_deployed.go b/test/e2e/managedcluster/validate_deployed.go index b8224b4e2..abb8c9511 100644 --- a/test/e2e/managedcluster/validate_deployed.go +++ b/test/e2e/managedcluster/validate_deployed.go @@ -19,8 +19,6 @@ import ( "fmt" "strings" - "github.com/Mirantis/hmc/test/e2e/kubeclient" - "github.com/Mirantis/hmc/test/utils" . "github.com/onsi/ginkgo/v2" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -28,6 +26,9 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/util/intstr" + + "github.com/Mirantis/hmc/test/e2e/kubeclient" + "github.com/Mirantis/hmc/test/utils" ) // resourceValidationFunc is intended to validate a specific kubernetes diff --git a/test/e2e/provider_aws_test.go b/test/e2e/provider_aws_test.go index 048eaed9d..6614698b4 100644 --- a/test/e2e/provider_aws_test.go +++ b/test/e2e/provider_aws_test.go @@ -21,14 +21,15 @@ import ( "os/exec" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + internalutils "github.com/Mirantis/hmc/internal/utils" "github.com/Mirantis/hmc/test/e2e/kubeclient" "github.com/Mirantis/hmc/test/e2e/managedcluster" "github.com/Mirantis/hmc/test/e2e/managedcluster/aws" "github.com/Mirantis/hmc/test/e2e/managedcluster/clusteridentity" "github.com/Mirantis/hmc/test/utils" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Describe("AWS Templates", Label("provider:cloud", "provider:aws"), Ordered, func() { diff --git a/test/e2e/provider_azure_test.go b/test/e2e/provider_azure_test.go index 6681668f3..fcdbe27c7 100644 --- a/test/e2e/provider_azure_test.go +++ b/test/e2e/provider_azure_test.go @@ -21,14 +21,15 @@ import ( "os/exec" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + internalutils "github.com/Mirantis/hmc/internal/utils" "github.com/Mirantis/hmc/test/e2e/kubeclient" "github.com/Mirantis/hmc/test/e2e/managedcluster" "github.com/Mirantis/hmc/test/e2e/managedcluster/azure" "github.com/Mirantis/hmc/test/e2e/managedcluster/clusteridentity" "github.com/Mirantis/hmc/test/utils" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Context("Azure Templates", Label("provider:cloud", "provider:azure"), Ordered, func() { diff --git a/test/e2e/provider_vsphere_test.go b/test/e2e/provider_vsphere_test.go index a6079665d..202d7deda 100644 --- a/test/e2e/provider_vsphere_test.go +++ b/test/e2e/provider_vsphere_test.go @@ -19,13 +19,14 @@ import ( "os" "time" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + internalutils "github.com/Mirantis/hmc/internal/utils" "github.com/Mirantis/hmc/test/e2e/kubeclient" "github.com/Mirantis/hmc/test/e2e/managedcluster" "github.com/Mirantis/hmc/test/e2e/managedcluster/clusteridentity" "github.com/Mirantis/hmc/test/e2e/managedcluster/vsphere" - . "github.com/onsi/ginkgo/v2" - . "github.com/onsi/gomega" ) var _ = Context("vSphere Templates", Label("provider:onprem", "provider:vsphere"), Ordered, func() { diff --git a/test/objects/template/template.go b/test/objects/template/template.go index 073be7207..3d2b0e550 100644 --- a/test/objects/template/template.go +++ b/test/objects/template/template.go @@ -193,7 +193,7 @@ func WithProviderStatusCAPIContracts(coreAndProvidersContracts ...string) Opt { pt.Status.CAPIContracts = make(v1alpha1.CompatibilityContracts) } - for i := 0; i < len(coreAndProvidersContracts)/2; i++ { + for i := range len(coreAndProvidersContracts) / 2 { pt.Status.CAPIContracts[coreAndProvidersContracts[i*2]] = coreAndProvidersContracts[i*2+1] } } diff --git a/test/utils/utils.go b/test/utils/utils.go index 8c64a729a..f158af7ba 100644 --- a/test/utils/utils.go +++ b/test/utils/utils.go @@ -106,7 +106,7 @@ func GetProjectDir() (string, error) { if err != nil { return wd, err } - wd = strings.Replace(wd, "/test/e2e", "", -1) + wd = strings.ReplaceAll(wd, "/test/e2e", "") return wd, nil } @@ -190,7 +190,7 @@ func ValidateObjectNamePrefix(unstrObj *unstructured.Unstructured, clusterName s return nil } -func ObjKindName(unstrObj *unstructured.Unstructured) (kind string, name string) { +func ObjKindName(unstrObj *unstructured.Unstructured) (kind, name string) { return unstrObj.GetKind(), unstrObj.GetName() }