diff --git a/.golangci.yml b/.golangci.yml index 65923d74e..e3576681f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -39,7 +39,7 @@ linters: - nilnil - nlreturn - noctx -# - nolintlint + - nolintlint - nosprintfhostport - perfsprint - prealloc @@ -66,7 +66,7 @@ linters: - zerologlint settings: cyclop: - max-complexity: 10 + max-complexity: 12 package-average: 0 errorlint: errorf: true @@ -216,19 +216,19 @@ linters: - chan nlreturn: block-size: 2 -# nolintlint: -# # Disable to ensure that all nolint directives actually have an effect. -# # Default: false -# allow-unused: true -# # Exclude following linters from requiring an explanation. -# # Default: [] -# allow-no-explanation: [ ] -# # Enable to require an explanation of nonzero length after each nolint directive. -# # Default: false -# require-explanation: true -# # Enable to require nolint directives to mention the specific linter being suppressed. -# # Default: false -# require-specific: true + nolintlint: + # Disable to ensure that all nolint directives actually have an effect. + # Default: false + allow-unused: true + # Exclude following linters from requiring an explanation. + # Default: [] + allow-no-explanation: [ ] + # Enable to require an explanation of nonzero length after each nolint directive. + # Default: false + require-explanation: true + # Enable to require nolint directives to mention the specific linter being suppressed. + # Default: false + require-specific: true prealloc: simple: true range-loops: true @@ -285,7 +285,7 @@ linters: disabled: false - name: cognitive-complexity arguments: - - 10 + - 12 severity: warning disabled: false - name: comment-spacings @@ -310,7 +310,7 @@ linters: disabled: false - name: cyclomatic arguments: - - 10 + - 12 severity: warning disabled: false - name: datarace diff --git a/internal/backoff/backoff.go b/internal/backoff/backoff.go index 0ceef8c73..ec0afc8bb 100644 --- a/internal/backoff/backoff.go +++ b/internal/backoff/backoff.go @@ -65,7 +65,8 @@ func WaitUntil( // WaitUntilWithData Implementation of backoff operations that increases the back off period for each retry // attempt using a randomization function that grows exponentially. This does not allow for parameters. -// nolint: ireturn +// +//nolint:ireturn // must return an interface func WaitUntilWithData[T any]( ctx context.Context, backoffSettings *config.BackOff, @@ -76,7 +77,7 @@ func WaitUntilWithData[T any]( return backoff.RetryWithData(operation, backoffWithContext) } -// nolint: ireturn +//nolint:ireturn // must return an interface func Context(ctx context.Context, backoffSettings *config.BackOff) backoff.BackOffContext { eb := backoff.NewExponentialBackOff() eb.InitialInterval = backoffSettings.InitialInterval diff --git a/internal/collector/containermetricsreceiver/factory.go b/internal/collector/containermetricsreceiver/factory.go index 0b9a1ac04..87ad6e92b 100644 --- a/internal/collector/containermetricsreceiver/factory.go +++ b/internal/collector/containermetricsreceiver/factory.go @@ -21,7 +21,7 @@ import ( "github.com/nginx/agent/v3/internal/collector/containermetricsreceiver/internal/metadata" ) -// nolint: ireturn +//nolint:ireturn // must return metrics interface func NewFactory() receiver.Factory { return receiver.NewFactory( metadata.Type, @@ -33,7 +33,7 @@ func NewFactory() receiver.Factory { ) } -// nolint: ireturn +//nolint:ireturn // must return metrics interface func createMetricsReceiver( _ context.Context, params receiver.Settings, diff --git a/internal/collector/containermetricsreceiver/internal/config/config.go b/internal/collector/containermetricsreceiver/internal/config/config.go index 2268b78cd..7c77bcc31 100644 --- a/internal/collector/containermetricsreceiver/internal/config/config.go +++ b/internal/collector/containermetricsreceiver/internal/config/config.go @@ -14,7 +14,7 @@ type Config struct { scraperhelper.ControllerConfig `mapstructure:",squash"` } -// nolint: ireturn +//nolint:ireturn // must return a default metrics controller interface func CreateDefaultConfig() component.Config { cfg := scraperhelper.NewDefaultControllerConfig() return &Config{ diff --git a/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/factory.go b/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/factory.go index e16db6166..6ad883c17 100644 --- a/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/factory.go +++ b/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/factory.go @@ -15,8 +15,7 @@ import ( "go.opentelemetry.io/collector/scraper" ) -// NewFactory for CPU scraper. -// nolint: ireturn +//nolint:ireturn // must return a CPU scraper interface. func NewFactory() scraper.Factory { return scraper.NewFactory( metadata.Type, @@ -25,16 +24,14 @@ func NewFactory() scraper.Factory { ) } -// createDefaultConfig creates the default configuration for the Scraper. -// nolint: ireturn +//nolint:ireturn // must create the default configuration for the Scraper. func createDefaultConfig() component.Config { return &Config{ MetricsBuilderConfig: metadata.DefaultMetricsBuilderConfig(), } } -// createMetricsScraper creates a scraper based on provided config. -// nolint: ireturn +//nolint:ireturn // must create and return a scraper based on provided config. func createMetricsScraper( ctx context.Context, settings scraper.Settings, diff --git a/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/internal/cgroup/cpu.go b/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/internal/cgroup/cpu.go index a750f0104..868346ba6 100644 --- a/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/internal/cgroup/cpu.go +++ b/internal/collector/containermetricsreceiver/internal/scraper/cpuscraper/internal/cgroup/cpu.go @@ -73,9 +73,9 @@ func (cs *CPUSource) Collect(ctx context.Context) (ContainerCPUStats, error) { return cpuStats, nil } -// nolint: mnd func (cs *CPUSource) collectCPUStats(ctx context.Context) (ContainerCPUStats, error) { clockTicks, err := clockTicks(ctx) + const nanosecondsPerMillisecond = 1000 if err != nil { return ContainerCPUStats{}, err } @@ -85,7 +85,7 @@ func (cs *CPUSource) collectCPUStats(ctx context.Context) (ContainerCPUStats, er userKey := V2UserKey sysKey := V2SystemKey convertUsage := func(usage float64) float64 { - return usage * 1000 + return usage * nanosecondsPerMillisecond } if !cs.isCgroupV2 { // cgroup v1 @@ -162,7 +162,7 @@ func (cs *CPUSource) cpuUsageTimes(filePath, userKey, systemKey string) (*Contai return cpuTimes, nil } -// nolint: revive, gocritic +//nolint:revive // cognitive complexity is 14 func systemCPUUsage(clockTicks int) (float64, error) { lines, err := internal.ReadLines(CPUStatsPath) if err != nil { @@ -171,8 +171,7 @@ func systemCPUUsage(clockTicks int) (float64, error) { for _, line := range lines { parts := strings.Fields(line) - switch parts[0] { - case "cpu": + if parts[0] == "cpu" { if len(parts) < CPUStatsFileLineLength { return 0, errors.New("unable to process " + CPUStatsPath + ". Invalid number of fields for cpu line") } diff --git a/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/factory.go b/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/factory.go index 2901eacdf..15ea1700b 100644 --- a/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/factory.go +++ b/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/factory.go @@ -16,7 +16,8 @@ import ( ) // NewFactory for CPU scraper. -// nolint: ireturn +// +//nolint:ireturn // must return a CPU scraper func NewFactory() scraper.Factory { return scraper.NewFactory( metadata.Type, @@ -26,7 +27,8 @@ func NewFactory() scraper.Factory { } // createDefaultConfig creates the default configuration for the Scraper. -// nolint: ireturn +// +//nolint:ireturn // must return a default configuration for scraper func createDefaultConfig() component.Config { return &Config{ MetricsBuilderConfig: metadata.DefaultMetricsBuilderConfig(), @@ -34,7 +36,8 @@ func createDefaultConfig() component.Config { } // createMetricsScraper creates a scraper based on provided config. -// nolint: ireturn +// +//nolint:ireturn // must return a metric scraper interface func createMetricsScraper( ctx context.Context, settings scraper.Settings, diff --git a/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/internal/cgroup/memory.go b/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/internal/cgroup/memory.go index 9d86c0957..d64a152a1 100644 --- a/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/internal/cgroup/memory.go +++ b/internal/collector/containermetricsreceiver/internal/scraper/memoryscraper/internal/cgroup/memory.go @@ -64,7 +64,6 @@ func (ms *MemorySource) Collect() { } } -// nolint: unparam func (ms *MemorySource) VirtualMemoryStatWithContext(ctx context.Context) (*mem.VirtualMemoryStat, error) { var cgroupStat mem.VirtualMemoryStat var memoryStat MemoryStat @@ -146,8 +145,8 @@ func MemoryLimitInBytes(ctx context.Context, filePath string) (uint64, error) { return strconv.ParseUint(memTotalString, 10, 64) } -// nolint: revive, mnd func CalculateMemoryStat(statFile, cachedKey, sharedKey string) (MemoryStat, error) { + const requiredFields = 2 memoryStat := MemoryStat{} lines, err := internal.ReadLines(statFile) if err != nil { @@ -155,7 +154,7 @@ func CalculateMemoryStat(statFile, cachedKey, sharedKey string) (MemoryStat, err } for _, line := range lines { fields := strings.Fields(line) - if len(fields) != 2 { + if len(fields) != requiredFields { return memoryStat, fmt.Errorf("%+v required 2 fields", fields) } diff --git a/internal/collector/containermetricsreceiver/internal/utils.go b/internal/collector/containermetricsreceiver/internal/utils.go index 26ab7b977..08dee617f 100644 --- a/internal/collector/containermetricsreceiver/internal/utils.go +++ b/internal/collector/containermetricsreceiver/internal/utils.go @@ -21,7 +21,7 @@ func ReadLines(filename string) ([]string, error) { return ReadLinesOffsetN(filename, 0, -1) } -// nolint: revive +//nolint:revive // cognitive complexity is 16 func ReadLinesOffsetN(filename string, offset uint, n int) (lines []string, err error) { f, err := os.Open(filename) defer func() { diff --git a/internal/collector/logsgzipprocessor/processor.go b/internal/collector/logsgzipprocessor/processor.go index e8d1ca1de..9e3635beb 100644 --- a/internal/collector/logsgzipprocessor/processor.go +++ b/internal/collector/logsgzipprocessor/processor.go @@ -21,7 +21,7 @@ import ( "go.uber.org/zap" ) -// nolint: ireturn +//nolint:ireturn // must return factory processor interface for collector func NewFactory() processor.Factory { return processor.NewFactory( component.MustNewType("logsgzip"), @@ -32,7 +32,7 @@ func NewFactory() processor.Factory { ) } -// nolint: ireturn +//nolint:ireturn // returns a zip processor interface func createLogsGzipProcessor(_ context.Context, settings processor.Settings, cfg component.Config, diff --git a/internal/collector/logsgzipprocessor/processor_benchmark_test.go b/internal/collector/logsgzipprocessor/processor_benchmark_test.go index 82477aef7..b99baf5bb 100644 --- a/internal/collector/logsgzipprocessor/processor_benchmark_test.go +++ b/internal/collector/logsgzipprocessor/processor_benchmark_test.go @@ -73,7 +73,7 @@ func BenchmarkGzipProcessor(b *testing.B) { // Optional: Benchmark with concurrency to simulate real pipeline load func BenchmarkGzipProcessor_Concurrent(b *testing.B) { - // nolint:unused // concurrent runs require total parallel workers to be specified + //nolint: unused // concurrent runs require total parallel workers to be specified const workers = 8 logs := generateLogs(1000, 1000) consumer := &consumertest.LogsSink{} diff --git a/internal/collector/logsgzipprocessor/processor_test.go b/internal/collector/logsgzipprocessor/processor_test.go index a1c7423b3..98bff9f7c 100644 --- a/internal/collector/logsgzipprocessor/processor_test.go +++ b/internal/collector/logsgzipprocessor/processor_test.go @@ -171,7 +171,7 @@ func TestGzipProcessorFailure(t *testing.T) { } } -// nolint: revive +//nolint:revive // isGzipWriteErr flag is mandatory func customMockWriter(isGzipWriteErr, isGzipCloseErr bool) *mockGzipWriter { return &mockGzipWriter{ WriteFunc: func(p []byte) (int, error) { diff --git a/internal/collector/nginxossreceiver/factory.go b/internal/collector/nginxossreceiver/factory.go index 5932f2883..74ade854d 100644 --- a/internal/collector/nginxossreceiver/factory.go +++ b/internal/collector/nginxossreceiver/factory.go @@ -21,7 +21,7 @@ import ( "go.opentelemetry.io/collector/scraper/scraperhelper" ) -// nolint: ireturn +//nolint:ireturn // return a factory interface func NewFactory() receiver.Factory { return receiver.NewFactory( metadata.Type, @@ -30,7 +30,7 @@ func NewFactory() receiver.Factory { ) } -// nolint: ireturn +//nolint:ireturn // returns a metric interface which is required func createMetrics( _ context.Context, params receiver.Settings, diff --git a/internal/collector/nginxossreceiver/internal/config/config.go b/internal/collector/nginxossreceiver/internal/config/config.go index 55b2bd0ad..3d272c1a4 100644 --- a/internal/collector/nginxossreceiver/internal/config/config.go +++ b/internal/collector/nginxossreceiver/internal/config/config.go @@ -41,7 +41,7 @@ type AccessLog struct { FilePath string `mapstructure:"file_path"` } -// nolint: ireturn +//nolint:ireturn // Return default interface required by Collector func CreateDefaultConfig() component.Config { cfg := scraperhelper.NewDefaultControllerConfig() cfg.CollectionInterval = defaultCollectInterval diff --git a/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper.go b/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper.go index 0e0b59b6b..79cb51128 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper.go +++ b/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper.go @@ -104,7 +104,7 @@ func (nls *NginxLogScraper) ID() component.ID { return component.NewID(metadata.Type) } -// nolint: unparam +//nolint:unparam // Result is always nil func (nls *NginxLogScraper) Start(parentCtx context.Context, _ component.Host) error { nls.logger.Info("NGINX access log scraper started") ctx, cancel := context.WithCancel(parentCtx) diff --git a/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper_test.go b/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper_test.go index cb3f340ca..3905a57f9 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper_test.go +++ b/internal/collector/nginxossreceiver/internal/scraper/accesslog/nginx_log_scraper_test.go @@ -85,7 +85,8 @@ func TestAccessLogScraper(t *testing.T) { // Copies the contents of one file to another with the given delay. Used to simulate writing log entries to a log file. // Reason for nolint: we must use testify's assert instead of require, // for more info see https://github.com/stretchr/testify/issues/772#issuecomment-945166599 -// nolint: testifylint +// +//nolint:testifylint // we must use testify's assert instead of require func simulateLogging(t *testing.T, sourcePath, destinationPath string, writeDelay time.Duration) { t.Helper() diff --git a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config.go b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config.go index 803eeee62..121a43db5 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config.go +++ b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config.go @@ -46,7 +46,8 @@ func NewConfigWithID(operatorID string) *Config { } // Build will build a file input operator from the supplied configuration -// nolint: ireturn +// +//nolint:ireturn // The function returns a specific interface type as required by the OpenTelemetry Collector framework. func (c Config) Build(set component.TelemetrySettings) (operator.Operator, error) { logger := set.Logger diff --git a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config_test.go b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config_test.go index 70ee83087..3bddf058c 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config_test.go +++ b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/config_test.go @@ -17,7 +17,7 @@ import ( "go.uber.org/zap" ) -// nolint: lll +//nolint:lll // this needs to be in one line const ( accessLogPattern = `$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"` accessLogLine = "127.0.0.1 - - [19/May/2022:09:30:39 +0000] \"GET /nginx_status HTTP/1.1\" 200 98 \"-\" \"Go-http-client/1.1\" \"-\"\n" diff --git a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/grok.go b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/grok.go index 936d62464..109e772c8 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/grok.go +++ b/internal/collector/nginxossreceiver/internal/scraper/accesslog/operator/input/file/grok.go @@ -16,7 +16,7 @@ import ( ) var ( - //nolint: gocritic + //nolint:gocritic // this is required for request key formatVariables = map[string]string{ "$remote_addr": "%{IPORHOST:remote_addr}", "$remote_user": "%{USERNAME:remote_user}", diff --git a/internal/collector/nginxossreceiver/internal/scraper/stubstatus/stub_status_scraper.go b/internal/collector/nginxossreceiver/internal/scraper/stubstatus/stub_status_scraper.go index f908d022d..15b61ec93 100644 --- a/internal/collector/nginxossreceiver/internal/scraper/stubstatus/stub_status_scraper.go +++ b/internal/collector/nginxossreceiver/internal/scraper/stubstatus/stub_status_scraper.go @@ -62,7 +62,7 @@ func (s *NginxStubStatusScraper) ID() component.ID { return component.NewID(metadata.Type) } -// nolint: unparam +//nolint:unparam // Result is always nil func (s *NginxStubStatusScraper) Start(_ context.Context, _ component.Host) error { s.logger.Info("Starting NGINX stub status scraper") httpClient := http.DefaultClient @@ -103,7 +103,7 @@ func (s *NginxStubStatusScraper) Start(_ context.Context, _ component.Host) erro return nil } -// nolint: unparam +//nolint:unparam // Result is always nil func (s *NginxStubStatusScraper) Shutdown(_ context.Context) error { s.logger.Info("Shutting down NGINX stub status scraper") return nil diff --git a/internal/collector/nginxplusreceiver/config.go b/internal/collector/nginxplusreceiver/config.go index 7689442c1..6e622aaea 100644 --- a/internal/collector/nginxplusreceiver/config.go +++ b/internal/collector/nginxplusreceiver/config.go @@ -33,7 +33,7 @@ type APIDetails struct { } // Validate checks if the receiver configuration is valid -// nolint: ireturn + func (cfg *Config) Validate() error { if cfg.APIDetails.URL == "" { return errors.New("endpoint cannot be empty for nginxplusreceiver") @@ -46,7 +46,7 @@ func (cfg *Config) Validate() error { return nil } -// nolint: ireturn +//nolint:ireturn // must return default controller interface func createDefaultConfig() component.Config { cfg := scraperhelper.NewDefaultControllerConfig() cfg.CollectionInterval = defaultCollectInterval diff --git a/internal/collector/nginxplusreceiver/factory.go b/internal/collector/nginxplusreceiver/factory.go index fb1b9c34c..8040435d6 100644 --- a/internal/collector/nginxplusreceiver/factory.go +++ b/internal/collector/nginxplusreceiver/factory.go @@ -19,10 +19,9 @@ import ( "github.com/nginx/agent/v3/internal/collector/nginxplusreceiver/internal/metadata" ) -// nolint: ireturn const defaultTimeout = 10 * time.Second -// nolint: ireturn +//nolint:ireturn // must return metrics receiver interface func NewFactory() receiver.Factory { return receiver.NewFactory( metadata.Type, @@ -30,7 +29,7 @@ func NewFactory() receiver.Factory { receiver.WithMetrics(createMetricsReceiver, metadata.MetricsStability)) } -// nolint: ireturn +//nolint:ireturn // must return metrics receiver interface func createMetricsReceiver( ctx context.Context, params receiver.Settings, diff --git a/internal/collector/nginxplusreceiver/scraper.go b/internal/collector/nginxplusreceiver/scraper.go index c6dba8bc3..bbf3285fe 100644 --- a/internal/collector/nginxplusreceiver/scraper.go +++ b/internal/collector/nginxplusreceiver/scraper.go @@ -880,8 +880,7 @@ func (nps *NginxPlusScraper) recordServerZoneMetrics(stats *plusapi.Stats, now p } } -// Duplicate of recordLocationZoneHTTPMetrics but same function can not be used due to plusapi.ServerZone -// nolint: dupl +//nolint:dupl // Duplicate of recordLocationZoneHTTPMetrics but same function can not be used due to plusapi.ServerZone func (nps *NginxPlusScraper) recordServerZoneHTTPMetrics(sz plusapi.ServerZone, szName string, now pcommon.Timestamp) { nps.mb.RecordNginxHTTPResponseStatusDataPoint(now, int64(sz.Responses.Responses1xx), metadata.AttributeNginxStatusRange1xx, @@ -985,8 +984,7 @@ func (nps *NginxPlusScraper) recordLocationZoneMetrics(stats *plusapi.Stats, now } } -// Duplicate of recordServerZoneHTTPMetrics but same function can not be used due to plusapi.LocationZone -// nolint: dupl +//nolint:dupl // Duplicate of recordServerZoneHTTPMetrics but same function can not be used due to plusapi.LocationZone func (nps *NginxPlusScraper) recordLocationZoneHTTPMetrics(lz plusapi.LocationZone, lzName string, now pcommon.Timestamp, ) { @@ -1219,7 +1217,7 @@ func socketClient(ctx context.Context, socketPath string) *http.Client { } } -// nolint: revive +//nolint:revive // booleanValue flag is mandatory func boolToInt64(booleanValue bool) int64 { if booleanValue { return 1 diff --git a/internal/collector/otel_collector_plugin.go b/internal/collector/otel_collector_plugin.go index 7bf31be8f..0ecc70af8 100644 --- a/internal/collector/otel_collector_plugin.go +++ b/internal/collector/otel_collector_plugin.go @@ -221,7 +221,7 @@ func (oc *Collector) processReceivers(ctx context.Context, receivers map[string] } } -// nolint: revive, cyclop +//nolint:revive // cognitive complexity is 13 func (oc *Collector) bootup(ctx context.Context) error { errChan := make(chan error) @@ -657,7 +657,6 @@ func (oc *Collector) doesTcplogReceiverAlreadyExist(listenAddress string) bool { return false } -// nolint: revive func (oc *Collector) updateResourceAttributes( attributesToAdd []config.ResourceAttribute, ) (actionUpdated bool) { diff --git a/internal/collector/otel_collector_plugin_test.go b/internal/collector/otel_collector_plugin_test.go index 5fcb9d3e1..a59ba6f5b 100644 --- a/internal/collector/otel_collector_plugin_test.go +++ b/internal/collector/otel_collector_plugin_test.go @@ -153,7 +153,7 @@ func TestCollector_InitAndClose(t *testing.T) { assert.Equal(t, otelcol.StateClosed, collector.State()) } -// nolint: revive +//nolint:revive // cognitive complexity is 13 func TestCollector_ProcessNginxConfigUpdateTopic(t *testing.T) { tests := []struct { name string @@ -469,7 +469,6 @@ func TestCollector_ProcessResourceUpdateTopicFails(t *testing.T) { } } -// nolint: dupl func TestCollector_updateExistingNginxOSSReceiver(t *testing.T) { conf := types.OTelConfig(t) conf.Collector.Log.Path = "" @@ -578,7 +577,6 @@ func TestCollector_updateExistingNginxOSSReceiver(t *testing.T) { } } -// nolint: dupl func TestCollector_updateExistingNginxPlusReceiver(t *testing.T) { conf := types.OTelConfig(t) conf.Collector.Log.Path = "" diff --git a/internal/collector/settings_test.go b/internal/collector/settings_test.go index f8b8c7be4..0d7b5ce34 100644 --- a/internal/collector/settings_test.go +++ b/internal/collector/settings_test.go @@ -157,8 +157,8 @@ func TestTemplateWrite(t *testing.T) { } cfg.Collector.Exporters.OtlpExporters["default"].Authenticator = "headers_setter" - // nolint: lll - cfg.Collector.Exporters.OtlpExporters["default"].Compression = types.AgentConfig().Collector.Exporters.OtlpExporters["default"].Compression + cfg.Collector.Exporters.OtlpExporters["default"].Compression = types.AgentConfig(). + Collector.Exporters.OtlpExporters["default"].Compression cfg.Collector.Exporters.OtlpExporters["default"].Server.Port = 1234 cfg.Collector.Receivers.OtlpReceivers["default"].Server.Port = 4317 cfg.Collector.Extensions.Health.Server.Port = 1337 diff --git a/internal/command/command_plugin.go b/internal/command/command_plugin.go index 7ace559ce..e3315720b 100644 --- a/internal/command/command_plugin.go +++ b/internal/command/command_plugin.go @@ -244,7 +244,7 @@ func (cp *CommandPlugin) processConnectionReset(ctx context.Context, msg *bus.Me } } -// nolint: revive, cyclop +//nolint:revive // cognitive complexity is 14 func (cp *CommandPlugin) monitorSubscribeChannel(ctx context.Context) { for { select { diff --git a/internal/command/command_service.go b/internal/command/command_service.go index f0edc3615..a242b92a2 100644 --- a/internal/command/command_service.go +++ b/internal/command/command_service.go @@ -400,7 +400,8 @@ func (cs *CommandService) dataPlaneHealthCallback( } // Retry callback for receiving messages from the Management Plane subscription. -// nolint: revive +// +//nolint:revive // cognitive complexity is 18 func (cs *CommandService) receiveCallback(ctx context.Context) func() error { return func() error { cs.subscribeClientMutex.Lock() diff --git a/internal/command/command_service_test.go b/internal/command/command_service_test.go index 6226585b6..d91e9fe0f 100644 --- a/internal/command/command_service_test.go +++ b/internal/command/command_service_test.go @@ -39,7 +39,7 @@ func (*FakeSubscribeClient) Send(*mpi.DataPlaneResponse) error { return nil } -// nolint: nilnil +//nolint:nilnil // required nil return func (*FakeSubscribeClient) Recv() (*mpi.ManagementPlaneRequest, error) { time.Sleep(1 * time.Second) @@ -54,7 +54,6 @@ func (*FakeConfigApplySubscribeClient) Send(*mpi.DataPlaneResponse) error { return nil } -// nolint: nilnil func (*FakeConfigApplySubscribeClient) Recv() (*mpi.ManagementPlaneRequest, error) { nginxInstance := protos.NginxOssInstance([]string{}) diff --git a/internal/config/config.go b/internal/config/config.go index dfd8d1e8f..54cd65529 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -251,8 +251,8 @@ func addAuthHeader(collector *Collector, token string) { Headers: header, } } else { - // nolint: lll - collector.Extensions.HeadersSetter.Headers = append(collector.Extensions.HeadersSetter.Headers, header...) + collector.Extensions.HeadersSetter.Headers = append(collector.Extensions.HeadersSetter. + Headers, header...) } } @@ -1093,7 +1093,7 @@ func resolveProcessors() Processors { } // generate self-signed certificate for OTel receiver -// nolint: revive + func handleSelfSignedCertificates(col *Collector) error { if col.Receivers.OtlpReceivers != nil { for _, receiver := range col.Receivers.OtlpReceivers { diff --git a/internal/config/types.go b/internal/config/types.go index 4159c6a83..5d4973032 100644 --- a/internal/config/types.go +++ b/internal/config/types.go @@ -322,7 +322,7 @@ type ( Watchers struct { FileWatcher FileWatcher `yaml:"file_watcher" mapstructure:"file_watcher"` InstanceWatcher InstanceWatcher `yaml:"instance_watcher" mapstructure:"instance_watcher"` - // nolint: lll + //nolint:lll // this needs to be in one line InstanceHealthWatcher InstanceHealthWatcher `yaml:"instance_health_watcher" mapstructure:"instance_health_watcher"` } @@ -430,7 +430,6 @@ func (c *Config) IsACollectorExporterConfigured() bool { c.Collector.Exporters.Debug != nil } -// nolint: cyclop, revive func (c *Config) AreReceiversConfigured() bool { if c.Collector == nil { return false diff --git a/internal/datasource/config/nginx_config_parser.go b/internal/datasource/config/nginx_config_parser.go index 1d9c6bc92..1cb034f15 100644 --- a/internal/datasource/config/nginx_config_parser.go +++ b/internal/datasource/config/nginx_config_parser.go @@ -102,7 +102,7 @@ func (ncp *NginxConfigParser) Parse(ctx context.Context, instance *mpi.Instance) return ncp.createNginxConfigContext(ctx, instance, payload) } -// nolint: cyclop,revive,gocognit,gocyclo +//nolint:gocognit,gocyclo,revive,cyclop // cognitive complexity is 51 func (ncp *NginxConfigParser) createNginxConfigContext( ctx context.Context, instance *mpi.Instance, @@ -618,7 +618,7 @@ func (ncp *NginxConfigParser) pingAPIEndpoint(ctx context.Context, statusAPIDeta return true } -// nolint: revive +//nolint:revive // cognitive complexity is 18 func (ncp *NginxConfigParser) urlsForLocationDirectiveAPIDetails( ctx context.Context, parent, current *crossplane.Directive, locationDirectiveName string, diff --git a/internal/datasource/config/nginx_config_parser_test.go b/internal/datasource/config/nginx_config_parser_test.go index f6405674f..9423ba18f 100644 --- a/internal/datasource/config/nginx_config_parser_test.go +++ b/internal/datasource/config/nginx_config_parser_test.go @@ -288,7 +288,7 @@ server { ` ) -// nolint: maintidx +//nolint:maintidx // The test cannot be refactored func TestNginxConfigParser_Parse(t *testing.T) { ctx := context.Background() dir := t.TempDir() @@ -805,7 +805,7 @@ func TestNginxConfigParser_checkLog(t *testing.T) { } } -// nolint: maintidx +//nolint:maintidx // test can not be refactored func TestNginxConfigParser_urlsForLocationDirective(t *testing.T) { tmpDir := t.TempDir() for _, tt := range []struct { @@ -1153,7 +1153,7 @@ func TestNginxConfigParser_urlsForLocationDirective(t *testing.T) { } // linter doesn't like the duplicate handler and server function -// nolint: dupl + func TestNginxConfigParser_pingAPIEndpoint_PlusAPI(t *testing.T) { handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if req.URL.String() == "/good_api" { @@ -1215,7 +1215,7 @@ func TestNginxConfigParser_pingAPIEndpoint_PlusAPI(t *testing.T) { } // linter doesn't like the duplicate handler and server function -// nolint: dupl + func TestNginxConfigParser_pingAPIEndpoint_StubStatus(t *testing.T) { handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if req.URL.String() == "/good_api" { diff --git a/internal/datasource/host/info.go b/internal/datasource/host/info.go index bb47c6933..600a49b25 100644 --- a/internal/datasource/host/info.go +++ b/internal/datasource/host/info.go @@ -54,15 +54,15 @@ var ( // example: /docker/f244832c5a58377c3f1c7581b311c5bd8479808741f3e912d8bea8afe6431cb4 basePattern = regexp.MustCompile("/([a-f0-9]{64})$") - // nolint: lll + //nolint:lll // needs to be in one line // example: /system.slice/containerd.service/kubepods-besteffort-pod214f3ba8_4b69_4bdb_a7d5_5ecc73f04ae9.slice:cri-containerd:d4e8e05a546c86b6443f101966c618e47753ed01fa9929cae00d3b692f7a9f80 colonPattern = regexp.MustCompile(":([a-f0-9]{64})$") // example: /system.slice/crio-9e524432d716aa750574c9b6c01dee49e4b453445006684aad94c3d6df849e5c.scope scopePattern = regexp.MustCompile(`/.+-(.+?).scope$`) - // nolint: lll + //nolint:lll // needs to be in one line // example: /containers/storage/overlay-containers/ba0be90007be48bca767be0a462390ad2c9b0e910608158f79c8d6a984302b7e/userdata/hostname containersPattern = regexp.MustCompile("containers/([a-f0-9]{64})") - // nolint: lll + //nolint:lll // needs to be in one line // example: /var/lib/containerd/io.containerd.grpc.v1.cri/sandboxes/d7cb24ec5dede02990283dec30bd1e6ae1f93e3e19b152b708b7e0e133c6baec/hostname containerdPattern = regexp.MustCompile("sandboxes/([a-f0-9]{64})") ) diff --git a/internal/datasource/host/info_test.go b/internal/datasource/host/info_test.go index fb056a518..e4e7b050a 100644 --- a/internal/datasource/host/info_test.go +++ b/internal/datasource/host/info_test.go @@ -71,7 +71,7 @@ UBUNTU_CODENAME=focal ` ) -// nolint: lll +//nolint:lll // single lines are required var envMountInfo = [10]string{ `NO CONTAINER ID PRESENT IN MOUNTINFO`, `822 773 0:55 / / rw,relatime master:312 - overlay overlay rw,lowerdir=/var/lib/docker/overlay2/l/OVIJO6CZHWIXJDDHZXRECADDI3:/var/lib/docker/overlay2/l/3D3QYHJJTMCK6GLLVY7MMM6K4V:/var/lib/docker/overlay2/l/OKH52ZN3IE727BHLU3G3LEVI6S:/var/lib/docker/overlay2/l/K3BV3TCWQS2WDAY3ZVXO5GIHLQ:/var/lib/docker/overlay2/l/2KZOTUQIESHNC4FHZHYULXIKZ5,upperdir=/var/lib/docker/overlay2/f8c1fa1c3a6eb3731265dc674bf238c60fb594eedc4639cdbefef93ad443f55d/diff,workdir=/var/lib/docker/overlay2/f8c1fa1c3a6eb3731265dc674bf238c60fb594eedc4639cdbefef93ad443f55d/work,xino=off diff --git a/internal/file/file_manager_service.go b/internal/file/file_manager_service.go index 8953aaf5a..0b83fafae 100644 --- a/internal/file/file_manager_service.go +++ b/internal/file/file_manager_service.go @@ -178,7 +178,6 @@ func (fms *FileManagerService) ClearCache() { clear(fms.previousManifestFiles) } -// nolint:revive,cyclop func (fms *FileManagerService) Rollback(ctx context.Context, instanceID string) error { slog.InfoContext(ctx, "Rolling back config for instance", "instance_id", instanceID) @@ -272,7 +271,8 @@ func (fms *FileManagerService) ConfigUpload(ctx context.Context, configUploadReq // DetermineFileActions compares two sets of files to determine the file action for each file. Returns a map of files // that have changed and a map of the contents for each updated and deleted file. Key to both maps is file path -// nolint: revive,cyclop,gocognit +// +//nolint:gocognit,revive,cyclop // cognitive complexity is 23 func (fms *FileManagerService) DetermineFileActions( ctx context.Context, currentFiles map[string]*mpi.File, @@ -291,11 +291,10 @@ func (fms *FileManagerService) DetermineFileActions( _, filesMap, manifestFileErr := fms.manifestFile() if manifestFileErr != nil { - if errors.Is(manifestFileErr, os.ErrNotExist) { - filesMap = currentFiles - } else { + if !errors.Is(manifestFileErr, os.ErrNotExist) { return nil, nil, manifestFileErr } + filesMap = currentFiles } // if file is in manifestFiles but not in modified files, file has been deleted @@ -310,9 +309,9 @@ func (fms *FileManagerService) DetermineFileActions( if errors.Is(readErr, os.ErrNotExist) { slog.DebugContext(ctx, "Unable to backup file contents since file does not exist", "file", fileName) continue - } else { - return nil, nil, fmt.Errorf("error reading file %s: %w", fileName, readErr) } + + return nil, nil, fmt.Errorf("error reading file %s: %w", fileName, readErr) } fileContents[fileName] = fileContent @@ -381,7 +380,8 @@ func (fms *FileManagerService) UpdateCurrentFilesOnDisk( } // seems to be a control flag, avoid control coupling -// nolint: revive +// +//nolint:revive // referenced is a required flag func (fms *FileManagerService) UpdateManifestFile(currentFiles map[string]*mpi.File, referenced bool) (err error) { slog.Debug("Updating manifest file", "current_files", currentFiles, "referenced", referenced) currentManifestFiles, _, readError := fms.manifestFile() diff --git a/internal/file/file_plugin.go b/internal/file/file_plugin.go index d94796d2f..c093fe62e 100644 --- a/internal/file/file_plugin.go +++ b/internal/file/file_plugin.go @@ -81,7 +81,6 @@ func (fp *FilePlugin) Info() *bus.Info { } } -// nolint: cyclop, revive func (fp *FilePlugin) Process(ctx context.Context, msg *bus.Message) { ctxWithMetadata := fp.config.NewContextWithLabels(ctx) diff --git a/internal/grpc/grpc.go b/internal/grpc/grpc.go index fe0feaf62..f9099b334 100644 --- a/internal/grpc/grpc.go +++ b/internal/grpc/grpc.go @@ -69,7 +69,6 @@ var ( _ GrpcConnectionInterface = (*GrpcConnection)(nil) ) -// nolint: ireturn func NewGrpcConnection(ctx context.Context, agentConfig *config.Config, commandConfig *config.Command, ) (*GrpcConnection, error) { @@ -102,7 +101,7 @@ func NewGrpcConnection(ctx context.Context, agentConfig *config.Config, return grpcConnection, nil } -// nolint: ireturn +//nolint:ireturn // gRPC generated interface func (gc *GrpcConnection) CommandServiceClient() mpi.CommandServiceClient { gc.mutex.Lock() defer gc.mutex.Unlock() @@ -110,7 +109,7 @@ func (gc *GrpcConnection) CommandServiceClient() mpi.CommandServiceClient { return mpi.NewCommandServiceClient(gc.conn) } -// nolint: ireturn +//nolint:ireturn // gRPC generated interface func (gc *GrpcConnection) FileServiceClient() mpi.FileServiceClient { gc.mutex.Lock() defer gc.mutex.Unlock() diff --git a/internal/grpc/grpc_test.go b/internal/grpc/grpc_test.go index 2da040470..e1f3164a4 100644 --- a/internal/grpc/grpc_test.go +++ b/internal/grpc/grpc_test.go @@ -31,7 +31,7 @@ import ( type ClientStream struct{} func (*ClientStream) Header() (metadata.MD, error) { - // nolint: nilnil + //nolint:nilnil // required nil return return nil, nil } diff --git a/internal/model/config.go b/internal/model/config.go index 9dd24aeac..88b083e65 100644 --- a/internal/model/config.go +++ b/internal/model/config.go @@ -79,8 +79,7 @@ type ConfigApplySuccess struct { DataPlaneResponse *v1.DataPlaneResponse } -// Complexity is 11, allowed is 10 -// nolint: revive, cyclop +//nolint:revive,cyclop // cyclomatic complexity is 16 func (ncc *NginxConfigContext) Equal(otherNginxConfigContext *NginxConfigContext) bool { if ncc.StubStatus != nil && otherNginxConfigContext.StubStatus != nil { if ncc.StubStatus.URL != otherNginxConfigContext.StubStatus.URL || ncc.StubStatus.Listen != diff --git a/internal/resource/nginx_log_tailer_operator.go b/internal/resource/nginx_log_tailer_operator.go index 3a62f12ee..ea6da44f5 100644 --- a/internal/resource/nginx_log_tailer_operator.go +++ b/internal/resource/nginx_log_tailer_operator.go @@ -25,9 +25,9 @@ var _ logTailerOperator = (*NginxLogTailerOperator)(nil) var ( // Line is over 120 characters long, regex needs to be on one line so needs to be ignored by linter - // nolint: lll + //nolint:lll // needs to be on one line reloadErrorList = re.MustCompile(`\d{1,4}\/\d{1,2}\/\d{1,2} ([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9] ?(nginx\:|) (\[emerg\]|\[alert\]|\[crit\])`) - // nolint: lll + //nolint:lll // needs to be on one line warningRegex = re.MustCompile(`\d{1,4}\/\d{1,2}\/\d{1,2} ([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9] ?(nginx\:|) (\[warn\])`) ignoreErrorList = re.MustCompile(`.*(usage report| license expired).*`) ) diff --git a/internal/resource/resource_plugin.go b/internal/resource/resource_plugin.go index 32ec56606..c3d7467b6 100644 --- a/internal/resource/resource_plugin.go +++ b/internal/resource/resource_plugin.go @@ -71,7 +71,7 @@ func (*Resource) Info() *bus.Info { } // cyclomatic complexity 11 max is 10 -// nolint: revive, cyclop + func (r *Resource) Process(ctx context.Context, msg *bus.Message) { switch msg.Topic { case bus.AddInstancesTopic: diff --git a/internal/resource/resource_plugin_test.go b/internal/resource/resource_plugin_test.go index cecb17bbb..a427262bb 100644 --- a/internal/resource/resource_plugin_test.go +++ b/internal/resource/resource_plugin_test.go @@ -212,7 +212,6 @@ func TestResource_createPlusAPIError(t *testing.T) { assert.Equal(t, errors.New(string(expectedJSON)), result) } -// nolint: dupl func TestResource_Process_APIAction_GetHTTPServers(t *testing.T) { ctx := context.Background() @@ -288,42 +287,13 @@ func TestResource_Process_APIAction_GetHTTPServers(t *testing.T) { } for _, test := range tests { - t.Run(test.name, func(tt *testing.T) { - fakeResourceService := &resourcefakes.FakeResourceServiceInterface{} - fakeResourceService.GetHTTPUpstreamServersReturns(test.upstreams, test.err) - if test.instance.GetInstanceMeta().GetInstanceId() != "e1374cb1-462d-3b6c-9f3b-f28332b5f10f" { - fakeResourceService.InstanceReturns(test.instance) - } - - messagePipe := busfakes.NewFakeMessagePipe() - - resourcePlugin := NewResource(types.AgentConfig()) - resourcePlugin.resourceService = fakeResourceService - - err := messagePipe.Register(2, []bus.Plugin{resourcePlugin}) - require.NoError(t, err) - - resourcePlugin.messagePipe = messagePipe - - resourcePlugin.Process(ctx, test.message) - - assert.Equal(t, test.topic[0], messagePipe.Messages()[0].Topic) - - response, ok := messagePipe.Messages()[0].Data.(*mpi.DataPlaneResponse) - assert.True(tt, ok) - - if test.err != nil { - assert.Equal(tt, test.err.Error(), response.GetCommandResponse().GetError()) - assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_FAILURE, response.GetCommandResponse().GetStatus()) - } else { - assert.Empty(t, response.GetCommandResponse().GetError()) - assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_OK, response.GetCommandResponse().GetStatus()) - } - }) + runResourceTestHelper(t, ctx, test.name, func(fakeService *resourcefakes.FakeResourceServiceInterface) { + fakeService.GetHTTPUpstreamServersReturns(test.upstreams, test.err) + }, test.instance, test.message, test.topic, test.err) } } -// nolint: dupl +//nolint:dupl // need to refactor so that redundant code can be removed func TestResource_Process_APIAction_UpdateHTTPUpstreams(t *testing.T) { ctx := context.Background() tests := []struct { @@ -426,7 +396,7 @@ func TestResource_Process_APIAction_UpdateHTTPUpstreams(t *testing.T) { } } -// nolint: dupl +//nolint:dupl // need to refactor so that redundant code can be removed func TestResource_Process_APIAction_UpdateStreamServers(t *testing.T) { ctx := context.Background() tests := []struct { @@ -529,7 +499,6 @@ func TestResource_Process_APIAction_UpdateStreamServers(t *testing.T) { } } -// nolint: dupl func TestResource_Process_APIAction_GetStreamUpstreams(t *testing.T) { ctx := context.Background() @@ -671,7 +640,6 @@ func TestResource_Process_APIAction_GetStreamUpstreams(t *testing.T) { } } -// nolint: dupl func TestResource_Process_APIAction_GetUpstreams(t *testing.T) { ctx := context.Background() @@ -786,38 +754,9 @@ func TestResource_Process_APIAction_GetUpstreams(t *testing.T) { } for _, test := range tests { - t.Run(test.name, func(tt *testing.T) { - fakeResourceService := &resourcefakes.FakeResourceServiceInterface{} - fakeResourceService.GetUpstreamsReturns(test.upstreams, test.err) - if test.instance.GetInstanceMeta().GetInstanceId() != "e1374cb1-462d-3b6c-9f3b-f28332b5f10f" { - fakeResourceService.InstanceReturns(test.instance) - } - - messagePipe := busfakes.NewFakeMessagePipe() - - resourcePlugin := NewResource(types.AgentConfig()) - resourcePlugin.resourceService = fakeResourceService - - err := messagePipe.Register(2, []bus.Plugin{resourcePlugin}) - require.NoError(t, err) - - resourcePlugin.messagePipe = messagePipe - - resourcePlugin.Process(ctx, test.message) - - assert.Equal(t, test.topic[0], messagePipe.Messages()[0].Topic) - - response, ok := messagePipe.Messages()[0].Data.(*mpi.DataPlaneResponse) - assert.True(tt, ok) - - if test.err != nil { - assert.Equal(tt, test.err.Error(), response.GetCommandResponse().GetError()) - assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_FAILURE, response.GetCommandResponse().GetStatus()) - } else { - assert.Empty(t, response.GetCommandResponse().GetError()) - assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_OK, response.GetCommandResponse().GetStatus()) - } - }) + runResourceTestHelper(t, ctx, test.name, func(fakeService *resourcefakes.FakeResourceServiceInterface) { + fakeService.GetUpstreamsReturns(test.upstreams, test.err) + }, test.instance, test.message, test.topic, test.err) } } @@ -931,3 +870,40 @@ func TestResource_Init(t *testing.T) { assert.Empty(t, messages) } + +//nolint:revive,lll // maximum number of arguments exceed +func runResourceTestHelper(t *testing.T, ctx context.Context, testName string, getUpstreamsFunc func(*resourcefakes.FakeResourceServiceInterface), instance *mpi.Instance, message *bus.Message, topic []string, err error) { + t.Helper() + + t.Run(testName, func(tt *testing.T) { + fakeResourceService := &resourcefakes.FakeResourceServiceInterface{} + getUpstreamsFunc(fakeResourceService) + + if instance.GetInstanceMeta().GetInstanceId() != "e1374cb1-462d-3b6c-9f3b-f28332b5f10f" { + fakeResourceService.InstanceReturns(instance) + } + + messagePipe := busfakes.NewFakeMessagePipe() + resourcePlugin := NewResource(types.AgentConfig()) + resourcePlugin.resourceService = fakeResourceService + + registerErr := messagePipe.Register(2, []bus.Plugin{resourcePlugin}) + require.NoError(t, registerErr) + + resourcePlugin.messagePipe = messagePipe + resourcePlugin.Process(ctx, message) + + assert.Equal(tt, topic[0], messagePipe.Messages()[0].Topic) + + response, ok := messagePipe.Messages()[0].Data.(*mpi.DataPlaneResponse) + assert.True(tt, ok) + + if err != nil { + assert.Equal(tt, err.Error(), response.GetCommandResponse().GetError()) + assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_FAILURE, response.GetCommandResponse().GetStatus()) + } else { + assert.Empty(tt, response.GetCommandResponse().GetError()) + assert.Equal(tt, mpi.CommandResponse_COMMAND_STATUS_OK, response.GetCommandResponse().GetStatus()) + } + }) +} diff --git a/internal/resource/resource_service.go b/internal/resource/resource_service.go index 52c4cf3e0..9cfc1b88d 100644 --- a/internal/resource/resource_service.go +++ b/internal/resource/resource_service.go @@ -280,7 +280,8 @@ func (r *ResourceService) GetStreamUpstreams(ctx context.Context, instance *mpi. } // max number of returns from function is 3 -// nolint: revive +// +//nolint:revive // maximum return allowed is 3 func (r *ResourceService) UpdateStreamServers(ctx context.Context, instance *mpi.Instance, upstream string, upstreams []*structpb.Struct, ) (added, updated, deleted []client.StreamUpstreamServer, err error) { @@ -300,7 +301,8 @@ func (r *ResourceService) UpdateStreamServers(ctx context.Context, instance *mpi } // max number of returns from function is 3 -// nolint: revive +// +//nolint:revive // maximum return allowed is 3 func (r *ResourceService) UpdateHTTPUpstreamServers(ctx context.Context, instance *mpi.Instance, upstream string, upstreams []*structpb.Struct, ) (added, updated, deleted []client.UpstreamServer, err error) { diff --git a/internal/resource/resource_service_test.go b/internal/resource/resource_service_test.go index a3eb71074..e4b4beb05 100644 --- a/internal/resource/resource_service_test.go +++ b/internal/resource/resource_service_test.go @@ -392,7 +392,6 @@ func TestResourceService_ApplyConfig(t *testing.T) { } } -// nolint: dupl func Test_convertToUpstreamServer(t *testing.T) { expectedMax := 2 expectedFails := 0 @@ -412,30 +411,11 @@ func Test_convertToUpstreamServer(t *testing.T) { }, } - test := []*structpb.Struct{ - { - Fields: map[string]*structpb.Value{ - "max_conns": structpb.NewNumberValue(2), - "max_fails": structpb.NewNumberValue(0), - "backup": structpb.NewBoolValue(expectedBackup), - "server": structpb.NewStringValue("test_server"), - }, - }, - { - Fields: map[string]*structpb.Value{ - "max_conns": structpb.NewNumberValue(2), - "max_fails": structpb.NewNumberValue(0), - "backup": structpb.NewBoolValue(expectedBackup), - "server": structpb.NewStringValue("test_server2"), - }, - }, - } - - result := convertToUpstreamServer(test) - assert.Equal(t, expected, result) + runUpstreamServerConversionTest(t, expected, func(data []*structpb.Struct) interface{} { + return convertToUpstreamServer(data) + }) } -// nolint: dupl func Test_convertToStreamUpstreamServer(t *testing.T) { expectedMax := 2 expectedFails := 0 @@ -455,25 +435,37 @@ func Test_convertToStreamUpstreamServer(t *testing.T) { }, } - test := []*structpb.Struct{ + runUpstreamServerConversionTest(t, expected, func(data []*structpb.Struct) interface{} { + return convertToStreamUpstreamServer(data) + }) +} + +//nolint:lll // this need to be in one line else we will get gofumpt error +func runUpstreamServerConversionTest(t *testing.T, expectedUpstreamServers interface{}, conversionFunc func([]*structpb.Struct) interface{}) { + t.Helper() + expectedMax := 2 + expectedFails := 0 + expectedBackup := true + + testData := []*structpb.Struct{ { Fields: map[string]*structpb.Value{ - "max_conns": structpb.NewNumberValue(2), - "max_fails": structpb.NewNumberValue(0), + "max_conns": structpb.NewNumberValue(float64(expectedMax)), + "max_fails": structpb.NewNumberValue(float64(expectedFails)), "backup": structpb.NewBoolValue(expectedBackup), "server": structpb.NewStringValue("test_server"), }, }, { Fields: map[string]*structpb.Value{ - "max_conns": structpb.NewNumberValue(2), - "max_fails": structpb.NewNumberValue(0), + "max_conns": structpb.NewNumberValue(float64(expectedMax)), + "max_fails": structpb.NewNumberValue(float64(expectedFails)), "backup": structpb.NewBoolValue(expectedBackup), "server": structpb.NewStringValue("test_server2"), }, }, } - result := convertToStreamUpstreamServer(test) - assert.Equal(t, expected, result) + result := conversionFunc(testData) + assert.Equal(t, expectedUpstreamServers, result) } diff --git a/internal/watcher/instance/nginx_process_parser.go b/internal/watcher/instance/nginx_process_parser.go index f228dd157..f2ffc1bba 100644 --- a/internal/watcher/instance/nginx_process_parser.go +++ b/internal/watcher/instance/nginx_process_parser.go @@ -45,7 +45,8 @@ func NewNginxProcessParser() *NginxProcessParser { // cognitive complexity of 16 because of the if statements in the for loop // don't think can be avoided due to the need for continue -// nolint: revive +// +//nolint:revive // cognitive complexity of 20 because of the if statements in the for loop func (npp *NginxProcessParser) Parse(ctx context.Context, processes []*nginxprocess.Process) map[string]*mpi.Instance { instanceMap := make(map[string]*mpi.Instance) // key is instanceID workers := make(map[int32][]*mpi.InstanceChild) // key is ppid of process diff --git a/internal/watcher/watcher_plugin.go b/internal/watcher/watcher_plugin.go index d9f6755e9..4e3afd143 100644 --- a/internal/watcher/watcher_plugin.go +++ b/internal/watcher/watcher_plugin.go @@ -30,7 +30,6 @@ import ( //go:generate go run github.com/maxbrunsfeld/counterfeiter/v6@v6.8.1 -generate //counterfeiter:generate . instanceWatcherServiceInterface -// nolint type ( Watcher struct { messagePipe bus.MessagePipeInterface @@ -93,7 +92,6 @@ func NewWatcher(agentConfig *config.Config) *Watcher { } } -// nolint: unparam // error is always nil func (w *Watcher) Init(ctx context.Context, messagePipe bus.MessagePipeInterface) error { slog.DebugContext(ctx, "Starting watcher plugin") @@ -123,7 +121,6 @@ func (w *Watcher) Init(ctx context.Context, messagePipe bus.MessagePipeInterface return nil } -// nolint: unparam // error is always nil func (w *Watcher) Close(ctx context.Context) error { slog.InfoContext(ctx, "Closing watcher plugin") diff --git a/pkg/files/file_stream_test.go b/pkg/files/file_stream_test.go index 2c9e19dff..926a19e98 100644 --- a/pkg/files/file_stream_test.go +++ b/pkg/files/file_stream_test.go @@ -22,7 +22,7 @@ import ( var letters = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") -//nolint:gosec +//nolint:gosec // random number generater is fine for test case. func randBytes(n int) []byte { b := make([]byte, n) for i := range b { @@ -32,7 +32,7 @@ func randBytes(n int) []byte { return b } -//nolint:gocognit,revive +//nolint:gocognit,revive // cognitive complexity is 26 func TestSendChunkedFile(t *testing.T) { tests := []struct { name string @@ -217,7 +217,7 @@ func (b badWriter) Write(p []byte) (n int, err error) { return 0, errors.New("error") } -//nolint:revive,govet,maintidx +//nolint:revive,maintidx,govet // cognitive complexity is 14 func TestRecvChunkedFile(t *testing.T) { recvErr := errors.New("recv error") type recvReturn struct { diff --git a/pkg/nginxprocess/process.go b/pkg/nginxprocess/process.go index aebf0fd57..9d95e6731 100644 --- a/pkg/nginxprocess/process.go +++ b/pkg/nginxprocess/process.go @@ -56,11 +56,12 @@ type Option interface{ apply(opts *options) } type optionFunc func(*options) -//nolint:ireturn func (f optionFunc) apply(o *options) { f(o) } // WithStatus runs an additional lookup to load the process status. -func WithStatus(v bool) Option { //nolint:ireturn // functional options can be opaque +// +//nolint:ireturn // functional options can be opaque +func WithStatus(v bool) Option { return optionFunc(func(o *options) { o.loadStatus = v }) } diff --git a/pkg/tls/self_signed_cert.go b/pkg/tls/self_signed_cert.go index 4410afd37..8ac7fdc1f 100644 --- a/pkg/tls/self_signed_cert.go +++ b/pkg/tls/self_signed_cert.go @@ -114,8 +114,6 @@ func GenerateCA(now time.Time, caCertPath string) (*x509.Certificate, *ecdsa.Pri // GenerateServerCerts creates a server CA, Cert and Key and writes them to specified destinations. // Hostnames are a list of subject alternative names. // If cert files are already present, does nothing, returns true. -// -//nolint:revive func GenerateServerCerts(hostnames []string, caPath, certPath, keyPath string) (existingCert bool, err error) { // Check for and return existing cert if it already exists existingCert, existingCertErr := DoesCertAlreadyExist(certPath) diff --git a/pkg/tls/self_signed_cert_test.go b/pkg/tls/self_signed_cert_test.go index bbcf0bdd1..29289d9ee 100644 --- a/pkg/tls/self_signed_cert_test.go +++ b/pkg/tls/self_signed_cert_test.go @@ -17,7 +17,7 @@ import ( "github.com/stretchr/testify/require" ) -//nolint:revive,gocognit +//nolint:gocognit,revive // cognitive complexity is 24 func TestGenerateSelfSignedCert(t *testing.T) { // Setup temp file paths caPath := "/tmp/test_ca.pem" diff --git a/test/helpers/nginx_plus.go b/test/helpers/nginx_plus.go index f51a8c420..ea808390f 100644 --- a/test/helpers/nginx_plus.go +++ b/test/helpers/nginx_plus.go @@ -20,7 +20,7 @@ const ( serverID = 1234 ) -//nolint:gocyclo,revive,cyclop,maintidx +//nolint:gocyclo,revive,cyclop,maintidx // cyclomatic complexity is 23 func NewMockNGINXPlusAPIServer(t *testing.T) *httptest.Server { t.Helper() return httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { diff --git a/test/helpers/os_utils_test.go b/test/helpers/os_utils_test.go index a3b8d3688..de8866ea8 100644 --- a/test/helpers/os_utils_test.go +++ b/test/helpers/os_utils_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" ) -//nolint:staticcheck +//nolint:staticcheck,gofumpt // required for testing func TestRemoveASCIIControlSignals(t *testing.T) { tests := []struct { name string diff --git a/test/helpers/test_containers_utils.go b/test/helpers/test_containers_utils.go index baee47d40..f90ab3182 100644 --- a/test/helpers/test_containers_utils.go +++ b/test/helpers/test_containers_utils.go @@ -300,7 +300,7 @@ func ToPtr[T any](value T) *T { return &value } -// nolint: revive +//nolint:revive // expectNoErrorsInLogs flag is required func LogAndTerminateContainers( ctx context.Context, tb testing.TB, diff --git a/test/integration/utils/grpc_management_plane_utils.go b/test/integration/utils/grpc_management_plane_utils.go index 2ce2d5c74..de8d20f72 100644 --- a/test/integration/utils/grpc_management_plane_utils.go +++ b/test/integration/utils/grpc_management_plane_utils.go @@ -91,7 +91,8 @@ func SetupConnectionTest(tb testing.TB, expectNoErrorsInLogs, nginxless, auxilia } // setupContainerEnvironment sets up the container environment for testing. -// nolint: revive +// +//nolint:revive // "auxiliaryServer" flag is required for container func setupContainerEnvironment(ctx context.Context, tb testing.TB, nginxless, auxiliaryServer bool, agentConfig string, ) { diff --git a/test/mock/collector/mock-collector/auth/auth.go b/test/mock/collector/mock-collector/auth/auth.go index 02531138a..ee75558a7 100644 --- a/test/mock/collector/mock-collector/auth/auth.go +++ b/test/mock/collector/mock-collector/auth/auth.go @@ -33,7 +33,7 @@ type Option func(*HeadersCheck) // Ensure that the authenticator implements the auth.Server interface. var _ auth.Server = (*HeadersCheck)(nil) -//nolint:ireturn +//nolint:ireturn //must return an interface func NewFactory() extension.Factory { return extension.NewFactory( aType, @@ -56,7 +56,7 @@ func (a *HeadersCheck) Authenticate(ctx context.Context, headers map[string][]st return ctx, nil } -//nolint:ireturn +//nolint:ireturn //must return an interface func CreateAuthExtensionFunc( _ context.Context, setting extension.Settings, diff --git a/test/mock/collector/mock-collector/auth/config.go b/test/mock/collector/mock-collector/auth/config.go index c6e087899..2988ebca2 100644 --- a/test/mock/collector/mock-collector/auth/config.go +++ b/test/mock/collector/mock-collector/auth/config.go @@ -17,7 +17,7 @@ type Config struct { AuthenticatorID component.ID `mapstructure:",squash"` } -//nolint:ireturn +//nolint:ireturn //must return an interface func CreateDefaultConfig() component.Config { return &Config{ AuthenticatorID: HeadersCheckID, diff --git a/test/mock/grpc/mock_management_file_service.go b/test/mock/grpc/mock_management_file_service.go index 9ee302aae..9b916cb76 100644 --- a/test/mock/grpc/mock_management_file_service.go +++ b/test/mock/grpc/mock_management_file_service.go @@ -75,7 +75,6 @@ func (mgs *FileService) GetOverview( }, nil } -// nolint: unparam func (mgs *FileService) UpdateOverview( ctx context.Context, request *v1.UpdateOverviewRequest, diff --git a/test/model/config.go b/test/model/config.go index 67ffcc0ac..e1370d06b 100644 --- a/test/model/config.go +++ b/test/model/config.go @@ -22,7 +22,7 @@ func ConfigContext() *model.NginxConfigContext { } } -// nolint: revive +//nolint:revive // all the arguments are necessary. func ConfigContextWithNames( accessLogName, combinedAccessLogName,