From 344345a984d355f2fb5cf52af9a31f86175c8b12 Mon Sep 17 00:00:00 2001 From: Luca Comellini Date: Tue, 4 Jun 2024 18:55:07 -0700 Subject: [PATCH] Add more linters Problem: We want to catch errors and styling issues as early as possible. Solution: Enable new linters. --- .github/workflows/ci.yml | 6 +++++ .golangci.yml | 24 +++++++++++++++++++ Makefile | 2 +- apis/v1alpha1/clientsettingspolicy_types.go | 2 +- apis/v1alpha1/register.go | 4 ++-- cmd/gateway/commands.go | 3 ++- cmd/gateway/commands_test.go | 1 + cmd/gateway/main.go | 2 +- cmd/gateway/validation.go | 5 ++-- .../framework/controller/predicate/service.go | 2 +- internal/framework/controller/reconciler.go | 6 ++++- internal/framework/kinds/kinds.go | 4 ++-- internal/framework/runnables/cronjob.go | 2 +- internal/framework/status/updater.go | 2 -- internal/mode/static/handler.go | 17 +++++++------ internal/mode/static/manager.go | 7 +++--- .../static/metrics/collectors/controller.go | 2 +- .../mode/static/metrics/collectors/nginx.go | 4 ++-- .../metrics/collectors/nginx_runtime.go | 4 ++-- internal/mode/static/metrics/metrics.go | 1 - .../nginx/config/base_http_config_test.go | 1 - internal/mode/static/nginx/config/maps.go | 2 +- internal/mode/static/nginx/config/servers.go | 10 ++++---- .../mode/static/nginx/config/split_clients.go | 6 ++--- .../nginx/config/validation/framework_test.go | 5 ++++ .../nginx/config/validation/http_validator.go | 2 +- .../mode/static/nginx/file/manager_test.go | 12 +++++----- .../mode/static/nginx/file/os_filemanager.go | 2 +- internal/mode/static/nginx/runtime/verify.go | 2 +- .../mode/static/nginx/runtime/verify_test.go | 2 +- .../policies/clientsettings/validator.go | 1 - .../static/state/dataplane/configuration.go | 3 +-- .../mode/static/state/graph/backend_refs.go | 1 - internal/mode/static/state/graph/gateway.go | 2 +- .../mode/static/state/graph/gateway_test.go | 1 - .../mode/static/state/graph/graph_test.go | 1 - internal/mode/static/state/graph/grpcroute.go | 2 +- .../mode/static/state/graph/policies_test.go | 2 +- .../static/state/graph/reference_grant.go | 1 - .../mode/static/state/graph/route_common.go | 14 +++++------ .../mode/static/state/resolver/resolver.go | 3 --- .../static/state/resolver/resolver_test.go | 3 ++- internal/mode/static/state/store.go | 4 ++-- .../mode/static/status/prepare_requests.go | 2 -- internal/mode/static/status/status_setters.go | 7 +++--- internal/mode/static/usage/reporter.go | 4 ++-- internal/mode/static/usage/reporter_test.go | 4 ++-- tests/framework/generate_manifests.go | 6 ++--- tests/framework/load.go | 2 +- tests/framework/prometheus.go | 6 ++--- tests/framework/resourcemanager.go | 6 ++--- tests/suite/scale_test.go | 2 +- tests/suite/tracing_test.go | 5 ++-- 53 files changed, 123 insertions(+), 103 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a4b9bfb04c..f7f6017f4f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,9 @@ jobs: uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1 with: go-version: stable + cache-dependency-path: | + go.sum + .github/.cache/buster-for-vars - name: Check for changes uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 @@ -81,6 +84,9 @@ jobs: uses: actions/setup-go@cdcb36043654635271a94b9a6d1392de5bb323a7 # v5.0.1 with: go-version: stable + cache-dependency-path: | + go.sum + .github/.cache/buster-for-unit-tests - name: Run Tests run: make unit-test diff --git a/.golangci.yml b/.golangci.yml index 041ff220a3..c1928bd424 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -37,33 +37,57 @@ linters-settings: - fieldalignment lll: line-length: 120 + dupword: + ignore: + - "test" linters: enable: + - asasalint - asciicheck + - dupword - errcheck + - errname - errorlint + - exportloopref + - fatcontext + - forcetypeassert - ginkgolinter + - gocheckcompilerdirectives - gocyclo + - godot - gofmt - gofumpt - goimports - gosec - gosimple + - gosmopolitan - govet - ineffassign + - intrange - lll + - loggercheck - makezero - misspell - nilerr - noctx + - nolintlint + - prealloc - predeclared + - promlinter + - reassign - revive + - spancheck - staticcheck + - stylecheck + - tenv + - thelper - typecheck - unconvert - unparam - unused + - usestdlibvars - wastedassign + - whitespace disable-all: true issues: max-issues-per-linter: 0 diff --git a/Makefile b/Makefile index 9311a5b1d6..f26c1aef5e 100644 --- a/Makefile +++ b/Makefile @@ -188,7 +188,7 @@ check-golangci-lint: .PHONY: lint lint: check-golangci-lint ## Run golangci-lint against code - golangci-lint run + golangci-lint run --fix .PHONY: unit-test unit-test: ## Run unit tests for the go code diff --git a/apis/v1alpha1/clientsettingspolicy_types.go b/apis/v1alpha1/clientsettingspolicy_types.go index e4497e4521..6948f3339a 100644 --- a/apis/v1alpha1/clientsettingspolicy_types.go +++ b/apis/v1alpha1/clientsettingspolicy_types.go @@ -108,7 +108,7 @@ type ClientKeepAlive struct { } // ClientKeepAliveTimeout defines the timeouts related to keep-alive client connections. -// Default: Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout. +// Default: https://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout. type ClientKeepAliveTimeout struct { // Server sets the timeout during which a keep-alive client connection will stay open on the server side. // Setting this value to 0 disables keep-alive client connections. diff --git a/apis/v1alpha1/register.go b/apis/v1alpha1/register.go index c0f23fcac3..bacf47d737 100644 --- a/apis/v1alpha1/register.go +++ b/apis/v1alpha1/register.go @@ -9,10 +9,10 @@ import ( // GroupName specifies the group name used to register the objects. const GroupName = "gateway.nginx.org" -// SchemeGroupVersion is group version used to register these objects +// SchemeGroupVersion is group version used to register these objects. var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} -// Resource takes an unqualified resource and returns a Group qualified GroupResource +// Resource takes an unqualified resource and returns a Group qualified GroupResource. func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } diff --git a/cmd/gateway/commands.go b/cmd/gateway/commands.go index 222088f795..ce2cdcb0ec 100644 --- a/cmd/gateway/commands.go +++ b/cmd/gateway/commands.go @@ -444,8 +444,9 @@ func createProvisionerModeCommand() *cobra.Command { // FIXME(pleshakov): Remove this command once NGF min supported Kubernetes version supports sleep action in // preStop hook. -// nolint:lll // See https://github.com/kubernetes/enhancements/tree/4ec371d92dcd4f56a2ab18c8ba20bb85d8d20efe/keps/sig-node/3960-pod-lifecycle-sleep-action +// +//nolint:lll func createSleepCommand() *cobra.Command { // flag names const durationFlag = "duration" diff --git a/cmd/gateway/commands_test.go b/cmd/gateway/commands_test.go index c2ae80a238..4d777d0671 100644 --- a/cmd/gateway/commands_test.go +++ b/cmd/gateway/commands_test.go @@ -18,6 +18,7 @@ type flagTestCase struct { } func testFlag(t *testing.T, cmd *cobra.Command, test flagTestCase) { + t.Helper() g := NewWithT(t) // discard any output generated by cobra cmd.SetOut(io.Discard) diff --git a/cmd/gateway/main.go b/cmd/gateway/main.go index 8761e3f1cd..435a0064c5 100644 --- a/cmd/gateway/main.go +++ b/cmd/gateway/main.go @@ -5,7 +5,7 @@ import ( "os" ) -// Set during go build +// Set during go build. var ( version string commit string diff --git a/cmd/gateway/validation.go b/cmd/gateway/validation.go index 2e3d60b3b7..5559713f6d 100644 --- a/cmd/gateway/validation.go +++ b/cmd/gateway/validation.go @@ -14,7 +14,6 @@ import ( ) const ( - // nolint:lll // Regex from: https://github.com/kubernetes-sigs/gateway-api/blob/v1.1.0/apis/v1/shared_types.go#L647 controllerNameRegex = `^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*\/[A-Za-z0-9\/\-._~%!$&'()*+,;=:]+$` //nolint:lll ) @@ -163,7 +162,7 @@ func validateEndpoint(endpoint string) error { return fmt.Errorf("%q must be in the format :", endpoint) } -// validatePort makes sure a given port is inside the valid port range for its usage +// validatePort makes sure a given port is inside the valid port range for its usage. func validatePort(port int) error { if port < 1024 || port > 65535 { return fmt.Errorf("port outside of valid port range [1024 - 65535]: %v", port) @@ -171,7 +170,7 @@ func validatePort(port int) error { return nil } -// ensureNoPortCollisions checks if the same port has been defined multiple times +// ensureNoPortCollisions checks if the same port has been defined multiple times. func ensureNoPortCollisions(ports ...int) error { seen := make(map[int]struct{}) diff --git a/internal/framework/controller/predicate/service.go b/internal/framework/controller/predicate/service.go index d1b361fb13..04eea8f5d2 100644 --- a/internal/framework/controller/predicate/service.go +++ b/internal/framework/controller/predicate/service.go @@ -50,7 +50,7 @@ func (ServicePortsChangedPredicate) Update(e event.UpdateEvent) bool { oldPortSet := make(map[ports]struct{}) newPortSet := make(map[ports]struct{}) - for i := 0; i < len(oldSvc.Spec.Ports); i++ { + for i := range len(oldSvc.Spec.Ports) { oldPortSet[ports{servicePort: oldPorts[i].Port, targetPort: oldPorts[i].TargetPort}] = struct{}{} newPortSet[ports{servicePort: newPorts[i].Port, targetPort: newPorts[i].TargetPort}] = struct{}{} } diff --git a/internal/framework/controller/reconciler.go b/internal/framework/controller/reconciler.go index 629c0ba5f0..42bf1947bd 100644 --- a/internal/framework/controller/reconciler.go +++ b/internal/framework/controller/reconciler.go @@ -65,7 +65,11 @@ func (r *Reconciler) newObject(objectType ngftypes.ObjectType) ngftypes.ObjectTy t := reflect.TypeOf(objectType).Elem() // We could've used objectType.DeepCopyObject() here, but it's a bit slower confirmed by benchmarks. - return reflect.New(t).Interface().(client.Object) + obj, ok := reflect.New(t).Interface().(client.Object) + if !ok { + panic("failed to create a new object") + } + return obj } // Reconcile implements the reconcile.Reconciler Reconcile method. diff --git a/internal/framework/kinds/kinds.go b/internal/framework/kinds/kinds.go index 790ae4eabc..f5efa38187 100644 --- a/internal/framework/kinds/kinds.go +++ b/internal/framework/kinds/kinds.go @@ -9,9 +9,9 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) -// Gateway API Kinds +// Gateway API Kinds. const ( - // Gateway is the Gateway Kind + // Gateway is the Gateway Kind. Gateway = "Gateway" // GatewayClass is the GatewayClass Kind. GatewayClass = "GatewayClass" diff --git a/internal/framework/runnables/cronjob.go b/internal/framework/runnables/cronjob.go index 3bd4f32eaf..d9c2eaf631 100644 --- a/internal/framework/runnables/cronjob.go +++ b/internal/framework/runnables/cronjob.go @@ -37,7 +37,7 @@ func NewCronJob(cfg CronJobConfig) *CronJob { } // Start starts the cronjob. -// Implements controller-runtime manager.Runnable +// Implements controller-runtime manager.Runnable. func (j *CronJob) Start(ctx context.Context) error { select { case <-j.cfg.ReadyCh: diff --git a/internal/framework/status/updater.go b/internal/framework/status/updater.go index b66dd733ff..604a2ead07 100644 --- a/internal/framework/status/updater.go +++ b/internal/framework/status/updater.go @@ -121,8 +121,6 @@ func (u *Updater) writeStatuses( // // Note: this function is public because fake dependencies require us to test this function from the test package // to avoid import cycles. -// -//nolint:nilerr func NewRetryUpdateFunc( getter controller.Getter, updater K8sUpdater, diff --git a/internal/mode/static/handler.go b/internal/mode/static/handler.go index 2dfcbb2e56..d90edc337e 100644 --- a/internal/mode/static/handler.go +++ b/internal/mode/static/handler.go @@ -8,7 +8,6 @@ import ( "github.com/go-logr/logr" ngxclient "github.com/nginxinc/nginx-plus-go-client/client" - apiv1 "k8s.io/api/core/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" @@ -20,7 +19,7 @@ import ( "github.com/nginxinc/nginx-gateway-fabric/internal/framework/events" "github.com/nginxinc/nginx-gateway-fabric/internal/framework/helpers" frameworkStatus "github.com/nginxinc/nginx-gateway-fabric/internal/framework/status" - "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/config" + ngfConfig "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/config" ngxConfig "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/config" "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/nginx/file" @@ -75,7 +74,7 @@ type eventHandlerConfig struct { // eventRecorder records events for Kubernetes resources. eventRecorder record.EventRecorder // usageReportConfig contains the configuration for NGINX Plus usage reporting. - usageReportConfig *config.UsageReportConfig + usageReportConfig *ngfConfig.UsageReportConfig // nginxConfiguredOnStartChecker sets the health of the Pod to Ready once we've written out our initial config. nginxConfiguredOnStartChecker *nginxConfiguredOnStartChecker // gatewayPodConfig contains information about this Pod. @@ -89,7 +88,7 @@ type eventHandlerConfig struct { } const ( - // groups for GroupStatusUpdater + // groups for GroupStatusUpdater. groupAllExceptGateways = "all-graphs-except-gateways" groupGateways = "gateways" groupControlPlane = "control-plane" @@ -308,7 +307,7 @@ func (h *eventHandlerImpl) parseAndCaptureEvent(ctx context.Context, logger logr } } -// updateNginxConf updates nginx conf files and reloads nginx +// updateNginxConf updates nginx conf files and reloads nginx. func (h *eventHandlerImpl) updateNginxConf(ctx context.Context, conf dataplane.Configuration) error { files := h.cfg.generator.Generate(conf) if err := h.cfg.nginxFileMgr.ReplaceFiles(files); err != nil { @@ -324,7 +323,7 @@ func (h *eventHandlerImpl) updateNginxConf(ctx context.Context, conf dataplane.C // updateUpstreamServers is called only when endpoints have changed. It updates nginx conf files and then: // - if using NGINX Plus, determines which servers have changed and uses the N+ API to update them; -// - otherwise if not using NGINX Plus, or an error was returned from the API, reloads nginx +// - otherwise if not using NGINX Plus, or an error was returned from the API, reloads nginx. func (h *eventHandlerImpl) updateUpstreamServers( ctx context.Context, logger logr.Logger, @@ -410,7 +409,7 @@ func serversEqual(newServers []ngxclient.UpstreamServer, oldServers []ngxclient. } // updateControlPlaneAndSetStatus updates the control plane configuration and then sets the status -// based on the outcome +// based on the outcome. func (h *eventHandlerImpl) updateControlPlaneAndSetStatus( ctx context.Context, logger logr.Logger, @@ -429,7 +428,7 @@ func (h *eventHandlerImpl) updateControlPlaneAndSetStatus( logger.Error(err, msg) h.cfg.eventRecorder.Eventf( cfg, - apiv1.EventTypeWarning, + v1.EventTypeWarning, "UpdateFailed", msg+": %s", err.Error(), @@ -454,7 +453,7 @@ func getGatewayAddresses( ctx context.Context, k8sClient client.Client, svc *v1.Service, - podConfig config.GatewayPodConfig, + podConfig ngfConfig.GatewayPodConfig, ) ([]gatewayv1.GatewayStatusAddress, error) { podAddress := []gatewayv1.GatewayStatusAddress{ { diff --git a/internal/mode/static/manager.go b/internal/mode/static/manager.go index 36db684cb5..f8545aa627 100644 --- a/internal/mode/static/manager.go +++ b/internal/mode/static/manager.go @@ -63,7 +63,7 @@ import ( ) const ( - // clusterTimeout is a timeout for connections to the Kubernetes API + // clusterTimeout is a timeout for connections to the Kubernetes API. clusterTimeout = 10 * time.Second ) @@ -80,7 +80,7 @@ func init() { utilruntime.Must(appsv1.AddToScheme(scheme)) } -// nolint:gocyclo +//nolint:gocyclo func StartManager(cfg config.Config) error { nginxChecker := newNginxConfiguredOnStartChecker() mgr, err := createManager(cfg, nginxChecker) @@ -530,7 +530,7 @@ func registerControllers( } // 10 min jitter is enough per telemetry destination recommendation -// For the default period of 24 hours, jitter will be 10min /(24*60)min = 0.0069 +// For the default period of 24 hours, jitter will be 10min /(24*60)min = 0.0069. const telemetryJitterFactor = 10.0 / (24 * 60) // added jitter is bound by jitterFactor * period func createTelemetryJob( @@ -566,7 +566,6 @@ func createTelemetryJob( if err != nil { return nil, fmt.Errorf("cannot create telemetry exporter: %w", err) } - } else { exporter = telemetry.NewLoggingExporter(cfg.Logger.WithName("telemetryExporter").V(1 /* debug */)) } diff --git a/internal/mode/static/metrics/collectors/controller.go b/internal/mode/static/metrics/collectors/controller.go index d578786601..fa1f9757ef 100644 --- a/internal/mode/static/metrics/collectors/controller.go +++ b/internal/mode/static/metrics/collectors/controller.go @@ -15,7 +15,7 @@ type ControllerCollector struct { eventBatchProcessDuration prometheus.Histogram } -// NewControllerCollector creates a new ControllerCollector +// NewControllerCollector creates a new ControllerCollector. func NewControllerCollector(constLabels map[string]string) *ControllerCollector { nc := &ControllerCollector{ eventBatchProcessDuration: prometheus.NewHistogram( diff --git a/internal/mode/static/metrics/collectors/nginx.go b/internal/mode/static/metrics/collectors/nginx.go index 87d8039e22..28cbc635d3 100644 --- a/internal/mode/static/metrics/collectors/nginx.go +++ b/internal/mode/static/metrics/collectors/nginx.go @@ -16,7 +16,7 @@ const ( nginxStatusURI = "http://config-status/stub_status" ) -// NewNginxMetricsCollector creates an NginxCollector which fetches stats from NGINX over a unix socket +// NewNginxMetricsCollector creates an NginxCollector which fetches stats from NGINX over a unix socket. func NewNginxMetricsCollector(constLabels map[string]string, logger log.Logger) prometheus.Collector { httpClient := runtime.GetSocketClient(nginxStatusSock) ngxClient := prometheusClient.NewNginxClient(&httpClient, nginxStatusURI) @@ -24,7 +24,7 @@ func NewNginxMetricsCollector(constLabels map[string]string, logger log.Logger) return nginxCollector.NewNginxCollector(ngxClient, metrics.Namespace, constLabels, logger) } -// NewNginxPlusMetricsCollector creates an NginxCollector which fetches stats from NGINX Plus API over a unix socket +// NewNginxPlusMetricsCollector creates an NginxCollector which fetches stats from NGINX Plus API over a unix socket. func NewNginxPlusMetricsCollector( plusClient *client.NginxClient, constLabels map[string]string, diff --git a/internal/mode/static/metrics/collectors/nginx_runtime.go b/internal/mode/static/metrics/collectors/nginx_runtime.go index 4f57cca61d..5195e603d6 100644 --- a/internal/mode/static/metrics/collectors/nginx_runtime.go +++ b/internal/mode/static/metrics/collectors/nginx_runtime.go @@ -8,7 +8,7 @@ import ( "github.com/nginxinc/nginx-gateway-fabric/internal/mode/static/metrics" ) -// NginxRuntimeCollector implements runtime.Collector interface and prometheus.Collector interface +// NginxRuntimeCollector implements runtime.Collector interface and prometheus.Collector interface. type NginxRuntimeCollector struct { // Metrics reloadsTotal prometheus.Counter @@ -17,7 +17,7 @@ type NginxRuntimeCollector struct { reloadsDuration prometheus.Histogram } -// NewManagerMetricsCollector creates a new NginxRuntimeCollector +// NewManagerMetricsCollector creates a new NginxRuntimeCollector. func NewManagerMetricsCollector(constLabels map[string]string) *NginxRuntimeCollector { nc := &NginxRuntimeCollector{ reloadsTotal: prometheus.NewCounter( diff --git a/internal/mode/static/metrics/metrics.go b/internal/mode/static/metrics/metrics.go index 83cf1948e0..0dbaec8069 100644 --- a/internal/mode/static/metrics/metrics.go +++ b/internal/mode/static/metrics/metrics.go @@ -1,4 +1,3 @@ package metrics -// nolint:gosec // flagged as potential hardcoded credentials, but is not sensitive const Namespace = "nginx_gateway_fabric" diff --git a/internal/mode/static/nginx/config/base_http_config_test.go b/internal/mode/static/nginx/config/base_http_config_test.go index 2f609d8409..4eb202ba1b 100644 --- a/internal/mode/static/nginx/config/base_http_config_test.go +++ b/internal/mode/static/nginx/config/base_http_config_test.go @@ -42,7 +42,6 @@ func TestExecuteBaseHttp(t *testing.T) { } for _, test := range tests { - g := NewWithT(t) res := executeBaseHTTPConfig(test.conf) diff --git a/internal/mode/static/nginx/config/maps.go b/internal/mode/static/nginx/config/maps.go index 97f5486a98..a784390170 100644 --- a/internal/mode/static/nginx/config/maps.go +++ b/internal/mode/static/nginx/config/maps.go @@ -48,7 +48,7 @@ func buildAddHeaderMaps(servers []dataplane.VirtualServer) []http.Map { const ( // In order to prepend any passed client header values to values specified in the add headers field of request - // header modifiers, we need to create a map parameter regex for any string value + // header modifiers, we need to create a map parameter regex for any string value. anyStringFmt = `~.*` ) diff --git a/internal/mode/static/nginx/config/servers.go b/internal/mode/static/nginx/config/servers.go index cc385449a4..54bbe709ed 100644 --- a/internal/mode/static/nginx/config/servers.go +++ b/internal/mode/static/nginx/config/servers.go @@ -21,7 +21,7 @@ const ( rootPath = "/" ) -// httpBaseHeaders contains the constant headers set in each HTTP server block +// httpBaseHeaders contains the constant headers set in each HTTP server block. var httpBaseHeaders = []http.Header{ { Name: "Host", @@ -41,7 +41,7 @@ var httpBaseHeaders = []http.Header{ }, } -// grpcBaseHeaders contains the constant headers set in each gRPC server block +// grpcBaseHeaders contains the constant headers set in each gRPC server block. var grpcBaseHeaders = []http.Header{ { Name: "Host", @@ -203,7 +203,7 @@ func createServer(virtualServer dataplane.VirtualServer, serverID int) (http.Ser } // rewriteConfig contains the configuration for a location to rewrite paths, -// as specified in a URLRewrite filter +// as specified in a URLRewrite filter. type rewriteConfig struct { // Rewrite rewrites the original URI to the new URI (ex: /coffee -> /beans) Rewrite string @@ -284,7 +284,7 @@ func updateLocationsForIncludes(locations []http.Location, includes []string) [] } // pathAndTypeMap contains a map of paths and any path types defined for that path -// for example, {/foo: {exact: {}, prefix: {}}} +// for example, {/foo: {exact: {}, prefix: {}}}. type pathAndTypeMap map[string]map[dataplane.PathType]struct{} // To calculate the maximum number of locations, we need to take into account the following: @@ -759,7 +759,7 @@ func createDefaultRootLocation() http.Location { } } -// isNonSlashedPrefixPath returns whether or not a path is of type Prefix and does not contain a trailing slash +// isNonSlashedPrefixPath returns whether or not a path is of type Prefix and does not contain a trailing slash. func isNonSlashedPrefixPath(pathType dataplane.PathType, path string) bool { return pathType == dataplane.PathTypePrefix && !strings.HasSuffix(path, "/") } diff --git a/internal/mode/static/nginx/config/split_clients.go b/internal/mode/static/nginx/config/split_clients.go index 0cc050e7c0..0e196a2065 100644 --- a/internal/mode/static/nginx/config/split_clients.go +++ b/internal/mode/static/nginx/config/split_clients.go @@ -38,7 +38,6 @@ func createSplitClients(backendGroups []dataplane.BackendGroup) []http.SplitClie splitClients := make([]http.SplitClient, 0, numSplits) for _, group := range backendGroups { - distributions := createSplitClientDistributions(group) if distributions == nil { continue @@ -48,7 +47,6 @@ func createSplitClients(backendGroups []dataplane.BackendGroup) []http.SplitClie VariableName: convertStringToSafeVariableName(group.Name()), Distributions: distributions, }) - } return splitClients @@ -82,7 +80,7 @@ func createSplitClientDistributions(group dataplane.BackendGroup) []http.SplitCl // Iterate over all backends except the last one. // The last backend will get the remaining percentage. - for i := 0; i < len(backends)-1; i++ { + for i := range len(backends) - 1 { b := backends[i] percentage := percentOf(b.Weight, totalWeight) @@ -117,7 +115,7 @@ func getSplitClientValue(b dataplane.Backend) string { // The percentage is rounded to 2 decimal places using the Floor method. // Floor is used here in order to guarantee that the sum of all percentages does not exceed 100. // Ex. percentOf(2, 3) = 66.66 -// Ex. percentOf(800, 2000) = 40.00 +// Ex. percentOf(800, 2000) = 40.00. func percentOf(weight, totalWeight int32) float64 { p := (float64(weight) * 100) / float64(totalWeight) return math.Floor(p*100) / 100 diff --git a/internal/mode/static/nginx/config/validation/framework_test.go b/internal/mode/static/nginx/config/validation/framework_test.go index 6b5c64117a..58e727fbc7 100644 --- a/internal/mode/static/nginx/config/validation/framework_test.go +++ b/internal/mode/static/nginx/config/validation/framework_test.go @@ -12,6 +12,7 @@ type simpleValidatorFunc[T configValue] func(v T) error type supportedValuesValidatorFunc[T configValue] func(v T) (bool, []string) func runValidatorTests[T configValue](t *testing.T, run func(g *WithT, v T), caseNamePrefix string, values ...T) { + t.Helper() for i, v := range values { t.Run(fmt.Sprintf("%s_case_#%d", caseNamePrefix, i), func(t *testing.T) { g := NewWithT(t) @@ -25,6 +26,7 @@ func createFailureMessage[T any](v T) string { } func testValidValuesForSimpleValidator[T configValue](t *testing.T, f simpleValidatorFunc[T], values ...T) { + t.Helper() runValidatorTests(t, func(g *WithT, v T) { err := f(v) g.Expect(err).ToNot(HaveOccurred(), createFailureMessage(v)) @@ -32,6 +34,7 @@ func testValidValuesForSimpleValidator[T configValue](t *testing.T, f simpleVali } func testInvalidValuesForSimpleValidator[T configValue](t *testing.T, f simpleValidatorFunc[T], values ...T) { + t.Helper() runValidatorTests(t, func(g *WithT, v T) { err := f(v) g.Expect(err).To(HaveOccurred(), createFailureMessage(v)) @@ -43,6 +46,7 @@ func testValidValuesForSupportedValuesValidator[T configValue]( f supportedValuesValidatorFunc[T], values ...T, ) { + t.Helper() runValidatorTests( t, func(g *WithT, v T) { @@ -61,6 +65,7 @@ func testInvalidValuesForSupportedValuesValidator[T configValue]( supportedValuesMap map[T]struct{}, values ...T, ) { + t.Helper() runValidatorTests( t, func(g *WithT, v T) { diff --git a/internal/mode/static/nginx/config/validation/http_validator.go b/internal/mode/static/nginx/config/validation/http_validator.go index 4e744124c2..9d0ef9ca80 100644 --- a/internal/mode/static/nginx/config/validation/http_validator.go +++ b/internal/mode/static/nginx/config/validation/http_validator.go @@ -6,7 +6,7 @@ import ( // HTTPValidator validates values that will propagate into the NGINX configuration http context. // The validation rules are based on the nginx/config/http types and how they are used in the configuration templates -// of the nginx/config package. Changes to those might require changing the validation rules +// of the nginx/config package. Changes to those might require changing the validation rules. type HTTPValidator struct { HTTPNJSMatchValidator HTTPRedirectValidator diff --git a/internal/mode/static/nginx/file/manager_test.go b/internal/mode/static/nginx/file/manager_test.go index 1963090f6b..5a2d5d57bc 100644 --- a/internal/mode/static/nginx/file/manager_test.go +++ b/internal/mode/static/nginx/file/manager_test.go @@ -169,7 +169,7 @@ var _ = Describe("EventHandler", func() { Content: []byte("secret"), }, } - testErr = errors.New("test error") + errTest = errors.New("test error") ) DescribeTable( @@ -186,13 +186,13 @@ var _ = Describe("EventHandler", func() { err := mgr.ReplaceFiles(files) Expect(err).Should(HaveOccurred()) - Expect(err).To(MatchError(testErr)) + Expect(err).To(MatchError(errTest)) }, Entry( "Remove", &filefakes.FakeOSFileManager{ RemoveStub: func(_ string) error { - return testErr + return errTest }, }, ), @@ -200,7 +200,7 @@ var _ = Describe("EventHandler", func() { "Create", &filefakes.FakeOSFileManager{ CreateStub: func(_ string) (*os.File, error) { - return nil, testErr + return nil, errTest }, }, ), @@ -208,7 +208,7 @@ var _ = Describe("EventHandler", func() { "Chmod", &filefakes.FakeOSFileManager{ ChmodStub: func(_ *os.File, _ os.FileMode) error { - return testErr + return errTest }, }, ), @@ -216,7 +216,7 @@ var _ = Describe("EventHandler", func() { "Write", &filefakes.FakeOSFileManager{ WriteStub: func(_ *os.File, _ []byte) error { - return testErr + return errTest }, }, ), diff --git a/internal/mode/static/nginx/file/os_filemanager.go b/internal/mode/static/nginx/file/os_filemanager.go index ffac7caa7a..05547cb046 100644 --- a/internal/mode/static/nginx/file/os_filemanager.go +++ b/internal/mode/static/nginx/file/os_filemanager.go @@ -25,7 +25,7 @@ func (s *StdLibOSFileManager) Remove(name string) error { return os.Remove(name) } -// Write wraps os.File.Write +// Write wraps os.File.Write. func (s *StdLibOSFileManager) Write(file *os.File, contents []byte) error { _, err := file.Write(contents) diff --git a/internal/mode/static/nginx/runtime/verify.go b/internal/mode/static/nginx/runtime/verify.go index c88ce2faa4..4e3ff68732 100644 --- a/internal/mode/static/nginx/runtime/verify.go +++ b/internal/mode/static/nginx/runtime/verify.go @@ -45,7 +45,7 @@ func (c *verifyClient) getConfigVersion() (int, error) { ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() - req, err := http.NewRequestWithContext(ctx, "GET", "http://config-version/version", nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://config-version/version", nil) if err != nil { return 0, fmt.Errorf("error creating request: %w", err) } diff --git a/internal/mode/static/nginx/runtime/verify_test.go b/internal/mode/static/nginx/runtime/verify_test.go index 0a5431d59c..fda58b56f3 100644 --- a/internal/mode/static/nginx/runtime/verify_test.go +++ b/internal/mode/static/nginx/runtime/verify_test.go @@ -16,7 +16,7 @@ type transport struct{} func (c transport) RoundTrip(_ *http.Request) (*http.Response, error) { return &http.Response{ - StatusCode: 200, + StatusCode: http.StatusOK, Body: io.NopCloser(bytes.NewBufferString("42")), Header: make(http.Header), }, nil diff --git a/internal/mode/static/policies/clientsettings/validator.go b/internal/mode/static/policies/clientsettings/validator.go index 4e5ea1007f..bcc9f6ebfc 100644 --- a/internal/mode/static/policies/clientsettings/validator.go +++ b/internal/mode/static/policies/clientsettings/validator.go @@ -72,7 +72,6 @@ func conflicts(a, b ngfAPI.ClientSettingsPolicySpec) bool { if a.KeepAlive.Timeout != nil && b.KeepAlive.Timeout != nil { return true } - } return false diff --git a/internal/mode/static/state/dataplane/configuration.go b/internal/mode/static/state/dataplane/configuration.go index be2e39fd65..56569aa432 100644 --- a/internal/mode/static/state/dataplane/configuration.go +++ b/internal/mode/static/state/dataplane/configuration.go @@ -240,7 +240,7 @@ func buildServers(g *graph.Graph, generator policies.ConfigGenerator) (http, ssl return httpServers, sslServers } -// portPathRules keeps track of hostPathRules per port +// portPathRules keeps track of hostPathRules per port. type portPathRules map[v1.PortNumber]*hostPathRules func (p portPathRules) buildServers() []VirtualServer { @@ -478,7 +478,6 @@ func buildUpstreams( uniqueUpstreams := make(map[string]Upstream) for _, l := range listeners { - if !l.Valid { continue } diff --git a/internal/mode/static/state/graph/backend_refs.go b/internal/mode/static/state/graph/backend_refs.go index 5e36338972..2673fa4365 100644 --- a/internal/mode/static/state/graph/backend_refs.go +++ b/internal/mode/static/state/graph/backend_refs.go @@ -255,7 +255,6 @@ func findBackendTLSPolicyForService( } } } - } if beTLSPolicy != nil { diff --git a/internal/mode/static/state/graph/gateway.go b/internal/mode/static/state/graph/gateway.go index 6a826f80fc..2b73b46be2 100644 --- a/internal/mode/static/state/graph/gateway.go +++ b/internal/mode/static/state/graph/gateway.go @@ -33,7 +33,7 @@ type processedGateways struct { Ignored map[types.NamespacedName]*v1.Gateway } -// GetAllNsNames returns all the NamespacedNames of the Gateway resources that belong to NGF +// GetAllNsNames returns all the NamespacedNames of the Gateway resources that belong to NGF. func (gws processedGateways) GetAllNsNames() []types.NamespacedName { winnerCnt := 0 if gws.Winner != nil { diff --git a/internal/mode/static/state/graph/gateway_test.go b/internal/mode/static/state/graph/gateway_test.go index 8bb89471c4..26f3f48c88 100644 --- a/internal/mode/static/state/graph/gateway_test.go +++ b/internal/mode/static/state/graph/gateway_test.go @@ -1,4 +1,3 @@ -//nolint:gosec package graph import ( diff --git a/internal/mode/static/state/graph/graph_test.go b/internal/mode/static/state/graph/graph_test.go index 7c3bc3ea06..2081fd881c 100644 --- a/internal/mode/static/state/graph/graph_test.go +++ b/internal/mode/static/state/graph/graph_test.go @@ -1,4 +1,3 @@ -//nolint:gosec package graph import ( diff --git a/internal/mode/static/state/graph/grpcroute.go b/internal/mode/static/state/graph/grpcroute.go index cbbbaf65b3..ea3f576972 100644 --- a/internal/mode/static/state/graph/grpcroute.go +++ b/internal/mode/static/state/graph/grpcroute.go @@ -274,7 +274,7 @@ func validateGRPCFilter( } // convertGRPCFilters converts GRPCRouteFilters (a subset of HTTPRouteFilter) to HTTPRouteFilters -// so we can reuse the logic from HTTPRoute filter validation and processing +// so we can reuse the logic from HTTPRoute filter validation and processing. func convertGRPCFilters(filters []v1.GRPCRouteFilter) []v1.HTTPRouteFilter { if len(filters) == 0 { return nil diff --git a/internal/mode/static/state/graph/policies_test.go b/internal/mode/static/state/graph/policies_test.go index b41d663532..a555f4f4a4 100644 --- a/internal/mode/static/state/graph/policies_test.go +++ b/internal/mode/static/state/graph/policies_test.go @@ -925,7 +925,7 @@ func createTestPolicyWithAncestors(numAncestors int) policies.Policy { ancestors := make([]v1alpha2.PolicyAncestorStatus, numAncestors) - for i := 0; i < numAncestors; i++ { + for i := range numAncestors { ancestors[i] = v1alpha2.PolicyAncestorStatus{ControllerName: "some-other-controller"} } diff --git a/internal/mode/static/state/graph/reference_grant.go b/internal/mode/static/state/graph/reference_grant.go index b833825d73..de04211ba8 100644 --- a/internal/mode/static/state/graph/reference_grant.go +++ b/internal/mode/static/state/graph/reference_grant.go @@ -80,7 +80,6 @@ func newReferenceGrantResolver(refGrants map[types.NamespacedName]*v1beta1.Refer for nsname, grant := range refGrants { for _, to := range grant.Spec.To { for _, from := range grant.Spec.From { - toName := "" if to.Name != nil { toName = string(*to.Name) diff --git a/internal/mode/static/state/graph/route_common.go b/internal/mode/static/state/graph/route_common.go index 25001cc323..cbf16027cb 100644 --- a/internal/mode/static/state/graph/route_common.go +++ b/internal/mode/static/state/graph/route_common.go @@ -49,13 +49,13 @@ type ParentRefAttachmentStatus struct { type RouteType string const ( - // RouteTypeHTTP indicates that the RouteType of the L7Route is HTTP + // RouteTypeHTTP indicates that the RouteType of the L7Route is HTTP. RouteTypeHTTP RouteType = "http" - // RouteTypeGRPC indicates that the RouteType of the L7Route is gRPC + // RouteTypeGRPC indicates that the RouteType of the L7Route is gRPC. RouteTypeGRPC RouteType = "grpc" ) -// RouteKey is the unique identifier for a L7Route +// RouteKey is the unique identifier for a L7Route. type RouteKey struct { // NamespacedName is the NamespacedName of the Route. NamespacedName types.NamespacedName @@ -63,7 +63,7 @@ type RouteKey struct { RouteType RouteType } -// L7Route is the generic type for the layer 7 routes, HTTPRoute and GRPCRoute +// L7Route is the generic type for the layer 7 routes, HTTPRoute and GRPCRoute. type L7Route struct { // Source is the source Gateway API object of the Route. Source client.Object @@ -111,7 +111,7 @@ type RouteBackendRef struct { Filters []any } -// CreateRouteKey takes a client.Object and creates a RouteKey +// CreateRouteKey takes a client.Object and creates a RouteKey. func CreateRouteKey(obj client.Object) RouteKey { nsName := types.NamespacedName{ Name: obj.GetName(), @@ -267,7 +267,7 @@ func bindRouteToListeners( return } - for i := 0; i < len(route.ParentRefs); i++ { + for i := range route.ParentRefs { attachment := &ParentRefAttachmentStatus{ AcceptedHostnames: make(map[string][]string), } @@ -467,7 +467,7 @@ func match(listenerHost, routeHost string) bool { // // This function assumes that the two hostnames match each other, either: // - Exactly -// - One as a substring of the other +// - One as a substring of the other. func GetMoreSpecificHostname(hostname1, hostname2 string) string { if hostname1 == hostname2 { return hostname1 diff --git a/internal/mode/static/state/resolver/resolver.go b/internal/mode/static/state/resolver/resolver.go index 303fb6d1bf..1200add7f3 100644 --- a/internal/mode/static/state/resolver/resolver.go +++ b/internal/mode/static/state/resolver/resolver.go @@ -81,7 +81,6 @@ func calculateReadyEndpoints(endpointSlices []discoveryV1.EndpointSlice) int { for _, eps := range endpointSlices { for _, endpoint := range eps.Endpoints { - if !endpointReady(endpoint) { continue } @@ -111,7 +110,6 @@ func resolveEndpoints( for _, eps := range filteredSlices { for _, endpoint := range eps.Endpoints { - if !endpointReady(endpoint) { continue } @@ -191,7 +189,6 @@ func findPort(ports []discoveryV1.EndpointPort, svcPort v1.ServicePort) int32 { portName := svcPort.Name for _, p := range ports { - if p.Port == nil { return getDefaultPort(svcPort) } diff --git a/internal/mode/static/state/resolver/resolver_test.go b/internal/mode/static/state/resolver/resolver_test.go index 69c43e0240..1b7c248621 100644 --- a/internal/mode/static/state/resolver/resolver_test.go +++ b/internal/mode/static/state/resolver/resolver_test.go @@ -488,7 +488,7 @@ func generateEndpointSliceList(n int) discoveryV1.EndpointSliceList { }, } - for j := 0; j < c; j++ { + for j := range c { slice.Endpoints[j] = discoveryV1.Endpoint{ Addresses: []string{fmt.Sprintf("10.0.%d.%d", i, j)}, Conditions: discoveryV1.EndpointConditions{ @@ -540,6 +540,7 @@ func BenchmarkResolve(b *testing.B) { func bench(b *testing.B, svcNsName types.NamespacedName, list discoveryV1.EndpointSliceList, initSet initEndpointSetFunc, n int, ) { + b.Helper() for i := 0; i < b.N; i++ { res, err := resolveEndpoints(svcNsName, v1.ServicePort{Port: 80}, list, initSet) if len(res) != n { diff --git a/internal/mode/static/state/store.go b/internal/mode/static/state/store.go index a03cc7f6a5..6309639ecd 100644 --- a/internal/mode/static/state/store.go +++ b/internal/mode/static/state/store.go @@ -20,7 +20,7 @@ type Updater interface { Delete(objType ngftypes.ObjectType, nsname types.NamespacedName) } -// objectStore is a store of client.Object +// objectStore is a store of client.Object. type objectStore interface { get(objType ngftypes.ObjectType, nsname types.NamespacedName) client.Object upsert(obj client.Object) @@ -297,7 +297,7 @@ func (s *changeTrackingUpdater) getAndResetChangedStatus() ChangeType { // - if no change occurred on this object, then keep the changeType as-is (could've been set by another object event) // - if changeType is already a ClusterStateChange, then we don't need to update the value // - otherwise, if we are processing an Endpoint update, then this is an EndpointsOnlyChange changeType -// - otherwise, this is a different object, and is a ClusterStateChange changeType +// - otherwise, this is a different object, and is a ClusterStateChange changeType. func (s *changeTrackingUpdater) setChangeType(obj client.Object, changed bool) { if changed && s.changeType != ClusterStateChange { if _, ok := obj.(*discoveryV1.EndpointSlice); ok { diff --git a/internal/mode/static/status/prepare_requests.go b/internal/mode/static/status/prepare_requests.go index b0b00c7978..c8bde98cec 100644 --- a/internal/mode/static/status/prepare_requests.go +++ b/internal/mode/static/status/prepare_requests.go @@ -35,7 +35,6 @@ func PrepareRouteRequests( reqs := make([]frameworkStatus.UpdateRequest, 0, len(routes)) for routeKey, r := range routes { - routeStatus := prepareRouteStatus( gatewayCtlrName, r.ParentRefs, @@ -72,7 +71,6 @@ func PrepareRouteRequests( } else { panic(fmt.Sprintf("Unknown route type: %s", r.RouteType)) } - } return reqs diff --git a/internal/mode/static/status/status_setters.go b/internal/mode/static/status/status_setters.go index 141a1a3411..7a23f56f73 100644 --- a/internal/mode/static/status/status_setters.go +++ b/internal/mode/static/status/status_setters.go @@ -6,7 +6,6 @@ import ( "sigs.k8s.io/controller-runtime/pkg/client" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" "sigs.k8s.io/gateway-api/apis/v1alpha2" - gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" "sigs.k8s.io/gateway-api/apis/v1alpha3" ngfAPI "github.com/nginxinc/nginx-gateway-fabric/apis/v1alpha1" @@ -224,7 +223,7 @@ func newBackendTLSPolicyStatusSetter( } func newNGFPolicyStatusSetter( - status gatewayv1alpha2.PolicyStatus, + status v1alpha2.PolicyStatus, gatewayCtlrName string, ) frameworkStatus.Setter { return func(object client.Object) (wasSet bool) { @@ -234,7 +233,7 @@ func newNGFPolicyStatusSetter( // maxAncestors is the max number of ancestor statuses which is the sum of all new ancestor statuses and all old // ancestor statuses. maxAncestors := len(status.Ancestors) + len(prevStatus.Ancestors) - ancestors := make([]gatewayv1alpha2.PolicyAncestorStatus, 0, maxAncestors) + ancestors := make([]v1alpha2.PolicyAncestorStatus, 0, maxAncestors) // keep all the ancestor statuses that belong to other controllers for _, as := range prevStatus.Ancestors { @@ -255,7 +254,7 @@ func newNGFPolicyStatusSetter( } } -func policyStatusEqual(gatewayCtlrName string, prev, cur gatewayv1alpha2.PolicyStatus) bool { +func policyStatusEqual(gatewayCtlrName string, prev, cur v1alpha2.PolicyStatus) bool { // Since other controllers may update Policy status we can't assume anything about the order of the // statuses, and we have to ignore statuses written by other controllers when checking for equality. // Therefore, we can't use slices.EqualFunc here because it cares about the order. diff --git a/internal/mode/static/usage/reporter.go b/internal/mode/static/usage/reporter.go index 0b4b0e66ba..43fbcd01d2 100644 --- a/internal/mode/static/usage/reporter.go +++ b/internal/mode/static/usage/reporter.go @@ -113,8 +113,8 @@ func (r *NIMReporter) Report(ctx context.Context, data ClusterDetails) error { req.Header.Add("Content-Type", "application/json") username, password := r.credentials.GetCredentials() if username == nil || password == nil { - return errors.New("username or password not set for NGINX Plus usage reporting; unable to send reports. " + - "Ensure that the usage Secret exists and the username and password are set.") + return errors.New("username or password not set for NGINX Plus usage reporting; unable to send reports." + + " Ensure that the usage Secret exists and the username and password are set") } req.SetBasicAuth(string(username), string(password)) diff --git a/internal/mode/static/usage/reporter_test.go b/internal/mode/static/usage/reporter_test.go index 5099dfb591..b57a5b3613 100644 --- a/internal/mode/static/usage/reporter_test.go +++ b/internal/mode/static/usage/reporter_test.go @@ -55,7 +55,7 @@ func TestReport(t *testing.T) { g.Expect(ok).To(BeTrue()) g.Expect(contentType[0]).To(Equal("application/json")) - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) }), ) defer server.Close() @@ -83,7 +83,7 @@ func TestReport_ServerError(t *testing.T) { server := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(500) + w.WriteHeader(http.StatusInternalServerError) }), ) defer server.Close() diff --git a/tests/framework/generate_manifests.go b/tests/framework/generate_manifests.go index 46c7b92b32..b5dd81ebd0 100644 --- a/tests/framework/generate_manifests.go +++ b/tests/framework/generate_manifests.go @@ -53,7 +53,7 @@ spec: - name: {{ .BackendName }} port: 80` -// nolint:all +//nolint:all const secretTmplTxt = `apiVersion: v1 kind: Secret metadata: @@ -157,7 +157,7 @@ func GenerateScaleListenerObjects(numListeners int, tls bool) (ScaleObjects, err backends := make([]string, 0) secrets := make([]string, 0) - for i := 0; i < numListeners; i++ { + for i := range numListeners { listenerName := fmt.Sprintf("listener-%d", i) hostnamePrefix := fmt.Sprintf("%d", i) backendName := fmt.Sprintf("backend-%d", i) @@ -240,7 +240,7 @@ func GenerateScaleHTTPRouteObjects(numRoutes int) (ScaleObjects, error) { backendName := "backend" - for i := 0; i < numRoutes; i++ { + for i := range numRoutes { r := route{ Name: fmt.Sprintf("route-%d", i), HostnamePrefix: fmt.Sprintf("%d", i), diff --git a/tests/framework/load.go b/tests/framework/load.go index db3b84c7ac..c687f275b1 100644 --- a/tests/framework/load.go +++ b/tests/framework/load.go @@ -47,7 +47,7 @@ type Metrics struct { } // RunLoadTest uses Vegeta to send traffic to the provided Targets at the given rate for the given duration and writes -// the results to the provided file +// the results to the provided file. func RunLoadTest(cfg LoadTestConfig) (vegeta.Results, Metrics) { vegTargets := convertTargetToVegetaTarget(cfg.Targets) targeter := vegeta.NewStaticTargeter(vegTargets...) diff --git a/tests/framework/prometheus.go b/tests/framework/prometheus.go index caec955443..358ec5d09a 100644 --- a/tests/framework/prometheus.go +++ b/tests/framework/prometheus.go @@ -24,7 +24,7 @@ const ( var defaultPrometheusQueryTimeout = 2 * time.Second -// PrometheusConfig is the configuration for installing Prometheus +// PrometheusConfig is the configuration for installing Prometheus. type PrometheusConfig struct { // ScrapeInterval is the interval at which Prometheus scrapes metrics. ScrapeInterval time.Duration @@ -61,7 +61,7 @@ func InstallPrometheus( scrapeInterval := fmt.Sprintf("%ds", int(cfg.ScrapeInterval.Seconds())) - // nolint:gosec + //nolint:gosec output, err = exec.Command( "helm", "install", @@ -90,7 +90,7 @@ func InstallPrometheus( pod := pods[0] if pod.Status.PodIP == "" { - return PrometheusInstance{}, errors.New("Prometheus pod has no IP") + return PrometheusInstance{}, errors.New("the Prometheus pod has no IP") } var queryTimeout time.Duration diff --git a/tests/framework/resourcemanager.go b/tests/framework/resourcemanager.go index caae52e855..8e3de3707f 100644 --- a/tests/framework/resourcemanager.go +++ b/tests/framework/resourcemanager.go @@ -54,7 +54,7 @@ type ResourceManager struct { TimeoutConfig TimeoutConfig } -// ClusterInfo holds the cluster metadata +// ClusterInfo holds the cluster metadata. type ClusterInfo struct { K8sVersion string // ID is the UID of kube-system namespace @@ -482,7 +482,7 @@ func (rm *ResourceManager) waitForLBStatusToBeReady(ctx context.Context, svcNsNa ) } -// GetClusterInfo retrieves node info and Kubernetes version from the cluster +// GetClusterInfo retrieves node info and Kubernetes version from the cluster. func (rm *ResourceManager) GetClusterInfo() (ClusterInfo, error) { ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout) defer cancel() @@ -575,7 +575,7 @@ func (rm *ResourceManager) GetPod(namespace, name string) (*core.Pod, error) { return &pod, nil } -// GetPodLogs returns the logs from the specified Pod +// GetPodLogs returns the logs from the specified Pod. func (rm *ResourceManager) GetPodLogs(namespace, name string, opts *core.PodLogOptions) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), rm.TimeoutConfig.GetTimeout) defer cancel() diff --git a/tests/suite/scale_test.go b/tests/suite/scale_test.go index 4813a908df..357e64f8f3 100644 --- a/tests/suite/scale_test.go +++ b/tests/suite/scale_test.go @@ -490,7 +490,7 @@ var _ = Describe("Scale test", Ordered, Label("nfr", "scale"), func() { Expect(resourceManager.WaitForPodsToBeReady(ctx, namespace)).To(Succeed()) - for i := 0; i < len(objects.ScaleIterationGroups); i++ { + for i := range len(objects.ScaleIterationGroups) { Expect(resourceManager.Apply(objects.ScaleIterationGroups[i])).To(Succeed()) var url string diff --git a/tests/suite/tracing_test.go b/tests/suite/tracing_test.go index dfe23d487e..9876792c18 100644 --- a/tests/suite/tracing_test.go +++ b/tests/suite/tracing_test.go @@ -15,7 +15,6 @@ import ( "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" - v1 "sigs.k8s.io/gateway-api/apis/v1" gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2" ngfAPI "github.com/nginxinc/nginx-gateway-fabric/apis/v1alpha1" @@ -25,7 +24,7 @@ import ( // This test can be flaky when waiting to see traces show up in the collector logs. // Sometimes they get there right away, sometimes it takes 30 seconds. Retries were -// added to attempt to mitigate the issue, but it didn't fix it 100% +// added to attempt to mitigate the issue, but it didn't fix it 100%. var _ = Describe("Tracing", FlakeAttempts(2), Label("functional", "tracing"), func() { var ( files = []string{ @@ -222,7 +221,7 @@ func verifyGatewayClassResolvedRefs() error { ctx, cancel := context.WithTimeout(context.Background(), timeoutConfig.GetTimeout) defer cancel() - var gc v1.GatewayClass + var gc gatewayv1.GatewayClass if err := k8sClient.Get(ctx, types.NamespacedName{Name: gatewayClassName}, &gc); err != nil { return err }