From 229e2342556345af4ceb048315d0854efd217e1c Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sat, 30 Dec 2023 10:32:33 +0000 Subject: [PATCH] use go standard errors Signed-off-by: Matthieu MOREL --- .../validation/securitypolicy_validate.go | 4 +-- go.mod | 31 +++++++++---------- internal/cmd/certgen.go | 8 ++--- internal/cmd/egctl/envoy_stats.go | 12 +++---- internal/cmd/egctl/version.go | 3 +- internal/crypto/certgen.go | 2 +- internal/crypto/certgen_test.go | 2 +- internal/infrastructure/kubernetes/infra.go | 22 ++++++------- .../infrastructure/kubernetes/infra_client.go | 6 ++-- internal/kubernetes/client.go | 4 +-- internal/kubernetes/port-forwarder.go | 9 +++--- internal/kubernetes/secret.go | 2 +- internal/provider/kubernetes/controller.go | 24 +++++++------- internal/provider/kubernetes/filters.go | 4 +-- internal/provider/kubernetes/helpers.go | 4 +-- internal/provider/kubernetes/kubernetes.go | 2 +- internal/provider/kubernetes/routes.go | 10 +++--- internal/utils/regex/regex.go | 2 +- internal/xds/bootstrap/bootstrap.go | 2 +- internal/xds/server/runner/runner_test.go | 4 ++- internal/xds/translator/jsonpatch.go | 16 +++++----- internal/xds/translator/tracing.go | 7 +++-- internal/xds/types/resourceversiontable.go | 10 +++--- test/e2e/tests/metric.go | 2 +- tools/linter/golangci-lint/.golangci.yml | 7 +++-- 25 files changed, 99 insertions(+), 100 deletions(-) diff --git a/api/v1alpha1/validation/securitypolicy_validate.go b/api/v1alpha1/validation/securitypolicy_validate.go index 66bee6a8eb5..628d3f80173 100644 --- a/api/v1alpha1/validation/securitypolicy_validate.go +++ b/api/v1alpha1/validation/securitypolicy_validate.go @@ -73,14 +73,14 @@ func ValidateJWTProvider(providers []egv1a1.JWTProvider) error { if _, err := url.ParseRequestURI(provider.Issuer); err != nil { _, err := mail.ParseAddress(provider.Issuer) if err != nil { - errs = append(errs, fmt.Errorf("invalid issuer; must be a URL or email address: %v", err)) + errs = append(errs, fmt.Errorf("invalid issuer; must be a URL or email address: %w", err)) } } case len(provider.RemoteJWKS.URI) == 0: errs = append(errs, fmt.Errorf("uri must be set for remote JWKS provider: %s", provider.Name)) } if _, err := url.ParseRequestURI(provider.RemoteJWKS.URI); err != nil { - errs = append(errs, fmt.Errorf("invalid remote JWKS URI: %v", err)) + errs = append(errs, fmt.Errorf("invalid remote JWKS URI: %w", err)) } if len(errs) == 0 { diff --git a/go.mod b/go.mod index df6526b7ca3..4835e5800f5 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( github.com/google/go-cmp v0.6.0 github.com/grafana/tempo v1.5.0 github.com/miekg/dns v1.1.57 - github.com/pkg/errors v0.9.1 + github.com/prometheus/client_golang v1.18.0 github.com/prometheus/common v0.45.0 github.com/spf13/cobra v1.8.0 github.com/spf13/pflag v1.0.5 @@ -45,27 +45,15 @@ require ( k8s.io/utils v0.0.0-20230726121419-3b25d923346b sigs.k8s.io/controller-runtime v0.16.3 sigs.k8s.io/gateway-api v1.0.0 + sigs.k8s.io/mcs-api v0.1.0 sigs.k8s.io/yaml v1.4.0 ) -require ( - github.com/cenkalti/backoff/v4 v4.2.1 // indirect - github.com/go-logr/stdr v1.2.2 // indirect - github.com/gorilla/websocket v1.5.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect - github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect - github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect - go.opentelemetry.io/otel/sdk v1.21.0 // indirect - go.opentelemetry.io/otel/trace v1.21.0 // indirect - golang.org/x/mod v0.13.0 // indirect - golang.org/x/sync v0.4.0 // indirect - golang.org/x/tools v0.14.0 // indirect -) - require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/MakeNowJust/heredoc v1.0.0 // indirect github.com/beorn7/perks v1.0.1 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect github.com/census-instrumentation/opencensus-proto v0.4.1 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chai2010/gettext-go v1.0.2 // indirect @@ -76,6 +64,7 @@ require ( github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/go-asn1-ber/asn1-ber v1.5.4 // indirect github.com/go-errors/errors v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/jsonpointer v0.20.0 // indirect github.com/go-openapi/jsonreference v0.20.2 // indirect github.com/go-openapi/swag v0.22.4 // indirect @@ -85,7 +74,9 @@ require ( github.com/google/gofuzz v1.2.0 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/google/uuid v1.3.1 // indirect + github.com/gorilla/websocket v1.5.0 // indirect github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.0 // indirect github.com/hashicorp/errwrap v1.1.0 // indirect github.com/imdario/mergo v0.3.16 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect @@ -95,6 +86,7 @@ require ( github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect github.com/lyft/gostats v0.4.1 // indirect github.com/mailru/easyjson v0.7.7 // indirect + github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/moby/spdystream v0.2.0 // indirect github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect @@ -102,23 +94,29 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect github.com/peterbourgon/diskv v2.0.1+incompatible // indirect + github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_golang v1.18.0 github.com/prometheus/client_model v0.5.0 // indirect github.com/prometheus/procfs v0.12.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/sirupsen/logrus v1.9.0 // indirect github.com/tsaarni/x500dn v1.0.0 // indirect github.com/xlab/treeprint v1.2.0 // indirect + go.opentelemetry.io/otel/sdk v1.21.0 // indirect + go.opentelemetry.io/otel/trace v1.21.0 // indirect go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect go.uber.org/multierr v1.11.0 // indirect + golang.org/x/mod v0.13.0 // indirect golang.org/x/net v0.17.0 // indirect golang.org/x/oauth2 v0.13.0 // indirect + golang.org/x/sync v0.4.0 // indirect golang.org/x/sys v0.15.0 // indirect golang.org/x/term v0.13.0 // indirect golang.org/x/text v0.13.0 // indirect golang.org/x/time v0.3.0 // indirect + golang.org/x/tools v0.14.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect google.golang.org/appengine v1.6.8 // indirect google.golang.org/genproto v0.0.0-20231002182017-d307bd883b97 // indirect @@ -132,6 +130,5 @@ require ( sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/kustomize/api v0.13.5-0.20230601165947-6ce0bf390ce3 // indirect sigs.k8s.io/kustomize/kyaml v0.14.3-0.20230601165947-6ce0bf390ce3 // indirect - sigs.k8s.io/mcs-api v0.1.0 sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect ) diff --git a/internal/cmd/certgen.go b/internal/cmd/certgen.go index 83dafca8440..ed58ae68f8d 100644 --- a/internal/cmd/certgen.go +++ b/internal/cmd/certgen.go @@ -44,17 +44,17 @@ func certGen() error { certs, err := crypto.GenerateCerts(cfg) if err != nil { - return fmt.Errorf("failed to generate certificates: %v", err) + return fmt.Errorf("failed to generate certificates: %w", err) } log.Info("generated certificates") cli, err := client.New(clicfg.GetConfigOrDie(), client.Options{Scheme: envoygateway.GetScheme()}) if err != nil { - return fmt.Errorf("failed to create controller-runtime client: %v", err) + return fmt.Errorf("failed to create controller-runtime client: %w", err) } if err := outputCerts(ctrl.SetupSignalHandler(), cli, cfg, certs); err != nil { - return fmt.Errorf("failed to output certificates: %v", err) + return fmt.Errorf("failed to output certificates: %w", err) } return nil @@ -79,7 +79,7 @@ func outputCerts(ctx context.Context, cli client.Client, cfg *config.Server, cer return nil } - return fmt.Errorf("failed to create or update secrets: %v", err) + return fmt.Errorf("failed to create or update secrets: %w", err) } for i := range secrets { diff --git a/internal/cmd/egctl/envoy_stats.go b/internal/cmd/egctl/envoy_stats.go index 50e3ddb2b9b..8df0dec5ba7 100644 --- a/internal/cmd/egctl/envoy_stats.go +++ b/internal/cmd/egctl/envoy_stats.go @@ -148,17 +148,17 @@ func setupEnvoyServerStatsConfig(kubeClient kubernetes.CLIClient, podName, podNa fw, err := portForwarder(kubeClient, types.NamespacedName{Namespace: podNamespace, Name: podName}) if err != nil { - return "", fmt.Errorf("failed to initialize pod-forwarding for %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to initialize pod-forwarding for %s/%s: %w", podNamespace, podName, err) } err = fw.Start() if err != nil { - return "", fmt.Errorf("failed to start port forwarding for pod %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to start port forwarding for pod %s/%s: %w", podNamespace, podName, err) } defer fw.Stop() result, err := statsRequest(fw.Address(), path) if err != nil { - return "", fmt.Errorf("failed to get stats on envoy for pod %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to get stats on envoy for pod %s/%s: %w", podNamespace, podName, err) } return string(result), nil } @@ -171,17 +171,17 @@ func setupEnvoyClusterStatsConfig(kubeClient kubernetes.CLIClient, podName, podN } fw, err := portForwarder(kubeClient, types.NamespacedName{Namespace: podNamespace, Name: podName}) if err != nil { - return "", fmt.Errorf("failed to initialize pod-forwarding for %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to initialize pod-forwarding for %s/%s: %w", podNamespace, podName, err) } err = fw.Start() if err != nil { - return "", fmt.Errorf("failed to start port forwarding for pod %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to start port forwarding for pod %s/%s: %w", podNamespace, podName, err) } defer fw.Stop() result, err := statsRequest(fw.Address(), path) if err != nil { - return "", fmt.Errorf("failed to get stats on envoy for pod %s/%s: %v", podNamespace, podName, err) + return "", fmt.Errorf("failed to get stats on envoy for pod %s/%s: %w", podNamespace, podName, err) } return string(result), nil } diff --git a/internal/cmd/egctl/version.go b/internal/cmd/egctl/version.go index c960d14cb3e..de3cde37a61 100644 --- a/internal/cmd/egctl/version.go +++ b/internal/cmd/egctl/version.go @@ -11,7 +11,6 @@ import ( "io" "sort" - "github.com/pkg/errors" "github.com/spf13/cobra" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -95,7 +94,7 @@ func versions(w io.Writer, containerName, output string, remote bool) error { pods, err := c.PodsForSelector(metav1.NamespaceAll, "control-plane=envoy-gateway") if err != nil { - return errors.Wrap(err, "list EG pods failed") + return fmt.Errorf("list EG pods failed: %w", err) } for _, pod := range pods.Items { diff --git a/internal/crypto/certgen.go b/internal/crypto/certgen.go index 4f0e86f6bfc..5f4ff4a69a5 100644 --- a/internal/crypto/certgen.go +++ b/internal/crypto/certgen.go @@ -186,7 +186,7 @@ func newCert(request *certificateRequest) ([]byte, []byte, error) { newKey, err := rsa.GenerateKey(rand.Reader, keySize) if err != nil { - return nil, nil, fmt.Errorf("cannot generate key: %v", err) + return nil, nil, fmt.Errorf("cannot generate key: %w", err) } now := time.Now() diff --git a/internal/crypto/certgen_test.go b/internal/crypto/certgen_test.go index f5bb534cf9e..0b9c8d91028 100644 --- a/internal/crypto/certgen_test.go +++ b/internal/crypto/certgen_test.go @@ -149,7 +149,7 @@ func verifyCert(certPEM []byte, roots *x509.CertPool, dnsname string, currentTim CurrentTime: currentTime, } if _, err = cert.Verify(opts); err != nil { - return fmt.Errorf("certificate verification failed: %s", err) + return fmt.Errorf("certificate verification failed: %w", err) } return nil diff --git a/internal/infrastructure/kubernetes/infra.go b/internal/infrastructure/kubernetes/infra.go index 0d1f6e18c03..882d29ef8b4 100644 --- a/internal/infrastructure/kubernetes/infra.go +++ b/internal/infrastructure/kubernetes/infra.go @@ -7,8 +7,8 @@ package kubernetes import ( "context" + "fmt" - "github.com/pkg/errors" appsv1 "k8s.io/api/apps/v1" autoscalingv2 "k8s.io/api/autoscaling/v2" corev1 "k8s.io/api/core/v1" @@ -55,23 +55,23 @@ func NewInfra(cli client.Client, cfg *config.Server) *Infra { // provided ResourceRender, if it doesn't exist and updates it if it does. func (i *Infra) createOrUpdate(ctx context.Context, r ResourceRender) error { if err := i.createOrUpdateServiceAccount(ctx, r); err != nil { - return errors.Wrapf(err, "failed to create or update serviceaccount %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to create or update serviceaccount %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.createOrUpdateConfigMap(ctx, r); err != nil { - return errors.Wrapf(err, "failed to create or update configmap %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to create or update configmap %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.createOrUpdateDeployment(ctx, r); err != nil { - return errors.Wrapf(err, "failed to create or update deployment %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to create or update deployment %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.createOrUpdateService(ctx, r); err != nil { - return errors.Wrapf(err, "failed to create or update service %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to create or update service %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.createOrUpdateHPA(ctx, r); err != nil { - return errors.Wrapf(err, "failed to create or update hpa %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to create or update hpa %s/%s: %w", i.Namespace, r.Name(), err) } return nil @@ -80,23 +80,23 @@ func (i *Infra) createOrUpdate(ctx context.Context, r ResourceRender) error { // delete deletes the ServiceAccount/ConfigMap/Deployment/Service in the kube api server, if it exists. func (i *Infra) delete(ctx context.Context, r ResourceRender) error { if err := i.deleteServiceAccount(ctx, r); err != nil { - return errors.Wrapf(err, "failed to delete serviceaccount %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to delete serviceaccount %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.deleteConfigMap(ctx, r); err != nil { - return errors.Wrapf(err, "failed to delete configmap %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to delete configmap %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.deleteDeployment(ctx, r); err != nil { - return errors.Wrapf(err, "failed to delete deployment %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to delete deployment %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.deleteService(ctx, r); err != nil { - return errors.Wrapf(err, "failed to delete service %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to delete service %s/%s: %w", i.Namespace, r.Name(), err) } if err := i.deleteHPA(ctx, r); err != nil { - return errors.Wrapf(err, "failed to delete hpa %s/%s", i.Namespace, r.Name()) + return fmt.Errorf("failed to delete hpa %s/%s: %w", i.Namespace, r.Name(), err) } return nil diff --git a/internal/infrastructure/kubernetes/infra_client.go b/internal/infrastructure/kubernetes/infra_client.go index e9b8090b970..e1c2a0b2b89 100644 --- a/internal/infrastructure/kubernetes/infra_client.go +++ b/internal/infrastructure/kubernetes/infra_client.go @@ -7,8 +7,8 @@ package kubernetes import ( "context" + "fmt" - "github.com/pkg/errors" kerrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/util/retry" @@ -31,7 +31,7 @@ func (cli *InfraClient) CreateOrUpdate(ctx context.Context, key client.ObjectKey if kerrors.IsNotFound(err) { // Create if it does not exist. if err := cli.Client.Create(ctx, specific); err != nil { - return errors.Wrap(err, "for Create") + return fmt.Errorf("for Create: %w", err) } } } else { @@ -40,7 +40,7 @@ func (cli *InfraClient) CreateOrUpdate(ctx context.Context, key client.ObjectKey if updateChecker() { specific.SetUID(current.GetUID()) if err := cli.Client.Update(ctx, specific); err != nil { - return errors.Wrap(err, "for Update") + return fmt.Errorf("for Update: %w", err) } } } diff --git a/internal/kubernetes/client.go b/internal/kubernetes/client.go index 205e13eabd2..317ed852c37 100644 --- a/internal/kubernetes/client.go +++ b/internal/kubernetes/client.go @@ -129,10 +129,10 @@ func (c *client) PodExec(namespacedName types.NamespacedName, container string, defer func() { if err != nil { if len(stderr) > 0 { - err = fmt.Errorf("error exec into %s/%s container %s: %v\n%s", + err = fmt.Errorf("error exec into %s/%s container %s: %w\n%s", namespacedName.Namespace, namespacedName.Name, container, err, stderr) } else { - err = fmt.Errorf("error exec into %s/%s container %s: %v", + err = fmt.Errorf("error exec into %s/%s container %s: %w", namespacedName.Namespace, namespacedName.Name, container, err) } } diff --git a/internal/kubernetes/port-forwarder.go b/internal/kubernetes/port-forwarder.go index b38fe7b93a8..a58e88ea5cd 100644 --- a/internal/kubernetes/port-forwarder.go +++ b/internal/kubernetes/port-forwarder.go @@ -11,7 +11,6 @@ import ( "net/http" "os" - "github.com/pkg/errors" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/rest" "k8s.io/client-go/tools/portforward" @@ -53,7 +52,7 @@ func NewLocalPortForwarder(client CLIClient, namespacedName types.NamespacedName // get a random port p, err := netutil.LocalAvailablePort() if err != nil { - return nil, errors.Wrapf(err, "failed to get a local available port for Pod %q", namespacedName) + return nil, fmt.Errorf("failed to get a local available port for Pod %q: %w", namespacedName, err) } f.localPort = p } @@ -90,7 +89,7 @@ func (f *localForwarder) Start() error { select { case err := <-errCh: - return errors.Wrap(err, "failed to start port forwarder") + return fmt.Errorf("failed to start port forwarder: %w", err) case <-readyCh: return nil } @@ -107,7 +106,7 @@ func (f *localForwarder) buildKubernetesPortForwarder(readyCh chan struct{}) (*p roundTripper, upgrader, err := spdy.RoundTripperFor(f.RESTConfig()) if err != nil { - return nil, fmt.Errorf("failure creating roundtripper: %v", err) + return nil, fmt.Errorf("failure creating roundtripper: %w", err) } dialer := spdy.NewDialer(upgrader, &http.Client{Transport: roundTripper}, http.MethodPost, serverURL) @@ -119,7 +118,7 @@ func (f *localForwarder) buildKubernetesPortForwarder(readyCh chan struct{}) (*p io.Discard, os.Stderr) if err != nil { - return nil, fmt.Errorf("failed establishing portforward: %v", err) + return nil, fmt.Errorf("failed establishing portforward: %w", err) } return fw, nil diff --git a/internal/kubernetes/secret.go b/internal/kubernetes/secret.go index 700c9b8a4d6..ff98d61874b 100644 --- a/internal/kubernetes/secret.go +++ b/internal/kubernetes/secret.go @@ -7,9 +7,9 @@ package kubernetes import ( "context" + "errors" "fmt" - "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" k8smachinery "k8s.io/apimachinery/pkg/types" k8sclient "sigs.k8s.io/controller-runtime/pkg/client" diff --git a/internal/provider/kubernetes/controller.go b/internal/provider/kubernetes/controller.go index 7eee07267c4..f9bca7f01a1 100644 --- a/internal/provider/kubernetes/controller.go +++ b/internal/provider/kubernetes/controller.go @@ -155,7 +155,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, _ reconcile.Reques var gatewayClasses gwapiv1.GatewayClassList if err := r.client.List(ctx, &gatewayClasses); err != nil { - return reconcile.Result{}, fmt.Errorf("error listing gatewayclasses: %v", err) + return reconcile.Result{}, fmt.Errorf("error listing gatewayclasses: %w", err) } var cc controlledClasses @@ -269,7 +269,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, _ reconcile.Reques if r.envoyGateway.ExtensionAPIs != nil && r.envoyGateway.ExtensionAPIs.EnableEnvoyPatchPolicy { envoyPatchPolicies := v1alpha1.EnvoyPatchPolicyList{} if err := r.client.List(ctx, &envoyPatchPolicies); err != nil { - return reconcile.Result{}, fmt.Errorf("error listing EnvoyPatchPolicies: %v", err) + return reconcile.Result{}, fmt.Errorf("error listing EnvoyPatchPolicies: %w", err) } for _, policy := range envoyPatchPolicies.Items { @@ -284,7 +284,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, _ reconcile.Reques // Add all ClientTrafficPolicies clientTrafficPolicies := v1alpha1.ClientTrafficPolicyList{} if err := r.client.List(ctx, &clientTrafficPolicies); err != nil { - return reconcile.Result{}, fmt.Errorf("error listing ClientTrafficPolicies: %v", err) + return reconcile.Result{}, fmt.Errorf("error listing ClientTrafficPolicies: %w", err) } for _, policy := range clientTrafficPolicies.Items { @@ -299,7 +299,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, _ reconcile.Reques // Add all BackendTrafficPolicies backendTrafficPolicies := v1alpha1.BackendTrafficPolicyList{} if err := r.client.List(ctx, &backendTrafficPolicies); err != nil { - return reconcile.Result{}, fmt.Errorf("error listing BackendTrafficPolicies: %v", err) + return reconcile.Result{}, fmt.Errorf("error listing BackendTrafficPolicies: %w", err) } for _, policy := range backendTrafficPolicies.Items { @@ -313,7 +313,7 @@ func (r *gatewayAPIReconciler) Reconcile(ctx context.Context, _ reconcile.Reques // Add all SecurityPolicies securityPolicies := v1alpha1.SecurityPolicyList{} if err := r.client.List(ctx, &securityPolicies); err != nil { - return reconcile.Result{}, fmt.Errorf("error listing SecurityPolicies: %v", err) + return reconcile.Result{}, fmt.Errorf("error listing SecurityPolicies: %w", err) } for _, policy := range securityPolicies.Items { @@ -472,7 +472,7 @@ func (r *gatewayAPIReconciler) processSecretRef( refGrant, err := r.findReferenceGrant(ctx, from, to) switch { case err != nil: - return fmt.Errorf("failed to find ReferenceGrant: %v", err) + return fmt.Errorf("failed to find ReferenceGrant: %w", err) case refGrant == nil: return fmt.Errorf( "no matching ReferenceGrants found: from %s/%s to %s/%s", @@ -573,7 +573,7 @@ func (r *gatewayAPIReconciler) findReferenceGrant(ctx context.Context, from, to refGrantList := new(gwapiv1b1.ReferenceGrantList) opts := &client.ListOptions{FieldSelector: fields.OneTermEqualSelector(targetRefGrantRouteIndex, to.kind)} if err := r.client.List(ctx, refGrantList, opts); err != nil { - return nil, fmt.Errorf("failed to list ReferenceGrants: %v", err) + return nil, fmt.Errorf("failed to list ReferenceGrants: %w", err) } refGrants := refGrantList.Items @@ -584,7 +584,7 @@ func (r *gatewayAPIReconciler) findReferenceGrant(ctx context.Context, from, to ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return nil, fmt.Errorf("failed to check namespace labels for ReferenceGrant %s in namespace %s: %s", refGrant.GetName(), ns, err) + return nil, fmt.Errorf("failed to check namespace labels for ReferenceGrant %s in namespace %s: %w", refGrant.GetName(), ns, err) } if !ok { // TODO: should log? @@ -628,7 +628,7 @@ func (r *gatewayAPIReconciler) processGateways(ctx context.Context, acceptedGC * ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for gateway %s in namespace %s: %s", gtw.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for gateway %s in namespace %s: %w", gtw.GetName(), ns, err) } if ok { @@ -1697,7 +1697,7 @@ func (r *gatewayAPIReconciler) processParamsRef(ctx context.Context, gc *gwapiv1 // The EnvoyProxy must be in the same namespace as EG. if err := r.client.List(ctx, epList, &client.ListOptions{Namespace: r.namespace}); err != nil { - return fmt.Errorf("failed to list envoyproxies in namespace %s: %v", r.namespace, err) + return fmt.Errorf("failed to list envoyproxies in namespace %s: %w", r.namespace, err) } if len(epList.Items) == 0 { @@ -1714,7 +1714,7 @@ func (r *gatewayAPIReconciler) processParamsRef(ctx context.Context, gc *gwapiv1 if classRefsEnvoyProxy(gc, &ep) { found = true if err := validation.ValidateEnvoyProxy(&ep); err != nil { - validationErr = fmt.Errorf("invalid envoyproxy: %v", err) + validationErr = fmt.Errorf("invalid envoyproxy: %w", err) continue } valid = true @@ -1728,7 +1728,7 @@ func (r *gatewayAPIReconciler) processParamsRef(ctx context.Context, gc *gwapiv1 } if !valid { - return fmt.Errorf("invalid gatewayclass %s: %v", gc.Name, validationErr) + return fmt.Errorf("invalid gatewayclass %s: %w", gc.Name, validationErr) } return nil diff --git a/internal/provider/kubernetes/filters.go b/internal/provider/kubernetes/filters.go index d526e06d12e..caa3cb1018d 100644 --- a/internal/provider/kubernetes/filters.go +++ b/internal/provider/kubernetes/filters.go @@ -19,7 +19,7 @@ func (r *gatewayAPIReconciler) getExtensionRefFilters(ctx context.Context) ([]un uExtResourceList.SetGroupVersionKind(gvk) if err := r.client.List(ctx, uExtResourceList); err != nil { r.log.Info("no associated resources found for %s", gvk.String()) - return nil, fmt.Errorf("failed to list %s: %v", gvk.String(), err) + return nil, fmt.Errorf("failed to list %s: %w", gvk.String(), err) } uExtResources := uExtResourceList.Items @@ -30,7 +30,7 @@ func (r *gatewayAPIReconciler) getExtensionRefFilters(ctx context.Context) ([]un ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return nil, fmt.Errorf("failed to check namespace labels for ExtensionRefFilter %s in namespace %s: %s", extR.GetName(), ns, err) + return nil, fmt.Errorf("failed to check namespace labels for ExtensionRefFilter %s in namespace %s: %w", extR.GetName(), ns, err) } if ok { extRs = append(extRs, extR) diff --git a/internal/provider/kubernetes/helpers.go b/internal/provider/kubernetes/helpers.go index 04bf83fecba..d8d6a74b29f 100644 --- a/internal/provider/kubernetes/helpers.go +++ b/internal/provider/kubernetes/helpers.go @@ -61,13 +61,13 @@ func validateParentRefs(ctx context.Context, client client.Client, namespace str gw := new(gwapiv1.Gateway) if err := client.Get(ctx, gwKey, gw); err != nil { - return nil, fmt.Errorf("failed to get gateway %s/%s: %v", gwKey.Namespace, gwKey.Name, err) + return nil, fmt.Errorf("failed to get gateway %s/%s: %w", gwKey.Namespace, gwKey.Name, err) } gcKey := types.NamespacedName{Name: string(gw.Spec.GatewayClassName)} gc := new(gwapiv1.GatewayClass) if err := client.Get(ctx, gcKey, gc); err != nil { - return nil, fmt.Errorf("failed to get gatewayclass %s: %v", gcKey.Name, err) + return nil, fmt.Errorf("failed to get gatewayclass %s: %w", gcKey.Name, err) } if gc.Spec.ControllerName == gatewayClassController { gateways = append(gateways, *gw) diff --git a/internal/provider/kubernetes/kubernetes.go b/internal/provider/kubernetes/kubernetes.go index 104400f2b05..e84b9d442ff 100644 --- a/internal/provider/kubernetes/kubernetes.go +++ b/internal/provider/kubernetes/kubernetes.go @@ -56,7 +56,7 @@ func New(cfg *rest.Config, svr *config.Server, resources *message.ProviderResour updateHandler := status.NewUpdateHandler(mgr.GetLogger(), mgr.GetClient()) if err := mgr.Add(updateHandler); err != nil { - return nil, fmt.Errorf("failed to add status update handler %v", err) + return nil, fmt.Errorf("failed to add status update handler %w", err) } // Create and register the controllers with the manager. diff --git a/internal/provider/kubernetes/routes.go b/internal/provider/kubernetes/routes.go index a85277f9a29..39ea26f1309 100644 --- a/internal/provider/kubernetes/routes.go +++ b/internal/provider/kubernetes/routes.go @@ -41,7 +41,7 @@ func (r *gatewayAPIReconciler) processTLSRoutes(ctx context.Context, gatewayName ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for TLSRoute %s in namespace %s: %s", rt.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for TLSRoute %s in namespace %s: %w", rt.GetName(), ns, err) } if ok { @@ -122,7 +122,7 @@ func (r *gatewayAPIReconciler) processGRPCRoutes(ctx context.Context, gatewayNam ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for GRPCRoute %s in namespace %s: %s", gr.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for GRPCRoute %s in namespace %s: %w", gr.GetName(), ns, err) } if ok { grs = append(grs, gr) @@ -251,7 +251,7 @@ func (r *gatewayAPIReconciler) processHTTPRoutes(ctx context.Context, gatewayNam ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for HTTPRoute %s in namespace %s: %s", hr.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for HTTPRoute %s in namespace %s: %w", hr.GetName(), ns, err) } if ok { @@ -424,7 +424,7 @@ func (r *gatewayAPIReconciler) processTCPRoutes(ctx context.Context, gatewayName ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for TCPRoute %s in namespace %s: %s", tr.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for TCPRoute %s in namespace %s: %w", tr.GetName(), ns, err) } if ok { @@ -505,7 +505,7 @@ func (r *gatewayAPIReconciler) processUDPRoutes(ctx context.Context, gatewayName ok, err := r.checkObjectNamespaceLabels(ns) if err != nil { // TODO: should return? or just proceed? - return fmt.Errorf("failed to check namespace labels for UDPRoute %s in namespace %s: %s", ur.GetName(), ns, err) + return fmt.Errorf("failed to check namespace labels for UDPRoute %s in namespace %s: %w", ur.GetName(), ns, err) } if ok { diff --git a/internal/utils/regex/regex.go b/internal/utils/regex/regex.go index cefd1603ddd..e4c686a6eab 100644 --- a/internal/utils/regex/regex.go +++ b/internal/utils/regex/regex.go @@ -13,7 +13,7 @@ import ( // Validate validates a regex string. func Validate(regex string) error { if _, err := regexp.Compile(regex); err != nil { - return fmt.Errorf("regex %q is invalid: %v", regex, err) + return fmt.Errorf("regex %q is invalid: %w", regex, err) } return nil } diff --git a/internal/xds/bootstrap/bootstrap.go b/internal/xds/bootstrap/bootstrap.go index 867ef313b40..8d6b2b67b77 100644 --- a/internal/xds/bootstrap/bootstrap.go +++ b/internal/xds/bootstrap/bootstrap.go @@ -114,7 +114,7 @@ type StatsMatcherParameters struct { func (b *bootstrapConfig) render() error { buf := new(strings.Builder) if err := bootstrapTmpl.Execute(buf, b.parameters); err != nil { - return fmt.Errorf("failed to render bootstrap config: %v", err) + return fmt.Errorf("failed to render bootstrap config: %w", err) } b.rendered = buf.String() diff --git a/internal/xds/server/runner/runner_test.go b/internal/xds/server/runner/runner_test.go index 6f574e2f9f2..b86b9760345 100644 --- a/internal/xds/server/runner/runner_test.go +++ b/internal/xds/server/runner/runner_test.go @@ -9,6 +9,7 @@ import ( "context" "crypto/tls" "crypto/x509" + "errors" "net" "os" "path/filepath" @@ -180,7 +181,8 @@ func peekError(conn net.Conn) error { _ = conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond)) _, err := conn.Read(make([]byte, 1)) if err != nil { - if netErr, ok := err.(net.Error); !ok || !netErr.Timeout() { + var netErr net.Error + if !errors.As(netErr, &netErr) || !netErr.Timeout() { return err } } diff --git a/internal/xds/translator/jsonpatch.go b/internal/xds/translator/jsonpatch.go index c9364c769dc..c57e0010874 100644 --- a/internal/xds/translator/jsonpatch.go +++ b/internal/xds/translator/jsonpatch.go @@ -134,7 +134,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* } if resourceJSON, err = m.Marshal(listener); err != nil { - err := fmt.Errorf("unable to marshal xds resource %s: %s, err:%v", p.Type, p.Name, err) + err := fmt.Errorf("unable to marshal xds resource %s: %s, err: %w", p.Type, p.Name, err) errs = multierror.Append(errs, err) continue } @@ -147,7 +147,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* } if resourceJSON, err = m.Marshal(routeConfig); err != nil { - err = fmt.Errorf("unable to marshal xds resource %s: %s, err:%v", p.Type, p.Name, err) + err = fmt.Errorf("unable to marshal xds resource %s: %s, err: %w", p.Type, p.Name, err) errs = multierror.Append(errs, err) continue } @@ -160,7 +160,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* } if resourceJSON, err = m.Marshal(cluster); err != nil { - err = fmt.Errorf("unable to marshal xds resource %s: %s, err:%v", p.Type, p.Name, err) + err = fmt.Errorf("unable to marshal xds resource %s: %s, err: %w", p.Type, p.Name, err) errs = multierror.Append(errs, err) continue } @@ -171,7 +171,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* continue } if resourceJSON, err = m.Marshal(endpoint); err != nil { - err = fmt.Errorf("unable to marshal xds resource %s: %s, err:%v", p.Type, p.Name, err) + err = fmt.Errorf("unable to marshal xds resource %s: %s, err: %w", p.Type, p.Name, err) errs = multierror.Append(errs, err) continue } @@ -226,7 +226,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* continue } if err = deepCopyPtr(temp, listener); err != nil { - err := fmt.Errorf("unable to copy xds resource %s, err:%v", string(modifiedJSON), err) + err := fmt.Errorf("unable to copy xds resource %s, err: %w", string(modifiedJSON), err) errs = multierror.Append(errs, err) continue } @@ -243,7 +243,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* continue } if err = deepCopyPtr(temp, routeConfig); err != nil { - err := fmt.Errorf("unable to copy xds resource %s, err:%v", string(modifiedJSON), err) + err := fmt.Errorf("unable to copy xds resource %s, err: %w", string(modifiedJSON), err) errs = multierror.Append(errs, err) continue } @@ -260,7 +260,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* continue } if err = deepCopyPtr(temp, cluster); err != nil { - err := fmt.Errorf("unable to copy xds resource %s, err:%v", string(modifiedJSON), err) + err := fmt.Errorf("unable to copy xds resource %s, err: %w", string(modifiedJSON), err) errs = multierror.Append(errs, err) continue } @@ -277,7 +277,7 @@ func processJSONPatches(tCtx *types.ResourceVersionTable, envoyPatchPolicies []* continue } if err = deepCopyPtr(temp, endpoint); err != nil { - err := fmt.Errorf("unable to copy xds resource %s, err:%v", string(modifiedJSON), err) + err := fmt.Errorf("unable to copy xds resource %s, err: %w", string(modifiedJSON), err) errs = multierror.Append(errs, err) continue } diff --git a/internal/xds/translator/tracing.go b/internal/xds/translator/tracing.go index 1349995ff86..60a66bec79b 100644 --- a/internal/xds/translator/tracing.go +++ b/internal/xds/translator/tracing.go @@ -6,6 +6,8 @@ package translator import ( + "errors" + "fmt" "sort" corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" @@ -13,7 +15,6 @@ import ( hcm "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" tracingtype "github.com/envoyproxy/go-control-plane/envoy/type/tracing/v3" xdstype "github.com/envoyproxy/go-control-plane/envoy/type/v3" - "github.com/pkg/errors" "k8s.io/utils/ptr" egv1a1 "github.com/envoyproxy/gateway/api/v1alpha1" @@ -41,7 +42,7 @@ func buildHCMTracing(tracing *ir.Tracing) (*hcm.HttpConnectionManager_Tracing, e ocAny, err := protocov.ToAnyWithError(oc) if err != nil { - return nil, errors.Wrap(err, "failed to marshal OpenTelemetryConfig") + return nil, fmt.Errorf("failed to marshal OpenTelemetryConfig: %w", err) } tags := []*tracingtype.CustomTag{} @@ -88,7 +89,7 @@ func buildHCMTracing(tracing *ir.Tracing) (*hcm.HttpConnectionManager_Tracing, e }, }) default: - return nil, errors.Errorf("unknown custom tag type: %s", v.Type) + return nil, fmt.Errorf("unknown custom tag type: %s", v.Type) } } // sort tags by tag name, make result consistent diff --git a/internal/xds/types/resourceversiontable.go b/internal/xds/types/resourceversiontable.go index 067f67273c1..bf0d5a865f6 100644 --- a/internal/xds/types/resourceversiontable.go +++ b/internal/xds/types/resourceversiontable.go @@ -82,7 +82,7 @@ func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource // Handle Type specific operations if resourceOfType, ok := xdsResource.(*listenerv3.Listener); ok { if err := resourceOfType.ValidateAll(); err != nil { - return fmt.Errorf("validation failed for xds resource %+v, err:%v", xdsResource, err) + return fmt.Errorf("validation failed for xds resource %+v, err: %w", xdsResource, err) } } else { return fmt.Errorf("failed to cast xds resource %+v to Listener type", xdsResource) @@ -91,7 +91,7 @@ func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource // Handle Type specific operations if resourceOfType, ok := xdsResource.(*routev3.RouteConfiguration); ok { if err := resourceOfType.ValidateAll(); err != nil { - return fmt.Errorf("validation failed for xds resource %+v, err:%v", xdsResource, err) + return fmt.Errorf("validation failed for xds resource %+v, err: %w", xdsResource, err) } } else { return fmt.Errorf("failed to cast xds resource %+v to RouteConfiguration type", xdsResource) @@ -101,7 +101,7 @@ func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource // Handle specific operations if resourceOfType, ok := xdsResource.(*tlsv3.Secret); ok { if err := resourceOfType.ValidateAll(); err != nil { - return fmt.Errorf("validation failed for xds resource %+v, err:%v", xdsResource, err) + return fmt.Errorf("validation failed for xds resource %+v, err: %w", xdsResource, err) } } else { return fmt.Errorf("failed to cast xds resource %+v to Secret type", xdsResource) @@ -110,7 +110,7 @@ func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource case resourcev3.EndpointType: if resourceOfType, ok := xdsResource.(*endpointv3.ClusterLoadAssignment); ok { if err := resourceOfType.ValidateAll(); err != nil { - return fmt.Errorf("validation failed for xds resource %+v, err:%v", xdsResource, err) + return fmt.Errorf("validation failed for xds resource %+v, err: %w", xdsResource, err) } } else { return fmt.Errorf("failed to cast xds resource %+v to ClusterLoadAssignment type", xdsResource) @@ -120,7 +120,7 @@ func (t *ResourceVersionTable) AddXdsResource(rType resourcev3.Type, xdsResource // Handle specific operations if resourceOfType, ok := xdsResource.(*clusterv3.Cluster); ok { if err := resourceOfType.ValidateAll(); err != nil { - return fmt.Errorf("validation failed for xds resource %+v, err:%v", xdsResource, err) + return fmt.Errorf("validation failed for xds resource %+v, err: %w", xdsResource, err) } } else { return fmt.Errorf("failed to cast xds resource %+v to Cluster type", xdsResource) diff --git a/test/e2e/tests/metric.go b/test/e2e/tests/metric.go index 2c9a8c296c3..fe658252198 100644 --- a/test/e2e/tests/metric.go +++ b/test/e2e/tests/metric.go @@ -131,7 +131,7 @@ func ScrapeMetrics(t *testing.T, c client.Client, nn types.NamespacedName, port } res, err := httpClient.Get(url) if err != nil { - return fmt.Errorf("failed to scrape metrics: %v", err) + return fmt.Errorf("failed to scrape metrics: %w", err) } if res.StatusCode != http.StatusOK { return fmt.Errorf("failed to scrape metrics: %s", res.Status) diff --git a/tools/linter/golangci-lint/.golangci.yml b/tools/linter/golangci-lint/.golangci.yml index 56f8ee1278e..ca5ffcc63e3 100644 --- a/tools/linter/golangci-lint/.golangci.yml +++ b/tools/linter/golangci-lint/.golangci.yml @@ -1,11 +1,11 @@ run: - deadline: 10m + timeout: 10m linters: enable: - - stylecheck - bodyclose - depguard + - errorlint - exportloopref - gofmt - goimports @@ -14,6 +14,7 @@ linters: - gosec - misspell - revive + - stylecheck - unconvert - unparam @@ -37,7 +38,7 @@ linters-settings: # Contains all imports that could not be matched to another section type. - default # Groups all imports with the specified Prefix. - - prefix(github.com/envoyproxy/gateway/) + - prefix(github.com/envoyproxy/gateway) goimports: # put imports beginning with prefix after 3rd-party packages; # it's a comma-separated list of prefixes