From 74a1acd8144b6929171efffdf44a1135442b1588 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Mon, 22 Mar 2021 18:21:36 +0100 Subject: [PATCH] Linter fixes - revive:unused-parameter, unparam, varcheck and unused (#8984) * Linter fixes - revive:unused-parameter and unparam * Linter fixes - revive:unused-parameter and unparam * Linter fixes - revive:unused-parameter and unparam * "nolint"'s removed * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. * Fixes for "varcheck" and "unused" added. Co-authored-by: Pawel Zak --- .golangci.yml | 58 +----- agent/agent.go | 123 +++-------- agent/tick.go | 2 - cmd/telegraf/telegraf.go | 22 +- cmd/telegraf/telegraf_posix.go | 4 +- cmd/telegraf/telegraf_windows.go | 22 +- config/config.go | 16 +- internal/goplugin/noplugin.go | 2 +- internal/internal_test.go | 2 +- metric/metric.go | 4 +- metric/tracking_test.go | 15 +- models/buffer.go | 19 -- models/running_input_test.go | 6 +- models/running_output.go | 1 - models/running_output_test.go | 45 ++-- plugins/aggregators/merge/merge.go | 1 - plugins/aggregators/quantile/algorithms.go | 4 +- plugins/common/shim/config_test.go | 2 +- plugins/common/shim/goshim_test.go | 2 +- plugins/common/shim/input_test.go | 4 +- plugins/inputs/aerospike/aerospike.go | 8 - plugins/inputs/aliyuncms/aliyuncms_test.go | 2 +- plugins/inputs/apcupsd/apcupsd_test.go | 2 +- plugins/inputs/cassandra/cassandra_test.go | 17 +- plugins/inputs/ceph/ceph_test.go | 2 +- plugins/inputs/chrony/chrony_test.go | 2 +- .../cisco_telemetry_mdt.go | 60 +++--- .../cisco_telemetry_util.go | 28 +-- plugins/inputs/clickhouse/clickhouse_test.go | 2 +- plugins/inputs/cloud_pubsub/pubsub.go | 2 +- plugins/inputs/cloud_pubsub/pubsub_test.go | 2 +- .../inputs/cloud_pubsub/subscription_stub.go | 2 +- .../inputs/cloud_pubsub_push/pubsub_push.go | 14 +- .../cloud_pubsub_push/pubsub_push_test.go | 8 +- plugins/inputs/cloudwatch/cloudwatch.go | 14 +- plugins/inputs/cloudwatch/cloudwatch_test.go | 8 +- plugins/inputs/cpu/cpu_test.go | 101 ++++----- plugins/inputs/dcos/client.go | 9 +- plugins/inputs/dcos/creds.go | 8 +- plugins/inputs/dcos/dcos.go | 5 +- .../directory_monitor/directory_monitor.go | 10 +- .../directory_monitor_test.go | 7 - plugins/inputs/disque/disque.go | 7 +- plugins/inputs/docker/docker.go | 11 - plugins/inputs/docker/docker_test.go | 3 +- plugins/inputs/docker_log/docker_log.go | 14 +- plugins/inputs/dovecot/dovecot.go | 2 - plugins/inputs/elasticsearch/elasticsearch.go | 12 +- .../elasticsearch/elasticsearch_test.go | 32 +-- .../eventhub_consumer/eventhub_consumer.go | 12 +- plugins/inputs/exec/exec_test.go | 19 +- plugins/inputs/execd/execd_posix.go | 2 +- plugins/inputs/execd/shim/goshim.go | 1 - plugins/inputs/execd/shim/shim_test.go | 4 +- plugins/inputs/fail2ban/fail2ban_test.go | 2 +- plugins/inputs/fluentd/fluentd_test.go | 2 - plugins/inputs/graylog/graylog.go | 1 - plugins/inputs/hddtemp/hddtemp_test.go | 2 +- .../http_listener_v2/http_listener_v2.go | 5 - .../http_response/http_response_test.go | 6 +- .../intel_powerstat/intel_powerstat_test.go | 6 +- plugins/inputs/intel_rdt/publisher.go | 1 - plugins/inputs/ipmi_sensor/connection_test.go | 5 - plugins/inputs/ipmi_sensor/ipmi_test.go | 4 +- plugins/inputs/jenkins/jenkins.go | 13 -- plugins/inputs/jolokia/jolokia_test.go | 19 +- plugins/inputs/jolokia2/jolokia_test.go | 18 +- .../openconfig_telemetry.go | 13 +- .../openconfig_telemetry_test.go | 8 +- .../inputs/kafka_consumer/kafka_consumer.go | 7 +- .../kafka_consumer/kafka_consumer_test.go | 8 +- .../kafka_consumer_legacy.go | 2 +- .../kafka_consumer_legacy_integration_test.go | 4 +- .../kinesis_consumer/kinesis_consumer.go | 1 - plugins/inputs/kube_inventory/client_test.go | 12 -- plugins/inputs/kube_inventory/daemonset.go | 9 +- .../inputs/kube_inventory/daemonset_test.go | 10 +- plugins/inputs/kube_inventory/deployment.go | 9 +- .../inputs/kube_inventory/deployment_test.go | 10 +- plugins/inputs/kube_inventory/statefulset.go | 9 +- .../inputs/kube_inventory/statefulset_test.go | 10 +- plugins/inputs/kubernetes/kubernetes.go | 15 +- plugins/inputs/lanz/lanz.go | 2 +- plugins/inputs/logparser/logparser.go | 2 +- plugins/inputs/lustre2/lustre2.go | 1 - plugins/inputs/mesos/mesos.go | 43 ---- plugins/inputs/minecraft/client.go | 37 ++-- plugins/inputs/minecraft/client_test.go | 8 +- plugins/inputs/minecraft/minecraft.go | 13 +- plugins/inputs/monit/monit_test.go | 2 +- plugins/inputs/mqtt_consumer/mqtt_consumer.go | 6 +- .../mqtt_consumer/mqtt_consumer_test.go | 6 +- plugins/inputs/nats_consumer/nats_consumer.go | 2 +- .../inputs/net_response/net_response_test.go | 10 +- plugins/inputs/nfsclient/nfsclient.go | 22 +- plugins/inputs/nfsclient/nfsclient_test.go | 8 +- .../nginx_plus_api_metrics_test.go | 28 +-- plugins/inputs/nsd/nsd.go | 4 +- plugins/inputs/nsd/nsd_test.go | 10 +- plugins/inputs/nsq_consumer/nsq_consumer.go | 4 +- plugins/inputs/nstat/nstat.go | 51 ++--- plugins/inputs/nstat/nstat_test.go | 13 +- plugins/inputs/openntpd/openntpd.go | 9 +- plugins/inputs/openntpd/openntpd_test.go | 20 +- plugins/inputs/opensmtpd/opensmtpd.go | 3 +- plugins/inputs/opensmtpd/opensmtpd_test.go | 10 +- .../inputs/openweathermap/openweathermap.go | 9 +- plugins/inputs/pgbouncer/pgbouncer.go | 6 +- plugins/inputs/phpfpm/fcgi.go | 6 +- plugins/inputs/phpfpm/fcgi_test.go | 20 +- plugins/inputs/phpfpm/phpfpm.go | 4 +- plugins/inputs/phpfpm/phpfpm_test.go | 2 +- plugins/inputs/ping/ping_test.go | 16 +- .../powerdns_recursor_test.go | 2 - plugins/inputs/procstat/process.go | 2 +- plugins/inputs/procstat/procstat.go | 15 +- plugins/inputs/procstat/procstat_test.go | 40 ++-- .../inputs/procstat/win_service_notwindows.go | 2 +- plugins/inputs/prometheus/kubernetes.go | 5 - plugins/inputs/prometheus/kubernetes_test.go | 4 - plugins/inputs/prometheus/parser_test.go | 61 ------ plugins/inputs/prometheus/prometheus.go | 3 +- plugins/inputs/proxmox/proxmox.go | 11 +- plugins/inputs/proxmox/proxmox_test.go | 2 +- plugins/inputs/redis/redis_test.go | 2 +- plugins/inputs/rethinkdb/rethinkdb.go | 4 +- .../riemann_listener/riemann_listener_test.go | 8 +- plugins/inputs/sensors/sensors_test.go | 2 +- plugins/inputs/sflow/sflow.go | 2 - plugins/inputs/sflow/types.go | 10 - plugins/inputs/snmp/snmp_mocks_test.go | 2 +- plugins/inputs/snmp_legacy/snmp_legacy.go | 3 +- plugins/inputs/snmp_trap/snmp_trap.go | 4 +- plugins/inputs/snmp_trap/snmp_trap_test.go | 194 ++++++++++-------- .../inputs/stackdriver/stackdriver_test.go | 4 +- plugins/inputs/statsd/statsd.go | 6 +- plugins/inputs/suricata/suricata.go | 2 +- plugins/inputs/suricata/suricata_testutil.go | 38 ---- plugins/inputs/syslog/nontransparent_test.go | 15 +- plugins/inputs/syslog/octetcounting_test.go | 11 +- plugins/inputs/sysstat/sysstat_test.go | 2 +- plugins/inputs/system/mock_PS.go | 4 +- plugins/inputs/system/ps.go | 8 - plugins/inputs/tail/tail.go | 5 +- plugins/inputs/tcp_listener/tcp_listener.go | 4 +- .../inputs/tcp_listener/tcp_listener_test.go | 2 +- plugins/inputs/udp_listener/udp_listener.go | 4 +- .../inputs/udp_listener/udp_listener_test.go | 2 +- plugins/inputs/unbound/unbound.go | 49 +++-- plugins/inputs/unbound/unbound_test.go | 15 +- plugins/inputs/varnish/varnish_test.go | 14 +- plugins/inputs/vsphere/client.go | 37 ++-- plugins/inputs/vsphere/endpoint.go | 12 +- plugins/inputs/vsphere/vsphere.go | 2 +- plugins/inputs/vsphere/vsphere_test.go | 6 +- .../webhooks/mandrill/mandrill_webhooks.go | 2 +- plugins/inputs/zfs/zfs.go | 6 +- plugins/inputs/zfs/zfs_linux_test.go | 61 ------ .../stress_test_write/stress_test_write.go | 2 - plugins/inputs/zipkin/codec/codec_test.go | 3 - plugins/inputs/zipkin/zipkin.go | 2 +- plugins/outputs/amqp/amqp_test.go | 6 - .../application_insights_test.go | 9 - plugins/outputs/cloud_pubsub/topic_gcp.go | 2 - plugins/outputs/cratedb/cratedb_test.go | 1 + plugins/outputs/discard/discard.go | 2 +- plugins/outputs/graylog/graylog.go | 14 +- plugins/outputs/health/health.go | 2 +- plugins/outputs/influxdb/udp.go | 2 +- plugins/outputs/influxdb/udp_test.go | 2 +- plugins/outputs/influxdb_v2/influxdb_test.go | 2 +- plugins/outputs/kafka/kafka.go | 3 - plugins/outputs/kafka/kafka_test.go | 2 +- plugins/outputs/newrelic/newrelic_test.go | 3 - .../outputs/prometheus_client/v2/collector.go | 2 +- plugins/outputs/signalfx/signalfx.go | 3 - plugins/outputs/signalfx/signalfx_test.go | 8 +- plugins/outputs/sumologic/sumologic.go | 12 +- plugins/outputs/sumologic/sumologic_test.go | 21 +- plugins/outputs/warp10/warp10.go | 4 - .../yandex_cloud_monitoring_test.go | 7 +- plugins/parsers/csv/parser.go | 15 +- plugins/parsers/dropwizard/parser.go | 5 - plugins/parsers/influx/handler.go | 1 - plugins/parsers/influx/machine_test.go | 18 +- plugins/parsers/nagios/parser_test.go | 13 -- plugins/parsers/prometheus/parser_test.go | 3 - plugins/parsers/wavefront/element.go | 17 +- plugins/parsers/wavefront/scanner.go | 5 - plugins/processors/aws/ec2/ec2.go | 2 +- plugins/processors/dedup/dedup_test.go | 34 +-- plugins/processors/execd/execd.go | 2 +- plugins/processors/ifname/ifname.go | 2 +- .../processors/reverse_dns/rdnscache_test.go | 4 +- plugins/processors/reverse_dns/reversedns.go | 2 +- plugins/processors/starlark/builtins.go | 10 +- plugins/processors/starlark/logging.go | 4 +- plugins/processors/starlark/starlark.go | 6 +- plugins/processors/topk/topk_test.go | 34 ++- .../serializers/splunkmetric/splunkmetric.go | 18 +- plugins/serializers/wavefront/wavefront.go | 6 +- selfstat/stat.go | 1 - selfstat/timingStat.go | 1 - testutil/accumulator.go | 22 +- 204 files changed, 802 insertions(+), 1600 deletions(-) delete mode 100644 plugins/inputs/suricata/suricata_testutil.go diff --git a/.golangci.yml b/.golangci.yml index 8eeb577c52ff0..9f01ba6881010 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,4 +1,5 @@ linters: + disable-all: true enable: - bodyclose - dogsled @@ -18,55 +19,6 @@ linters: - unparam - unused - varcheck - disable: - - asciicheck - - deadcode - - depguard - - dupl - - exhaustive - - funlen - - gci - - gochecknoglobals - - gochecknoinits - - gocognit - - goconst - - gocritic - - gocyclo - - godot - - godox - - goerr113 - - gofmt - - gofumpt - - goheader - - goimports - - golint - - gomnd - - gomodguard - - gosec - - ifshort - - interfacer - - lll - - makezero - - maligned - - megacheck - - misspell - - nestif - - nlreturn - - noctx - - nolintlint - - paralleltest - - prealloc - - rowserrcheck - - scopelint - - structcheck - - stylecheck - - testpackage - - thelper - - tparallel - - wastedassign - - whitespace - - wrapcheck - - wsl linters-settings: revive: @@ -131,7 +83,7 @@ linters-settings: run: # timeout for analysis, e.g. 30s, 5m, default is 1m - timeout: 5m + timeout: 10m # which dirs to skip: issues from them won't be reported; # can use regexp here: generated.*, regexp is applied on full path; @@ -169,10 +121,8 @@ issues: linters: - govet - # Show only new issues created after git revision `HEAD~` - # Great for CI setups - # It's not practical to fix all existing issues at the moment of integration: much better to not allow issues in new code. - # new-from-rev: "HEAD~" + - path: _test\.go + text: "parameter.*seems to be a control flag, avoid control coupling" output: format: tab diff --git a/agent/agent.go b/agent/agent.go index 3d40e74a1bcdf..96e8596b851b2 100644 --- a/agent/agent.go +++ b/agent/agent.go @@ -126,10 +126,7 @@ func (a *Agent) Run(ctx context.Context) error { } } - next, au, err = a.startAggregators(aggC, next, a.Config.Aggregators) - if err != nil { - return err - } + next, au = a.startAggregators(aggC, next, a.Config.Aggregators) } var pu []*processorUnit @@ -149,29 +146,20 @@ func (a *Agent) Run(ctx context.Context) error { wg.Add(1) go func() { defer wg.Done() - err := a.runOutputs(ou) - if err != nil { - log.Printf("E! [agent] Error running outputs: %v", err) - } + a.runOutputs(ou) }() if au != nil { wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(apu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(apu) }() wg.Add(1) go func() { defer wg.Done() - err := a.runAggregators(startTime, au) - if err != nil { - log.Printf("E! [agent] Error running aggregators: %v", err) - } + a.runAggregators(startTime, au) }() } @@ -179,20 +167,14 @@ func (a *Agent) Run(ctx context.Context) error { wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(pu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(pu) }() } wg.Add(1) go func() { defer wg.Done() - err := a.runInputs(ctx, startTime, iu) - if err != nil { - log.Printf("E! [agent] Error running inputs: %v", err) - } + a.runInputs(ctx, startTime, iu) }() wg.Wait() @@ -288,7 +270,7 @@ func (a *Agent) runInputs( ctx context.Context, startTime time.Time, unit *inputUnit, -) error { +) { var wg sync.WaitGroup for _, input := range unit.inputs { // Overwrite agent interval if this plugin has its own. @@ -334,8 +316,6 @@ func (a *Agent) runInputs( close(unit.dst) log.Printf("D! [agent] Input channel closed") - - return nil } // testStartInputs is a variation of startInputs for use in --test and --once @@ -344,7 +324,7 @@ func (a *Agent) runInputs( func (a *Agent) testStartInputs( dst chan<- telegraf.Metric, inputs []*models.RunningInput, -) (*inputUnit, error) { +) *inputUnit { log.Printf("D! [agent] Starting service inputs") unit := &inputUnit{ @@ -369,7 +349,7 @@ func (a *Agent) testStartInputs( unit.inputs = append(unit.inputs, input) } - return unit, nil + return unit } // testRunInputs is a variation of runInputs for use in --test and --once mode. @@ -378,7 +358,7 @@ func (a *Agent) testRunInputs( ctx context.Context, wait time.Duration, unit *inputUnit, -) error { +) { var wg sync.WaitGroup nul := make(chan telegraf.Metric) @@ -434,7 +414,6 @@ func (a *Agent) testRunInputs( close(unit.dst) log.Printf("D! [agent] Input channel closed") - return nil } // stopServiceInputs stops all service inputs. @@ -553,7 +532,7 @@ func (a *Agent) startProcessors( // closed and all metrics have been written. func (a *Agent) runProcessors( units []*processorUnit, -) error { +) { var wg sync.WaitGroup for _, unit := range units { wg.Add(1) @@ -573,8 +552,6 @@ func (a *Agent) runProcessors( }(unit) } wg.Wait() - - return nil } // startAggregators sets up the aggregator unit and returns the source channel. @@ -582,7 +559,7 @@ func (a *Agent) startAggregators( aggC chan<- telegraf.Metric, outputC chan<- telegraf.Metric, aggregators []*models.RunningAggregator, -) (chan<- telegraf.Metric, *aggregatorUnit, error) { +) (chan<- telegraf.Metric, *aggregatorUnit) { src := make(chan telegraf.Metric, 100) unit := &aggregatorUnit{ src: src, @@ -590,7 +567,7 @@ func (a *Agent) startAggregators( outputC: outputC, aggregators: aggregators, } - return src, unit, nil + return src, unit } // runAggregators beings aggregating metrics and runs until the source channel @@ -598,7 +575,7 @@ func (a *Agent) startAggregators( func (a *Agent) runAggregators( startTime time.Time, unit *aggregatorUnit, -) error { +) { ctx, cancel := context.WithCancel(context.Background()) // Before calling Add, initialize the aggregation window. This ensures @@ -650,8 +627,6 @@ func (a *Agent) runAggregators( // processor chain will close the outputC when it finishes processing. close(unit.aggC) log.Printf("D! [agent] Aggregator channel closed") - - return nil } func updateWindow(start time.Time, roundInterval bool, period time.Duration) (time.Time, time.Time) { @@ -744,7 +719,7 @@ func (a *Agent) connectOutput(ctx context.Context, output *models.RunningOutput) // written one last time and dropped if unsuccessful. func (a *Agent) runOutputs( unit *outputUnit, -) error { +) { var wg sync.WaitGroup // Start flush loop @@ -793,8 +768,6 @@ func (a *Agent) runOutputs( log.Println("I! [agent] Stopping running outputs") stopRunningOutputs(unit.outputs) - - return nil } // flushLoop runs an output's flush function periodically until the context is @@ -924,10 +897,7 @@ func (a *Agent) test(ctx context.Context, wait time.Duration, outputC chan<- tel } } - next, au, err = a.startAggregators(procC, next, a.Config.Aggregators) - if err != nil { - return err - } + next, au = a.startAggregators(procC, next, a.Config.Aggregators) } var pu []*processorUnit @@ -938,30 +908,20 @@ func (a *Agent) test(ctx context.Context, wait time.Duration, outputC chan<- tel } } - iu, err := a.testStartInputs(next, a.Config.Inputs) - if err != nil { - return err - } + iu := a.testStartInputs(next, a.Config.Inputs) var wg sync.WaitGroup - if au != nil { wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(apu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(apu) }() wg.Add(1) go func() { defer wg.Done() - err := a.runAggregators(startTime, au) - if err != nil { - log.Printf("E! [agent] Error running aggregators: %v", err) - } + a.runAggregators(startTime, au) }() } @@ -969,20 +929,14 @@ func (a *Agent) test(ctx context.Context, wait time.Duration, outputC chan<- tel wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(pu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(pu) }() } wg.Add(1) go func() { defer wg.Done() - err := a.testRunInputs(ctx, wait, iu) - if err != nil { - log.Printf("E! [agent] Error running inputs: %v", err) - } + a.testRunInputs(ctx, wait, iu) }() wg.Wait() @@ -1042,10 +996,7 @@ func (a *Agent) once(ctx context.Context, wait time.Duration) error { } } - next, au, err = a.startAggregators(procC, next, a.Config.Aggregators) - if err != nil { - return err - } + next, au = a.startAggregators(procC, next, a.Config.Aggregators) } var pu []*processorUnit @@ -1056,38 +1007,26 @@ func (a *Agent) once(ctx context.Context, wait time.Duration) error { } } - iu, err := a.testStartInputs(next, a.Config.Inputs) - if err != nil { - return err - } + iu := a.testStartInputs(next, a.Config.Inputs) var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() - err := a.runOutputs(ou) - if err != nil { - log.Printf("E! [agent] Error running outputs: %v", err) - } + a.runOutputs(ou) }() if au != nil { wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(apu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(apu) }() wg.Add(1) go func() { defer wg.Done() - err := a.runAggregators(startTime, au) - if err != nil { - log.Printf("E! [agent] Error running aggregators: %v", err) - } + a.runAggregators(startTime, au) }() } @@ -1095,20 +1034,14 @@ func (a *Agent) once(ctx context.Context, wait time.Duration) error { wg.Add(1) go func() { defer wg.Done() - err := a.runProcessors(pu) - if err != nil { - log.Printf("E! [agent] Error running processors: %v", err) - } + a.runProcessors(pu) }() } wg.Add(1) go func() { defer wg.Done() - err := a.testRunInputs(ctx, wait, iu) - if err != nil { - log.Printf("E! [agent] Error running inputs: %v", err) - } + a.testRunInputs(ctx, wait, iu) }() wg.Wait() diff --git a/agent/tick.go b/agent/tick.go index 6afef2fa70edd..9696cd2c18c16 100644 --- a/agent/tick.go +++ b/agent/tick.go @@ -9,8 +9,6 @@ import ( "github.com/influxdata/telegraf/internal" ) -type empty struct{} - type Ticker interface { Elapsed() <-chan time.Time Stop() diff --git a/cmd/telegraf/telegraf.go b/cmd/telegraf/telegraf.go index c6b2cc0eef41b..459f81a90dc7c 100644 --- a/cmd/telegraf/telegraf.go +++ b/cmd/telegraf/telegraf.go @@ -61,11 +61,22 @@ var fProcessorFilters = flag.String("processor-filter", "", "filter the processors to enable, separator is :") var fUsage = flag.String("usage", "", "print usage for a plugin, ie, 'telegraf --usage mysql'") + +//nolint:varcheck,unused // False positive - this var is used for non-default build tag: windows var fService = flag.String("service", "", "operate on the service (windows only)") -var fServiceName = flag.String("service-name", "telegraf", "service name (windows only)") -var fServiceDisplayName = flag.String("service-display-name", "Telegraf Data Collector Service", "service display name (windows only)") -var fRunAsConsole = flag.Bool("console", false, "run as console application (windows only)") + +//nolint:varcheck,unused // False positive - this var is used for non-default build tag: windows +var fServiceName = flag.String("service-name", "telegraf", + "service name (windows only)") + +//nolint:varcheck,unused // False positive - this var is used for non-default build tag: windows +var fServiceDisplayName = flag.String("service-display-name", "Telegraf Data Collector Service", + "service display name (windows only)") + +//nolint:varcheck,unused // False positive - this var is used for non-default build tag: windows +var fRunAsConsole = flag.Bool("console", false, + "run as console application (windows only)") var fPlugins = flag.String("plugin-directory", "", "path to directory containing external plugins") var fRunOnce = flag.Bool("once", false, "run one gather and exit") @@ -81,14 +92,11 @@ var stop chan struct{} func reloadLoop( inputFilters []string, outputFilters []string, - aggregatorFilters []string, - processorFilters []string, ) { reload := make(chan bool, 1) reload <- true for <-reload { reload <- false - ctx, cancel := context.WithCancel(context.Background()) signals := make(chan os.Signal, 1) @@ -363,7 +371,5 @@ func main() { run( inputFilters, outputFilters, - aggregatorFilters, - processorFilters, ) } diff --git a/cmd/telegraf/telegraf_posix.go b/cmd/telegraf/telegraf_posix.go index ca28622f16752..a2d6b1e4e365c 100644 --- a/cmd/telegraf/telegraf_posix.go +++ b/cmd/telegraf/telegraf_posix.go @@ -2,12 +2,10 @@ package main -func run(inputFilters, outputFilters, aggregatorFilters, processorFilters []string) { +func run(inputFilters, outputFilters []string) { stop = make(chan struct{}) reloadLoop( inputFilters, outputFilters, - aggregatorFilters, - processorFilters, ) } diff --git a/cmd/telegraf/telegraf_windows.go b/cmd/telegraf/telegraf_windows.go index 52b9c43b99a2f..d04bfc34c7555 100644 --- a/cmd/telegraf/telegraf_windows.go +++ b/cmd/telegraf/telegraf_windows.go @@ -11,7 +11,7 @@ import ( "github.com/kardianos/service" ) -func run(inputFilters, outputFilters, aggregatorFilters, processorFilters []string) { +func run(inputFilters, outputFilters []string) { // Register the eventlog logging target for windows. logger.RegisterEventLogger(*fServiceName) @@ -19,25 +19,19 @@ func run(inputFilters, outputFilters, aggregatorFilters, processorFilters []stri runAsWindowsService( inputFilters, outputFilters, - aggregatorFilters, - processorFilters, ) } else { stop = make(chan struct{}) reloadLoop( inputFilters, outputFilters, - aggregatorFilters, - processorFilters, ) } } type program struct { - inputFilters []string - outputFilters []string - aggregatorFilters []string - processorFilters []string + inputFilters []string + outputFilters []string } func (p *program) Start(s service.Service) error { @@ -49,8 +43,6 @@ func (p *program) run() { reloadLoop( p.inputFilters, p.outputFilters, - p.aggregatorFilters, - p.processorFilters, ) } func (p *program) Stop(s service.Service) error { @@ -58,7 +50,7 @@ func (p *program) Stop(s service.Service) error { return nil } -func runAsWindowsService(inputFilters, outputFilters, aggregatorFilters, processorFilters []string) { +func runAsWindowsService(inputFilters, outputFilters []string) { programFiles := os.Getenv("ProgramFiles") if programFiles == "" { // Should never happen programFiles = "C:\\Program Files" @@ -72,10 +64,8 @@ func runAsWindowsService(inputFilters, outputFilters, aggregatorFilters, process } prg := &program{ - inputFilters: inputFilters, - outputFilters: outputFilters, - aggregatorFilters: aggregatorFilters, - processorFilters: processorFilters, + inputFilters: inputFilters, + outputFilters: outputFilters, } s, err := service.New(prg, svcConfig) if err != nil { diff --git a/config/config.go b/config/config.go index 55d101cbf8754..b7c11a95ff8c4 100644 --- a/config/config.go +++ b/config/config.go @@ -1006,14 +1006,14 @@ func (c *Config) addProcessor(name string, table *ast.Table) error { return err } - rf, err := c.newRunningProcessor(creator, processorConfig, name, table) + rf, err := c.newRunningProcessor(creator, processorConfig, table) if err != nil { return err } c.Processors = append(c.Processors, rf) // save a copy for the aggregator - rf, err = c.newRunningProcessor(creator, processorConfig, name, table) + rf, err = c.newRunningProcessor(creator, processorConfig, table) if err != nil { return err } @@ -1025,7 +1025,6 @@ func (c *Config) addProcessor(name string, table *ast.Table) error { func (c *Config) newRunningProcessor( creator processors.StreamingCreator, processorConfig *models.ProcessorConfig, - name string, table *ast.Table, ) (*models.RunningProcessor, error) { processor := creator() @@ -1058,7 +1057,7 @@ func (c *Config) addOutput(name string, table *ast.Table) error { // arbitrary types of output, so build the serializer and set it. switch t := output.(type) { case serializers.SerializerOutput: - serializer, err := c.buildSerializer(name, table) + serializer, err := c.buildSerializer(table) if err != nil { return err } @@ -1074,8 +1073,7 @@ func (c *Config) addOutput(name string, table *ast.Table) error { return err } - ro := models.NewRunningOutput(name, output, outputConfig, - c.Agent.MetricBatchSize, c.Agent.MetricBufferLimit) + ro := models.NewRunningOutput(output, outputConfig, c.Agent.MetricBatchSize, c.Agent.MetricBufferLimit) c.Outputs = append(c.Outputs, ro) return nil } @@ -1377,8 +1375,8 @@ func (c *Config) getParserConfig(name string, tbl *ast.Table) (*parsers.Config, // buildSerializer grabs the necessary entries from the ast.Table for creating // a serializers.Serializer object, and creates it, which can then be added onto // an Output object. -func (c *Config) buildSerializer(name string, tbl *ast.Table) (serializers.Serializer, error) { - sc := &serializers.Config{TimestampUnits: time.Duration(1 * time.Second)} +func (c *Config) buildSerializer(tbl *ast.Table) (serializers.Serializer, error) { + sc := &serializers.Config{TimestampUnits: 1 * time.Second} c.getFieldString(tbl, "data_format", &sc.DataFormat) @@ -1449,7 +1447,7 @@ func (c *Config) buildOutput(name string, tbl *ast.Table) (*models.OutputConfig, return oc, nil } -func (c *Config) missingTomlField(typ reflect.Type, key string) error { +func (c *Config) missingTomlField(_ reflect.Type, key string) error { switch key { case "alias", "carbon2_format", "collectd_auth_file", "collectd_parse_multivalue", "collectd_security_level", "collectd_typesdb", "collection_jitter", "csv_column_names", diff --git a/internal/goplugin/noplugin.go b/internal/goplugin/noplugin.go index 23d8634c46520..089972d465196 100644 --- a/internal/goplugin/noplugin.go +++ b/internal/goplugin/noplugin.go @@ -4,6 +4,6 @@ package goplugin import "errors" -func LoadExternalPlugins(rootDir string) error { +func LoadExternalPlugins(_ string) error { return errors.New("go plugin support is not enabled") } diff --git a/internal/internal_test.go b/internal/internal_test.go index 890a787bf258c..16980ecef93af 100644 --- a/internal/internal_test.go +++ b/internal/internal_test.go @@ -46,7 +46,7 @@ func TestSnakeCase(t *testing.T) { } var ( - sleepbin, _ = exec.LookPath("sleep") + sleepbin, _ = exec.LookPath("sleep") //nolint:unused // Used in skipped tests echobin, _ = exec.LookPath("echo") shell, _ = exec.LookPath("sh") ) diff --git a/metric/metric.go b/metric/metric.go index 517645a831280..b1a6edcfe91c7 100644 --- a/metric/metric.go +++ b/metric/metric.go @@ -251,8 +251,8 @@ func (m *metric) Copy() telegraf.Metric { return m2 } -func (m *metric) SetAggregate(b bool) { - m.aggregate = true +func (m *metric) SetAggregate(aggregate bool) { + m.aggregate = aggregate } func (m *metric) IsAggregate() bool { diff --git a/metric/tracking_test.go b/metric/tracking_test.go index 0ca1ca4daa4bc..3464ea15f2ecb 100644 --- a/metric/tracking_test.go +++ b/metric/tracking_test.go @@ -78,12 +78,13 @@ func TestTracking(t *testing.T) { { name: "accept", metric: mustMetric( - "cpu", + "memory", map[string]string{}, map[string]interface{}{ "value": 42, }, time.Unix(0, 0), + telegraf.Gauge, ), actions: func(m telegraf.Metric) { m.Accept() @@ -93,12 +94,13 @@ func TestTracking(t *testing.T) { { name: "reject", metric: mustMetric( - "cpu", + "memory", map[string]string{}, map[string]interface{}{ "value": 42, }, time.Unix(0, 0), + telegraf.Gauge, ), actions: func(m telegraf.Metric) { m.Reject() @@ -108,12 +110,13 @@ func TestTracking(t *testing.T) { { name: "accept copy", metric: mustMetric( - "cpu", + "memory", map[string]string{}, map[string]interface{}{ "value": 42, }, time.Unix(0, 0), + telegraf.Gauge, ), actions: func(m telegraf.Metric) { m2 := m.Copy() @@ -125,12 +128,13 @@ func TestTracking(t *testing.T) { { name: "copy with accept and done", metric: mustMetric( - "cpu", + "memory", map[string]string{}, map[string]interface{}{ "value": 42, }, time.Unix(0, 0), + telegraf.Gauge, ), actions: func(m telegraf.Metric) { m2 := m.Copy() @@ -142,12 +146,13 @@ func TestTracking(t *testing.T) { { name: "copy with mixed delivery", metric: mustMetric( - "cpu", + "memory", map[string]string{}, map[string]interface{}{ "value": 42, }, time.Unix(0, 0), + telegraf.Gauge, ), actions: func(m telegraf.Metric) { m2 := m.Copy() diff --git a/models/buffer.go b/models/buffer.go index 6cd1a6c71ae26..5f721dc98081b 100644 --- a/models/buffer.go +++ b/models/buffer.go @@ -220,16 +220,6 @@ func (b *Buffer) Reject(batch []telegraf.Metric) { b.BufferSize.Set(int64(b.length())) } -// dist returns the distance between two indexes. Because this data structure -// uses a half open range the arguments must both either left side or right -// side pairs. -func (b *Buffer) dist(begin, end int) int { - if begin <= end { - return end - begin - } - return b.cap - begin + end -} - // next returns the next index with wrapping. func (b *Buffer) next(index int) int { index++ @@ -246,15 +236,6 @@ func (b *Buffer) nextby(index, count int) int { return index } -// next returns the prev index with wrapping. -func (b *Buffer) prev(index int) int { - index-- - if index < 0 { - return b.cap - 1 - } - return index -} - // prevby returns the index that is count older with wrapping. func (b *Buffer) prevby(index, count int) int { index -= count diff --git a/models/running_input_test.go b/models/running_input_test.go index ff3747116f6ca..5c639e6929ef3 100644 --- a/models/running_input_test.go +++ b/models/running_input_test.go @@ -289,6 +289,6 @@ func TestMetricErrorCounters(t *testing.T) { type testInput struct{} -func (t *testInput) Description() string { return "" } -func (t *testInput) SampleConfig() string { return "" } -func (t *testInput) Gather(acc telegraf.Accumulator) error { return nil } +func (t *testInput) Description() string { return "" } +func (t *testInput) SampleConfig() string { return "" } +func (t *testInput) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/models/running_output.go b/models/running_output.go index b7f3fe03f9000..6f5f8c0a84bad 100644 --- a/models/running_output.go +++ b/models/running_output.go @@ -56,7 +56,6 @@ type RunningOutput struct { } func NewRunningOutput( - name string, output telegraf.Output, config *OutputConfig, batchSize int, diff --git a/models/running_output_test.go b/models/running_output_test.go index abde752bc15e2..feea970336817 100644 --- a/models/running_output_test.go +++ b/models/running_output_test.go @@ -29,14 +29,6 @@ var next5 = []telegraf.Metric{ testutil.TestMetric(101, "metric10"), } -func reverse(metrics []telegraf.Metric) []telegraf.Metric { - result := make([]telegraf.Metric, 0, len(metrics)) - for i := len(metrics) - 1; i >= 0; i-- { - result = append(result, metrics[i]) - } - return result -} - // Benchmark adding metrics. func BenchmarkRunningOutputAddWrite(b *testing.B) { conf := &OutputConfig{ @@ -44,7 +36,7 @@ func BenchmarkRunningOutputAddWrite(b *testing.B) { } m := &perfOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for n := 0; n < b.N; n++ { ro.AddMetric(testutil.TestMetric(101, "metric1")) @@ -59,7 +51,7 @@ func BenchmarkRunningOutputAddWriteEvery100(b *testing.B) { } m := &perfOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for n := 0; n < b.N; n++ { ro.AddMetric(testutil.TestMetric(101, "metric1")) @@ -77,7 +69,7 @@ func BenchmarkRunningOutputAddFailWrites(b *testing.B) { m := &perfOutput{} m.failWrite = true - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for n := 0; n < b.N; n++ { ro.AddMetric(testutil.TestMetric(101, "metric1")) @@ -94,7 +86,7 @@ func TestRunningOutput_DropFilter(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for _, metric := range first5 { ro.AddMetric(metric) @@ -119,7 +111,7 @@ func TestRunningOutput_PassFilter(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for _, metric := range first5 { ro.AddMetric(metric) @@ -144,7 +136,7 @@ func TestRunningOutput_TagIncludeNoMatch(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -165,7 +157,7 @@ func TestRunningOutput_TagExcludeMatch(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -186,7 +178,7 @@ func TestRunningOutput_TagExcludeNoMatch(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -207,7 +199,7 @@ func TestRunningOutput_TagIncludeMatch(t *testing.T) { assert.NoError(t, conf.Filter.Compile()) m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -225,7 +217,7 @@ func TestRunningOutput_NameOverride(t *testing.T) { } m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -243,7 +235,7 @@ func TestRunningOutput_NamePrefix(t *testing.T) { } m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -261,7 +253,7 @@ func TestRunningOutput_NameSuffix(t *testing.T) { } m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) ro.AddMetric(testutil.TestMetric(101, "metric1")) assert.Len(t, m.Metrics(), 0) @@ -279,7 +271,7 @@ func TestRunningOutputDefault(t *testing.T) { } m := &mockOutput{} - ro := NewRunningOutput("test", m, conf, 1000, 10000) + ro := NewRunningOutput(m, conf, 1000, 10000) for _, metric := range first5 { ro.AddMetric(metric) @@ -301,7 +293,7 @@ func TestRunningOutputWriteFail(t *testing.T) { m := &mockOutput{} m.failWrite = true - ro := NewRunningOutput("test", m, conf, 4, 12) + ro := NewRunningOutput(m, conf, 4, 12) // Fill buffer to limit twice for _, metric := range first5 { @@ -334,7 +326,7 @@ func TestRunningOutputWriteFailOrder(t *testing.T) { m := &mockOutput{} m.failWrite = true - ro := NewRunningOutput("test", m, conf, 100, 1000) + ro := NewRunningOutput(m, conf, 100, 1000) // add 5 metrics for _, metric := range first5 { @@ -372,7 +364,7 @@ func TestRunningOutputWriteFailOrder2(t *testing.T) { m := &mockOutput{} m.failWrite = true - ro := NewRunningOutput("test", m, conf, 5, 100) + ro := NewRunningOutput(m, conf, 5, 100) // add 5 metrics for _, metric := range first5 { @@ -436,7 +428,7 @@ func TestRunningOutputWriteFailOrder3(t *testing.T) { m := &mockOutput{} m.failWrite = true - ro := NewRunningOutput("test", m, conf, 5, 1000) + ro := NewRunningOutput(m, conf, 5, 1000) // add 5 metrics for _, metric := range first5 { @@ -470,7 +462,6 @@ func TestRunningOutputWriteFailOrder3(t *testing.T) { func TestInternalMetrics(t *testing.T) { _ = NewRunningOutput( - "test_internal", &mockOutput{}, &OutputConfig{ Filter: Filter{}, @@ -581,7 +572,7 @@ func (m *perfOutput) SampleConfig() string { return "" } -func (m *perfOutput) Write(metrics []telegraf.Metric) error { +func (m *perfOutput) Write(_ []telegraf.Metric) error { if m.failWrite { return fmt.Errorf("failed write") } diff --git a/plugins/aggregators/merge/merge.go b/plugins/aggregators/merge/merge.go index 35be286d3bc01..e11aad07a4b7d 100644 --- a/plugins/aggregators/merge/merge.go +++ b/plugins/aggregators/merge/merge.go @@ -19,7 +19,6 @@ const ( type Merge struct { grouper *metric.SeriesGrouper - log telegraf.Logger } func (a *Merge) Init() error { diff --git a/plugins/aggregators/quantile/algorithms.go b/plugins/aggregators/quantile/algorithms.go index d2a5ac685397a..641844f3f4e77 100644 --- a/plugins/aggregators/quantile/algorithms.go +++ b/plugins/aggregators/quantile/algorithms.go @@ -21,7 +21,7 @@ type exactAlgorithmR7 struct { sorted bool } -func newExactR7(compression float64) (algorithm, error) { +func newExactR7(_ float64) (algorithm, error) { return &exactAlgorithmR7{xs: make([]float64, 0, 100), sorted: false}, nil } @@ -68,7 +68,7 @@ type exactAlgorithmR8 struct { sorted bool } -func newExactR8(compression float64) (algorithm, error) { +func newExactR8(_ float64) (algorithm, error) { return &exactAlgorithmR8{xs: make([]float64, 0, 100), sorted: false}, nil } diff --git a/plugins/common/shim/config_test.go b/plugins/common/shim/config_test.go index 97d2004200b44..75ad18239fbb0 100644 --- a/plugins/common/shim/config_test.go +++ b/plugins/common/shim/config_test.go @@ -81,7 +81,7 @@ func (i *testDurationInput) SampleConfig() string { func (i *testDurationInput) Description() string { return "" } -func (i *testDurationInput) Gather(acc telegraf.Accumulator) error { +func (i *testDurationInput) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/common/shim/goshim_test.go b/plugins/common/shim/goshim_test.go index 080a513ade250..bbd1a0b703cc5 100644 --- a/plugins/common/shim/goshim_test.go +++ b/plugins/common/shim/goshim_test.go @@ -71,7 +71,7 @@ func (i *erroringInput) Gather(acc telegraf.Accumulator) error { return nil } -func (i *erroringInput) Start(acc telegraf.Accumulator) error { +func (i *erroringInput) Start(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/common/shim/input_test.go b/plugins/common/shim/input_test.go index 32f97d5924bc5..7cbfe6413975f 100644 --- a/plugins/common/shim/input_test.go +++ b/plugins/common/shim/input_test.go @@ -100,7 +100,7 @@ func (i *testInput) Gather(acc telegraf.Accumulator) error { return nil } -func (i *testInput) Start(acc telegraf.Accumulator) error { +func (i *testInput) Start(_ telegraf.Accumulator) error { return nil } @@ -133,7 +133,7 @@ func (i *serviceInput) Gather(acc telegraf.Accumulator) error { return nil } -func (i *serviceInput) Start(acc telegraf.Accumulator) error { +func (i *serviceInput) Start(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/aerospike/aerospike.go b/plugins/inputs/aerospike/aerospike.go index b5c13ddc45a7b..0c88ba840f822 100644 --- a/plugins/inputs/aerospike/aerospike.go +++ b/plugins/inputs/aerospike/aerospike.go @@ -486,14 +486,6 @@ func parseAerospikeValue(key string, v string) interface{} { } } -func copyTags(m map[string]string) map[string]string { - out := make(map[string]string) - for k, v := range m { - out[k] = v - } - return out -} - func init() { inputs.Add("aerospike", func() telegraf.Input { return &Aerospike{} diff --git a/plugins/inputs/aliyuncms/aliyuncms_test.go b/plugins/inputs/aliyuncms/aliyuncms_test.go index f0ac60e932761..a844ab4ee7a3a 100644 --- a/plugins/inputs/aliyuncms/aliyuncms_test.go +++ b/plugins/inputs/aliyuncms/aliyuncms_test.go @@ -71,7 +71,7 @@ type mockAliyunSDKCli struct { resp *responses.CommonResponse } -func (m *mockAliyunSDKCli) ProcessCommonRequest(req *requests.CommonRequest) (response *responses.CommonResponse, err error) { +func (m *mockAliyunSDKCli) ProcessCommonRequest(_ *requests.CommonRequest) (response *responses.CommonResponse, err error) { return m.resp, nil } diff --git a/plugins/inputs/apcupsd/apcupsd_test.go b/plugins/inputs/apcupsd/apcupsd_test.go index 7ab64ba114cc6..3cd90812bba15 100644 --- a/plugins/inputs/apcupsd/apcupsd_test.go +++ b/plugins/inputs/apcupsd/apcupsd_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestApcupsdDocs(t *testing.T) { +func TestApcupsdDocs(_ *testing.T) { apc := &ApcUpsd{} apc.Description() apc.SampleConfig() diff --git a/plugins/inputs/cassandra/cassandra_test.go b/plugins/inputs/cassandra/cassandra_test.go index 9b0798207ef16..325c267d9274b 100644 --- a/plugins/inputs/cassandra/cassandra_test.go +++ b/plugins/inputs/cassandra/cassandra_test.go @@ -77,19 +77,6 @@ const validCassandraNestedMultiValueJSON = ` } }` -const validSingleValueJSON = ` -{ - "request":{ - "path":"used", - "mbean":"java.lang:type=Memory", - "attribute":"HeapMemoryUsage", - "type":"read" - }, - "value":209274376, - "timestamp":1446129256, - "status":200 -}` - const validJavaMultiTypeJSON = ` { "request":{ @@ -104,8 +91,6 @@ const validJavaMultiTypeJSON = ` const invalidJSON = "I don't think this is JSON" -const empty = "" - var Servers = []string{"10.10.10.10:8778"} var AuthServers = []string{"user:passwd@10.10.10.10:8778"} var MultipleServers = []string{"10.10.10.10:8778", "10.10.10.11:8778"} @@ -121,7 +106,7 @@ type jolokiaClientStub struct { statusCode int } -func (c jolokiaClientStub) MakeRequest(req *http.Request) (*http.Response, error) { +func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) { resp := http.Response{} resp.StatusCode = c.statusCode resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) diff --git a/plugins/inputs/ceph/ceph_test.go b/plugins/inputs/ceph/ceph_test.go index e46a18049c354..08075fd03be49 100644 --- a/plugins/inputs/ceph/ceph_test.go +++ b/plugins/inputs/ceph/ceph_test.go @@ -86,7 +86,7 @@ func TestDecodeOSDPoolStats(t *testing.T) { } } -func TestGather(t *testing.T) { +func TestGather(_ *testing.T) { saveFind := findSockets saveDump := perfDump defer func() { diff --git a/plugins/inputs/chrony/chrony_test.go b/plugins/inputs/chrony/chrony_test.go index 4b8ad85ccf932..7c614dbbc75ce 100644 --- a/plugins/inputs/chrony/chrony_test.go +++ b/plugins/inputs/chrony/chrony_test.go @@ -65,7 +65,7 @@ func fakeExecCommand(command string, args ...string) *exec.Cmd { // For example, if you run: // GO_WANT_HELPER_PROCESS=1 go test -test.run=TestHelperProcess -- chrony tracking // it returns below mockData. -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go index e0cbb87d4371c..6dad06061f1cd 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_mdt.go @@ -88,15 +88,15 @@ func (c *CiscoTelemetryMDT) Start(acc telegraf.Accumulator) error { // Invert aliases list c.warned = make(map[string]struct{}) c.aliases = make(map[string]string, len(c.Aliases)) - for alias, path := range c.Aliases { - c.aliases[path] = alias + for alias, encodingPath := range c.Aliases { + c.aliases[encodingPath] = alias } c.initDb() c.dmesFuncs = make(map[string]string, len(c.Dmes)) - for dme, path := range c.Dmes { - c.dmesFuncs[path] = dme - switch path { + for dme, dmeKey := range c.Dmes { + c.dmesFuncs[dmeKey] = dme + switch dmeKey { case "uint64 to int": c.propMap[dme] = nxosValueXformUint64Toint64 case "uint64 to string": @@ -115,7 +115,7 @@ func (c *CiscoTelemetryMDT) Start(acc telegraf.Accumulator) error { } var jsStruct NxPayloadXfromStructure - err := json.Unmarshal([]byte(path), &jsStruct) + err := json.Unmarshal([]byte(dmeKey), &jsStruct) if err != nil { continue } @@ -449,9 +449,10 @@ func (c *CiscoTelemetryMDT) parseKeyField(tags map[string]string, field *telemet } } -func (c *CiscoTelemetryMDT) parseRib(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, prefix string, path string, tags map[string]string, timestamp time.Time) { +func (c *CiscoTelemetryMDT) parseRib(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, + encodingPath string, tags map[string]string, timestamp time.Time) { // RIB - measurement := path + measurement := encodingPath for _, subfield := range field.Fields { //For Every table fill the keys which are vrfName, address and masklen switch subfield.Name { @@ -481,13 +482,14 @@ func (c *CiscoTelemetryMDT) parseRib(grouper *metric.SeriesGrouper, field *telem } } -func (c *CiscoTelemetryMDT) parseClassAttributeField(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, prefix string, path string, tags map[string]string, timestamp time.Time) { +func (c *CiscoTelemetryMDT) parseClassAttributeField(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, + encodingPath string, tags map[string]string, timestamp time.Time) { // DME structure: https://developer.cisco.com/site/nxapi-dme-model-reference-api/ var nxAttributes *telemetry.TelemetryField - isDme := strings.Contains(path, "sys/") - if path == "rib" { + isDme := strings.Contains(encodingPath, "sys/") + if encodingPath == "rib" { //handle native data path rib - c.parseRib(grouper, field, prefix, path, tags, timestamp) + c.parseRib(grouper, field, encodingPath, tags, timestamp) return } if field == nil || !isDme || len(field.Fields) == 0 || len(field.Fields[0].Fields) == 0 || len(field.Fields[0].Fields[0].Fields) == 0 { @@ -503,13 +505,13 @@ func (c *CiscoTelemetryMDT) parseClassAttributeField(grouper *metric.SeriesGroup if subfield.Name == "dn" { tags["dn"] = decodeTag(subfield) } else { - c.parseContentField(grouper, subfield, "", path, tags, timestamp) + c.parseContentField(grouper, subfield, "", encodingPath, tags, timestamp) } } } func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, field *telemetry.TelemetryField, prefix string, - path string, tags map[string]string, timestamp time.Time) { + encodingPath string, tags map[string]string, timestamp time.Time) { name := strings.Replace(field.Name, "-", "_", -1) if (name == "modTs" || name == "createTs") && decodeValue(field) == "never" { @@ -521,23 +523,23 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie name = prefix + "/" + name } - extraTags := c.extraTags[strings.Replace(path, "-", "_", -1)+"/"+name] + extraTags := c.extraTags[strings.Replace(encodingPath, "-", "_", -1)+"/"+name] if value := decodeValue(field); value != nil { // Do alias lookup, to shorten measurement names - measurement := path - if alias, ok := c.aliases[path]; ok { + measurement := encodingPath + if alias, ok := c.aliases[encodingPath]; ok { measurement = alias } else { c.mutex.Lock() - if _, haveWarned := c.warned[path]; !haveWarned { - c.Log.Debugf("No measurement alias for encoding path: %s", path) - c.warned[path] = struct{}{} + if _, haveWarned := c.warned[encodingPath]; !haveWarned { + c.Log.Debugf("No measurement alias for encoding path: %s", encodingPath) + c.warned[encodingPath] = struct{}{} } c.mutex.Unlock() } - if val := c.nxosValueXform(field, value, path); val != nil { + if val := c.nxosValueXform(field, value, encodingPath); val != nil { grouper.Add(measurement, tags, timestamp, name, val) } else { grouper.Add(measurement, tags, timestamp, name, value) @@ -554,8 +556,8 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie } var nxAttributes, nxChildren, nxRows *telemetry.TelemetryField - isNXOS := !strings.ContainsRune(path, ':') // IOS-XR and IOS-XE have a colon in their encoding path, NX-OS does not - isEVENT := isNXOS && strings.Contains(path, "EVENT-LIST") + isNXOS := !strings.ContainsRune(encodingPath, ':') // IOS-XR and IOS-XE have a colon in their encoding path, NX-OS does not + isEVENT := isNXOS && strings.Contains(encodingPath, "EVENT-LIST") nxChildren = nil nxAttributes = nil for _, subfield := range field.Fields { @@ -574,13 +576,13 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie if nxAttributes == nil { //call function walking over walking list. for _, sub := range subfield.Fields { - c.parseClassAttributeField(grouper, sub, name, path, tags, timestamp) + c.parseClassAttributeField(grouper, sub, encodingPath, tags, timestamp) } } } else if isNXOS && strings.HasPrefix(subfield.Name, "ROW_") { nxRows = subfield } else if _, isExtraTag := extraTags[subfield.Name]; !isExtraTag { // Regular telemetry decoding - c.parseContentField(grouper, subfield, name, path, tags, timestamp) + c.parseContentField(grouper, subfield, name, encodingPath, tags, timestamp) } } @@ -595,10 +597,10 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie //We can have subfield so recursively handle it. if len(row.Fields) == 1 { tags["row_number"] = strconv.FormatInt(int64(i), 10) - c.parseContentField(grouper, subfield, "", path, tags, timestamp) + c.parseContentField(grouper, subfield, "", encodingPath, tags, timestamp) } } else { - c.parseContentField(grouper, subfield, "", path, tags, timestamp) + c.parseContentField(grouper, subfield, "", encodingPath, tags, timestamp) } // Nxapi we can't identify keys always from prefix tags["row_number"] = strconv.FormatInt(int64(i), 10) @@ -629,14 +631,14 @@ func (c *CiscoTelemetryMDT) parseContentField(grouper *metric.SeriesGrouper, fie for _, subfield := range nxAttributes.Fields { if subfield.Name != "rn" { - c.parseContentField(grouper, subfield, "", path, tags, timestamp) + c.parseContentField(grouper, subfield, "", encodingPath, tags, timestamp) } } if nxChildren != nil { // This is a nested structure, children will inherit relative name keys of parent for _, subfield := range nxChildren.Fields { - c.parseContentField(grouper, subfield, prefix, path, tags, timestamp) + c.parseContentField(grouper, subfield, prefix, encodingPath, tags, timestamp) } } delete(tags, prefix) diff --git a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go index 60140c030fed2..52f3e6fd59021 100644 --- a/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go +++ b/plugins/inputs/cisco_telemetry_mdt/cisco_telemetry_util.go @@ -39,7 +39,7 @@ func nxosValueXformUint64Toint64(field *telemetry.TelemetryField, value interfac } //xform string to float -func nxosValueXformStringTofloat(field *telemetry.TelemetryField, value interface{}) interface{} { +func nxosValueXformStringTofloat(field *telemetry.TelemetryField, _ interface{}) interface{} { //convert property to float from string. vals := field.GetStringValue() if vals != "" { @@ -51,7 +51,7 @@ func nxosValueXformStringTofloat(field *telemetry.TelemetryField, value interfac } //xform string to uint64 -func nxosValueXformStringToUint64(field *telemetry.TelemetryField, value interface{}) interface{} { +func nxosValueXformStringToUint64(field *telemetry.TelemetryField, _ interface{}) interface{} { //string to uint64 vals := field.GetStringValue() if vals != "" { @@ -63,7 +63,7 @@ func nxosValueXformStringToUint64(field *telemetry.TelemetryField, value interfa } //xform string to int64 -func nxosValueXformStringToInt64(field *telemetry.TelemetryField, value interface{}) interface{} { +func nxosValueXformStringToInt64(field *telemetry.TelemetryField, _ interface{}) interface{} { //string to int64 vals := field.GetStringValue() if vals != "" { @@ -74,26 +74,8 @@ func nxosValueXformStringToInt64(field *telemetry.TelemetryField, value interfac return nil } -//auto-xform -func nxosValueAutoXform(field *telemetry.TelemetryField, value interface{}) interface{} { - //check if we want auto xformation - vals := field.GetStringValue() - if vals != "" { - if val64, err := strconv.ParseUint(vals, 10, 64); err == nil { - return val64 - } - if valf, err := strconv.ParseFloat(vals, 64); err == nil { - return valf - } - if val64, err := strconv.ParseInt(vals, 10, 64); err == nil { - return val64 - } - } // switch - return nil -} - //auto-xform float properties -func nxosValueAutoXformFloatProp(field *telemetry.TelemetryField, value interface{}) interface{} { +func nxosValueAutoXformFloatProp(field *telemetry.TelemetryField, _ interface{}) interface{} { //check if we want auto xformation vals := field.GetStringValue() if vals != "" { @@ -105,7 +87,7 @@ func nxosValueAutoXformFloatProp(field *telemetry.TelemetryField, value interfac } //xform uint64 to string -func nxosValueXformUint64ToString(field *telemetry.TelemetryField, value interface{}) interface{} { +func nxosValueXformUint64ToString(field *telemetry.TelemetryField, _ interface{}) interface{} { switch val := field.ValueByType.(type) { case *telemetry.TelemetryField_StringValue: if len(val.StringValue) > 0 { diff --git a/plugins/inputs/clickhouse/clickhouse_test.go b/plugins/inputs/clickhouse/clickhouse_test.go index c69c455b94c5e..bf53fdae007d8 100644 --- a/plugins/inputs/clickhouse/clickhouse_test.go +++ b/plugins/inputs/clickhouse/clickhouse_test.go @@ -548,7 +548,7 @@ func TestOfflineServer(t *testing.T) { assert.GreaterOrEqual(t, len(allMeasurements), len(acc.Errors)) } -func TestAutoDiscovery(t *testing.T) { +func TestAutoDiscovery(_ *testing.T) { var ( ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { type result struct { diff --git a/plugins/inputs/cloud_pubsub/pubsub.go b/plugins/inputs/cloud_pubsub/pubsub.go index 0ac40a2cf551d..41ecf09ec3051 100644 --- a/plugins/inputs/cloud_pubsub/pubsub.go +++ b/plugins/inputs/cloud_pubsub/pubsub.go @@ -67,7 +67,7 @@ func (ps *PubSub) SampleConfig() string { } // Gather does nothing for this service input. -func (ps *PubSub) Gather(acc telegraf.Accumulator) error { +func (ps *PubSub) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/cloud_pubsub/pubsub_test.go b/plugins/inputs/cloud_pubsub/pubsub_test.go index 0adc024872df7..d07dfe34f2290 100644 --- a/plugins/inputs/cloud_pubsub/pubsub_test.go +++ b/plugins/inputs/cloud_pubsub/pubsub_test.go @@ -207,7 +207,7 @@ func TestRunErrorInSubscriber(t *testing.T) { messages: make(chan *testMsg, 100), } fakeErrStr := "a fake error" - sub.receiver = testMessagesError(sub, errors.New("a fake error")) + sub.receiver = testMessagesError(errors.New("a fake error")) ps := &PubSub{ Log: testutil.Logger{}, diff --git a/plugins/inputs/cloud_pubsub/subscription_stub.go b/plugins/inputs/cloud_pubsub/subscription_stub.go index e061728caf7fe..1e5bd009bc138 100644 --- a/plugins/inputs/cloud_pubsub/subscription_stub.go +++ b/plugins/inputs/cloud_pubsub/subscription_stub.go @@ -22,7 +22,7 @@ func (s *stubSub) Receive(ctx context.Context, f func(context.Context, message)) type receiveFunc func(ctx context.Context, f func(context.Context, message)) error -func testMessagesError(s *stubSub, expectedErr error) receiveFunc { +func testMessagesError(expectedErr error) receiveFunc { return func(ctx context.Context, f func(context.Context, message)) error { return expectedErr } diff --git a/plugins/inputs/cloud_pubsub_push/pubsub_push.go b/plugins/inputs/cloud_pubsub_push/pubsub_push.go index b320daedbacc1..575bdae61f8c9 100644 --- a/plugins/inputs/cloud_pubsub_push/pubsub_push.go +++ b/plugins/inputs/cloud_pubsub_push/pubsub_push.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "encoding/json" "io/ioutil" - "net" "net/http" "sync" "time" @@ -39,13 +38,12 @@ type PubSubPush struct { tlsint.ServerConfig parsers.Parser - listener net.Listener - server *http.Server - acc telegraf.TrackingAccumulator - ctx context.Context - cancel context.CancelFunc - wg *sync.WaitGroup - mu *sync.Mutex + server *http.Server + acc telegraf.TrackingAccumulator + ctx context.Context + cancel context.CancelFunc + wg *sync.WaitGroup + mu *sync.Mutex undelivered map[telegraf.TrackingID]chan bool sem chan struct{} diff --git a/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go b/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go index ae7601b20cccc..ccce488a81c6e 100644 --- a/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go +++ b/plugins/inputs/cloud_pubsub_push/pubsub_push_test.go @@ -144,7 +144,7 @@ func TestServeHTTP(t *testing.T) { pubPush.SetParser(p) dst := make(chan telegraf.Metric, 1) - ro := models.NewRunningOutput("test", &testOutput{failWrite: test.fail}, &models.OutputConfig{}, 1, 1) + ro := models.NewRunningOutput(&testOutput{failWrite: test.fail}, &models.OutputConfig{}, 1, 1) pubPush.acc = agent.NewAccumulator(&testMetricMaker{}, dst).WithTracking(1) wg.Add(1) @@ -154,13 +154,13 @@ func TestServeHTTP(t *testing.T) { }() wg.Add(1) - go func(status int, d chan telegraf.Metric) { + go func(d chan telegraf.Metric) { defer wg.Done() for m := range d { ro.AddMetric(m) ro.Write() } - }(test.status, dst) + }(dst) ctx, cancel := context.WithTimeout(req.Context(), pubPush.WriteTimeout.Duration) req = req.WithContext(ctx) @@ -218,7 +218,7 @@ func (*testOutput) SampleConfig() string { return "" } -func (t *testOutput) Write(metrics []telegraf.Metric) error { +func (t *testOutput) Write(_ []telegraf.Metric) error { if t.failWrite { return fmt.Errorf("failed write") } diff --git a/plugins/inputs/cloudwatch/cloudwatch.go b/plugins/inputs/cloudwatch/cloudwatch.go index 1bc5379e56419..22fdcab38e0b6 100644 --- a/plugins/inputs/cloudwatch/cloudwatch.go +++ b/plugins/inputs/cloudwatch/cloudwatch.go @@ -208,11 +208,7 @@ func (c *CloudWatch) Gather(acc telegraf.Accumulator) error { c.updateWindow(time.Now()) // Get all of the possible queries so we can send groups of 100. - queries, err := c.getDataQueries(filteredMetrics) - if err != nil { - return err - } - + queries := c.getDataQueries(filteredMetrics) if len(queries) == 0 { return nil } @@ -441,9 +437,9 @@ func (c *CloudWatch) updateWindow(relativeTo time.Time) { } // getDataQueries gets all of the possible queries so we can maximize the request payload. -func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) ([]*cloudwatch.MetricDataQuery, error) { +func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) []*cloudwatch.MetricDataQuery { if c.metricCache != nil && c.metricCache.queries != nil && c.metricCache.isValid() { - return c.metricCache.queries, nil + return c.metricCache.queries } c.queryDimensions = map[string]*map[string]string{} @@ -518,7 +514,7 @@ func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) ([]*cloudw if len(dataQueries) == 0 { c.Log.Debug("no metrics found to collect") - return nil, nil + return nil } if c.metricCache == nil { @@ -531,7 +527,7 @@ func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) ([]*cloudw c.metricCache.queries = dataQueries } - return dataQueries, nil + return dataQueries } // gatherMetrics gets metric data from Cloudwatch. diff --git a/plugins/inputs/cloudwatch/cloudwatch_test.go b/plugins/inputs/cloudwatch/cloudwatch_test.go index 798cdff1f2bed..43fb01f058821 100644 --- a/plugins/inputs/cloudwatch/cloudwatch_test.go +++ b/plugins/inputs/cloudwatch/cloudwatch_test.go @@ -135,7 +135,7 @@ func TestGather(t *testing.T) { type mockSelectMetricsCloudWatchClient struct{} -func (m *mockSelectMetricsCloudWatchClient) ListMetrics(params *cloudwatch.ListMetricsInput) (*cloudwatch.ListMetricsOutput, error) { +func (m *mockSelectMetricsCloudWatchClient) ListMetrics(_ *cloudwatch.ListMetricsInput) (*cloudwatch.ListMetricsOutput, error) { metrics := []*cloudwatch.Metric{} // 4 metrics are available metricNames := []string{"Latency", "RequestCount", "HealthyHostCount", "UnHealthyHostCount"} @@ -182,7 +182,7 @@ func (m *mockSelectMetricsCloudWatchClient) ListMetrics(params *cloudwatch.ListM return result, nil } -func (m *mockSelectMetricsCloudWatchClient) GetMetricData(params *cloudwatch.GetMetricDataInput) (*cloudwatch.GetMetricDataOutput, error) { +func (m *mockSelectMetricsCloudWatchClient) GetMetricData(_ *cloudwatch.GetMetricDataInput) (*cloudwatch.GetMetricDataOutput, error) { return nil, nil } @@ -246,7 +246,7 @@ func TestGenerateStatisticsInputParams(t *testing.T) { c.updateWindow(now) statFilter, _ := filter.NewIncludeExcludeFilter(nil, nil) - queries, _ := c.getDataQueries([]filteredMetric{{metrics: []*cloudwatch.Metric{m}, statFilter: statFilter}}) + queries := c.getDataQueries([]filteredMetric{{metrics: []*cloudwatch.Metric{m}, statFilter: statFilter}}) params := c.getDataInputs(queries) assert.EqualValues(t, *params.EndTime, now.Add(-time.Duration(c.Delay))) @@ -283,7 +283,7 @@ func TestGenerateStatisticsInputParamsFiltered(t *testing.T) { c.updateWindow(now) statFilter, _ := filter.NewIncludeExcludeFilter([]string{"average", "sample_count"}, nil) - queries, _ := c.getDataQueries([]filteredMetric{{metrics: []*cloudwatch.Metric{m}, statFilter: statFilter}}) + queries := c.getDataQueries([]filteredMetric{{metrics: []*cloudwatch.Metric{m}, statFilter: statFilter}}) params := c.getDataInputs(queries) assert.EqualValues(t, *params.EndTime, now.Add(-time.Duration(c.Delay))) diff --git a/plugins/inputs/cpu/cpu_test.go b/plugins/inputs/cpu/cpu_test.go index bf356ec7b945c..d3849a5198038 100644 --- a/plugins/inputs/cpu/cpu_test.go +++ b/plugins/inputs/cpu/cpu_test.go @@ -48,26 +48,22 @@ func TestCPUStats(t *testing.T) { cs := NewCPUStats(&mps) - cputags := map[string]string{ - "cpu": "cpu0", - } - err := cs.Gather(&acc) require.NoError(t, err) // Computed values are checked with delta > 0 because of floating point arithmetic // imprecision - assertContainsTaggedFloat(t, &acc, "cpu", "time_user", 8.8, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_system", 8.2, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_idle", 80.1, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_active", 19.9, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_nice", 1.3, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_iowait", 0.8389, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_irq", 0.6, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_softirq", 0.11, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_steal", 0.0511, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_guest", 3.1, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_guest_nice", 0.324, 0, cputags) + assertContainsTaggedFloat(t, &acc, "time_user", 8.8, 0) + assertContainsTaggedFloat(t, &acc, "time_system", 8.2, 0) + assertContainsTaggedFloat(t, &acc, "time_idle", 80.1, 0) + assertContainsTaggedFloat(t, &acc, "time_active", 19.9, 0.0005) + assertContainsTaggedFloat(t, &acc, "time_nice", 1.3, 0) + assertContainsTaggedFloat(t, &acc, "time_iowait", 0.8389, 0) + assertContainsTaggedFloat(t, &acc, "time_irq", 0.6, 0) + assertContainsTaggedFloat(t, &acc, "time_softirq", 0.11, 0) + assertContainsTaggedFloat(t, &acc, "time_steal", 0.0511, 0) + assertContainsTaggedFloat(t, &acc, "time_guest", 3.1, 0) + assertContainsTaggedFloat(t, &acc, "time_guest_nice", 0.324, 0) mps2 := system.MockPS{} mps2.On("CPUTimes").Return([]cpu.TimesStat{cts2}, nil) @@ -77,29 +73,29 @@ func TestCPUStats(t *testing.T) { err = cs.Gather(&acc) require.NoError(t, err) - assertContainsTaggedFloat(t, &acc, "cpu", "time_user", 24.9, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_system", 10.9, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_idle", 157.9798, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_active", 42.0202, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_nice", 3.5, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_iowait", 0.929, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_irq", 1.2, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_softirq", 0.31, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_steal", 0.2812, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_guest", 11.4, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_guest_nice", 2.524, 0, cputags) - - assertContainsTaggedFloat(t, &acc, "cpu", "usage_user", 7.8, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_system", 2.7, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_idle", 77.8798, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_active", 22.1202, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_nice", 0, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_iowait", 0.0901, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_irq", 0.6, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_softirq", 0.2, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_steal", 0.2301, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_guest", 8.3, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_guest_nice", 2.2, 0.0005, cputags) + assertContainsTaggedFloat(t, &acc, "time_user", 24.9, 0) + assertContainsTaggedFloat(t, &acc, "time_system", 10.9, 0) + assertContainsTaggedFloat(t, &acc, "time_idle", 157.9798, 0) + assertContainsTaggedFloat(t, &acc, "time_active", 42.0202, 0.0005) + assertContainsTaggedFloat(t, &acc, "time_nice", 3.5, 0) + assertContainsTaggedFloat(t, &acc, "time_iowait", 0.929, 0) + assertContainsTaggedFloat(t, &acc, "time_irq", 1.2, 0) + assertContainsTaggedFloat(t, &acc, "time_softirq", 0.31, 0) + assertContainsTaggedFloat(t, &acc, "time_steal", 0.2812, 0) + assertContainsTaggedFloat(t, &acc, "time_guest", 11.4, 0) + assertContainsTaggedFloat(t, &acc, "time_guest_nice", 2.524, 0) + + assertContainsTaggedFloat(t, &acc, "usage_user", 7.8, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_system", 2.7, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_idle", 77.8798, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_active", 22.1202, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_nice", 0, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_iowait", 0.0901, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_irq", 0.6, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_softirq", 0.2, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_steal", 0.2301, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_guest", 8.3, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_guest_nice", 2.2, 0.0005) } // Asserts that a given accumulator contains a measurement of type float64 with @@ -109,24 +105,21 @@ func TestCPUStats(t *testing.T) { // Parameters: // t *testing.T : Testing object to use // acc testutil.Accumulator: Accumulator to examine -// measurement string : Name of the measurement to examine +// field string : Name of field to examine // expectedValue float64 : Value to search for within the measurement // delta float64 : Maximum acceptable distance of an accumulated value // from the expectedValue parameter. Useful when // floating-point arithmetic imprecision makes looking // for an exact match impractical -// tags map[string]string : Tag set the found measurement must have. Set to nil to -// ignore the tag set. func assertContainsTaggedFloat( t *testing.T, acc *testutil.Accumulator, - measurement string, field string, expectedValue float64, delta float64, - tags map[string]string, ) { var actualValue float64 + measurement := "cpu" // always cpu for _, pt := range acc.Metrics { if pt.Measurement == measurement { for fieldname, value := range pt.Fields { @@ -218,18 +211,14 @@ func TestCPUTimesDecrease(t *testing.T) { cs := NewCPUStats(&mps) - cputags := map[string]string{ - "cpu": "cpu0", - } - err := cs.Gather(&acc) require.NoError(t, err) // Computed values are checked with delta > 0 because of floating point arithmetic // imprecision - assertContainsTaggedFloat(t, &acc, "cpu", "time_user", 18, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_idle", 80, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_iowait", 2, 0, cputags) + assertContainsTaggedFloat(t, &acc, "time_user", 18, 0) + assertContainsTaggedFloat(t, &acc, "time_idle", 80, 0) + assertContainsTaggedFloat(t, &acc, "time_iowait", 2, 0) mps2 := system.MockPS{} mps2.On("CPUTimes").Return([]cpu.TimesStat{cts2}, nil) @@ -246,11 +235,11 @@ func TestCPUTimesDecrease(t *testing.T) { err = cs.Gather(&acc) require.NoError(t, err) - assertContainsTaggedFloat(t, &acc, "cpu", "time_user", 56, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_idle", 120, 0, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "time_iowait", 3, 0, cputags) + assertContainsTaggedFloat(t, &acc, "time_user", 56, 0) + assertContainsTaggedFloat(t, &acc, "time_idle", 120, 0) + assertContainsTaggedFloat(t, &acc, "time_iowait", 3, 0) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_user", 18, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_idle", 80, 0.0005, cputags) - assertContainsTaggedFloat(t, &acc, "cpu", "usage_iowait", 2, 0.0005, cputags) + assertContainsTaggedFloat(t, &acc, "usage_user", 18, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_idle", 80, 0.0005) + assertContainsTaggedFloat(t, &acc, "usage_iowait", 2, 0.0005) } diff --git a/plugins/inputs/dcos/client.go b/plugins/inputs/dcos/client.go index 32eab80867cd4..f31c4588ba555 100644 --- a/plugins/inputs/dcos/client.go +++ b/plugins/inputs/dcos/client.go @@ -92,11 +92,10 @@ type AuthToken struct { // ClusterClient is a Client that uses the cluster URL. type ClusterClient struct { - clusterURL *url.URL - httpClient *http.Client - credentials *Credentials - token string - semaphore chan struct{} + clusterURL *url.URL + httpClient *http.Client + token string + semaphore chan struct{} } type claims struct { diff --git a/plugins/inputs/dcos/creds.go b/plugins/inputs/dcos/creds.go index 0178315bb7076..2fd5f078e46e5 100644 --- a/plugins/inputs/dcos/creds.go +++ b/plugins/inputs/dcos/creds.go @@ -47,13 +47,13 @@ func (c *ServiceAccount) IsExpired() bool { return c.auth.Text != "" || c.auth.Expire.Add(relogDuration).After(time.Now()) } -func (c *TokenCreds) Token(ctx context.Context, client Client) (string, error) { +func (c *TokenCreds) Token(_ context.Context, _ Client) (string, error) { octets, err := ioutil.ReadFile(c.Path) if err != nil { - return "", fmt.Errorf("Error reading token file %q: %s", c.Path, err) + return "", fmt.Errorf("error reading token file %q: %s", c.Path, err) } if !utf8.Valid(octets) { - return "", fmt.Errorf("Token file does not contain utf-8 encoded text: %s", c.Path) + return "", fmt.Errorf("token file does not contain utf-8 encoded text: %s", c.Path) } token := strings.TrimSpace(string(octets)) return token, nil @@ -63,7 +63,7 @@ func (c *TokenCreds) IsExpired() bool { return true } -func (c *NullCreds) Token(ctx context.Context, client Client) (string, error) { +func (c *NullCreds) Token(_ context.Context, _ Client) (string, error) { return "", nil } diff --git a/plugins/inputs/dcos/dcos.go b/plugins/inputs/dcos/dcos.go index 1cdd40f1112fc..20cb47fd34288 100644 --- a/plugins/inputs/dcos/dcos.go +++ b/plugins/inputs/dcos/dcos.go @@ -66,7 +66,6 @@ type DCOS struct { nodeFilter filter.Filter containerFilter filter.Filter appFilter filter.Filter - taskNameFilter filter.Filter } func (d *DCOS) Description() string { @@ -223,7 +222,7 @@ type point struct { fields map[string]interface{} } -func (d *DCOS) createPoints(acc telegraf.Accumulator, m *Metrics) []*point { +func (d *DCOS) createPoints(m *Metrics) []*point { points := make(map[string]*point) for _, dp := range m.Datapoints { fieldKey := strings.Replace(dp.Name, ".", "_", -1) @@ -288,7 +287,7 @@ func (d *DCOS) createPoints(acc telegraf.Accumulator, m *Metrics) []*point { func (d *DCOS) addMetrics(acc telegraf.Accumulator, cluster, mname string, m *Metrics, tagDimensions []string) { tm := time.Now() - points := d.createPoints(acc, m) + points := d.createPoints(m) for _, p := range points { tags := make(map[string]string) diff --git a/plugins/inputs/directory_monitor/directory_monitor.go b/plugins/inputs/directory_monitor/directory_monitor.go index 30820659338d8..06ac3ea9568f5 100644 --- a/plugins/inputs/directory_monitor/directory_monitor.go +++ b/plugins/inputs/directory_monitor/directory_monitor.go @@ -106,7 +106,7 @@ func (monitor *DirectoryMonitor) Description() string { return "Ingests files in a directory and then moves them to a target directory." } -func (monitor *DirectoryMonitor) Gather(acc telegraf.Accumulator) error { +func (monitor *DirectoryMonitor) Gather(_ telegraf.Accumulator) error { // Get all files sitting in the directory. files, err := ioutil.ReadDir(monitor.Directory) if err != nil { @@ -130,7 +130,7 @@ func (monitor *DirectoryMonitor) Gather(acc telegraf.Accumulator) error { // If file is decaying, process it. if timeThresholdExceeded { - monitor.processFile(file, acc) + monitor.processFile(file) } } @@ -149,7 +149,7 @@ func (monitor *DirectoryMonitor) Start(acc telegraf.Accumulator) error { // Monitor the files channel and read what they receive. monitor.waitGroup.Add(1) go func() { - monitor.Monitor(acc) + monitor.Monitor() monitor.waitGroup.Done() }() @@ -164,7 +164,7 @@ func (monitor *DirectoryMonitor) Stop() { monitor.waitGroup.Wait() } -func (monitor *DirectoryMonitor) Monitor(acc telegraf.Accumulator) { +func (monitor *DirectoryMonitor) Monitor() { for filePath := range monitor.filesToProcess { if monitor.context.Err() != nil { return @@ -182,7 +182,7 @@ func (monitor *DirectoryMonitor) Monitor(acc telegraf.Accumulator) { } } -func (monitor *DirectoryMonitor) processFile(file os.FileInfo, acc telegraf.Accumulator) { +func (monitor *DirectoryMonitor) processFile(file os.FileInfo) { if file.IsDir() { return } diff --git a/plugins/inputs/directory_monitor/directory_monitor_test.go b/plugins/inputs/directory_monitor/directory_monitor_test.go index 265f371885f29..b9cfbad8df42a 100644 --- a/plugins/inputs/directory_monitor/directory_monitor_test.go +++ b/plugins/inputs/directory_monitor/directory_monitor_test.go @@ -77,13 +77,6 @@ func TestCSVGZImport(t *testing.T) { require.NoError(t, err) } -// For JSON data. -type event struct { - Name string - Speed float64 - Length float64 -} - func TestMultipleJSONFileImports(t *testing.T) { acc := testutil.Accumulator{} testJsonFile := "test.json" diff --git a/plugins/inputs/disque/disque.go b/plugins/inputs/disque/disque.go index 6cdff83ee3f16..8ae098011b0a1 100644 --- a/plugins/inputs/disque/disque.go +++ b/plugins/inputs/disque/disque.go @@ -18,8 +18,7 @@ import ( type Disque struct { Servers []string - c net.Conn - buf []byte + c net.Conn } var sampleConfig = ` @@ -87,10 +86,10 @@ func (d *Disque) Gather(acc telegraf.Accumulator) error { u.Path = "" } wg.Add(1) - go func(serv string) { + go func() { defer wg.Done() acc.AddError(d.gatherServer(u, acc)) - }(serv) + }() } wg.Wait() diff --git a/plugins/inputs/docker/docker.go b/plugins/inputs/docker/docker.go index d3f4c23976cee..ec3453eda042b 100644 --- a/plugins/inputs/docker/docker.go +++ b/plugins/inputs/docker/docker.go @@ -6,7 +6,6 @@ import ( "encoding/json" "fmt" "io" - "net/http" "regexp" "strconv" "strings" @@ -57,7 +56,6 @@ type Docker struct { newClient func(string, *tls.Config) (Client, error) client Client - httpClient *http.Client engineHost string serverVersion string filtersCreated bool @@ -937,15 +935,6 @@ func copyTags(in map[string]string) map[string]string { return out } -func sliceContains(in string, sl []string) bool { - for _, str := range sl { - if str == in { - return true - } - } - return false -} - // Parses the human-readable size string into the amount it represents. func parseSize(sizeStr string) (int64, error) { matches := sizeRegex.FindStringSubmatch(sizeStr) diff --git a/plugins/inputs/docker/docker_test.go b/plugins/inputs/docker/docker_test.go index b0c9f9791ec8b..e6ecce32323f8 100644 --- a/plugins/inputs/docker/docker_test.go +++ b/plugins/inputs/docker/docker_test.go @@ -99,7 +99,7 @@ var baseClient = MockClient{ }, } -func newClient(host string, tlsConfig *tls.Config) (Client, error) { +func newClient(_ string, _ *tls.Config) (Client, error) { return &baseClient, nil } @@ -1127,7 +1127,6 @@ func TestHostnameFromID(t *testing.T) { func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { type args struct { stat *types.StatsJSON - acc telegraf.Accumulator tags map[string]string id string perDeviceInclude []string diff --git a/plugins/inputs/docker_log/docker_log.go b/plugins/inputs/docker_log/docker_log.go index 4ae09e71cca65..878bf4a63fbe3 100644 --- a/plugins/inputs/docker_log/docker_log.go +++ b/plugins/inputs/docker_log/docker_log.go @@ -64,11 +64,6 @@ var sampleConfig = ` const ( defaultEndpoint = "unix:///var/run/docker.sock" - - // Maximum bytes of a log line before it will be split, size is mirroring - // docker code: - // https://github.com/moby/moby/blob/master/daemon/logger/copier.go#L21 - maxLineBytes = 16 * 1024 ) var ( @@ -160,18 +155,16 @@ func (d *DockerLogs) Init() error { return nil } -func (d *DockerLogs) addToContainerList(containerID string, cancel context.CancelFunc) error { +func (d *DockerLogs) addToContainerList(containerID string, cancel context.CancelFunc) { d.mu.Lock() defer d.mu.Unlock() d.containerList[containerID] = cancel - return nil } -func (d *DockerLogs) removeFromContainerList(containerID string) error { +func (d *DockerLogs) removeFromContainerList(containerID string) { d.mu.Lock() defer d.mu.Unlock() delete(d.containerList, containerID) - return nil } func (d *DockerLogs) containerInContainerList(containerID string) bool { @@ -181,13 +174,12 @@ func (d *DockerLogs) containerInContainerList(containerID string) bool { return ok } -func (d *DockerLogs) cancelTails() error { +func (d *DockerLogs) cancelTails() { d.mu.Lock() defer d.mu.Unlock() for _, cancel := range d.containerList { cancel() } - return nil } func (d *DockerLogs) matchedContainerName(names []string) string { diff --git a/plugins/inputs/dovecot/dovecot.go b/plugins/inputs/dovecot/dovecot.go index b9875079d9feb..be2ea49d48134 100644 --- a/plugins/inputs/dovecot/dovecot.go +++ b/plugins/inputs/dovecot/dovecot.go @@ -48,8 +48,6 @@ var validQuery = map[string]bool{ func (d *Dovecot) SampleConfig() string { return sampleConfig } -const defaultPort = "24242" - // Reads stats from all configured servers. func (d *Dovecot) Gather(acc telegraf.Accumulator) error { if !validQuery[d.Type] { diff --git a/plugins/inputs/elasticsearch/elasticsearch.go b/plugins/inputs/elasticsearch/elasticsearch.go index f8064e606e57f..505bb69835041 100644 --- a/plugins/inputs/elasticsearch/elasticsearch.go +++ b/plugins/inputs/elasticsearch/elasticsearch.go @@ -558,11 +558,7 @@ func (e *Elasticsearch) gatherIndicesStats(url string, acc telegraf.Accumulator) // gatherSortedIndicesStats gathers stats for all indices in no particular order. func (e *Elasticsearch) gatherIndividualIndicesStats(indices map[string]indexStat, now time.Time, acc telegraf.Accumulator) error { // Sort indices into buckets based on their configured prefix, if any matches. - categorizedIndexNames, err := e.categorizeIndices(indices) - if err != nil { - return err - } - + categorizedIndexNames := e.categorizeIndices(indices) for _, matchingIndices := range categorizedIndexNames { // Establish the number of each category of indices to use. User can configure to use only the latest 'X' amount. indicesCount := len(matchingIndices) @@ -590,7 +586,7 @@ func (e *Elasticsearch) gatherIndividualIndicesStats(indices map[string]indexSta return nil } -func (e *Elasticsearch) categorizeIndices(indices map[string]indexStat) (map[string][]string, error) { +func (e *Elasticsearch) categorizeIndices(indices map[string]indexStat) map[string][]string { categorizedIndexNames := map[string][]string{} // If all indices are configured to be gathered, bucket them all together. @@ -599,7 +595,7 @@ func (e *Elasticsearch) categorizeIndices(indices map[string]indexStat) (map[str categorizedIndexNames["_all"] = append(categorizedIndexNames["_all"], indexName) } - return categorizedIndexNames, nil + return categorizedIndexNames } // Bucket each returned index with its associated configured index (if any match). @@ -617,7 +613,7 @@ func (e *Elasticsearch) categorizeIndices(indices map[string]indexStat) (map[str categorizedIndexNames[match] = append(categorizedIndexNames[match], indexName) } - return categorizedIndexNames, nil + return categorizedIndexNames } func (e *Elasticsearch) gatherSingleIndexStats(name string, index indexStat, now time.Time, acc telegraf.Accumulator) error { diff --git a/plugins/inputs/elasticsearch/elasticsearch_test.go b/plugins/inputs/elasticsearch/elasticsearch_test.go index 0700c7833dc15..184acbbbcbf57 100644 --- a/plugins/inputs/elasticsearch/elasticsearch_test.go +++ b/plugins/inputs/elasticsearch/elasticsearch_test.go @@ -33,9 +33,9 @@ type transportMock struct { body string } -func newTransportMock(statusCode int, body string) http.RoundTripper { +func newTransportMock(body string) http.RoundTripper { return &transportMock{ - statusCode: statusCode, + statusCode: http.StatusOK, body: body, } } @@ -77,7 +77,7 @@ func checkNodeStatsResult(t *testing.T, acc *testutil.Accumulator) { func TestGather(t *testing.T) { es := newElasticsearchWithClient() es.Servers = []string{"http://example.com:9200"} - es.client.Transport = newTransportMock(http.StatusOK, nodeStatsResponse) + es.client.Transport = newTransportMock(nodeStatsResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -94,7 +94,7 @@ func TestGatherIndividualStats(t *testing.T) { es := newElasticsearchWithClient() es.Servers = []string{"http://example.com:9200"} es.NodeStats = []string{"jvm", "process"} - es.client.Transport = newTransportMock(http.StatusOK, nodeStatsResponseJVMProcess) + es.client.Transport = newTransportMock(nodeStatsResponseJVMProcess) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -120,7 +120,7 @@ func TestGatherIndividualStats(t *testing.T) { func TestGatherNodeStats(t *testing.T) { es := newElasticsearchWithClient() es.Servers = []string{"http://example.com:9200"} - es.client.Transport = newTransportMock(http.StatusOK, nodeStatsResponse) + es.client.Transport = newTransportMock(nodeStatsResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -138,7 +138,7 @@ func TestGatherClusterHealthEmptyClusterHealth(t *testing.T) { es.Servers = []string{"http://example.com:9200"} es.ClusterHealth = true es.ClusterHealthLevel = "" - es.client.Transport = newTransportMock(http.StatusOK, clusterHealthResponse) + es.client.Transport = newTransportMock(clusterHealthResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -165,7 +165,7 @@ func TestGatherClusterHealthSpecificClusterHealth(t *testing.T) { es.Servers = []string{"http://example.com:9200"} es.ClusterHealth = true es.ClusterHealthLevel = "cluster" - es.client.Transport = newTransportMock(http.StatusOK, clusterHealthResponse) + es.client.Transport = newTransportMock(clusterHealthResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -192,7 +192,7 @@ func TestGatherClusterHealthAlsoIndicesHealth(t *testing.T) { es.Servers = []string{"http://example.com:9200"} es.ClusterHealth = true es.ClusterHealthLevel = "indices" - es.client.Transport = newTransportMock(http.StatusOK, clusterHealthResponseWithIndices) + es.client.Transport = newTransportMock(clusterHealthResponseWithIndices) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -223,7 +223,7 @@ func TestGatherClusterStatsMaster(t *testing.T) { info := serverInfo{nodeID: "SDFsfSDFsdfFSDSDfSFDSDF", masterID: ""} // first get catMaster - es.client.Transport = newTransportMock(http.StatusOK, IsMasterResult) + es.client.Transport = newTransportMock(IsMasterResult) masterID, err := es.getCatMaster("junk") require.NoError(t, err) info.masterID = masterID @@ -238,7 +238,7 @@ func TestGatherClusterStatsMaster(t *testing.T) { // now get node status, which determines whether we're master var acc testutil.Accumulator es.Local = true - es.client.Transport = newTransportMock(http.StatusOK, nodeStatsResponse) + es.client.Transport = newTransportMock(nodeStatsResponse) if err := es.gatherNodeStats("junk", &acc); err != nil { t.Fatal(err) } @@ -247,7 +247,7 @@ func TestGatherClusterStatsMaster(t *testing.T) { checkNodeStatsResult(t, &acc) // now test the clusterstats method - es.client.Transport = newTransportMock(http.StatusOK, clusterStatsResponse) + es.client.Transport = newTransportMock(clusterStatsResponse) require.NoError(t, es.gatherClusterStats("junk", &acc)) tags := map[string]string{ @@ -269,7 +269,7 @@ func TestGatherClusterStatsNonMaster(t *testing.T) { es.serverInfo["http://example.com:9200"] = serverInfo{nodeID: "SDFsfSDFsdfFSDSDfSFDSDF", masterID: ""} // first get catMaster - es.client.Transport = newTransportMock(http.StatusOK, IsNotMasterResult) + es.client.Transport = newTransportMock(IsNotMasterResult) masterID, err := es.getCatMaster("junk") require.NoError(t, err) @@ -282,7 +282,7 @@ func TestGatherClusterStatsNonMaster(t *testing.T) { // now get node status, which determines whether we're master var acc testutil.Accumulator es.Local = true - es.client.Transport = newTransportMock(http.StatusOK, nodeStatsResponse) + es.client.Transport = newTransportMock(nodeStatsResponse) if err := es.gatherNodeStats("junk", &acc); err != nil { t.Fatal(err) } @@ -296,7 +296,7 @@ func TestGatherClusterIndicesStats(t *testing.T) { es := newElasticsearchWithClient() es.IndicesInclude = []string{"_all"} es.Servers = []string{"http://example.com:9200"} - es.client.Transport = newTransportMock(http.StatusOK, clusterIndicesResponse) + es.client.Transport = newTransportMock(clusterIndicesResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() @@ -315,7 +315,7 @@ func TestGatherDateStampedIndicesStats(t *testing.T) { es.IndicesInclude = []string{"twitter*", "influx*", "penguins"} es.NumMostRecentIndices = 2 es.Servers = []string{"http://example.com:9200"} - es.client.Transport = newTransportMock(http.StatusOK, dateStampedIndicesResponse) + es.client.Transport = newTransportMock(dateStampedIndicesResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() es.Init() @@ -357,7 +357,7 @@ func TestGatherClusterIndiceShardsStats(t *testing.T) { es := newElasticsearchWithClient() es.IndicesLevel = "shards" es.Servers = []string{"http://example.com:9200"} - es.client.Transport = newTransportMock(http.StatusOK, clusterIndicesShardsResponse) + es.client.Transport = newTransportMock(clusterIndicesShardsResponse) es.serverInfo = make(map[string]serverInfo) es.serverInfo["http://example.com:9200"] = defaultServerInfo() diff --git a/plugins/inputs/eventhub_consumer/eventhub_consumer.go b/plugins/inputs/eventhub_consumer/eventhub_consumer.go index 17092de3217eb..da66872da6284 100644 --- a/plugins/inputs/eventhub_consumer/eventhub_consumer.go +++ b/plugins/inputs/eventhub_consumer/eventhub_consumer.go @@ -207,11 +207,7 @@ func (e *EventHub) Start(acc telegraf.Accumulator) error { }() // Configure receiver options - receiveOpts, err := e.configureReceiver() - if err != nil { - return err - } - + receiveOpts := e.configureReceiver() partitions := e.PartitionIDs if len(e.PartitionIDs) == 0 { @@ -224,7 +220,7 @@ func (e *EventHub) Start(acc telegraf.Accumulator) error { } for _, partitionID := range partitions { - _, err = e.hub.Receive(ctx, partitionID, e.onMessage, receiveOpts...) + _, err := e.hub.Receive(ctx, partitionID, e.onMessage, receiveOpts...) if err != nil { return fmt.Errorf("creating receiver for partition %q: %v", partitionID, err) } @@ -233,7 +229,7 @@ func (e *EventHub) Start(acc telegraf.Accumulator) error { return nil } -func (e *EventHub) configureReceiver() ([]eventhub.ReceiveOption, error) { +func (e *EventHub) configureReceiver() []eventhub.ReceiveOption { receiveOpts := []eventhub.ReceiveOption{} if e.ConsumerGroup != "" { @@ -254,7 +250,7 @@ func (e *EventHub) configureReceiver() ([]eventhub.ReceiveOption, error) { receiveOpts = append(receiveOpts, eventhub.ReceiveWithEpoch(e.Epoch)) } - return receiveOpts, nil + return receiveOpts } // OnMessage handles an Event. When this function returns without error the diff --git a/plugins/inputs/exec/exec_test.go b/plugins/inputs/exec/exec_test.go index 8d77f0cef4757..67609bf64af9e 100644 --- a/plugins/inputs/exec/exec_test.go +++ b/plugins/inputs/exec/exec_test.go @@ -18,9 +18,6 @@ import ( "github.com/stretchr/testify/require" ) -// Midnight 9/22/2015 -const baseTimeSeconds = 1442905200 - const validJSON = ` { "status": "green", @@ -40,20 +37,6 @@ const malformedJSON = ` "status": "green", ` -const lineProtocol = "cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1\n" -const lineProtocolEmpty = "" -const lineProtocolShort = "ab" - -const lineProtocolMulti = ` -cpu,cpu=cpu0,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu1,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu2,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu3,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu4,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu5,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu6,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -` - type CarriageReturnTest struct { input []byte output []byte @@ -91,7 +74,7 @@ func newRunnerMock(out []byte, errout []byte, err error) Runner { } } -func (r runnerMock) Run(command string, _ time.Duration) ([]byte, []byte, error) { +func (r runnerMock) Run(_ string, _ time.Duration) ([]byte, []byte, error) { return r.out, r.errout, r.err } diff --git a/plugins/inputs/execd/execd_posix.go b/plugins/inputs/execd/execd_posix.go index 4d8789a8d3215..08275c62db5be 100644 --- a/plugins/inputs/execd/execd_posix.go +++ b/plugins/inputs/execd/execd_posix.go @@ -12,7 +12,7 @@ import ( "github.com/influxdata/telegraf" ) -func (e *Execd) Gather(acc telegraf.Accumulator) error { +func (e *Execd) Gather(_ telegraf.Accumulator) error { if e.process == nil || e.process.Cmd == nil { return nil } diff --git a/plugins/inputs/execd/shim/goshim.go b/plugins/inputs/execd/shim/goshim.go index 2ea0b839b3e2f..920d40f8dfddf 100644 --- a/plugins/inputs/execd/shim/goshim.go +++ b/plugins/inputs/execd/shim/goshim.go @@ -26,7 +26,6 @@ import ( type empty struct{} var ( - forever = 100 * 365 * 24 * time.Hour envVarEscaper = strings.NewReplacer( `"`, `\"`, `\`, `\\`, diff --git a/plugins/inputs/execd/shim/shim_test.go b/plugins/inputs/execd/shim/shim_test.go index dbc3462211222..07afde130e04c 100644 --- a/plugins/inputs/execd/shim/shim_test.go +++ b/plugins/inputs/execd/shim/shim_test.go @@ -104,7 +104,7 @@ func (i *testInput) Gather(acc telegraf.Accumulator) error { return nil } -func (i *testInput) Start(acc telegraf.Accumulator) error { +func (i *testInput) Start(_ telegraf.Accumulator) error { return nil } @@ -156,7 +156,7 @@ func (i *serviceInput) Gather(acc telegraf.Accumulator) error { return nil } -func (i *serviceInput) Start(acc telegraf.Accumulator) error { +func (i *serviceInput) Start(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/fail2ban/fail2ban_test.go b/plugins/inputs/fail2ban/fail2ban_test.go index b28d824ee3aed..ecb539acd3166 100644 --- a/plugins/inputs/fail2ban/fail2ban_test.go +++ b/plugins/inputs/fail2ban/fail2ban_test.go @@ -92,7 +92,7 @@ func fakeExecCommand(command string, args ...string) *exec.Cmd { return cmd } -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } diff --git a/plugins/inputs/fluentd/fluentd_test.go b/plugins/inputs/fluentd/fluentd_test.go index 795b6dbcf546d..6279f6cf5ef7e 100644 --- a/plugins/inputs/fluentd/fluentd_test.go +++ b/plugins/inputs/fluentd/fluentd_test.go @@ -96,8 +96,6 @@ const sampleJSON = ` var ( zero float64 - err error - pluginOutput []pluginData expectedOutput = []pluginData{ // {"object:f48698", "dummy", "input", nil, nil, nil}, // {"object:e27138", "dummy", "input", nil, nil, nil}, diff --git a/plugins/inputs/graylog/graylog.go b/plugins/inputs/graylog/graylog.go index bc286631fcd7f..585a05ee32bea 100644 --- a/plugins/inputs/graylog/graylog.go +++ b/plugins/inputs/graylog/graylog.go @@ -19,7 +19,6 @@ import ( ) type ResponseMetrics struct { - total int Metrics []Metric `json:"metrics"` } diff --git a/plugins/inputs/hddtemp/hddtemp_test.go b/plugins/inputs/hddtemp/hddtemp_test.go index 6d7301bbcf320..79fceb72e8129 100644 --- a/plugins/inputs/hddtemp/hddtemp_test.go +++ b/plugins/inputs/hddtemp/hddtemp_test.go @@ -12,7 +12,7 @@ import ( type mockFetcher struct { } -func (h *mockFetcher) Fetch(address string) ([]hddtemp.Disk, error) { +func (h *mockFetcher) Fetch(_ string) ([]hddtemp.Disk, error) { return []hddtemp.Disk{ { DeviceName: "Disk1", diff --git a/plugins/inputs/http_listener_v2/http_listener_v2.go b/plugins/inputs/http_listener_v2/http_listener_v2.go index cd41f303e7feb..0c94437354feb 100644 --- a/plugins/inputs/http_listener_v2/http_listener_v2.go +++ b/plugins/inputs/http_listener_v2/http_listener_v2.go @@ -319,11 +319,6 @@ func methodNotAllowed(res http.ResponseWriter) { res.Write([]byte(`{"error":"http: method not allowed"}`)) } -func internalServerError(res http.ResponseWriter) { - res.Header().Set("Content-Type", "application/json") - res.WriteHeader(http.StatusInternalServerError) -} - func badRequest(res http.ResponseWriter) { res.Header().Set("Content-Type", "application/json") res.WriteHeader(http.StatusBadRequest) diff --git a/plugins/inputs/http_response/http_response_test.go b/plugins/inputs/http_response/http_response_test.go index 24ded226346b6..5c05d84264112 100644 --- a/plugins/inputs/http_response/http_response_test.go +++ b/plugins/inputs/http_response/http_response_test.go @@ -912,10 +912,8 @@ type fakeClient struct { err error } -func (f *fakeClient) Do(req *http.Request) (*http.Response, error) { - return &http.Response{ - StatusCode: f.statusCode, - }, f.err +func (f *fakeClient) Do(_ *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: f.statusCode}, f.err } func TestNetworkErrors(t *testing.T) { diff --git a/plugins/inputs/intel_powerstat/intel_powerstat_test.go b/plugins/inputs/intel_powerstat/intel_powerstat_test.go index 13006de3c6e81..d65756595927e 100644 --- a/plugins/inputs/intel_powerstat/intel_powerstat_test.go +++ b/plugins/inputs/intel_powerstat/intel_powerstat_test.go @@ -196,9 +196,9 @@ func TestAddMetricsForSingleCoreNegative(t *testing.T) { func TestAddCPUFrequencyMetric(t *testing.T) { var acc testutil.Accumulator - cpuID := "0" - coreID := "2" - packageID := "1" + cpuID := "1" + coreID := "3" + packageID := "0" frequency := 1200000.2 power, _, _, msrMock := getPowerWithMockedServices() prepareCPUInfoForSingleCPU(power, cpuID, coreID, packageID) diff --git a/plugins/inputs/intel_rdt/publisher.go b/plugins/inputs/intel_rdt/publisher.go index 5ca9890472b27..ca36e40525c12 100644 --- a/plugins/inputs/intel_rdt/publisher.go +++ b/plugins/inputs/intel_rdt/publisher.go @@ -18,7 +18,6 @@ type Publisher struct { BufferChanProcess chan processMeasurement BufferChanCores chan string errChan chan error - stopChan chan bool } func NewPublisher(acc telegraf.Accumulator, log telegraf.Logger, shortenedMetrics bool) Publisher { diff --git a/plugins/inputs/ipmi_sensor/connection_test.go b/plugins/inputs/ipmi_sensor/connection_test.go index 21d1957c95126..0f40464fbd83a 100644 --- a/plugins/inputs/ipmi_sensor/connection_test.go +++ b/plugins/inputs/ipmi_sensor/connection_test.go @@ -6,11 +6,6 @@ import ( "github.com/stretchr/testify/require" ) -type conTest struct { - Got string - Want *Connection -} - func TestNewConnection(t *testing.T) { testData := []struct { addr string diff --git a/plugins/inputs/ipmi_sensor/ipmi_test.go b/plugins/inputs/ipmi_sensor/ipmi_test.go index 422d2ab38471e..cb85d8fbc419b 100644 --- a/plugins/inputs/ipmi_sensor/ipmi_test.go +++ b/plugins/inputs/ipmi_sensor/ipmi_test.go @@ -227,7 +227,7 @@ func fakeExecCommand(command string, args ...string) *exec.Cmd { // For example, if you run: // GO_WANT_HELPER_PROCESS=1 go test -test.run=TestHelperProcess -- chrony tracking // it returns below mockData. -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } @@ -546,7 +546,7 @@ func fakeExecCommandV2(command string, args ...string) *exec.Cmd { // For example, if you run: // GO_WANT_HELPER_PROCESS=1 go test -test.run=TestHelperProcessV2 -- chrony tracking // it returns below mockData. -func TestHelperProcessV2(t *testing.T) { +func TestHelperProcessV2(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } diff --git a/plugins/inputs/jenkins/jenkins.go b/plugins/inputs/jenkins/jenkins.go index a4b34baaa4f1c..5844f0e7a8a69 100644 --- a/plugins/inputs/jenkins/jenkins.go +++ b/plugins/inputs/jenkins/jenkins.go @@ -295,18 +295,6 @@ func (j *Jenkins) gatherJobs(acc telegraf.Accumulator) { wg.Wait() } -// wrap the tcp request with doGet -// block tcp request if buffered channel is full -func (j *Jenkins) doGet(tcp func() error) error { - j.semaphore <- struct{}{} - if err := tcp(); err != nil { - <-j.semaphore - return err - } - <-j.semaphore - return nil -} - func (j *Jenkins) getJobDetail(jr jobRequest, acc telegraf.Accumulator) error { if j.MaxSubJobDepth > 0 && jr.layer == j.MaxSubJobDepth { return nil @@ -451,7 +439,6 @@ type jobRequest struct { name string parents []string layer int - number int64 } func (jr jobRequest) combined() []string { diff --git a/plugins/inputs/jolokia/jolokia_test.go b/plugins/inputs/jolokia/jolokia_test.go index 3f05274eb11a6..5c1bc50aa2ae7 100644 --- a/plugins/inputs/jolokia/jolokia_test.go +++ b/plugins/inputs/jolokia/jolokia_test.go @@ -98,25 +98,8 @@ const validMultiValueJSON = ` } ]` -const validSingleValueJSON = ` -[ - { - "request":{ - "path":"used", - "mbean":"java.lang:type=Memory", - "attribute":"HeapMemoryUsage", - "type":"read" - }, - "value":209274376, - "timestamp":1446129256, - "status":200 - } -]` - const invalidJSON = "I don't think this is JSON" -const empty = "" - var Servers = []Server{{Name: "as1", Host: "127.0.0.1", Port: "8080"}} var HeapMetric = Metric{Name: "heap_memory_usage", Mbean: "java.lang:type=Memory", Attribute: "HeapMemoryUsage"} @@ -130,7 +113,7 @@ type jolokiaClientStub struct { statusCode int } -func (c jolokiaClientStub) MakeRequest(req *http.Request) (*http.Response, error) { +func (c jolokiaClientStub) MakeRequest(_ *http.Request) (*http.Response, error) { resp := http.Response{} resp.StatusCode = c.statusCode resp.Body = ioutil.NopCloser(strings.NewReader(c.responseBody)) diff --git a/plugins/inputs/jolokia2/jolokia_test.go b/plugins/inputs/jolokia2/jolokia_test.go index 61c410c0b2067..4fe8b26290da6 100644 --- a/plugins/inputs/jolokia2/jolokia_test.go +++ b/plugins/inputs/jolokia2/jolokia_test.go @@ -74,7 +74,7 @@ func TestJolokia2_ScalarValues(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -234,7 +234,7 @@ func TestJolokia2_ObjectValues(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -322,7 +322,7 @@ func TestJolokia2_StatusCodes(t *testing.T) { "status": 500 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -372,7 +372,7 @@ func TestJolokia2_TagRenaming(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -465,7 +465,7 @@ func TestJolokia2_FieldRenaming(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -573,7 +573,7 @@ func TestJolokia2_MetricMbeanMatching(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -666,7 +666,7 @@ func TestJolokia2_MetricCompaction(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -727,7 +727,7 @@ func TestJolokia2_ProxyTargets(t *testing.T) { "status": 200 }]` - server := setupServer(http.StatusOK, response) + server := setupServer(response) defer server.Close() plugin := setupPlugin(t, fmt.Sprintf(config, server.URL)) @@ -762,7 +762,7 @@ func TestFillFields(t *testing.T) { assert.Equal(t, map[string]interface{}{}, results) } -func setupServer(status int, resp string) *httptest.Server { +func setupServer(resp string) *httptest.Server { return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) //body, err := ioutil.ReadAll(r.Body) diff --git a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go index e423588eed41f..ef8a1400b212b 100644 --- a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go +++ b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry.go @@ -102,7 +102,7 @@ func (m *OpenConfigTelemetry) Description() string { return "Read JTI OpenConfig Telemetry from listed sensors" } -func (m *OpenConfigTelemetry) Gather(acc telegraf.Accumulator) error { +func (m *OpenConfigTelemetry) Gather(_ telegraf.Accumulator) error { return nil } @@ -278,9 +278,12 @@ func (m *OpenConfigTelemetry) splitSensorConfig() int { } // Subscribes and collects OpenConfig telemetry data from given server -func (m *OpenConfigTelemetry) collectData(ctx context.Context, - grpcServer string, grpcClientConn *grpc.ClientConn, - acc telegraf.Accumulator) error { +func (m *OpenConfigTelemetry) collectData( + ctx context.Context, + grpcServer string, + grpcClientConn *grpc.ClientConn, + acc telegraf.Accumulator, +) { c := telemetry.NewOpenConfigTelemetryClient(grpcClientConn) for _, sensor := range m.sensorsConfig { m.wg.Add(1) @@ -342,8 +345,6 @@ func (m *OpenConfigTelemetry) collectData(ctx context.Context, } }(ctx, sensor) } - - return nil } func (m *OpenConfigTelemetry) Start(acc telegraf.Accumulator) error { diff --git a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go index 784b6a8c12526..d32866f2efbe6 100644 --- a/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go +++ b/plugins/inputs/jti_openconfig_telemetry/openconfig_telemetry_test.go @@ -63,19 +63,19 @@ func (s *openConfigTelemetryServer) TelemetrySubscribe(req *telemetry.Subscripti return nil } -func (s *openConfigTelemetryServer) CancelTelemetrySubscription(ctx context.Context, req *telemetry.CancelSubscriptionRequest) (*telemetry.CancelSubscriptionReply, error) { +func (s *openConfigTelemetryServer) CancelTelemetrySubscription(_ context.Context, _ *telemetry.CancelSubscriptionRequest) (*telemetry.CancelSubscriptionReply, error) { return nil, nil } -func (s *openConfigTelemetryServer) GetTelemetrySubscriptions(ctx context.Context, req *telemetry.GetSubscriptionsRequest) (*telemetry.GetSubscriptionsReply, error) { +func (s *openConfigTelemetryServer) GetTelemetrySubscriptions(_ context.Context, _ *telemetry.GetSubscriptionsRequest) (*telemetry.GetSubscriptionsReply, error) { return nil, nil } -func (s *openConfigTelemetryServer) GetTelemetryOperationalState(ctx context.Context, req *telemetry.GetOperationalStateRequest) (*telemetry.GetOperationalStateReply, error) { +func (s *openConfigTelemetryServer) GetTelemetryOperationalState(_ context.Context, _ *telemetry.GetOperationalStateRequest) (*telemetry.GetOperationalStateReply, error) { return nil, nil } -func (s *openConfigTelemetryServer) GetDataEncodings(ctx context.Context, req *telemetry.DataEncodingRequest) (*telemetry.DataEncodingReply, error) { +func (s *openConfigTelemetryServer) GetDataEncodings(_ context.Context, _ *telemetry.DataEncodingRequest) (*telemetry.DataEncodingReply, error) { return nil, nil } diff --git a/plugins/inputs/kafka_consumer/kafka_consumer.go b/plugins/inputs/kafka_consumer/kafka_consumer.go index 78feacdd30850..fe24f51724dad 100644 --- a/plugins/inputs/kafka_consumer/kafka_consumer.go +++ b/plugins/inputs/kafka_consumer/kafka_consumer.go @@ -107,7 +107,6 @@ const sampleConfig = ` const ( defaultMaxUndeliveredMessages = 1000 - defaultMaxMessageLen = 1000000 defaultConsumerGroup = "telegraf_metrics_consumers" reconnectDelay = 5 * time.Second ) @@ -256,7 +255,7 @@ func (k *KafkaConsumer) Start(acc telegraf.Accumulator) error { return nil } -func (k *KafkaConsumer) Gather(acc telegraf.Accumulator) error { +func (k *KafkaConsumer) Gather(_ telegraf.Accumulator) error { return nil } @@ -314,11 +313,11 @@ func (h *ConsumerGroupHandler) Setup(sarama.ConsumerGroupSession) error { } // Run processes any delivered metrics during the lifetime of the session. -func (h *ConsumerGroupHandler) run(ctx context.Context) error { +func (h *ConsumerGroupHandler) run(ctx context.Context) { for { select { case <-ctx.Done(): - return nil + return case track := <-h.acc.Delivered(): h.onDelivery(track) } diff --git a/plugins/inputs/kafka_consumer/kafka_consumer_test.go b/plugins/inputs/kafka_consumer/kafka_consumer_test.go index 90c362b9c01ea..f6aca25c7ed9a 100644 --- a/plugins/inputs/kafka_consumer/kafka_consumer_test.go +++ b/plugins/inputs/kafka_consumer/kafka_consumer_test.go @@ -23,7 +23,7 @@ type FakeConsumerGroup struct { errors chan error } -func (g *FakeConsumerGroup) Consume(ctx context.Context, topics []string, handler sarama.ConsumerGroupHandler) error { +func (g *FakeConsumerGroup) Consume(_ context.Context, _ []string, handler sarama.ConsumerGroupHandler) error { g.handler = handler g.handler.Setup(nil) return nil @@ -213,15 +213,15 @@ func (s *FakeConsumerGroupSession) GenerationID() int32 { panic("not implemented") } -func (s *FakeConsumerGroupSession) MarkOffset(topic string, partition int32, offset int64, metadata string) { +func (s *FakeConsumerGroupSession) MarkOffset(_ string, _ int32, _ int64, _ string) { panic("not implemented") } -func (s *FakeConsumerGroupSession) ResetOffset(topic string, partition int32, offset int64, metadata string) { +func (s *FakeConsumerGroupSession) ResetOffset(_ string, _ int32, _ int64, _ string) { panic("not implemented") } -func (s *FakeConsumerGroupSession) MarkMessage(msg *sarama.ConsumerMessage, metadata string) { +func (s *FakeConsumerGroupSession) MarkMessage(_ *sarama.ConsumerMessage, _ string) { } func (s *FakeConsumerGroupSession) Context() context.Context { diff --git a/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy.go b/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy.go index bc884a118c69d..8690b1637bac1 100644 --- a/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy.go +++ b/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy.go @@ -177,7 +177,7 @@ func (k *Kafka) Stop() { } } -func (k *Kafka) Gather(acc telegraf.Accumulator) error { +func (k *Kafka) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy_integration_test.go b/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy_integration_test.go index 31bea2210b741..976412a7196b5 100644 --- a/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy_integration_test.go +++ b/plugins/inputs/kafka_consumer_legacy/kafka_consumer_legacy_integration_test.go @@ -78,8 +78,8 @@ func TestReadsMetricsFromKafka(t *testing.T) { } } -// Waits for the metric that was sent to the kafka broker to arrive at the kafka -// consumer +//nolint:unused // Used in skipped tests +// Waits for the metric that was sent to the kafka broker to arrive at the kafka consumer func waitForPoint(acc *testutil.Accumulator, t *testing.T) { // Give the kafka container up to 2 seconds to get the point to the consumer ticker := time.NewTicker(5 * time.Millisecond) diff --git a/plugins/inputs/kinesis_consumer/kinesis_consumer.go b/plugins/inputs/kinesis_consumer/kinesis_consumer.go index 0a57955ce7f7b..bf63795f553b9 100644 --- a/plugins/inputs/kinesis_consumer/kinesis_consumer.go +++ b/plugins/inputs/kinesis_consumer/kinesis_consumer.go @@ -49,7 +49,6 @@ type ( cons *consumer.Consumer parser parsers.Parser cancel context.CancelFunc - ctx context.Context acc telegraf.TrackingAccumulator sem chan struct{} diff --git a/plugins/inputs/kube_inventory/client_test.go b/plugins/inputs/kube_inventory/client_test.go index 48874dca55209..622e35c65c57f 100644 --- a/plugins/inputs/kube_inventory/client_test.go +++ b/plugins/inputs/kube_inventory/client_test.go @@ -5,7 +5,6 @@ import ( "time" "github.com/influxdata/telegraf/plugins/common/tls" - "k8s.io/apimachinery/pkg/util/intstr" ) type mockHandler struct { @@ -20,21 +19,10 @@ func toInt32Ptr(i int32) *int32 { return &i } -func toInt64Ptr(i int64) *int64 { - return &i -} - func toBoolPtr(b bool) *bool { return &b } -func toIntStrPtrS(s string) *intstr.IntOrString { - return &intstr.IntOrString{StrVal: s} -} - -func toIntStrPtrI(i int32) *intstr.IntOrString { - return &intstr.IntOrString{IntVal: i} -} func TestNewClient(t *testing.T) { _, err := newClient("https://127.0.0.1:443/", "default", "abc123", time.Second, tls.ClientConfig{}) if err != nil { diff --git a/plugins/inputs/kube_inventory/daemonset.go b/plugins/inputs/kube_inventory/daemonset.go index b169ea16dbac6..c365d169cacdb 100644 --- a/plugins/inputs/kube_inventory/daemonset.go +++ b/plugins/inputs/kube_inventory/daemonset.go @@ -15,14 +15,11 @@ func collectDaemonSets(ctx context.Context, acc telegraf.Accumulator, ki *Kubern return } for _, d := range list.Items { - if err = ki.gatherDaemonSet(d, acc); err != nil { - acc.AddError(err) - return - } + ki.gatherDaemonSet(d, acc) } } -func (ki *KubernetesInventory) gatherDaemonSet(d v1.DaemonSet, acc telegraf.Accumulator) error { +func (ki *KubernetesInventory) gatherDaemonSet(d v1.DaemonSet, acc telegraf.Accumulator) { fields := map[string]interface{}{ "generation": d.Generation, "current_number_scheduled": d.Status.CurrentNumberScheduled, @@ -48,6 +45,4 @@ func (ki *KubernetesInventory) gatherDaemonSet(d v1.DaemonSet, acc telegraf.Accu } acc.AddFields(daemonSetMeasurement, fields, tags) - - return nil } diff --git a/plugins/inputs/kube_inventory/daemonset_test.go b/plugins/inputs/kube_inventory/daemonset_test.go index dede3d9a534f1..f67707d2c3d21 100644 --- a/plugins/inputs/kube_inventory/daemonset_test.go +++ b/plugins/inputs/kube_inventory/daemonset_test.go @@ -108,10 +108,7 @@ func TestDaemonSet(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, dset := range ((v.handler.responseMap["/daemonsets/"]).(*v1.DaemonSetList)).Items { - err := ks.gatherDaemonSet(dset, acc) - if err != nil { - t.Errorf("Failed to gather daemonset - %s", err.Error()) - } + ks.gatherDaemonSet(dset, acc) } err := acc.FirstError() @@ -284,10 +281,7 @@ func TestDaemonSetSelectorFilter(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, dset := range ((v.handler.responseMap["/daemonsets/"]).(*v1.DaemonSetList)).Items { - err := ks.gatherDaemonSet(dset, acc) - if err != nil { - t.Errorf("Failed to gather daemonset - %s", err.Error()) - } + ks.gatherDaemonSet(dset, acc) } // Grab selector tags diff --git a/plugins/inputs/kube_inventory/deployment.go b/plugins/inputs/kube_inventory/deployment.go index 613f9dff82b72..510cc68cecaa7 100644 --- a/plugins/inputs/kube_inventory/deployment.go +++ b/plugins/inputs/kube_inventory/deployment.go @@ -14,14 +14,11 @@ func collectDeployments(ctx context.Context, acc telegraf.Accumulator, ki *Kuber return } for _, d := range list.Items { - if err = ki.gatherDeployment(d, acc); err != nil { - acc.AddError(err) - return - } + ki.gatherDeployment(d, acc) } } -func (ki *KubernetesInventory) gatherDeployment(d v1.Deployment, acc telegraf.Accumulator) error { +func (ki *KubernetesInventory) gatherDeployment(d v1.Deployment, acc telegraf.Accumulator) { fields := map[string]interface{}{ "replicas_available": d.Status.AvailableReplicas, "replicas_unavailable": d.Status.UnavailableReplicas, @@ -38,6 +35,4 @@ func (ki *KubernetesInventory) gatherDeployment(d v1.Deployment, acc telegraf.Ac } acc.AddFields(deploymentMeasurement, fields, tags) - - return nil } diff --git a/plugins/inputs/kube_inventory/deployment_test.go b/plugins/inputs/kube_inventory/deployment_test.go index bb5e9101eb42c..9b4c74c9ad856 100644 --- a/plugins/inputs/kube_inventory/deployment_test.go +++ b/plugins/inputs/kube_inventory/deployment_test.go @@ -114,10 +114,7 @@ func TestDeployment(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, deployment := range ((v.handler.responseMap["/deployments/"]).(*v1.DeploymentList)).Items { - err := ks.gatherDeployment(deployment, acc) - if err != nil { - t.Errorf("Failed to gather deployment - %s", err.Error()) - } + ks.gatherDeployment(deployment, acc) } err := acc.FirstError() @@ -299,10 +296,7 @@ func TestDeploymentSelectorFilter(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, deployment := range ((v.handler.responseMap["/deployments/"]).(*v1.DeploymentList)).Items { - err := ks.gatherDeployment(deployment, acc) - if err != nil { - t.Errorf("Failed to gather deployment - %s", err.Error()) - } + ks.gatherDeployment(deployment, acc) } // Grab selector tags diff --git a/plugins/inputs/kube_inventory/statefulset.go b/plugins/inputs/kube_inventory/statefulset.go index 22bc7c8bc0c75..22b235116b22c 100644 --- a/plugins/inputs/kube_inventory/statefulset.go +++ b/plugins/inputs/kube_inventory/statefulset.go @@ -15,14 +15,11 @@ func collectStatefulSets(ctx context.Context, acc telegraf.Accumulator, ki *Kube return } for _, s := range list.Items { - if err = ki.gatherStatefulSet(s, acc); err != nil { - acc.AddError(err) - return - } + ki.gatherStatefulSet(s, acc) } } -func (ki *KubernetesInventory) gatherStatefulSet(s v1.StatefulSet, acc telegraf.Accumulator) error { +func (ki *KubernetesInventory) gatherStatefulSet(s v1.StatefulSet, acc telegraf.Accumulator) { status := s.Status fields := map[string]interface{}{ "created": s.GetCreationTimestamp().UnixNano(), @@ -45,6 +42,4 @@ func (ki *KubernetesInventory) gatherStatefulSet(s v1.StatefulSet, acc telegraf. } acc.AddFields(statefulSetMeasurement, fields, tags) - - return nil } diff --git a/plugins/inputs/kube_inventory/statefulset_test.go b/plugins/inputs/kube_inventory/statefulset_test.go index dee8b08b5b887..a6d703c205acf 100644 --- a/plugins/inputs/kube_inventory/statefulset_test.go +++ b/plugins/inputs/kube_inventory/statefulset_test.go @@ -102,10 +102,7 @@ func TestStatefulSet(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, ss := range ((v.handler.responseMap["/statefulsets/"]).(*v1.StatefulSetList)).Items { - err := ks.gatherStatefulSet(ss, acc) - if err != nil { - t.Errorf("Failed to gather ss - %s", err.Error()) - } + ks.gatherStatefulSet(ss, acc) } err := acc.FirstError() @@ -273,10 +270,7 @@ func TestStatefulSetSelectorFilter(t *testing.T) { ks.createSelectorFilters() acc := new(testutil.Accumulator) for _, ss := range ((v.handler.responseMap["/statefulsets/"]).(*v1.StatefulSetList)).Items { - err := ks.gatherStatefulSet(ss, acc) - if err != nil { - t.Errorf("Failed to gather ss - %s", err.Error()) - } + ks.gatherStatefulSet(ss, acc) } // Grab selector tags diff --git a/plugins/inputs/kubernetes/kubernetes.go b/plugins/inputs/kubernetes/kubernetes.go index 2516d084c3285..e4ebe268755ec 100644 --- a/plugins/inputs/kubernetes/kubernetes.go +++ b/plugins/inputs/kubernetes/kubernetes.go @@ -5,7 +5,6 @@ import ( "fmt" "io/ioutil" "net/http" - "net/url" "strings" "time" @@ -65,7 +64,6 @@ var sampleConfig = ` ` const ( - summaryEndpoint = `%s/stats/summary` defaultServiceAccountPath = "/run/secrets/kubernetes.io/serviceaccount/token" ) @@ -117,15 +115,6 @@ func (k *Kubernetes) Gather(acc telegraf.Accumulator) error { return nil } -func buildURL(endpoint string, base string) (*url.URL, error) { - u := fmt.Sprintf(endpoint, base) - addr, err := url.Parse(u) - if err != nil { - return nil, fmt.Errorf("Unable to parse address '%s': %s", u, err) - } - return addr, nil -} - func (k *Kubernetes) gatherSummary(baseURL string, acc telegraf.Accumulator) error { summaryMetrics := &SummaryMetrics{} err := k.LoadJSON(fmt.Sprintf("%s/stats/summary", baseURL), summaryMetrics) @@ -139,7 +128,7 @@ func (k *Kubernetes) gatherSummary(baseURL string, acc telegraf.Accumulator) err } buildSystemContainerMetrics(summaryMetrics, acc) buildNodeMetrics(summaryMetrics, acc) - buildPodMetrics(baseURL, summaryMetrics, podInfos, k.labelFilter, acc) + buildPodMetrics(summaryMetrics, podInfos, k.labelFilter, acc) return nil } @@ -243,7 +232,7 @@ func (k *Kubernetes) LoadJSON(url string, v interface{}) error { return nil } -func buildPodMetrics(baseURL string, summaryMetrics *SummaryMetrics, podInfo []Metadata, labelFilter filter.Filter, acc telegraf.Accumulator) { +func buildPodMetrics(summaryMetrics *SummaryMetrics, podInfo []Metadata, labelFilter filter.Filter, acc telegraf.Accumulator) { for _, pod := range summaryMetrics.Pods { for _, container := range pod.Containers { tags := map[string]string{ diff --git a/plugins/inputs/lanz/lanz.go b/plugins/inputs/lanz/lanz.go index 6a833175fde9f..86bb93a8f754b 100644 --- a/plugins/inputs/lanz/lanz.go +++ b/plugins/inputs/lanz/lanz.go @@ -43,7 +43,7 @@ func (l *Lanz) Description() string { return "Read metrics off Arista LANZ, via socket" } -func (l *Lanz) Gather(acc telegraf.Accumulator) error { +func (l *Lanz) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/logparser/logparser.go b/plugins/inputs/logparser/logparser.go index fc38b467e2505..5fec865eaa8d7 100644 --- a/plugins/inputs/logparser/logparser.go +++ b/plugins/inputs/logparser/logparser.go @@ -143,7 +143,7 @@ func (l *LogParserPlugin) Init() error { } // Gather is the primary function to collect the metrics for the plugin -func (l *LogParserPlugin) Gather(acc telegraf.Accumulator) error { +func (l *LogParserPlugin) Gather(_ telegraf.Accumulator) error { l.Lock() defer l.Unlock() diff --git a/plugins/inputs/lustre2/lustre2.go b/plugins/inputs/lustre2/lustre2.go index ecaafb50f86b3..5327386339f84 100644 --- a/plugins/inputs/lustre2/lustre2.go +++ b/plugins/inputs/lustre2/lustre2.go @@ -54,7 +54,6 @@ type mapping struct { inProc string // What to look for at the start of a line in /proc/fs/lustre/* field uint32 // which field to extract from that line reportAs string // What measurement name to use - tag string // Additional tag to add for this metric } var wantedOstFields = []*mapping{ diff --git a/plugins/inputs/mesos/mesos.go b/plugins/inputs/mesos/mesos.go index 0b3c7d26fa5e3..7f3d08b118176 100644 --- a/plugins/inputs/mesos/mesos.go +++ b/plugins/inputs/mesos/mesos.go @@ -532,49 +532,6 @@ type TaskStats struct { Statistics map[string]interface{} `json:"statistics"` } -func (m *Mesos) gatherSlaveTaskMetrics(u *url.URL, acc telegraf.Accumulator) error { - var metrics []TaskStats - - tags := map[string]string{ - "server": u.Hostname(), - "url": urlTag(u), - } - - resp, err := m.client.Get(withPath(u, "/monitor/statistics").String()) - - if err != nil { - return err - } - - data, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - return err - } - - if err = json.Unmarshal([]byte(data), &metrics); err != nil { - return errors.New("Error decoding JSON response") - } - - for _, task := range metrics { - tags["framework_id"] = task.FrameworkID - - jf := jsonparser.JSONFlattener{} - err = jf.FlattenJSON("", task.Statistics) - - if err != nil { - return err - } - - timestamp := time.Unix(int64(jf.Fields["timestamp"].(float64)), 0) - jf.Fields["executor_id"] = task.ExecutorID - - acc.AddFields("mesos_tasks", jf.Fields, tags, timestamp) - } - - return nil -} - func withPath(u *url.URL, path string) *url.URL { c := *u c.Path = path diff --git a/plugins/inputs/minecraft/client.go b/plugins/inputs/minecraft/client.go index bb829f6903581..641a8ae75db9f 100644 --- a/plugins/inputs/minecraft/client.go +++ b/plugins/inputs/minecraft/client.go @@ -25,12 +25,12 @@ type Connector interface { Connect() (Connection, error) } -func newConnector(hostname, port, password string) (*connector, error) { +func newConnector(hostname, port, password string) *connector { return &connector{ hostname: hostname, port: port, password: password, - }, nil + } } type connector struct { @@ -58,8 +58,8 @@ func (c *connector) Connect() (Connection, error) { return &connection{rcon: rcon}, nil } -func newClient(connector Connector) (*client, error) { - return &client{connector: connector}, nil +func newClient(connector Connector) *client { + return &client{connector: connector} } type client struct { @@ -90,13 +90,7 @@ func (c *client) Players() ([]string, error) { return nil, err } - players, err := parsePlayers(resp) - if err != nil { - c.conn = nil - return nil, err - } - - return players, nil + return parsePlayers(resp), nil } func (c *client) Scores(player string) ([]Score, error) { @@ -113,13 +107,7 @@ func (c *client) Scores(player string) ([]Score, error) { return nil, err } - scores, err := parseScores(resp) - if err != nil { - c.conn = nil - return nil, err - } - - return scores, nil + return parseScores(resp), nil } type connection struct { @@ -134,10 +122,10 @@ func (c *connection) Execute(command string) (string, error) { return packet.Body, nil } -func parsePlayers(input string) ([]string, error) { +func parsePlayers(input string) []string { parts := strings.SplitAfterN(input, ":", 2) if len(parts) != 2 { - return []string{}, nil + return []string{} } names := strings.Split(parts[1], ",") @@ -158,7 +146,7 @@ func parsePlayers(input string) ([]string, error) { } players = append(players, name) } - return players, nil + return players } // Score is an individual tracked scoreboard stat. @@ -167,9 +155,9 @@ type Score struct { Value int64 } -func parseScores(input string) ([]Score, error) { +func parseScores(input string) []Score { if strings.Contains(input, "has no scores") { - return []Score{}, nil + return []Score{} } // Detect Minecraft <= 1.12 @@ -200,5 +188,6 @@ func parseScores(input string) ([]Score, error) { } scores = append(scores, score) } - return scores, nil + + return scores } diff --git a/plugins/inputs/minecraft/client_test.go b/plugins/inputs/minecraft/client_test.go index 4a5ceb9db9cb7..59db9bf34a8d6 100644 --- a/plugins/inputs/minecraft/client_test.go +++ b/plugins/inputs/minecraft/client_test.go @@ -98,9 +98,7 @@ func TestClient_Player(t *testing.T) { conn: &MockConnection{commands: tt.commands}, } - client, err := newClient(connector) - require.NoError(t, err) - + client := newClient(connector) actual, err := client.Players() require.NoError(t, err) @@ -183,9 +181,7 @@ func TestClient_Scores(t *testing.T) { conn: &MockConnection{commands: tt.commands}, } - client, err := newClient(connector) - require.NoError(t, err) - + client := newClient(connector) actual, err := client.Scores(tt.player) require.NoError(t, err) diff --git a/plugins/inputs/minecraft/minecraft.go b/plugins/inputs/minecraft/minecraft.go index 939cc2c42a7a3..e953b3c2b5d7f 100644 --- a/plugins/inputs/minecraft/minecraft.go +++ b/plugins/inputs/minecraft/minecraft.go @@ -50,17 +50,8 @@ func (s *Minecraft) SampleConfig() string { func (s *Minecraft) Gather(acc telegraf.Accumulator) error { if s.client == nil { - connector, err := newConnector(s.Server, s.Port, s.Password) - if err != nil { - return err - } - - client, err := newClient(connector) - if err != nil { - return err - } - - s.client = client + connector := newConnector(s.Server, s.Port, s.Password) + s.client = newClient(connector) } players, err := s.client.Players() diff --git a/plugins/inputs/monit/monit_test.go b/plugins/inputs/monit/monit_test.go index 1a2970f1e2338..0381998d13ba0 100644 --- a/plugins/inputs/monit/monit_test.go +++ b/plugins/inputs/monit/monit_test.go @@ -17,7 +17,7 @@ import ( type transportMock struct { } -func (t *transportMock) RoundTrip(r *http.Request) (*http.Response, error) { +func (t *transportMock) RoundTrip(_ *http.Request) (*http.Response, error) { errorString := "Get http://127.0.0.1:2812/_status?format=xml: " + "read tcp 192.168.10.2:55610->127.0.0.1:2812: " + "read: connection reset by peer" diff --git a/plugins/inputs/mqtt_consumer/mqtt_consumer.go b/plugins/inputs/mqtt_consumer/mqtt_consumer.go index 006aaac2538a2..d5f5616b11e27 100644 --- a/plugins/inputs/mqtt_consumer/mqtt_consumer.go +++ b/plugins/inputs/mqtt_consumer/mqtt_consumer.go @@ -248,14 +248,14 @@ func (m *MQTTConsumer) connect() error { return nil } -func (m *MQTTConsumer) onConnectionLost(c mqtt.Client, err error) { +func (m *MQTTConsumer) onConnectionLost(_ mqtt.Client, err error) { m.acc.AddError(fmt.Errorf("connection lost: %v", err)) m.Log.Debugf("Disconnected %v", m.Servers) m.state = Disconnected return } -func (m *MQTTConsumer) recvMessage(c mqtt.Client, msg mqtt.Message) { +func (m *MQTTConsumer) recvMessage(_ mqtt.Client, msg mqtt.Message) { for { select { case track := <-m.acc.Delivered(): @@ -310,7 +310,7 @@ func (m *MQTTConsumer) Stop() { m.cancel() } -func (m *MQTTConsumer) Gather(acc telegraf.Accumulator) error { +func (m *MQTTConsumer) Gather(_ telegraf.Accumulator) error { if m.state == Disconnected { m.state = Connecting m.Log.Debugf("Connecting %v", m.Servers) diff --git a/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go b/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go index efa921cb1dd49..a9b85c108ab65 100644 --- a/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go +++ b/plugins/inputs/mqtt_consumer/mqtt_consumer_test.go @@ -49,15 +49,15 @@ type FakeParser struct { // FakeParser satisfies parsers.Parser var _ parsers.Parser = &FakeParser{} -func (p *FakeParser) Parse(buf []byte) ([]telegraf.Metric, error) { +func (p *FakeParser) Parse(_ []byte) ([]telegraf.Metric, error) { panic("not implemented") } -func (p *FakeParser) ParseLine(line string) (telegraf.Metric, error) { +func (p *FakeParser) ParseLine(_ string) (telegraf.Metric, error) { panic("not implemented") } -func (p *FakeParser) SetDefaultTags(tags map[string]string) { +func (p *FakeParser) SetDefaultTags(_ map[string]string) { panic("not implemented") } diff --git a/plugins/inputs/nats_consumer/nats_consumer.go b/plugins/inputs/nats_consumer/nats_consumer.go index 057c77ee795c4..70c3287d12299 100644 --- a/plugins/inputs/nats_consumer/nats_consumer.go +++ b/plugins/inputs/nats_consumer/nats_consumer.go @@ -264,7 +264,7 @@ func (n *natsConsumer) Stop() { n.clean() } -func (n *natsConsumer) Gather(acc telegraf.Accumulator) error { +func (n *natsConsumer) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/net_response/net_response_test.go b/plugins/inputs/net_response/net_response_test.go index 8f01d687927f3..a64d553164a45 100644 --- a/plugins/inputs/net_response/net_response_test.go +++ b/plugins/inputs/net_response/net_response_test.go @@ -125,7 +125,7 @@ func TestTCPOK1(t *testing.T) { } // Start TCP server wg.Add(1) - go TCPServer(t, &wg) + go TCPServer(&wg) wg.Wait() // Connect wg.Add(1) @@ -169,7 +169,7 @@ func TestTCPOK2(t *testing.T) { } // Start TCP server wg.Add(1) - go TCPServer(t, &wg) + go TCPServer(&wg) wg.Wait() // Connect wg.Add(1) @@ -247,7 +247,7 @@ func TestUDPOK1(t *testing.T) { } // Start UDP server wg.Add(1) - go UDPServer(t, &wg) + go UDPServer(&wg) wg.Wait() // Connect wg.Add(1) @@ -277,7 +277,7 @@ func TestUDPOK1(t *testing.T) { wg.Wait() } -func UDPServer(t *testing.T, wg *sync.WaitGroup) { +func UDPServer(wg *sync.WaitGroup) { udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:2004") conn, _ := net.ListenUDP("udp", udpAddr) wg.Done() @@ -288,7 +288,7 @@ func UDPServer(t *testing.T, wg *sync.WaitGroup) { wg.Done() } -func TCPServer(t *testing.T, wg *sync.WaitGroup) { +func TCPServer(wg *sync.WaitGroup) { tcpAddr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2004") tcpServer, _ := net.ListenTCP("tcp", tcpAddr) wg.Done() diff --git a/plugins/inputs/nfsclient/nfsclient.go b/plugins/inputs/nfsclient/nfsclient.go index e4005b57685a9..c2823dfa598d4 100644 --- a/plugins/inputs/nfsclient/nfsclient.go +++ b/plugins/inputs/nfsclient/nfsclient.go @@ -93,13 +93,13 @@ func convertToInt64(line []string) []int64 { return nline } -func (n *NFSClient) parseStat(mountpoint string, export string, version string, line []string, fullstat bool, acc telegraf.Accumulator) error { +func (n *NFSClient) parseStat(mountpoint string, export string, version string, line []string, acc telegraf.Accumulator) { tags := map[string]string{"mountpoint": mountpoint, "serverexport": export} nline := convertToInt64(line) if len(nline) == 0 { n.Log.Warnf("Parsing Stat line with one field: %s\n", line) - return nil + return } first := strings.Replace(line[0], ":", "", 1) @@ -191,7 +191,7 @@ func (n *NFSClient) parseStat(mountpoint string, export string, version string, acc.AddFields("nfsstat", fields, tags) } - if fullstat { + if n.Fullstat { switch first { case "events": if len(nline) >= len(eventsFields) { @@ -240,11 +240,9 @@ func (n *NFSClient) parseStat(mountpoint string, export string, version string, } } } - - return nil } -func (n *NFSClient) processText(scanner *bufio.Scanner, acc telegraf.Accumulator) error { +func (n *NFSClient) processText(scanner *bufio.Scanner, acc telegraf.Accumulator) { var mount string var version string var export string @@ -252,10 +250,9 @@ func (n *NFSClient) processText(scanner *bufio.Scanner, acc telegraf.Accumulator for scanner.Scan() { line := strings.Fields(scanner.Text()) + lineLength := len(line) - line_len := len(line) - - if line_len == 0 { + if lineLength == 0 { continue } @@ -263,10 +260,10 @@ func (n *NFSClient) processText(scanner *bufio.Scanner, acc telegraf.Accumulator // This denotes a new mount has been found, so set // mount and export, and stop skipping (for now) - if line_len > 4 && choice.Contains("fstype", line) && (choice.Contains("nfs", line) || choice.Contains("nfs4", line)) { + if lineLength > 4 && choice.Contains("fstype", line) && (choice.Contains("nfs", line) || choice.Contains("nfs4", line)) { mount = line[4] export = line[1] - } else if line_len > 5 && (choice.Contains("(nfs)", line) || choice.Contains("(nfs4)", line)) { + } else if lineLength > 5 && (choice.Contains("(nfs)", line) || choice.Contains("(nfs4)", line)) { version = strings.Split(line[5], "/")[1] } @@ -296,10 +293,9 @@ func (n *NFSClient) processText(scanner *bufio.Scanner, acc telegraf.Accumulator } if !skip { - n.parseStat(mount, export, version, line, n.Fullstat, acc) + n.parseStat(mount, export, version, line, acc) } } - return nil } func (n *NFSClient) getMountStatsPath() string { diff --git a/plugins/inputs/nfsclient/nfsclient_test.go b/plugins/inputs/nfsclient/nfsclient_test.go index 72813cc10be4e..4dab7b320f0c5 100644 --- a/plugins/inputs/nfsclient/nfsclient_test.go +++ b/plugins/inputs/nfsclient/nfsclient_test.go @@ -20,11 +20,11 @@ func getMountStatsPath() string { func TestNFSClientParsev3(t *testing.T) { var acc testutil.Accumulator - nfsclient := NFSClient{} + nfsclient := NFSClient{Fullstat: true} nfsclient.nfs3Ops = map[string]bool{"READLINK": true, "GETATTR": false} nfsclient.nfs4Ops = map[string]bool{"READLINK": true, "GETATTR": false} data := strings.Fields(" READLINK: 500 501 502 503 504 505 506 507") - nfsclient.parseStat("1.2.3.4:/storage/NFS", "/A", "3", data, true, &acc) + nfsclient.parseStat("1.2.3.4:/storage/NFS", "/A", "3", data, &acc) fields_ops := map[string]interface{}{ "ops": int64(500), @@ -42,11 +42,11 @@ func TestNFSClientParsev3(t *testing.T) { func TestNFSClientParsev4(t *testing.T) { var acc testutil.Accumulator - nfsclient := NFSClient{} + nfsclient := NFSClient{Fullstat: true} nfsclient.nfs3Ops = map[string]bool{"DESTROY_SESSION": true, "GETATTR": false} nfsclient.nfs4Ops = map[string]bool{"DESTROY_SESSION": true, "GETATTR": false} data := strings.Fields(" DESTROY_SESSION: 500 501 502 503 504 505 506 507") - nfsclient.parseStat("2.2.2.2:/nfsdata/", "/B", "4", data, true, &acc) + nfsclient.parseStat("2.2.2.2:/nfsdata/", "/B", "4", data, &acc) fields_ops := map[string]interface{}{ "ops": int64(500), diff --git a/plugins/inputs/nginx_plus_api/nginx_plus_api_metrics_test.go b/plugins/inputs/nginx_plus_api/nginx_plus_api_metrics_test.go index 5e05e9f0d4ac9..9ae9e43c29f7a 100644 --- a/plugins/inputs/nginx_plus_api/nginx_plus_api_metrics_test.go +++ b/plugins/inputs/nginx_plus_api/nginx_plus_api_metrics_test.go @@ -520,7 +520,7 @@ const streamServerZonesPayload = ` ` func TestGatherProcessesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, processesPath, defaultAPIVersion, processesPayload) + ts, n := prepareEndpoint(t, processesPath, processesPayload) defer ts.Close() var acc testutil.Accumulator @@ -541,7 +541,7 @@ func TestGatherProcessesMetrics(t *testing.T) { } func TestGatherConnectionsMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, connectionsPath, defaultAPIVersion, connectionsPayload) + ts, n := prepareEndpoint(t, connectionsPath, connectionsPayload) defer ts.Close() var acc testutil.Accumulator @@ -565,7 +565,7 @@ func TestGatherConnectionsMetrics(t *testing.T) { } func TestGatherSslMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, sslPath, defaultAPIVersion, sslPayload) + ts, n := prepareEndpoint(t, sslPath, sslPayload) defer ts.Close() var acc testutil.Accumulator @@ -588,7 +588,7 @@ func TestGatherSslMetrics(t *testing.T) { } func TestGatherHttpRequestsMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, httpRequestsPath, defaultAPIVersion, httpRequestsPayload) + ts, n := prepareEndpoint(t, httpRequestsPath, httpRequestsPayload) defer ts.Close() var acc testutil.Accumulator @@ -610,7 +610,7 @@ func TestGatherHttpRequestsMetrics(t *testing.T) { } func TestGatherHttpServerZonesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, httpServerZonesPath, defaultAPIVersion, httpServerZonesPayload) + ts, n := prepareEndpoint(t, httpServerZonesPath, httpServerZonesPayload) defer ts.Close() var acc testutil.Accumulator @@ -664,7 +664,7 @@ func TestGatherHttpServerZonesMetrics(t *testing.T) { } func TestGatherHttpLocationZonesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, httpLocationZonesPath, defaultAPIVersion, httpLocationZonesPayload) + ts, n := prepareEndpoint(t, httpLocationZonesPath, httpLocationZonesPayload) defer ts.Close() var acc testutil.Accumulator @@ -716,7 +716,7 @@ func TestGatherHttpLocationZonesMetrics(t *testing.T) { } func TestGatherHttpUpstreamsMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, httpUpstreamsPath, defaultAPIVersion, httpUpstreamsPayload) + ts, n := prepareEndpoint(t, httpUpstreamsPath, httpUpstreamsPayload) defer ts.Close() var acc testutil.Accumulator @@ -888,7 +888,7 @@ func TestGatherHttpUpstreamsMetrics(t *testing.T) { } func TestGatherHttpCachesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, httpCachesPath, defaultAPIVersion, httpCachesPayload) + ts, n := prepareEndpoint(t, httpCachesPath, httpCachesPayload) defer ts.Close() var acc testutil.Accumulator @@ -966,7 +966,7 @@ func TestGatherHttpCachesMetrics(t *testing.T) { } func TestGatherResolverZonesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, resolverZonesPath, defaultAPIVersion, resolverZonesPayload) + ts, n := prepareEndpoint(t, resolverZonesPath, resolverZonesPayload) defer ts.Close() var acc testutil.Accumulator @@ -1020,7 +1020,7 @@ func TestGatherResolverZonesMetrics(t *testing.T) { } func TestGatherStreamUpstreams(t *testing.T) { - ts, n := prepareEndpoint(t, streamUpstreamsPath, defaultAPIVersion, streamUpstreamsPayload) + ts, n := prepareEndpoint(t, streamUpstreamsPath, streamUpstreamsPayload) defer ts.Close() var acc testutil.Accumulator @@ -1162,7 +1162,7 @@ func TestGatherStreamUpstreams(t *testing.T) { } func TestGatherStreamServerZonesMetrics(t *testing.T) { - ts, n := prepareEndpoint(t, streamServerZonesPath, defaultAPIVersion, streamServerZonesPayload) + ts, n := prepareEndpoint(t, streamServerZonesPath, streamServerZonesPayload) defer ts.Close() var acc testutil.Accumulator @@ -1305,11 +1305,11 @@ func prepareAddr(t *testing.T, ts *httptest.Server) (*url.URL, string, string) { return addr, host, port } -func prepareEndpoint(t *testing.T, path string, apiVersion int64, payload string) (*httptest.Server, *NginxPlusAPI) { +func prepareEndpoint(t *testing.T, path string, payload string) (*httptest.Server, *NginxPlusAPI) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var rsp string - if r.URL.Path == fmt.Sprintf("/api/%d/%s", apiVersion, path) { + if r.URL.Path == fmt.Sprintf("/api/%d/%s", defaultAPIVersion, path) { rsp = payload w.Header()["Content-Type"] = []string{"application/json"} } else { @@ -1321,7 +1321,7 @@ func prepareEndpoint(t *testing.T, path string, apiVersion int64, payload string n := &NginxPlusAPI{ Urls: []string{fmt.Sprintf("%s/api", ts.URL)}, - APIVersion: apiVersion, + APIVersion: defaultAPIVersion, } client, err := n.createHTTPClient() diff --git a/plugins/inputs/nsd/nsd.go b/plugins/inputs/nsd/nsd.go index 37a7c482020b2..ef6c20a9aad4c 100644 --- a/plugins/inputs/nsd/nsd.go +++ b/plugins/inputs/nsd/nsd.go @@ -11,7 +11,6 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/filter" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/inputs" ) @@ -26,8 +25,7 @@ type NSD struct { Server string ConfigFile string - filter filter.Filter - run runner + run runner } var defaultBinary = "/usr/sbin/nsd-control" diff --git a/plugins/inputs/nsd/nsd_test.go b/plugins/inputs/nsd/nsd_test.go index fbe66ca9e3bdb..67ea6863c5208 100644 --- a/plugins/inputs/nsd/nsd_test.go +++ b/plugins/inputs/nsd/nsd_test.go @@ -3,16 +3,14 @@ package nsd import ( "bytes" "testing" - "time" + + "github.com/stretchr/testify/assert" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" ) -var TestTimeout = internal.Duration{Duration: time.Second} - -func NSDControl(output string, Timeout internal.Duration, useSudo bool, Server string, ConfigFile string) func(string, internal.Duration, bool, string, string) (*bytes.Buffer, error) { +func NSDControl(output string) func(string, internal.Duration, bool, string, string) (*bytes.Buffer, error) { return func(string, internal.Duration, bool, string, string) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } @@ -21,7 +19,7 @@ func NSDControl(output string, Timeout internal.Duration, useSudo bool, Server s func TestParseFullOutput(t *testing.T) { acc := &testutil.Accumulator{} v := &NSD{ - run: NSDControl(fullOutput, TestTimeout, true, "", ""), + run: NSDControl(fullOutput), } err := v.Gather(acc) diff --git a/plugins/inputs/nsq_consumer/nsq_consumer.go b/plugins/inputs/nsq_consumer/nsq_consumer.go index 2c25cce7d8114..1b731a07b3fa0 100644 --- a/plugins/inputs/nsq_consumer/nsq_consumer.go +++ b/plugins/inputs/nsq_consumer/nsq_consumer.go @@ -21,7 +21,7 @@ type logger struct { log telegraf.Logger } -func (l *logger) Output(calldepth int, s string) error { +func (l *logger) Output(_ int, s string) error { l.log.Debug(s) return nil } @@ -179,7 +179,7 @@ func (n *NSQConsumer) Stop() { } // Gather is a noop -func (n *NSQConsumer) Gather(acc telegraf.Accumulator) error { +func (n *NSQConsumer) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/nstat/nstat.go b/plugins/inputs/nstat/nstat.go index 4b25a44c0ab7d..5bc2bc85a3136 100644 --- a/plugins/inputs/nstat/nstat.go +++ b/plugins/inputs/nstat/nstat.go @@ -68,68 +68,47 @@ func (ns *Nstat) Gather(acc telegraf.Accumulator) error { } // collect netstat data - err = ns.gatherNetstat(netstat, acc) - if err != nil { - return err - } + ns.gatherNetstat(netstat, acc) // collect SNMP data snmp, err := ioutil.ReadFile(ns.ProcNetSNMP) if err != nil { return err } - err = ns.gatherSNMP(snmp, acc) - if err != nil { - return err - } + ns.gatherSNMP(snmp, acc) // collect SNMP6 data, if SNMP6 directory exists (IPv6 enabled) snmp6, err := ioutil.ReadFile(ns.ProcNetSNMP6) if err == nil { - err = ns.gatherSNMP6(snmp6, acc) - if err != nil { - return err - } + ns.gatherSNMP6(snmp6, acc) } else if !os.IsNotExist(err) { return err } return nil } -func (ns *Nstat) gatherNetstat(data []byte, acc telegraf.Accumulator) error { - metrics, err := loadUglyTable(data, ns.DumpZeros) - if err != nil { - return err - } +func (ns *Nstat) gatherNetstat(data []byte, acc telegraf.Accumulator) { + metrics := ns.loadUglyTable(data) tags := map[string]string{ "name": "netstat", } acc.AddFields("nstat", metrics, tags) - return nil } -func (ns *Nstat) gatherSNMP(data []byte, acc telegraf.Accumulator) error { - metrics, err := loadUglyTable(data, ns.DumpZeros) - if err != nil { - return err - } +func (ns *Nstat) gatherSNMP(data []byte, acc telegraf.Accumulator) { + metrics := ns.loadUglyTable(data) tags := map[string]string{ "name": "snmp", } acc.AddFields("nstat", metrics, tags) - return nil } -func (ns *Nstat) gatherSNMP6(data []byte, acc telegraf.Accumulator) error { - metrics, err := loadGoodTable(data, ns.DumpZeros) - if err != nil { - return err - } +func (ns *Nstat) gatherSNMP6(data []byte, acc telegraf.Accumulator) { + metrics := ns.loadGoodTable(data) tags := map[string]string{ "name": "snmp6", } acc.AddFields("nstat", metrics, tags) - return nil } // loadPaths can be used to read paths firstly from config @@ -148,7 +127,7 @@ func (ns *Nstat) loadPaths() { // loadGoodTable can be used to parse string heap that // headers and values are arranged in right order -func loadGoodTable(table []byte, dumpZeros bool) (map[string]interface{}, error) { +func (ns *Nstat) loadGoodTable(table []byte) map[string]interface{} { entries := map[string]interface{}{} fields := bytes.Fields(table) var value int64 @@ -158,7 +137,7 @@ func loadGoodTable(table []byte, dumpZeros bool) (map[string]interface{}, error) for i := 0; i < len(fields); i = i + 2 { // counter is zero if bytes.Equal(fields[i+1], zeroByte) { - if !dumpZeros { + if !ns.DumpZeros { continue } else { entries[string(fields[i])] = int64(0) @@ -171,12 +150,12 @@ func loadGoodTable(table []byte, dumpZeros bool) (map[string]interface{}, error) entries[string(fields[i])] = value } } - return entries, nil + return entries } // loadUglyTable can be used to parse string heap that // the headers and values are splitted with a newline -func loadUglyTable(table []byte, dumpZeros bool) (map[string]interface{}, error) { +func (ns *Nstat) loadUglyTable(table []byte) map[string]interface{} { entries := map[string]interface{}{} // split the lines by newline lines := bytes.Split(table, newLineByte) @@ -196,7 +175,7 @@ func loadUglyTable(table []byte, dumpZeros bool) (map[string]interface{}, error) for j := 1; j < len(headers); j++ { // counter is zero if bytes.Equal(metrics[j], zeroByte) { - if !dumpZeros { + if !ns.DumpZeros { continue } else { entries[string(append(prefix, headers[j]...))] = int64(0) @@ -210,7 +189,7 @@ func loadUglyTable(table []byte, dumpZeros bool) (map[string]interface{}, error) } } } - return entries, nil + return entries } // proc can be used to read file paths from env diff --git a/plugins/inputs/nstat/nstat_test.go b/plugins/inputs/nstat/nstat_test.go index 7f4c09ce4d4be..95b64777b08af 100644 --- a/plugins/inputs/nstat/nstat_test.go +++ b/plugins/inputs/nstat/nstat_test.go @@ -12,11 +12,8 @@ func TestLoadUglyTable(t *testing.T) { "IpExtInCEPkts": int64(2660494435), } - got, err := loadUglyTable([]byte(uglyStr), true) - if err != nil { - t.Fatal(err) - } - + n := Nstat{DumpZeros: true} + got := n.loadUglyTable([]byte(uglyStr)) if len(got) == 0 { t.Fatalf("want %+v, got %+v", parsed, got) } @@ -40,10 +37,8 @@ func TestLoadGoodTable(t *testing.T) { "Ip6InDelivers": int64(62), "Ip6InMcastOctets": int64(1242966), } - got, err := loadGoodTable([]byte(goodStr), true) - if err != nil { - t.Fatal(err) - } + n := Nstat{DumpZeros: true} + got := n.loadGoodTable([]byte(goodStr)) if len(got) == 0 { t.Fatalf("want %+v, got %+v", parsed, got) } diff --git a/plugins/inputs/openntpd/openntpd.go b/plugins/inputs/openntpd/openntpd.go index c3fc3e92e74fa..aedff242e9f07 100644 --- a/plugins/inputs/openntpd/openntpd.go +++ b/plugins/inputs/openntpd/openntpd.go @@ -10,16 +10,10 @@ import ( "time" "github.com/influxdata/telegraf" - "github.com/influxdata/telegraf/filter" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/plugins/inputs" ) -// Mapping of ntpctl header names to tag keys -var tagHeaders = map[string]string{ - "st": "stratum", -} - // Mapping of the ntpctl tag key to the index in the command output var tagI = map[string]int{ "stratum": 2, @@ -48,8 +42,7 @@ type Openntpd struct { Timeout internal.Duration UseSudo bool - filter filter.Filter - run runner + run runner } var defaultBinary = "/usr/sbin/ntpctl" diff --git a/plugins/inputs/openntpd/openntpd_test.go b/plugins/inputs/openntpd/openntpd_test.go index d629949a533c4..f9823e355f69a 100644 --- a/plugins/inputs/openntpd/openntpd_test.go +++ b/plugins/inputs/openntpd/openntpd_test.go @@ -3,16 +3,14 @@ package openntpd import ( "bytes" "testing" - "time" + + "github.com/stretchr/testify/assert" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" ) -var TestTimeout = internal.Duration{Duration: time.Second} - -func OpenntpdCTL(output string, Timeout internal.Duration, useSudo bool) func(string, internal.Duration, bool) (*bytes.Buffer, error) { +func OpenntpdCTL(output string) func(string, internal.Duration, bool) (*bytes.Buffer, error) { return func(string, internal.Duration, bool) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } @@ -21,7 +19,7 @@ func OpenntpdCTL(output string, Timeout internal.Duration, useSudo bool) func(st func TestParseSimpleOutput(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(simpleOutput, TestTimeout, false), + run: OpenntpdCTL(simpleOutput), } err := v.Gather(acc) @@ -52,7 +50,7 @@ func TestParseSimpleOutput(t *testing.T) { func TestParseSimpleOutputwithStatePrefix(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(simpleOutputwithStatePrefix, TestTimeout, false), + run: OpenntpdCTL(simpleOutputwithStatePrefix), } err := v.Gather(acc) @@ -84,7 +82,7 @@ func TestParseSimpleOutputwithStatePrefix(t *testing.T) { func TestParseSimpleOutputInvalidPeer(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(simpleOutputInvalidPeer, TestTimeout, false), + run: OpenntpdCTL(simpleOutputInvalidPeer), } err := v.Gather(acc) @@ -112,7 +110,7 @@ func TestParseSimpleOutputInvalidPeer(t *testing.T) { func TestParseSimpleOutputServersDNSError(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(simpleOutputServersDNSError, TestTimeout, false), + run: OpenntpdCTL(simpleOutputServersDNSError), } err := v.Gather(acc) @@ -154,7 +152,7 @@ func TestParseSimpleOutputServersDNSError(t *testing.T) { func TestParseSimpleOutputServerDNSError(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(simpleOutputServerDNSError, TestTimeout, false), + run: OpenntpdCTL(simpleOutputServerDNSError), } err := v.Gather(acc) @@ -182,7 +180,7 @@ func TestParseSimpleOutputServerDNSError(t *testing.T) { func TestParseFullOutput(t *testing.T) { acc := &testutil.Accumulator{} v := &Openntpd{ - run: OpenntpdCTL(fullOutput, TestTimeout, false), + run: OpenntpdCTL(fullOutput), } err := v.Gather(acc) diff --git a/plugins/inputs/opensmtpd/opensmtpd.go b/plugins/inputs/opensmtpd/opensmtpd.go index cea266cc81991..47850db09f012 100644 --- a/plugins/inputs/opensmtpd/opensmtpd.go +++ b/plugins/inputs/opensmtpd/opensmtpd.go @@ -23,8 +23,7 @@ type Opensmtpd struct { Timeout internal.Duration UseSudo bool - filter filter.Filter - run runner + run runner } var defaultBinary = "/usr/sbin/smtpctl" diff --git a/plugins/inputs/opensmtpd/opensmtpd_test.go b/plugins/inputs/opensmtpd/opensmtpd_test.go index 2a3f4cdcfb970..4ae3eb9868d40 100644 --- a/plugins/inputs/opensmtpd/opensmtpd_test.go +++ b/plugins/inputs/opensmtpd/opensmtpd_test.go @@ -2,17 +2,13 @@ package opensmtpd import ( "bytes" - "testing" - "time" - "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" + "testing" ) -var TestTimeout = internal.Duration{Duration: time.Second} - -func SMTPCTL(output string, Timeout internal.Duration, useSudo bool) func(string, internal.Duration, bool) (*bytes.Buffer, error) { +func SMTPCTL(output string) func(string, internal.Duration, bool) (*bytes.Buffer, error) { return func(string, internal.Duration, bool) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } @@ -21,7 +17,7 @@ func SMTPCTL(output string, Timeout internal.Duration, useSudo bool) func(string func TestFilterSomeStats(t *testing.T) { acc := &testutil.Accumulator{} v := &Opensmtpd{ - run: SMTPCTL(fullOutput, TestTimeout, false), + run: SMTPCTL(fullOutput), } err := v.Gather(acc) diff --git a/plugins/inputs/openweathermap/openweathermap.go b/plugins/inputs/openweathermap/openweathermap.go index 688f97782b027..426d412d09114 100644 --- a/plugins/inputs/openweathermap/openweathermap.go +++ b/plugins/inputs/openweathermap/openweathermap.go @@ -131,7 +131,7 @@ func (n *OpenWeatherMap) Gather(acc telegraf.Accumulator) error { return nil } -func (n *OpenWeatherMap) createHTTPClient() (*http.Client, error) { +func (n *OpenWeatherMap) createHTTPClient() *http.Client { if n.ResponseTimeout.Duration < time.Second { n.ResponseTimeout.Duration = defaultResponseTimeout } @@ -141,7 +141,7 @@ func (n *OpenWeatherMap) createHTTPClient() (*http.Client, error) { Timeout: n.ResponseTimeout.Duration, } - return client, nil + return client } func (n *OpenWeatherMap) gatherURL(addr string) (*Status, error) { @@ -318,10 +318,7 @@ func (n *OpenWeatherMap) Init() error { // Create an HTTP client that is re-used for each // collection interval - n.client, err = n.createHTTPClient() - if err != nil { - return err - } + n.client = n.createHTTPClient() switch n.Units { case "imperial", "standard", "metric": diff --git a/plugins/inputs/pgbouncer/pgbouncer.go b/plugins/inputs/pgbouncer/pgbouncer.go index 0b8c8c16acd02..17cdaea6966d3 100644 --- a/plugins/inputs/pgbouncer/pgbouncer.go +++ b/plugins/inputs/pgbouncer/pgbouncer.go @@ -61,7 +61,7 @@ func (p *PgBouncer) Gather(acc telegraf.Accumulator) error { } for rows.Next() { - tags, columnMap, err := p.accRow(rows, acc, columns) + tags, columnMap, err := p.accRow(rows, columns) if err != nil { return err @@ -111,7 +111,7 @@ func (p *PgBouncer) Gather(acc telegraf.Accumulator) error { } for poolRows.Next() { - tags, columnMap, err := p.accRow(poolRows, acc, columns) + tags, columnMap, err := p.accRow(poolRows, columns) if err != nil { return err } @@ -145,7 +145,7 @@ type scanner interface { Scan(dest ...interface{}) error } -func (p *PgBouncer) accRow(row scanner, acc telegraf.Accumulator, columns []string) (map[string]string, +func (p *PgBouncer) accRow(row scanner, columns []string) (map[string]string, map[string]*interface{}, error) { var columnVars []interface{} var dbname bytes.Buffer diff --git a/plugins/inputs/phpfpm/fcgi.go b/plugins/inputs/phpfpm/fcgi.go index 551164d15c490..b3ee3f475248b 100644 --- a/plugins/inputs/phpfpm/fcgi.go +++ b/plugins/inputs/phpfpm/fcgi.go @@ -45,12 +45,14 @@ const ( maxPad = 255 ) +//nolint:varcheck // For having proper order const ( roleResponder = iota + 1 // only Responders are implemented. roleAuthorizer roleFilter ) +//nolint:varcheck // For having proper order const ( statusRequestComplete = iota statusCantMultiplex @@ -58,8 +60,6 @@ const ( statusUnknownRole ) -const headerLen = 8 - type header struct { Version uint8 Type recType @@ -72,7 +72,7 @@ type header struct { type beginRequest struct { role uint16 flags uint8 - reserved [5]uint8 + reserved [5]uint8 //nolint:unused // Memory reservation } func (br *beginRequest) read(content []byte) error { diff --git a/plugins/inputs/phpfpm/fcgi_test.go b/plugins/inputs/phpfpm/fcgi_test.go index 7060955e0a10f..a7234225806cc 100644 --- a/plugins/inputs/phpfpm/fcgi_test.go +++ b/plugins/inputs/phpfpm/fcgi_test.go @@ -13,6 +13,8 @@ import ( "testing" ) +const requestID uint16 = 1 + var sizeTests = []struct { size uint32 bytes []byte @@ -124,7 +126,7 @@ func (c *writeOnlyConn) Write(p []byte) (int, error) { return len(p), nil } -func (c *writeOnlyConn) Read(p []byte) (int, error) { +func (c *writeOnlyConn) Read(_ []byte) (int, error) { return 0, errors.New("conn is write-only") } @@ -164,7 +166,6 @@ func nameValuePair11(nameData, valueData string) []byte { func makeRecord( recordType recType, - requestID uint16, contentData []byte, ) []byte { requestIDB1 := byte(requestID >> 8) @@ -185,14 +186,13 @@ func makeRecord( // request body var streamBeginTypeStdin = bytes.Join([][]byte{ // set up request 1 - makeRecord(typeBeginRequest, 1, - []byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}), + makeRecord(typeBeginRequest, []byte{0, byte(roleResponder), 0, 0, 0, 0, 0, 0}), // add required parameters to request 1 - makeRecord(typeParams, 1, nameValuePair11("REQUEST_METHOD", "GET")), - makeRecord(typeParams, 1, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")), - makeRecord(typeParams, 1, nil), + makeRecord(typeParams, nameValuePair11("REQUEST_METHOD", "GET")), + makeRecord(typeParams, nameValuePair11("SERVER_PROTOCOL", "HTTP/1.1")), + makeRecord(typeParams, nil), // begin sending body of request 1 - makeRecord(typeStdin, 1, []byte("0123456789abcdef")), + makeRecord(typeStdin, []byte("0123456789abcdef")), }, nil) @@ -204,7 +204,7 @@ var cleanUpTests = []struct { { bytes.Join([][]byte{ streamBeginTypeStdin, - makeRecord(typeAbortRequest, 1, nil), + makeRecord(typeAbortRequest, nil), }, nil), ErrRequestAborted, @@ -265,7 +265,7 @@ func (rwNopCloser) Close() error { } // Verifies it doesn't crash. Issue 11824. -func TestMalformedParams(t *testing.T) { +func TestMalformedParams(_ *testing.T) { input := []byte{ // beginRequest, requestId=1, contentLength=8, role=1, keepConn=1 1, 1, 0, 1, 0, 8, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, diff --git a/plugins/inputs/phpfpm/phpfpm.go b/plugins/inputs/phpfpm/phpfpm.go index c71d3290666ad..cc326c3b55577 100644 --- a/plugins/inputs/phpfpm/phpfpm.go +++ b/plugins/inputs/phpfpm/phpfpm.go @@ -219,7 +219,7 @@ func (p *phpfpm) gatherHTTP(addr string, acc telegraf.Accumulator) error { } // Import stat data into Telegraf system -func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) poolStat { +func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) { stats := make(poolStat) var currentPool string @@ -271,8 +271,6 @@ func importMetric(r io.Reader, acc telegraf.Accumulator, addr string) poolStat { } acc.AddFields("phpfpm", fields, tags) } - - return stats } func expandUrls(urls []string) ([]string, error) { diff --git a/plugins/inputs/phpfpm/phpfpm_test.go b/plugins/inputs/phpfpm/phpfpm_test.go index b077f7955b037..5f0be8999e81c 100644 --- a/plugins/inputs/phpfpm/phpfpm_test.go +++ b/plugins/inputs/phpfpm/phpfpm_test.go @@ -23,7 +23,7 @@ import ( type statServer struct{} // We create a fake server to return test data -func (s statServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { +func (s statServer) ServeHTTP(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/plain") w.Header().Set("Content-Length", fmt.Sprint(len(outputSample))) fmt.Fprint(w, outputSample) diff --git a/plugins/inputs/ping/ping_test.go b/plugins/inputs/ping/ping_test.go index e42f4b97a81f4..6d06988dbd6a0 100644 --- a/plugins/inputs/ping/ping_test.go +++ b/plugins/inputs/ping/ping_test.go @@ -3,10 +3,8 @@ package ping import ( - "context" "errors" "fmt" - "net" "reflect" "sort" "testing" @@ -231,7 +229,7 @@ func TestArguments(t *testing.T) { } } -func mockHostPinger(binary string, timeout float64, args ...string) (string, error) { +func mockHostPinger(_ string, _ float64, _ ...string) (string, error) { return linuxPingOutput, nil } @@ -289,7 +287,7 @@ PING www.google.com (216.58.218.164) 56(84) bytes of data. rtt min/avg/max/mdev = 35.225/44.033/51.806/5.325 ms ` -func mockLossyHostPinger(binary string, timeout float64, args ...string) (string, error) { +func mockLossyHostPinger(_ string, _ float64, _ ...string) (string, error) { return lossyPingOutput, nil } @@ -325,7 +323,7 @@ Request timeout for icmp_seq 0 2 packets transmitted, 0 packets received, 100.0% packet loss ` -func mockErrorHostPinger(binary string, timeout float64, args ...string) (string, error) { +func mockErrorHostPinger(_ string, _ float64, _ ...string) (string, error) { // This error will not trigger correct error paths return errorPingOutput, nil } @@ -350,7 +348,7 @@ func TestBadPingGather(t *testing.T) { acc.AssertContainsTaggedFields(t, "ping", fields, tags) } -func mockFatalHostPinger(binary string, timeout float64, args ...string) (string, error) { +func mockFatalHostPinger(_ string, _ float64, _ ...string) (string, error) { return fatalPingOutput, errors.New("So very bad") } @@ -415,12 +413,6 @@ func TestPingBinary(t *testing.T) { acc.GatherError(p.Gather) } -func mockHostResolver(ctx context.Context, ipv6 bool, host string) (*net.IPAddr, error) { - ipaddr := net.IPAddr{} - ipaddr.IP = net.IPv4(127, 0, 0, 1) - return &ipaddr, nil -} - // Test that Gather function works using native ping func TestPingGatherNative(t *testing.T) { type test struct { diff --git a/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go b/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go index 25d39dcd45560..ad0d9ab941ded 100644 --- a/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go +++ b/plugins/inputs/powerdns_recursor/powerdns_recursor_test.go @@ -13,8 +13,6 @@ import ( "github.com/stretchr/testify/require" ) -type statServer struct{} - var metrics = "all-outqueries\t3591637\nanswers-slow\t36451\nanswers0-1\t177297\nanswers1-10\t1209328\n" + "answers10-100\t1238786\nanswers100-1000\t402917\nauth-zone-queries\t4\nauth4-answers-slow\t44248\n" + "auth4-answers0-1\t59169\nauth4-answers1-10\t1747403\nauth4-answers10-100\t1315621\n" + diff --git a/plugins/inputs/procstat/process.go b/plugins/inputs/procstat/process.go index 8e3e934bbdc55..a8d8f3f51bfbd 100644 --- a/plugins/inputs/procstat/process.go +++ b/plugins/inputs/procstat/process.go @@ -68,7 +68,7 @@ func (p *Proc) Username() (string, error) { return p.Process.Username() } -func (p *Proc) Percent(interval time.Duration) (float64, error) { +func (p *Proc) Percent(_ time.Duration) (float64, error) { cpuPerc, err := p.Process.Percent(time.Duration(0)) if !p.hasCPUTimes && err == nil { p.hasCPUTimes = true diff --git a/plugins/inputs/procstat/procstat.go b/plugins/inputs/procstat/procstat.go index 62de739b212bd..b3fa30a56992d 100644 --- a/plugins/inputs/procstat/procstat.go +++ b/plugins/inputs/procstat/procstat.go @@ -133,20 +133,14 @@ func (p *Procstat) Gather(acc telegraf.Accumulator) error { return err } - procs, err := p.updateProcesses(pids, tags, p.procs) - if err != nil { - acc.AddError(fmt.Errorf("procstat getting process, exe: [%s] pidfile: [%s] pattern: [%s] user: [%s] %s", - p.Exe, p.PidFile, p.Pattern, p.User, err.Error())) - } - p.procs = procs - + p.procs = p.updateProcesses(pids, tags, p.procs) for _, proc := range p.procs { p.addMetric(proc, acc, now) } fields := map[string]interface{}{ "pid_count": len(pids), - "running": len(procs), + "running": len(p.procs), "result_code": 0, } tags["pid_finder"] = p.PidFinder @@ -319,7 +313,7 @@ func (p *Procstat) addMetric(proc Process, acc telegraf.Accumulator, t time.Time } // Update monitored Processes -func (p *Procstat) updateProcesses(pids []PID, tags map[string]string, prevInfo map[PID]Process) (map[PID]Process, error) { +func (p *Procstat) updateProcesses(pids []PID, tags map[string]string, prevInfo map[PID]Process) map[PID]Process { procs := make(map[PID]Process, len(prevInfo)) for _, pid := range pids { @@ -356,7 +350,8 @@ func (p *Procstat) updateProcesses(pids []PID, tags map[string]string, prevInfo } } } - return procs, nil + + return procs } // Create and return PIDGatherer lazily diff --git a/plugins/inputs/procstat/procstat_test.go b/plugins/inputs/procstat/procstat_test.go index 4f1c15f40150e..d59e327027cff 100644 --- a/plugins/inputs/procstat/procstat_test.go +++ b/plugins/inputs/procstat/procstat_test.go @@ -27,7 +27,7 @@ func mockExecCommand(arg0 string, args ...string) *exec.Cmd { cmd.Stderr = os.Stderr return cmd } -func TestMockExecCommand(t *testing.T) { +func TestMockExecCommand(_ *testing.T) { var cmd []string for _, arg := range os.Args { if arg == "--" { @@ -63,11 +63,11 @@ type testPgrep struct { err error } -func pidFinder(pids []PID, err error) func() (PIDFinder, error) { +func pidFinder(pids []PID) func() (PIDFinder, error) { return func() (PIDFinder, error) { return &testPgrep{ pids: pids, - err: err, + err: nil, }, nil } } @@ -176,7 +176,7 @@ func TestGather_CreateProcessErrorOk(t *testing.T) { p := Procstat{ Exe: exe, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: func(PID) (Process, error) { return nil, fmt.Errorf("createProcess error") }, @@ -202,7 +202,7 @@ func TestGather_ProcessName(t *testing.T) { p := Procstat{ Exe: exe, ProcessName: "custom_name", - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -216,7 +216,7 @@ func TestGather_NoProcessNameUsesReal(t *testing.T) { p := Procstat{ Exe: exe, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -229,7 +229,7 @@ func TestGather_NoPidTag(t *testing.T) { p := Procstat{ Exe: exe, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -243,7 +243,7 @@ func TestGather_PidTag(t *testing.T) { p := Procstat{ Exe: exe, PidTag: true, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -257,7 +257,7 @@ func TestGather_Prefix(t *testing.T) { p := Procstat{ Exe: exe, Prefix: "custom_prefix", - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -269,7 +269,7 @@ func TestGather_Exe(t *testing.T) { p := Procstat{ Exe: exe, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -283,7 +283,7 @@ func TestGather_User(t *testing.T) { p := Procstat{ User: user, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -297,7 +297,7 @@ func TestGather_Pattern(t *testing.T) { p := Procstat{ Pattern: pattern, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -309,7 +309,7 @@ func TestGather_MissingPidMethod(t *testing.T) { var acc testutil.Accumulator p := Procstat{ - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.Error(t, acc.GatherError(p.Gather)) @@ -321,7 +321,7 @@ func TestGather_PidFile(t *testing.T) { p := Procstat{ PidFile: pidfile, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -336,7 +336,7 @@ func TestGather_PercentFirstPass(t *testing.T) { p := Procstat{ Pattern: "foo", PidTag: true, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: NewProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -352,7 +352,7 @@ func TestGather_PercentSecondPass(t *testing.T) { p := Procstat{ Pattern: "foo", PidTag: true, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: NewProc, } require.NoError(t, acc.GatherError(p.Gather)) @@ -364,7 +364,7 @@ func TestGather_PercentSecondPass(t *testing.T) { func TestGather_systemdUnitPIDs(t *testing.T) { p := Procstat{ - createPIDFinder: pidFinder([]PID{}, nil), + createPIDFinder: pidFinder([]PID{}), SystemdUnit: "TestGather_systemdUnitPIDs", } pids, tags, err := p.findPids() @@ -385,7 +385,7 @@ func TestGather_cgroupPIDs(t *testing.T) { require.NoError(t, err) p := Procstat{ - createPIDFinder: pidFinder([]PID{}, nil), + createPIDFinder: pidFinder([]PID{}), CGroup: td, } pids, tags, err := p.findPids() @@ -396,7 +396,7 @@ func TestGather_cgroupPIDs(t *testing.T) { func TestProcstatLookupMetric(t *testing.T) { p := Procstat{ - createPIDFinder: pidFinder([]PID{543}, nil), + createPIDFinder: pidFinder([]PID{543}), Exe: "-Gsys", } var acc testutil.Accumulator @@ -411,7 +411,7 @@ func TestGather_SameTimestamps(t *testing.T) { p := Procstat{ PidFile: pidfile, - createPIDFinder: pidFinder([]PID{pid}, nil), + createPIDFinder: pidFinder([]PID{pid}), createProcess: newTestProc, } require.NoError(t, acc.GatherError(p.Gather)) diff --git a/plugins/inputs/procstat/win_service_notwindows.go b/plugins/inputs/procstat/win_service_notwindows.go index 3d539d9f9918c..a0a776d33736f 100644 --- a/plugins/inputs/procstat/win_service_notwindows.go +++ b/plugins/inputs/procstat/win_service_notwindows.go @@ -6,6 +6,6 @@ import ( "fmt" ) -func queryPidWithWinServiceName(winServiceName string) (uint32, error) { +func queryPidWithWinServiceName(_ string) (uint32, error) { return 0, fmt.Errorf("os not support win_service option") } diff --git a/plugins/inputs/prometheus/kubernetes.go b/plugins/inputs/prometheus/kubernetes.go index 97473ef96c7e3..d42e98dd7813b 100644 --- a/plugins/inputs/prometheus/kubernetes.go +++ b/plugins/inputs/prometheus/kubernetes.go @@ -25,11 +25,6 @@ import ( "k8s.io/client-go/rest" ) -type payload struct { - eventype string - pod *corev1.Pod -} - type podMetadata struct { ResourceVersion string `json:"resourceVersion"` SelfLink string `json:"selfLink"` diff --git a/plugins/inputs/prometheus/kubernetes_test.go b/plugins/inputs/prometheus/kubernetes_test.go index 18d9aa603a24c..662af9fc46fb9 100644 --- a/plugins/inputs/prometheus/kubernetes_test.go +++ b/plugins/inputs/prometheus/kubernetes_test.go @@ -160,7 +160,3 @@ func pod() *corev1.Pod { p.Namespace = "default" return p } - -func str(x string) *string { - return &x -} diff --git a/plugins/inputs/prometheus/parser_test.go b/plugins/inputs/prometheus/parser_test.go index a80cdbd5a48a3..293e1968d2b5d 100644 --- a/plugins/inputs/prometheus/parser_test.go +++ b/plugins/inputs/prometheus/parser_test.go @@ -3,13 +3,10 @@ package prometheus import ( "net/http" "testing" - "time" "github.com/stretchr/testify/assert" ) -var exptime = time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) - const validUniqueGauge = `# HELP cadvisor_version_info A metric with a constant '1' value labeled by kernel version, OS version, docker version, cadvisor version & cadvisor revision. # TYPE cadvisor_version_info gauge cadvisor_version_info{cadvisorRevision="",cadvisorVersion="",dockerVersion="1.8.2",kernelVersion="3.10.0-229.20.1.el7.x86_64",osVersion="CentOS Linux 7 (Core)"} 1 @@ -20,9 +17,6 @@ const validUniqueCounter = `# HELP get_token_fail_count Counter of failed Token( get_token_fail_count 0 ` -const validUniqueLine = `# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source -` - const validUniqueSummary = `# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. # TYPE http_request_duration_microseconds summary http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 552048.506 @@ -46,61 +40,6 @@ apiserver_request_latencies_sum{resource="bindings",verb="POST"} 1.02726334e+08 apiserver_request_latencies_count{resource="bindings",verb="POST"} 2025 ` -const validData = `# HELP cadvisor_version_info A metric with a constant '1' value labeled by kernel version, OS version, docker version, cadvisor version & cadvisor revision. -# TYPE cadvisor_version_info gauge -cadvisor_version_info{cadvisorRevision="",cadvisorVersion="",dockerVersion="1.8.2",kernelVersion="3.10.0-229.20.1.el7.x86_64",osVersion="CentOS Linux 7 (Core)"} 1 -# HELP go_gc_duration_seconds A summary of the GC invocation durations. -# TYPE go_gc_duration_seconds summary -go_gc_duration_seconds{quantile="0"} 0.013534896000000001 -go_gc_duration_seconds{quantile="0.25"} 0.02469263 -go_gc_duration_seconds{quantile="0.5"} 0.033727822000000005 -go_gc_duration_seconds{quantile="0.75"} 0.03840335 -go_gc_duration_seconds{quantile="1"} 0.049956604 -go_gc_duration_seconds_sum 1970.341293002 -go_gc_duration_seconds_count 65952 -# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. -# TYPE http_request_duration_microseconds summary -http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 552048.506 -http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 5.876804288e+06 -http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 5.876804288e+06 -http_request_duration_microseconds_sum{handler="prometheus"} 1.8909097205e+07 -http_request_duration_microseconds_count{handler="prometheus"} 9 -# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source -# TYPE get_token_fail_count counter -get_token_fail_count 0 -# HELP apiserver_request_latencies Response latency distribution in microseconds for each verb, resource and client. -# TYPE apiserver_request_latencies histogram -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="125000"} 1994 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="250000"} 1997 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="500000"} 2000 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="1e+06"} 2005 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="2e+06"} 2012 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="4e+06"} 2017 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="8e+06"} 2024 -apiserver_request_latencies_bucket{resource="bindings",verb="POST",le="+Inf"} 2025 -apiserver_request_latencies_sum{resource="bindings",verb="POST"} 1.02726334e+08 -apiserver_request_latencies_count{resource="bindings",verb="POST"} 2025 -` - -const prometheusMulti = ` -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -` - -const prometheusMultiSomeInvalid = ` -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu3, host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -cpu,cpu=cpu4 , usage_idle=99,usage_busy=1 -cpu,host=foo,datacenter=us-east usage_idle=99,usage_busy=1 -` - func TestParseValidPrometheus(t *testing.T) { // Gauge value metrics, err := Parse([]byte(validUniqueGauge), http.Header{}) diff --git a/plugins/inputs/prometheus/prometheus.go b/plugins/inputs/prometheus/prometheus.go index cdf3bc84bd7dd..c3ceb01c73ae8 100644 --- a/plugins/inputs/prometheus/prometheus.go +++ b/plugins/inputs/prometheus/prometheus.go @@ -74,7 +74,6 @@ type Prometheus struct { // Only for monitor_kubernetes_pods=true and pod_scrape_scope="node" podLabelSelector labels.Selector podFieldSelector fields.Selector - nodeIP string isNodeScrapeScope bool } @@ -456,7 +455,7 @@ func fieldSelectorIsSupported(fieldSelector fields.Selector) (bool, string) { } // Start will start the Kubernetes scraping if enabled in the configuration -func (p *Prometheus) Start(a telegraf.Accumulator) error { +func (p *Prometheus) Start(_ telegraf.Accumulator) error { if p.MonitorPods { var ctx context.Context ctx, p.cancel = context.WithCancel(context.Background()) diff --git a/plugins/inputs/proxmox/proxmox.go b/plugins/inputs/proxmox/proxmox.go index 423070a357c23..a66aa5286fac8 100644 --- a/plugins/inputs/proxmox/proxmox.go +++ b/plugins/inputs/proxmox/proxmox.go @@ -157,12 +157,7 @@ func gatherVMData(px *Proxmox, acc telegraf.Accumulator, rt ResourceType) { return } - fields, err := getFields(currentVMStatus) - if err != nil { - px.Log.Errorf("Error getting VM measurements: %v", err) - return - } - + fields := getFields(currentVMStatus) acc.AddFields("proxmox", fields, tags) } } @@ -216,7 +211,7 @@ func getVMConfig(px *Proxmox, vmID string, rt ResourceType) (VMConfig, error) { return vmConfig, nil } -func getFields(vmStat VMStat) (map[string]interface{}, error) { +func getFields(vmStat VMStat) map[string]interface{} { memTotal, memUsed, memFree, memUsedPercentage := getByteMetrics(vmStat.TotalMem, vmStat.UsedMem) swapTotal, swapUsed, swapFree, swapUsedPercentage := getByteMetrics(vmStat.TotalSwap, vmStat.UsedSwap) diskTotal, diskUsed, diskFree, diskUsedPercentage := getByteMetrics(vmStat.TotalDisk, vmStat.UsedDisk) @@ -237,7 +232,7 @@ func getFields(vmStat VMStat) (map[string]interface{}, error) { "disk_total": diskTotal, "disk_free": diskFree, "disk_used_percentage": diskUsedPercentage, - }, nil + } } func getByteMetrics(total json.Number, used json.Number) (int64, int64, int64, float64) { diff --git a/plugins/inputs/proxmox/proxmox_test.go b/plugins/inputs/proxmox/proxmox_test.go index 35ae559ed96c7..f05b6450bd7be 100644 --- a/plugins/inputs/proxmox/proxmox_test.go +++ b/plugins/inputs/proxmox/proxmox_test.go @@ -18,7 +18,7 @@ var lxcConfigTestData = `{"data":{"hostname":"container1","searchdomain":"test.e var lxcCurrentStatusTestData = `{"data":{"vmid":"111","type":"lxc","uptime":2078164,"swap":9412608,"disk":"744189952","maxmem":536870912,"mem":98500608,"maxswap":536870912,"cpu":0.00371567669193613,"status":"running","maxdisk":"5217320960","name":"container1"}}` var qemuCurrentStatusTestData = `{"data":{"name":"qemu1","status":"running","maxdisk":10737418240,"cpu":0.029336643550795,"vmid":"113","uptime":2159739,"disk":0,"maxmem":2147483648,"mem":1722451796}}` -func performTestRequest(px *Proxmox, apiURL string, method string, data url.Values) ([]byte, error) { +func performTestRequest(_ *Proxmox, apiURL string, _ string, _ url.Values) ([]byte, error) { var bytedata = []byte("") if strings.HasSuffix(apiURL, "dns") { diff --git a/plugins/inputs/redis/redis_test.go b/plugins/inputs/redis/redis_test.go index 7ce1112787d4f..6f8abbda6be0c 100644 --- a/plugins/inputs/redis/redis_test.go +++ b/plugins/inputs/redis/redis_test.go @@ -24,7 +24,7 @@ func (t *testClient) Info() *redis.StringCmd { return nil } -func (t *testClient) Do(returnType string, args ...interface{}) (interface{}, error) { +func (t *testClient) Do(_ string, _ ...interface{}) (interface{}, error) { return 2, nil } diff --git a/plugins/inputs/rethinkdb/rethinkdb.go b/plugins/inputs/rethinkdb/rethinkdb.go index e59350b5c69ca..35994cea65f40 100644 --- a/plugins/inputs/rethinkdb/rethinkdb.go +++ b/plugins/inputs/rethinkdb/rethinkdb.go @@ -62,10 +62,10 @@ func (r *RethinkDB) Gather(acc telegraf.Accumulator) error { u.Host = serv } wg.Add(1) - go func(serv string) { + go func() { defer wg.Done() acc.AddError(r.gatherServer(&Server{URL: u}, acc)) - }(serv) + }() } wg.Wait() diff --git a/plugins/inputs/riemann_listener/riemann_listener_test.go b/plugins/inputs/riemann_listener/riemann_listener_test.go index 6948354a85b8d..92af46e8afd03 100644 --- a/plugins/inputs/riemann_listener/riemann_listener_test.go +++ b/plugins/inputs/riemann_listener/riemann_listener_test.go @@ -25,10 +25,10 @@ func TestSocketListener_tcp(t *testing.T) { require.NoError(t, err) defer sl.Stop() - testStats(t, sl) - testMissingService(t, sl) + testStats(t) + testMissingService(t) } -func testStats(t *testing.T, sl *RiemannSocketListener) { +func testStats(t *testing.T) { c := riemanngo.NewTCPClient("127.0.0.1:5555", 5*time.Second) err := c.Connect() if err != nil { @@ -41,7 +41,7 @@ func testStats(t *testing.T, sl *RiemannSocketListener) { }) assert.Equal(t, result.GetOk(), true) } -func testMissingService(t *testing.T, sl *RiemannSocketListener) { +func testMissingService(t *testing.T) { c := riemanngo.NewTCPClient("127.0.0.1:5555", 5*time.Second) err := c.Connect() if err != nil { diff --git a/plugins/inputs/sensors/sensors_test.go b/plugins/inputs/sensors/sensors_test.go index 75fd3e46825ed..e5105caa3f787 100644 --- a/plugins/inputs/sensors/sensors_test.go +++ b/plugins/inputs/sensors/sensors_test.go @@ -306,7 +306,7 @@ func fakeExecCommand(command string, args ...string) *exec.Cmd { // For example, if you run: // GO_WANT_HELPER_PROCESS=1 go test -test.run=TestHelperProcess -- chrony tracking // it returns below mockData. -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } diff --git a/plugins/inputs/sflow/sflow.go b/plugins/inputs/sflow/sflow.go index f4283cabec095..2876cebe3dc0f 100644 --- a/plugins/inputs/sflow/sflow.go +++ b/plugins/inputs/sflow/sflow.go @@ -2,7 +2,6 @@ package sflow import ( "bytes" - "context" "fmt" "io" "net" @@ -40,7 +39,6 @@ type SFlow struct { addr net.Addr decoder *PacketDecoder closer io.Closer - cancel context.CancelFunc wg sync.WaitGroup } diff --git a/plugins/inputs/sflow/types.go b/plugins/inputs/sflow/types.go index c415db26f784a..7efd59aff0c71 100644 --- a/plugins/inputs/sflow/types.go +++ b/plugins/inputs/sflow/types.go @@ -6,13 +6,8 @@ import ( ) const ( - AddressTypeIPv6 uint32 = 2 // sflow_version_5.txt line: 1384 - AddressTypeIPv4 uint32 = 1 // sflow_version_5.txt line: 1383 - IPProtocolTCP uint8 = 6 IPProtocolUDP uint8 = 17 - - metricName = "sflow" ) var ETypeMap = map[uint16]string{ @@ -20,11 +15,6 @@ var ETypeMap = map[uint16]string{ 0x86DD: "IPv6", } -var IPvMap = map[uint32]string{ - 1: "IPV4", // sflow_version_5.txt line: 1383 - 2: "IPV6", // sflow_version_5.txt line: 1384 -} - type ContainsMetricData interface { GetTags() map[string]string GetFields() map[string]interface{} diff --git a/plugins/inputs/snmp/snmp_mocks_test.go b/plugins/inputs/snmp/snmp_mocks_test.go index 5b3bbd767e67d..a3b8fb8e69a6d 100644 --- a/plugins/inputs/snmp/snmp_mocks_test.go +++ b/plugins/inputs/snmp/snmp_mocks_test.go @@ -24,7 +24,7 @@ func mockExecCommand(arg0 string, args ...string) *exec.Cmd { // This is not a real test. This is just a way of mocking out commands. // // Idea based on https://github.com/golang/go/blob/7c31043/src/os/exec/exec_test.go#L568 -func TestMockExecCommand(t *testing.T) { +func TestMockExecCommand(_ *testing.T) { var cmd []string for _, arg := range os.Args { if string(arg) == "--" { diff --git a/plugins/inputs/snmp_legacy/snmp_legacy.go b/plugins/inputs/snmp_legacy/snmp_legacy.go index cff524b6b5390..5f6ecd3e0bd4f 100644 --- a/plugins/inputs/snmp_legacy/snmp_legacy.go +++ b/plugins/inputs/snmp_legacy/snmp_legacy.go @@ -395,7 +395,7 @@ func (s *Snmp) Gather(acc telegraf.Accumulator) error { // to do it only the first time // only if len(s.OidInstanceMapping) == 0 if len(host.OidInstanceMapping) >= 0 { - if err := host.SNMPMap(acc, s.nameToOid, s.subTableMap); err != nil { + if err := host.SNMPMap(s.nameToOid, s.subTableMap); err != nil { s.Log.Errorf("Mapping error for host %q: %s", host.Address, err.Error()) continue } @@ -412,7 +412,6 @@ func (s *Snmp) Gather(acc telegraf.Accumulator) error { } func (h *Host) SNMPMap( - acc telegraf.Accumulator, nameToOid map[string]string, subTableMap map[string]Subtable, ) error { diff --git a/plugins/inputs/snmp_trap/snmp_trap.go b/plugins/inputs/snmp_trap/snmp_trap.go index a887d53897461..b02483af768c1 100644 --- a/plugins/inputs/snmp_trap/snmp_trap.go +++ b/plugins/inputs/snmp_trap/snmp_trap.go @@ -111,11 +111,11 @@ func init() { }) } -func realExecCmd(Timeout internal.Duration, arg0 string, args ...string) ([]byte, error) { +func realExecCmd(timeout internal.Duration, arg0 string, args ...string) ([]byte, error) { cmd := exec.Command(arg0, args...) var out bytes.Buffer cmd.Stdout = &out - err := internal.RunTimeout(cmd, Timeout.Duration) + err := internal.RunTimeout(cmd, timeout.Duration) if err != nil { return nil, err } diff --git a/plugins/inputs/snmp_trap/snmp_trap_test.go b/plugins/inputs/snmp_trap/snmp_trap_test.go index a8c3d01c78bb5..424098cfae365 100644 --- a/plugins/inputs/snmp_trap/snmp_trap_test.go +++ b/plugins/inputs/snmp_trap/snmp_trap_test.go @@ -40,104 +40,111 @@ func fakeExecCmd(_ internal.Duration, x string, y ...string) ([]byte, error) { return nil, fmt.Errorf("mock " + x + " " + strings.Join(y, " ")) } -func sendTrap(t *testing.T, port uint16, now uint32, trap gosnmp.SnmpTrap, version gosnmp.SnmpVersion, secLevel string, username string, authProto string, authPass string, privProto string, privPass string, contextName string, engineID string) { - var s gosnmp.GoSNMP +func newMsgFlagsV3(secLevel string) gosnmp.SnmpV3MsgFlags { + var msgFlags gosnmp.SnmpV3MsgFlags + switch strings.ToLower(secLevel) { + case "noauthnopriv", "": + msgFlags = gosnmp.NoAuthNoPriv + case "authnopriv": + msgFlags = gosnmp.AuthNoPriv + case "authpriv": + msgFlags = gosnmp.AuthPriv + default: + msgFlags = gosnmp.NoAuthNoPriv + } - if version == gosnmp.Version3 { - var msgFlags gosnmp.SnmpV3MsgFlags - switch strings.ToLower(secLevel) { - case "noauthnopriv", "": - msgFlags = gosnmp.NoAuthNoPriv - case "authnopriv": - msgFlags = gosnmp.AuthNoPriv - case "authpriv": - msgFlags = gosnmp.AuthPriv - default: - msgFlags = gosnmp.NoAuthNoPriv - } + return msgFlags +} - var authenticationProtocol gosnmp.SnmpV3AuthProtocol - switch strings.ToLower(authProto) { - case "md5": - authenticationProtocol = gosnmp.MD5 - case "sha": - authenticationProtocol = gosnmp.SHA - //case "sha224": - // authenticationProtocol = gosnmp.SHA224 - //case "sha256": - // authenticationProtocol = gosnmp.SHA256 - //case "sha384": - // authenticationProtocol = gosnmp.SHA384 - //case "sha512": - // authenticationProtocol = gosnmp.SHA512 - case "": - authenticationProtocol = gosnmp.NoAuth - default: - authenticationProtocol = gosnmp.NoAuth - } +func newUsmSecurityParametersForV3(authProto string, privProto string, username string, privPass string, authPass string) *gosnmp.UsmSecurityParameters { + var authenticationProtocol gosnmp.SnmpV3AuthProtocol + switch strings.ToLower(authProto) { + case "md5": + authenticationProtocol = gosnmp.MD5 + case "sha": + authenticationProtocol = gosnmp.SHA + //case "sha224": + // authenticationProtocol = gosnmp.SHA224 + //case "sha256": + // authenticationProtocol = gosnmp.SHA256 + //case "sha384": + // authenticationProtocol = gosnmp.SHA384 + //case "sha512": + // authenticationProtocol = gosnmp.SHA512 + case "": + authenticationProtocol = gosnmp.NoAuth + default: + authenticationProtocol = gosnmp.NoAuth + } - var privacyProtocol gosnmp.SnmpV3PrivProtocol - switch strings.ToLower(privProto) { - case "aes": - privacyProtocol = gosnmp.AES - case "des": - privacyProtocol = gosnmp.DES - case "aes192": - privacyProtocol = gosnmp.AES192 - case "aes192c": - privacyProtocol = gosnmp.AES192C - case "aes256": - privacyProtocol = gosnmp.AES256 - case "aes256c": - privacyProtocol = gosnmp.AES256C - case "": - privacyProtocol = gosnmp.NoPriv - default: - privacyProtocol = gosnmp.NoPriv - } + var privacyProtocol gosnmp.SnmpV3PrivProtocol + switch strings.ToLower(privProto) { + case "aes": + privacyProtocol = gosnmp.AES + case "des": + privacyProtocol = gosnmp.DES + case "aes192": + privacyProtocol = gosnmp.AES192 + case "aes192c": + privacyProtocol = gosnmp.AES192C + case "aes256": + privacyProtocol = gosnmp.AES256 + case "aes256c": + privacyProtocol = gosnmp.AES256C + case "": + privacyProtocol = gosnmp.NoPriv + default: + privacyProtocol = gosnmp.NoPriv + } - sp := &gosnmp.UsmSecurityParameters{ - AuthoritativeEngineID: "1", - AuthoritativeEngineBoots: 1, - AuthoritativeEngineTime: 1, - UserName: username, - PrivacyProtocol: privacyProtocol, - PrivacyPassphrase: privPass, - AuthenticationPassphrase: authPass, - AuthenticationProtocol: authenticationProtocol, - } - s = gosnmp.GoSNMP{ - Port: port, - Version: version, - Timeout: time.Duration(2) * time.Second, - Retries: 1, - MaxOids: gosnmp.MaxOids, - Target: "127.0.0.1", - SecurityParameters: sp, - SecurityModel: gosnmp.UserSecurityModel, - MsgFlags: msgFlags, - ContextName: contextName, - ContextEngineID: engineID, - } - } else { - s = gosnmp.GoSNMP{ - Port: port, - Version: version, - Timeout: time.Duration(2) * time.Second, - Retries: 1, - MaxOids: gosnmp.MaxOids, - Target: "127.0.0.1", - Community: "public", - } + return &gosnmp.UsmSecurityParameters{ + AuthoritativeEngineID: "1", + AuthoritativeEngineBoots: 1, + AuthoritativeEngineTime: 1, + UserName: username, + PrivacyProtocol: privacyProtocol, + PrivacyPassphrase: privPass, + AuthenticationPassphrase: authPass, + AuthenticationProtocol: authenticationProtocol, } +} - err := s.Connect() +func newGoSNMPV3(port uint16, contextName string, engineID string, msgFlags gosnmp.SnmpV3MsgFlags, sp *gosnmp.UsmSecurityParameters) gosnmp.GoSNMP { + return gosnmp.GoSNMP{ + Port: port, + Version: gosnmp.Version3, + Timeout: time.Duration(2) * time.Second, + Retries: 1, + MaxOids: gosnmp.MaxOids, + Target: "127.0.0.1", + SecurityParameters: sp, + SecurityModel: gosnmp.UserSecurityModel, + MsgFlags: msgFlags, + ContextName: contextName, + ContextEngineID: engineID, + } +} + +func newGoSNMP(version gosnmp.SnmpVersion, port uint16) gosnmp.GoSNMP { + return gosnmp.GoSNMP{ + Port: port, + Version: version, + Timeout: time.Duration(2) * time.Second, + Retries: 1, + MaxOids: gosnmp.MaxOids, + Target: "127.0.0.1", + Community: "public", + } +} + +func sendTrap(t *testing.T, goSNMP gosnmp.GoSNMP, trap gosnmp.SnmpTrap) { + err := goSNMP.Connect() if err != nil { t.Errorf("Connect() err: %v", err) } - defer s.Conn.Close() + defer goSNMP.Conn.Close() - _, err = s.SendTrap(trap) + _, err = goSNMP.SendTrap(trap) if err != nil { t.Errorf("SendTrap() err: %v", err) } @@ -1302,8 +1309,17 @@ func TestReceiveTrap(t *testing.T) { s.load(entry.oid, entry.e) } + var goSNMP gosnmp.GoSNMP + if tt.version == gosnmp.Version3 { + msgFlags := newMsgFlagsV3(tt.secLevel) + sp := newUsmSecurityParametersForV3(tt.authProto, tt.privProto, tt.secName, tt.privPass, tt.authPass) + goSNMP = newGoSNMPV3(port, tt.contextName, tt.engineID, msgFlags, sp) + } else { + goSNMP = newGoSNMP(tt.version, port) + } + // Send the trap - sendTrap(t, port, now, tt.trap, tt.version, tt.secLevel, tt.secName, tt.authProto, tt.authPass, tt.privProto, tt.privPass, tt.contextName, tt.engineID) + sendTrap(t, goSNMP, tt.trap) // Wait for trap to be received select { diff --git a/plugins/inputs/stackdriver/stackdriver_test.go b/plugins/inputs/stackdriver/stackdriver_test.go index ee1f7ac9b01eb..0502c7bed9765 100644 --- a/plugins/inputs/stackdriver/stackdriver_test.go +++ b/plugins/inputs/stackdriver/stackdriver_test.go @@ -1125,8 +1125,8 @@ func TestListMetricDescriptorFilter(t *testing.T) { } } -func TestNewListTimeSeriesFilter(t *testing.T) { +func TestNewListTimeSeriesFilter(_ *testing.T) { } -func TestTimeSeriesConfCacheIsValid(t *testing.T) { +func TestTimeSeriesConfCacheIsValid(_ *testing.T) { } diff --git a/plugins/inputs/statsd/statsd.go b/plugins/inputs/statsd/statsd.go index bb9e9664683f8..bf63b6ee41a4d 100644 --- a/plugins/inputs/statsd/statsd.go +++ b/plugins/inputs/statsd/statsd.go @@ -92,8 +92,6 @@ type Statsd struct { accept chan bool // drops tracks the number of dropped metrics. drops int - // malformed tracks the number of malformed packets - malformed int // Channel for all incoming statsd packets in chan input @@ -538,11 +536,11 @@ func (s *Statsd) udpListen(conn *net.UDPConn) error { // parser monitors the s.in channel, if there is a packet ready, it parses the // packet into statsd strings and then calls parseStatsdLine, which parses a // single statsd metric into a struct. -func (s *Statsd) parser() error { +func (s *Statsd) parser() { for { select { case <-s.done: - return nil + return case in := <-s.in: start := time.Now() lines := strings.Split(in.Buffer.String(), "\n") diff --git a/plugins/inputs/suricata/suricata.go b/plugins/inputs/suricata/suricata.go index 17c0b571510b0..8cf374df65d3f 100644 --- a/plugins/inputs/suricata/suricata.go +++ b/plugins/inputs/suricata/suricata.go @@ -215,7 +215,7 @@ func (s *Suricata) parse(acc telegraf.Accumulator, sjson []byte) { // Gather measures and submits one full set of telemetry to Telegraf. // Not used here, submission is completely input-driven. -func (s *Suricata) Gather(acc telegraf.Accumulator) error { +func (s *Suricata) Gather(_ telegraf.Accumulator) error { return nil } diff --git a/plugins/inputs/suricata/suricata_testutil.go b/plugins/inputs/suricata/suricata_testutil.go deleted file mode 100644 index 55aa2bb9bae69..0000000000000 --- a/plugins/inputs/suricata/suricata_testutil.go +++ /dev/null @@ -1,38 +0,0 @@ -package suricata - -import ( - "bytes" - "sync" -) - -// A thread-safe Buffer wrapper to enable concurrent access to log output. -type buffer struct { - b bytes.Buffer - m sync.Mutex -} - -func (b *buffer) Read(p []byte) (n int, err error) { - b.m.Lock() - defer b.m.Unlock() - return b.b.Read(p) -} -func (b *buffer) Write(p []byte) (n int, err error) { - b.m.Lock() - defer b.m.Unlock() - return b.b.Write(p) -} -func (b *buffer) String() string { - b.m.Lock() - defer b.m.Unlock() - return b.b.String() -} -func (b *buffer) Reset() { - b.m.Lock() - defer b.m.Unlock() - b.b.Reset() -} -func (b *buffer) Bytes() []byte { - b.m.Lock() - defer b.m.Unlock() - return b.b.Bytes() -} diff --git a/plugins/inputs/syslog/nontransparent_test.go b/plugins/inputs/syslog/nontransparent_test.go index 544b31929f123..b71ddfee1a762 100644 --- a/plugins/inputs/syslog/nontransparent_test.go +++ b/plugins/inputs/syslog/nontransparent_test.go @@ -140,7 +140,7 @@ func testStrictNonTransparent(t *testing.T, protocol string, address string, wan for _, tc := range getTestCasesForNonTransparent() { t.Run(tc.name, func(t *testing.T) { // Creation of a strict mode receiver - receiver := newTCPSyslogReceiver(protocol+"://"+address, keepAlive, 0, false, framing.NonTransparent) + receiver := newTCPSyslogReceiver(protocol+"://"+address, keepAlive, 10, false, framing.NonTransparent) require.NotNil(t, receiver) if wantTLS { receiver.ServerConfig = *pki.TLSServerConfig() @@ -192,11 +192,12 @@ func testStrictNonTransparent(t *testing.T, protocol string, address string, wan } } -func testBestEffortNonTransparent(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *internal.Duration) { +func testBestEffortNonTransparent(t *testing.T, protocol string, address string, wantTLS bool) { + keepAlive := (*internal.Duration)(nil) for _, tc := range getTestCasesForNonTransparent() { t.Run(tc.name, func(t *testing.T) { // Creation of a best effort mode receiver - receiver := newTCPSyslogReceiver(protocol+"://"+address, keepAlive, 0, true, framing.NonTransparent) + receiver := newTCPSyslogReceiver(protocol+"://"+address, keepAlive, 10, true, framing.NonTransparent) require.NotNil(t, receiver) if wantTLS { receiver.ServerConfig = *pki.TLSServerConfig() @@ -245,7 +246,7 @@ func TestNonTransparentStrict_tcp(t *testing.T) { } func TestNonTransparentBestEffort_tcp(t *testing.T) { - testBestEffortNonTransparent(t, "tcp", address, false, nil) + testBestEffortNonTransparent(t, "tcp", address, false) } func TestNonTransparentStrict_tcp_tls(t *testing.T) { @@ -253,7 +254,7 @@ func TestNonTransparentStrict_tcp_tls(t *testing.T) { } func TestNonTransparentBestEffort_tcp_tls(t *testing.T) { - testBestEffortNonTransparent(t, "tcp", address, true, nil) + testBestEffortNonTransparent(t, "tcp", address, true) } func TestNonTransparentStrictWithKeepAlive_tcp_tls(t *testing.T) { @@ -277,7 +278,7 @@ func TestNonTransparentBestEffort_unix(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tmpdir) sock := filepath.Join(tmpdir, "syslog.TestBestEffort_unix.sock") - testBestEffortNonTransparent(t, "unix", sock, false, nil) + testBestEffortNonTransparent(t, "unix", sock, false) } func TestNonTransparentStrict_unix_tls(t *testing.T) { @@ -293,5 +294,5 @@ func TestNonTransparentBestEffort_unix_tls(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tmpdir) sock := filepath.Join(tmpdir, "syslog.TestBestEffort_unix_tls.sock") - testBestEffortNonTransparent(t, "unix", sock, true, nil) + testBestEffortNonTransparent(t, "unix", sock, true) } diff --git a/plugins/inputs/syslog/octetcounting_test.go b/plugins/inputs/syslog/octetcounting_test.go index 87909fcec2dd3..199c380601955 100644 --- a/plugins/inputs/syslog/octetcounting_test.go +++ b/plugins/inputs/syslog/octetcounting_test.go @@ -392,7 +392,8 @@ func testStrictOctetCounting(t *testing.T, protocol string, address string, want } } -func testBestEffortOctetCounting(t *testing.T, protocol string, address string, wantTLS bool, keepAlive *internal.Duration) { +func testBestEffortOctetCounting(t *testing.T, protocol string, address string, wantTLS bool) { + keepAlive := (*internal.Duration)(nil) for _, tc := range getTestCasesForOctetCounting() { t.Run(tc.name, func(t *testing.T) { // Creation of a best effort mode receiver @@ -445,7 +446,7 @@ func TestOctetCountingStrict_tcp(t *testing.T) { } func TestOctetCountingBestEffort_tcp(t *testing.T) { - testBestEffortOctetCounting(t, "tcp", address, false, nil) + testBestEffortOctetCounting(t, "tcp", address, false) } func TestOctetCountingStrict_tcp_tls(t *testing.T) { @@ -453,7 +454,7 @@ func TestOctetCountingStrict_tcp_tls(t *testing.T) { } func TestOctetCountingBestEffort_tcp_tls(t *testing.T) { - testBestEffortOctetCounting(t, "tcp", address, true, nil) + testBestEffortOctetCounting(t, "tcp", address, true) } func TestOctetCountingStrictWithKeepAlive_tcp_tls(t *testing.T) { @@ -477,7 +478,7 @@ func TestOctetCountingBestEffort_unix(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tmpdir) sock := filepath.Join(tmpdir, "syslog.TestBestEffort_unix.sock") - testBestEffortOctetCounting(t, "unix", sock, false, nil) + testBestEffortOctetCounting(t, "unix", sock, false) } func TestOctetCountingStrict_unix_tls(t *testing.T) { @@ -493,5 +494,5 @@ func TestOctetCountingBestEffort_unix_tls(t *testing.T) { require.NoError(t, err) defer os.RemoveAll(tmpdir) sock := filepath.Join(tmpdir, "syslog.TestBestEffort_unix_tls.sock") - testBestEffortOctetCounting(t, "unix", sock, true, nil) + testBestEffortOctetCounting(t, "unix", sock, true) } diff --git a/plugins/inputs/sysstat/sysstat_test.go b/plugins/inputs/sysstat/sysstat_test.go index 4aecfaacc2a15..0ef97f0e7c999 100644 --- a/plugins/inputs/sysstat/sysstat_test.go +++ b/plugins/inputs/sysstat/sysstat_test.go @@ -260,7 +260,7 @@ func fakeExecCommand(command string, args ...string) *exec.Cmd { // For example, if you run: // GO_WANT_HELPER_PROCESS=1 go test -test.run=TestHelperProcess -- sadf -p -- -p -C tmpFile // it returns mockData["C"] output. -func TestHelperProcess(t *testing.T) { +func TestHelperProcess(_ *testing.T) { if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" { return } diff --git a/plugins/inputs/system/mock_PS.go b/plugins/inputs/system/mock_PS.go index b3cf2c1707f5d..e1bd4f84b48e7 100644 --- a/plugins/inputs/system/mock_PS.go +++ b/plugins/inputs/system/mock_PS.go @@ -37,7 +37,7 @@ func (m *MockPS) LoadAvg() (*load.AvgStat, error) { return r0, r1 } -func (m *MockPS) CPUTimes(perCPU, totalCPU bool) ([]cpu.TimesStat, error) { +func (m *MockPS) CPUTimes(_, _ bool) ([]cpu.TimesStat, error) { ret := m.Called() r0 := ret.Get(0).([]cpu.TimesStat) @@ -74,7 +74,7 @@ func (m *MockPS) NetProto() ([]net.ProtoCountersStat, error) { return r0, r1 } -func (m *MockPS) DiskIO(names []string) (map[string]disk.IOCountersStat, error) { +func (m *MockPS) DiskIO(_ []string) (map[string]disk.IOCountersStat, error) { ret := m.Called() r0 := ret.Get(0).(map[string]disk.IOCountersStat) diff --git a/plugins/inputs/system/ps.go b/plugins/inputs/system/ps.go index abda443152359..d835d02633d02 100644 --- a/plugins/inputs/system/ps.go +++ b/plugins/inputs/system/ps.go @@ -5,7 +5,6 @@ import ( "path/filepath" "strings" - "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/internal" "github.com/shirou/gopsutil/cpu" @@ -34,13 +33,6 @@ type PSDiskDeps interface { PSDiskUsage(path string) (*disk.UsageStat, error) } -func add(acc telegraf.Accumulator, - name string, val float64, tags map[string]string) { - if val >= 0 { - acc.AddFields(name, map[string]interface{}{"value": val}, tags) - } -} - func NewSystemPS() *SystemPS { return &SystemPS{&SystemPSDisk{}} } diff --git a/plugins/inputs/tail/tail.go b/plugins/inputs/tail/tail.go index 54d42e44ada59..c7b16eb7a4631 100644 --- a/plugins/inputs/tail/tail.go +++ b/plugins/inputs/tail/tail.go @@ -22,8 +22,7 @@ import ( ) const ( - defaultWatchMethod = "inotify" - defaultMaxUndeliveredLines = 1000 + defaultWatchMethod = "inotify" ) var ( @@ -157,7 +156,7 @@ func (t *Tail) Init() error { return err } -func (t *Tail) Gather(acc telegraf.Accumulator) error { +func (t *Tail) Gather(_ telegraf.Accumulator) error { return t.tailNewFiles(true) } diff --git a/plugins/inputs/tcp_listener/tcp_listener.go b/plugins/inputs/tcp_listener/tcp_listener.go index 9016061cb565e..53297c4a68fb8 100644 --- a/plugins/inputs/tcp_listener/tcp_listener.go +++ b/plugins/inputs/tcp_listener/tcp_listener.go @@ -243,7 +243,7 @@ func (t *TCPListener) handler(conn *net.TCPConn, id string) { } // tcpParser parses the incoming tcp byte packets -func (t *TCPListener) tcpParser() error { +func (t *TCPListener) tcpParser() { defer t.wg.Done() var packet []byte @@ -254,7 +254,7 @@ func (t *TCPListener) tcpParser() error { case <-t.done: // drain input packets before finishing: if len(t.in) == 0 { - return nil + return } case packet = <-t.in: if len(packet) == 0 { diff --git a/plugins/inputs/tcp_listener/tcp_listener_test.go b/plugins/inputs/tcp_listener/tcp_listener_test.go index 5c476703e54cd..d6781b55020c3 100644 --- a/plugins/inputs/tcp_listener/tcp_listener_test.go +++ b/plugins/inputs/tcp_listener/tcp_listener_test.go @@ -254,7 +254,7 @@ func TestRunParser(t *testing.T) { ) } -func TestRunParserInvalidMsg(t *testing.T) { +func TestRunParserInvalidMsg(_ *testing.T) { var testmsg = []byte("cpu_load_short") listener, in := newTestTCPListener() diff --git a/plugins/inputs/udp_listener/udp_listener.go b/plugins/inputs/udp_listener/udp_listener.go index 4833b0fdfd132..7222f3b1fb6af 100644 --- a/plugins/inputs/udp_listener/udp_listener.go +++ b/plugins/inputs/udp_listener/udp_listener.go @@ -189,7 +189,7 @@ func (u *UDPListener) udpListenLoop() { } } -func (u *UDPListener) udpParser() error { +func (u *UDPListener) udpParser() { defer u.wg.Done() var packet []byte @@ -199,7 +199,7 @@ func (u *UDPListener) udpParser() error { select { case <-u.done: if len(u.in) == 0 { - return nil + return } case packet = <-u.in: metrics, err = u.parser.Parse(packet) diff --git a/plugins/inputs/udp_listener/udp_listener_test.go b/plugins/inputs/udp_listener/udp_listener_test.go index f3e034363e471..b6c0b5f09b082 100644 --- a/plugins/inputs/udp_listener/udp_listener_test.go +++ b/plugins/inputs/udp_listener/udp_listener_test.go @@ -136,7 +136,7 @@ func TestRunParser(t *testing.T) { ) } -func TestRunParserInvalidMsg(t *testing.T) { +func TestRunParserInvalidMsg(_ *testing.T) { log.SetOutput(ioutil.Discard) var testmsg = []byte("cpu_load_short") diff --git a/plugins/inputs/unbound/unbound.go b/plugins/inputs/unbound/unbound.go index 9b04bbf27f888..441d44c852f92 100644 --- a/plugins/inputs/unbound/unbound.go +++ b/plugins/inputs/unbound/unbound.go @@ -17,19 +17,18 @@ import ( "github.com/influxdata/telegraf/plugins/inputs" ) -type runner func(cmdName string, Timeout internal.Duration, UseSudo bool, Server string, ThreadAsTag bool, ConfigFile string) (*bytes.Buffer, error) +type runner func(unbound Unbound) (*bytes.Buffer, error) // Unbound is used to store configuration values type Unbound struct { - Binary string - Timeout internal.Duration - UseSudo bool - Server string - ThreadAsTag bool - ConfigFile string - - filter filter.Filter - run runner + Binary string `toml:"binary"` + Timeout internal.Duration `toml:"timeout"` + UseSudo bool `toml:"use_sudo"` + Server string `toml:"server"` + ThreadAsTag bool `toml:"thread_as_tag"` + ConfigFile string `toml:"config_file"` + + run runner } var defaultBinary = "/usr/sbin/unbound-control" @@ -71,26 +70,26 @@ func (s *Unbound) SampleConfig() string { } // Shell out to unbound_stat and return the output -func unboundRunner(cmdName string, Timeout internal.Duration, UseSudo bool, Server string, ThreadAsTag bool, ConfigFile string) (*bytes.Buffer, error) { +func unboundRunner(unbound Unbound) (*bytes.Buffer, error) { cmdArgs := []string{"stats_noreset"} - if Server != "" { - host, port, err := net.SplitHostPort(Server) + if unbound.Server != "" { + host, port, err := net.SplitHostPort(unbound.Server) if err != nil { // No port was specified - host = Server + host = unbound.Server port = "" } // Unbound control requires an IP address, and we want to be nice to the user resolver := net.Resolver{} - ctx, lookUpCancel := context.WithTimeout(context.Background(), Timeout.Duration) + ctx, lookUpCancel := context.WithTimeout(context.Background(), unbound.Timeout.Duration) defer lookUpCancel() serverIps, err := resolver.LookupIPAddr(ctx, host) if err != nil { - return nil, fmt.Errorf("error looking up ip for server: %s: %s", Server, err) + return nil, fmt.Errorf("error looking up ip for server: %s: %s", unbound.Server, err) } if len(serverIps) == 0 { - return nil, fmt.Errorf("error no ip for server: %s: %s", Server, err) + return nil, fmt.Errorf("error no ip for server: %s: %s", unbound.Server, err) } server := serverIps[0].IP.String() if port != "" { @@ -100,22 +99,22 @@ func unboundRunner(cmdName string, Timeout internal.Duration, UseSudo bool, Serv cmdArgs = append([]string{"-s", server}, cmdArgs...) } - if ConfigFile != "" { - cmdArgs = append([]string{"-c", ConfigFile}, cmdArgs...) + if unbound.ConfigFile != "" { + cmdArgs = append([]string{"-c", unbound.ConfigFile}, cmdArgs...) } - cmd := exec.Command(cmdName, cmdArgs...) + cmd := exec.Command(unbound.Binary, cmdArgs...) - if UseSudo { - cmdArgs = append([]string{cmdName}, cmdArgs...) + if unbound.UseSudo { + cmdArgs = append([]string{unbound.Binary}, cmdArgs...) cmd = exec.Command("sudo", cmdArgs...) } var out bytes.Buffer cmd.Stdout = &out - err := internal.RunTimeout(cmd, Timeout.Duration) + err := internal.RunTimeout(cmd, unbound.Timeout.Duration) if err != nil { - return &out, fmt.Errorf("error running unbound-control: %s (%s %v)", err, cmdName, cmdArgs) + return &out, fmt.Errorf("error running unbound-control: %s (%s %v)", err, unbound.Binary, cmdArgs) } return &out, nil @@ -132,7 +131,7 @@ func (s *Unbound) Gather(acc telegraf.Accumulator) error { return err } - out, err := s.run(s.Binary, s.Timeout, s.UseSudo, s.Server, s.ThreadAsTag, s.ConfigFile) + out, err := s.run(*s) if err != nil { return fmt.Errorf("error gathering metrics: %s", err) } diff --git a/plugins/inputs/unbound/unbound_test.go b/plugins/inputs/unbound/unbound_test.go index cc4b99daecc59..cac0316d7db01 100644 --- a/plugins/inputs/unbound/unbound_test.go +++ b/plugins/inputs/unbound/unbound_test.go @@ -3,17 +3,14 @@ package unbound import ( "bytes" "testing" - "time" - "github.com/influxdata/telegraf/internal" - "github.com/influxdata/telegraf/testutil" "github.com/stretchr/testify/assert" -) -var TestTimeout = internal.Duration{Duration: time.Second} + "github.com/influxdata/telegraf/testutil" +) -func UnboundControl(output string, Timeout internal.Duration, useSudo bool, Server string, ThreadAsTag bool, ConfigFile string) func(string, internal.Duration, bool, string, bool, string) (*bytes.Buffer, error) { - return func(string, internal.Duration, bool, string, bool, string) (*bytes.Buffer, error) { +func UnboundControl(output string) func(unbound Unbound) (*bytes.Buffer, error) { + return func(unbound Unbound) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } } @@ -21,7 +18,7 @@ func UnboundControl(output string, Timeout internal.Duration, useSudo bool, Serv func TestParseFullOutput(t *testing.T) { acc := &testutil.Accumulator{} v := &Unbound{ - run: UnboundControl(fullOutput, TestTimeout, true, "", false, ""), + run: UnboundControl(fullOutput), } err := v.Gather(acc) @@ -38,7 +35,7 @@ func TestParseFullOutput(t *testing.T) { func TestParseFullOutputThreadAsTag(t *testing.T) { acc := &testutil.Accumulator{} v := &Unbound{ - run: UnboundControl(fullOutput, TestTimeout, true, "", true, ""), + run: UnboundControl(fullOutput), ThreadAsTag: true, } err := v.Gather(acc) diff --git a/plugins/inputs/varnish/varnish_test.go b/plugins/inputs/varnish/varnish_test.go index 96e5c35562208..ee89105363235 100644 --- a/plugins/inputs/varnish/varnish_test.go +++ b/plugins/inputs/varnish/varnish_test.go @@ -7,14 +7,14 @@ import ( "fmt" "strings" "testing" - "time" + + "github.com/stretchr/testify/assert" "github.com/influxdata/telegraf/internal" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" ) -func fakeVarnishStat(output string, useSudo bool, InstanceName string, Timeout internal.Duration) func(string, bool, string, internal.Duration) (*bytes.Buffer, error) { +func fakeVarnishStat(output string) func(string, bool, string, internal.Duration) (*bytes.Buffer, error) { return func(string, bool, string, internal.Duration) (*bytes.Buffer, error) { return bytes.NewBuffer([]byte(output)), nil } @@ -23,7 +23,7 @@ func fakeVarnishStat(output string, useSudo bool, InstanceName string, Timeout i func TestGather(t *testing.T) { acc := &testutil.Accumulator{} v := &Varnish{ - run: fakeVarnishStat(smOutput, false, "", internal.Duration{Duration: time.Second}), + run: fakeVarnishStat(smOutput), Stats: []string{"*"}, } v.Gather(acc) @@ -39,7 +39,7 @@ func TestGather(t *testing.T) { func TestParseFullOutput(t *testing.T) { acc := &testutil.Accumulator{} v := &Varnish{ - run: fakeVarnishStat(fullOutput, true, "", internal.Duration{Duration: time.Second}), + run: fakeVarnishStat(fullOutput), Stats: []string{"*"}, } err := v.Gather(acc) @@ -54,7 +54,7 @@ func TestParseFullOutput(t *testing.T) { func TestFilterSomeStats(t *testing.T) { acc := &testutil.Accumulator{} v := &Varnish{ - run: fakeVarnishStat(fullOutput, false, "", internal.Duration{Duration: time.Second}), + run: fakeVarnishStat(fullOutput), Stats: []string{"MGT.*", "VBE.*"}, } err := v.Gather(acc) @@ -77,7 +77,7 @@ func TestFieldConfig(t *testing.T) { for fieldCfg, expected := range expect { acc := &testutil.Accumulator{} v := &Varnish{ - run: fakeVarnishStat(fullOutput, true, "", internal.Duration{Duration: time.Second}), + run: fakeVarnishStat(fullOutput), Stats: strings.Split(fieldCfg, ","), } err := v.Gather(acc) diff --git a/plugins/inputs/vsphere/client.go b/plugins/inputs/vsphere/client.go index b3096f7be300b..0eae3be6ffb97 100644 --- a/plugins/inputs/vsphere/client.go +++ b/plugins/inputs/vsphere/client.go @@ -10,7 +10,6 @@ import ( "sync" "time" - "github.com/influxdata/telegraf" "github.com/vmware/govmomi" "github.com/vmware/govmomi/object" "github.com/vmware/govmomi/performance" @@ -20,6 +19,8 @@ import ( "github.com/vmware/govmomi/vim25/methods" "github.com/vmware/govmomi/vim25/soap" "github.com/vmware/govmomi/vim25/types" + + "github.com/influxdata/telegraf" ) // The highest number of metrics we can query for, no matter what settings @@ -30,10 +31,10 @@ const absoluteMaxMetrics = 10000 // a single Client is reused across all functions and goroutines, but the client // is periodically recycled to avoid authentication expiration issues. type ClientFactory struct { - client *Client - mux sync.Mutex - url *url.URL - parent *VSphere + client *Client + mux sync.Mutex + vSphereURL *url.URL + parent *VSphere } // Client represents a connection to vSphere and is backed by a govmomi connection @@ -49,11 +50,11 @@ type Client struct { } // NewClientFactory creates a new ClientFactory and prepares it for use. -func NewClientFactory(ctx context.Context, url *url.URL, parent *VSphere) *ClientFactory { +func NewClientFactory(vSphereURL *url.URL, parent *VSphere) *ClientFactory { return &ClientFactory{ - client: nil, - parent: parent, - url: url, + client: nil, + parent: parent, + vSphereURL: vSphereURL, } } @@ -66,7 +67,7 @@ func (cf *ClientFactory) GetClient(ctx context.Context) (*Client, error) { for { if cf.client == nil { var err error - if cf.client, err = NewClient(ctx, cf.url, cf.parent); err != nil { + if cf.client, err = NewClient(ctx, cf.vSphereURL, cf.parent); err != nil { return nil, err } } @@ -98,8 +99,8 @@ func (cf *ClientFactory) GetClient(ctx context.Context) (*Client, error) { } // NewClient creates a new vSphere client based on the url and setting passed as parameters. -func NewClient(ctx context.Context, u *url.URL, vs *VSphere) (*Client, error) { - sw := NewStopwatch("connect", u.Host) +func NewClient(ctx context.Context, vSphereURL *url.URL, vs *VSphere) (*Client, error) { + sw := NewStopwatch("connect", vSphereURL.Host) defer sw.Stop() tlsCfg, err := vs.ClientConfig.TLSConfig() @@ -111,14 +112,14 @@ func NewClient(ctx context.Context, u *url.URL, vs *VSphere) (*Client, error) { tlsCfg = &tls.Config{} } if vs.Username != "" { - u.User = url.UserPassword(vs.Username, vs.Password) + vSphereURL.User = url.UserPassword(vs.Username, vs.Password) } - vs.Log.Debugf("Creating client: %s", u.Host) - soapClient := soap.NewClient(u, tlsCfg.InsecureSkipVerify) + vs.Log.Debugf("Creating client: %s", vSphereURL.Host) + soapClient := soap.NewClient(vSphereURL, tlsCfg.InsecureSkipVerify) // Add certificate if we have it. Use it to log us in. - if tlsCfg != nil && len(tlsCfg.Certificates) > 0 { + if len(tlsCfg.Certificates) > 0 { soapClient.SetCertificate(tlsCfg.Certificates[0]) } @@ -154,8 +155,8 @@ func NewClient(ctx context.Context, u *url.URL, vs *VSphere) (*Client, error) { } // Only login if the URL contains user information. - if u.User != nil { - if err := c.Login(ctx, u.User); err != nil { + if vSphereURL.User != nil { + if err := c.Login(ctx, vSphereURL.User); err != nil { return nil, err } } diff --git a/plugins/inputs/vsphere/endpoint.go b/plugins/inputs/vsphere/endpoint.go index 0eb1b0ab935dc..f8916242286e1 100644 --- a/plugins/inputs/vsphere/endpoint.go +++ b/plugins/inputs/vsphere/endpoint.go @@ -31,8 +31,6 @@ var isIPv6 = regexp.MustCompile("^(?:[A-Fa-f0-9]{0,4}:){1,7}[A-Fa-f0-9]{1,4}$") const metricLookback = 3 // Number of time periods to look back at for non-realtime metrics -const rtMetricLookback = 3 // Number of time periods to look back at for realtime metrics - const maxSampleConst = 10 // Absolute maximum number of samples regardless of period const maxMetadataSamples = 100 // Number of resources to sample for metric metadata @@ -126,7 +124,7 @@ func NewEndpoint(ctx context.Context, parent *VSphere, url *url.URL, log telegra hwMarks: NewTSCache(hwMarkTTL), lun2ds: make(map[string]string), initialized: false, - clientFactory: NewClientFactory(ctx, url, parent), + clientFactory: NewClientFactory(url, parent), customAttrFilter: newFilterOrPanic(parent.CustomAttributeInclude, parent.CustomAttributeExclude), customAttrEnabled: anythingEnabled(parent.CustomAttributeExclude), log: log, @@ -875,7 +873,7 @@ func submitChunkJob(ctx context.Context, te *ThrottledExecutor, job queryJob, pq }) } -func (e *Endpoint) chunkify(ctx context.Context, res *resourceKind, now time.Time, latest time.Time, acc telegraf.Accumulator, job queryJob) { +func (e *Endpoint) chunkify(ctx context.Context, res *resourceKind, now time.Time, latest time.Time, job queryJob) { te := NewThrottledExecutor(e.Parent.CollectConcurrency) maxMetrics := e.Parent.MaxQueryMetrics if maxMetrics < 1 { @@ -1017,9 +1015,9 @@ func (e *Endpoint) collectResource(ctx context.Context, resourceType string, acc latestSample := time.Time{} // Divide workload into chunks and process them concurrently - e.chunkify(ctx, res, now, latest, acc, + e.chunkify(ctx, res, now, latest, func(chunk queryChunk) { - n, localLatest, err := e.collectChunk(ctx, chunk, res, acc, now, estInterval) + n, localLatest, err := e.collectChunk(ctx, chunk, res, acc, estInterval) e.log.Debugf("CollectChunk for %s returned %d metrics", resourceType, n) if err != nil { acc.AddError(errors.New("while collecting " + res.name + ": " + err.Error())) @@ -1081,7 +1079,7 @@ func (e *Endpoint) alignSamples(info []types.PerfSampleInfo, values []int64, int return rInfo, rValues } -func (e *Endpoint) collectChunk(ctx context.Context, pqs queryChunk, res *resourceKind, acc telegraf.Accumulator, now time.Time, interval time.Duration) (int, time.Time, error) { +func (e *Endpoint) collectChunk(ctx context.Context, pqs queryChunk, res *resourceKind, acc telegraf.Accumulator, interval time.Duration) (int, time.Time, error) { e.log.Debugf("Query for %s has %d QuerySpecs", res.name, len(pqs)) latestSample := time.Time{} count := 0 diff --git a/plugins/inputs/vsphere/vsphere.go b/plugins/inputs/vsphere/vsphere.go index 300261358270d..a18a5ca70f982 100644 --- a/plugins/inputs/vsphere/vsphere.go +++ b/plugins/inputs/vsphere/vsphere.go @@ -258,7 +258,7 @@ func (v *VSphere) Description() string { // Start is called from telegraf core when a plugin is started and allows it to // perform initialization tasks. -func (v *VSphere) Start(acc telegraf.Accumulator) error { +func (v *VSphere) Start(_ telegraf.Accumulator) error { v.Log.Info("Starting plugin") ctx, cancel := context.WithCancel(context.Background()) v.cancel = cancel diff --git a/plugins/inputs/vsphere/vsphere_test.go b/plugins/inputs/vsphere/vsphere_test.go index 60e7e1c8dbf27..e0bcaac1c8eca 100644 --- a/plugins/inputs/vsphere/vsphere_test.go +++ b/plugins/inputs/vsphere/vsphere_test.go @@ -517,11 +517,11 @@ func testCollection(t *testing.T, excludeClusters bool) { hostMoid = hosts[0].Reference().Value hostCache[hostName] = hostMoid } - if isInCluster(t, v, client, cache, "HostSystem", hostMoid) { // If the VM lives in a cluster + if isInCluster(v, client, cache, "HostSystem", hostMoid) { // If the VM lives in a cluster mustContainAll(t, m.Tags, []string{"clustername"}) } } else if strings.HasPrefix(m.Measurement, "vsphere.host.") { - if isInCluster(t, v, client, cache, "HostSystem", m.Tags["moid"]) { // If the host lives in a cluster + if isInCluster(v, client, cache, "HostSystem", m.Tags["moid"]) { // If the host lives in a cluster mustContainAll(t, m.Tags, []string{"esxhostname", "clustername", "moid", "dcname"}) } else { mustContainAll(t, m.Tags, []string{"esxhostname", "moid", "dcname"}) @@ -535,7 +535,7 @@ func testCollection(t *testing.T, excludeClusters bool) { require.Empty(t, mustHaveMetrics, "Some metrics were not found") } -func isInCluster(t *testing.T, v *VSphere, client *Client, cache map[string]string, resourceKind, moid string) bool { +func isInCluster(v *VSphere, client *Client, cache map[string]string, resourceKind, moid string) bool { ctx := context.Background() ref := types.ManagedObjectReference{ Type: resourceKind, diff --git a/plugins/inputs/webhooks/mandrill/mandrill_webhooks.go b/plugins/inputs/webhooks/mandrill/mandrill_webhooks.go index 4a14c88947f97..a7e219c53c905 100644 --- a/plugins/inputs/webhooks/mandrill/mandrill_webhooks.go +++ b/plugins/inputs/webhooks/mandrill/mandrill_webhooks.go @@ -25,7 +25,7 @@ func (md *MandrillWebhook) Register(router *mux.Router, acc telegraf.Accumulator md.acc = acc } -func (md *MandrillWebhook) returnOK(w http.ResponseWriter, r *http.Request) { +func (md *MandrillWebhook) returnOK(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } diff --git a/plugins/inputs/zfs/zfs.go b/plugins/inputs/zfs/zfs.go index 297e3cc07ec42..4e1999cf68d30 100644 --- a/plugins/inputs/zfs/zfs.go +++ b/plugins/inputs/zfs/zfs.go @@ -13,9 +13,9 @@ type Zfs struct { KstatMetrics []string PoolMetrics bool DatasetMetrics bool - sysctl Sysctl - zpool Zpool - zdataset Zdataset + sysctl Sysctl //nolint:varcheck,unused // False positive - this var is used for non-default build tag: freebsd + zpool Zpool //nolint:varcheck,unused // False positive - this var is used for non-default build tag: freebsd + zdataset Zdataset //nolint:varcheck,unused // False positive - this var is used for non-default build tag: freebsd Log telegraf.Logger `toml:"-"` } diff --git a/plugins/inputs/zfs/zfs_linux_test.go b/plugins/inputs/zfs/zfs_linux_test.go index 8690fee4c3bf9..7d8aff81c689c 100644 --- a/plugins/inputs/zfs/zfs_linux_test.go +++ b/plugins/inputs/zfs/zfs_linux_test.go @@ -182,67 +182,6 @@ scatter_page_alloc_retry 4 99311 scatter_sg_table_retry 4 99221 ` -const dbufcachestatsContents = ` -15 1 0x01 11 2992 6257505590736 8516276189184 -name type data -size 4 242688 -size_max 4 338944 -max_bytes 4 62834368 -lowater_bytes 4 56550932 -hiwater_bytes 4 69117804 -total_evicts 4 0 -hash_collisions 4 0 -hash_elements 4 31 -hash_elements_max 4 32 -hash_chains 4 0 -hash_chain_max 4 0 -` - -const dnodestatsContents = ` -10 1 0x01 28 7616 6257498525011 8671911551753 -name type data -dnode_hold_dbuf_hold 4 0 -dnode_hold_dbuf_read 4 0 -dnode_hold_alloc_hits 4 1460 -dnode_hold_alloc_misses 4 0 -dnode_hold_alloc_interior 4 0 -dnode_hold_alloc_lock_retry 4 0 -dnode_hold_alloc_lock_misses 4 0 -dnode_hold_alloc_type_none 4 0 -dnode_hold_free_hits 4 2 -dnode_hold_free_misses 4 0 -dnode_hold_free_lock_misses 4 0 -dnode_hold_free_lock_retry 4 0 -dnode_hold_free_overflow 4 0 -dnode_hold_free_refcount 4 0 -dnode_hold_free_txg 4 0 -dnode_allocate 4 2 -dnode_reallocate 4 0 -dnode_buf_evict 4 6 -dnode_alloc_next_chunk 4 1 -dnode_alloc_race 4 0 -dnode_alloc_next_block 4 0 -dnode_move_invalid 4 0 -dnode_move_recheck1 4 0 -dnode_move_recheck2 4 0 -dnode_move_special 4 0 -dnode_move_handle 4 0 -dnode_move_rwlock 4 0 -dnode_move_active 4 0 -` - -const vdevmirrorcachestatsContents = ` -18 1 0x01 7 1904 6257505684227 9638257816287 -name type data -rotating_linear 4 0 -rotating_offset 4 0 -rotating_seek 4 0 -non_rotating_linear 4 0 -non_rotating_seek 4 0 -preferred_found 4 0 -preferred_not_found 4 43 -` - var testKstatPath = os.TempDir() + "/telegraf/proc/spl/kstat/zfs" func TestZfsPoolMetrics(t *testing.T) { diff --git a/plugins/inputs/zipkin/cmd/stress_test_write/stress_test_write.go b/plugins/inputs/zipkin/cmd/stress_test_write/stress_test_write.go index ea25b49a0fcca..61c2eda12bd96 100644 --- a/plugins/inputs/zipkin/cmd/stress_test_write/stress_test_write.go +++ b/plugins/inputs/zipkin/cmd/stress_test_write/stress_test_write.go @@ -35,8 +35,6 @@ var ( ZipkinServerHost string ) -const usage = `./stress_test_write -batch_size= -max_backlog= -batch_interval= -span_count -zipkin_host=` - func init() { flag.IntVar(&BatchSize, "batch_size", 10000, "") flag.IntVar(&MaxBackLog, "max_backlog", 100000, "") diff --git a/plugins/inputs/zipkin/codec/codec_test.go b/plugins/inputs/zipkin/codec/codec_test.go index 3525f30c201d6..c3d2fa655dcc6 100644 --- a/plugins/inputs/zipkin/codec/codec_test.go +++ b/plugins/inputs/zipkin/codec/codec_test.go @@ -12,9 +12,6 @@ import ( ) func Test_MicroToTime(t *testing.T) { - type args struct { - micro int64 - } tests := []struct { name string micro int64 diff --git a/plugins/inputs/zipkin/zipkin.go b/plugins/inputs/zipkin/zipkin.go index 4224fea3d2928..d0cf9b38dda64 100644 --- a/plugins/inputs/zipkin/zipkin.go +++ b/plugins/inputs/zipkin/zipkin.go @@ -79,7 +79,7 @@ func (z Zipkin) SampleConfig() string { // Gather is empty for the zipkin plugin; all gathering is done through // the separate goroutine launched in (*Zipkin).Start() -func (z *Zipkin) Gather(acc telegraf.Accumulator) error { return nil } +func (z *Zipkin) Gather(_ telegraf.Accumulator) error { return nil } // Start launches a separate goroutine for collecting zipkin client http requests, // passing in a telegraf.Accumulator such that data can be collected. diff --git a/plugins/outputs/amqp/amqp_test.go b/plugins/outputs/amqp/amqp_test.go index 32a9145281e48..537dd7d049b8c 100644 --- a/plugins/outputs/amqp/amqp_test.go +++ b/plugins/outputs/amqp/amqp_test.go @@ -15,8 +15,6 @@ type MockClient struct { PublishCallCount int CloseCallCount int - - t *testing.T } func (c *MockClient) Publish(key string, body []byte) error { @@ -29,10 +27,6 @@ func (c *MockClient) Close() error { return c.CloseF() } -func MockConnect(config *ClientConfig) (Client, error) { - return &MockClient{}, nil -} - func NewMockClient() Client { return &MockClient{ PublishF: func(key string, body []byte) error { diff --git a/plugins/outputs/application_insights/application_insights_test.go b/plugins/outputs/application_insights/application_insights_test.go index ceaad4a4e9472..8d4fb755646f5 100644 --- a/plugins/outputs/application_insights/application_insights_test.go +++ b/plugins/outputs/application_insights/application_insights_test.go @@ -459,15 +459,6 @@ func findTransmittedTelemetry(transmitter *mocks.Transmitter, telemetryName stri return nil } -func keys(m map[string]string) []string { - keys := make([]string, 0, len(m)) - for k := range m { - keys = append(keys, k) - } - - return keys -} - func assertMapContains(assert *assert.Assertions, expected, actual map[string]string) { if expected == nil && actual == nil { return diff --git a/plugins/outputs/cloud_pubsub/topic_gcp.go b/plugins/outputs/cloud_pubsub/topic_gcp.go index a85c6f39eb8f6..72ef50efcba79 100644 --- a/plugins/outputs/cloud_pubsub/topic_gcp.go +++ b/plugins/outputs/cloud_pubsub/topic_gcp.go @@ -6,8 +6,6 @@ import ( ) type ( - topicFactory func(string) (topic, error) - topic interface { ID() string Stop() diff --git a/plugins/outputs/cratedb/cratedb_test.go b/plugins/outputs/cratedb/cratedb_test.go index 993c9d7cbfeb2..43297afe2e5e7 100644 --- a/plugins/outputs/cratedb/cratedb_test.go +++ b/plugins/outputs/cratedb/cratedb_test.go @@ -216,6 +216,7 @@ func Test_hashID(t *testing.T) { } } +//nolint:unused // Used in skipped tests func testURL() string { url := os.Getenv("CRATE_URL") if url == "" { diff --git a/plugins/outputs/discard/discard.go b/plugins/outputs/discard/discard.go index 919f74b477ffa..de3696c3e6148 100644 --- a/plugins/outputs/discard/discard.go +++ b/plugins/outputs/discard/discard.go @@ -11,7 +11,7 @@ func (d *Discard) Connect() error { return nil } func (d *Discard) Close() error { return nil } func (d *Discard) SampleConfig() string { return "" } func (d *Discard) Description() string { return "Send metrics to nowhere at all" } -func (d *Discard) Write(metrics []telegraf.Metric) error { +func (d *Discard) Write(_ []telegraf.Metric) error { return nil } diff --git a/plugins/outputs/graylog/graylog.go b/plugins/outputs/graylog/graylog.go index c6cad89c0ba51..05feafe9effc1 100644 --- a/plugins/outputs/graylog/graylog.go +++ b/plugins/outputs/graylog/graylog.go @@ -70,13 +70,13 @@ func (g *Gelf) Write(message []byte) (n int, err error) { for i, index := 0, 0; i < length; i, index = i+chunksize, index+1 { packet := g.createChunkedMessage(index, chunkCountInt, id, &compressed) - _, err = g.send(packet.Bytes()) + err = g.send(packet.Bytes()) if err != nil { return 0, err } } } else { - _, err = g.send(compressed.Bytes()) + err = g.send(compressed.Bytes()) if err != nil { return 0, err } @@ -133,19 +133,19 @@ func (g *Gelf) compress(b []byte) bytes.Buffer { return buf } -func (g *Gelf) send(b []byte) (n int, err error) { +func (g *Gelf) send(b []byte) error { udpAddr, err := net.ResolveUDPAddr("udp", g.GelfConfig.GraylogEndpoint) if err != nil { - return + return err } conn, err := net.DialUDP("udp", nil, udpAddr) if err != nil { - return + return err } - n, err = conn.Write(b) - return + _, err = conn.Write(b) + return err } type Graylog struct { diff --git a/plugins/outputs/health/health.go b/plugins/outputs/health/health.go index c7b584076e779..7447c404c9b2d 100644 --- a/plugins/outputs/health/health.go +++ b/plugins/outputs/health/health.go @@ -178,7 +178,7 @@ func (h *Health) listen() (net.Listener, error) { return net.Listen(h.network, h.address) } -func (h *Health) ServeHTTP(rw http.ResponseWriter, req *http.Request) { +func (h *Health) ServeHTTP(rw http.ResponseWriter, _ *http.Request) { var code = http.StatusOK if !h.isHealthy() { code = http.StatusServiceUnavailable diff --git a/plugins/outputs/influxdb/udp.go b/plugins/outputs/influxdb/udp.go index 510df9463265b..62848417b124c 100644 --- a/plugins/outputs/influxdb/udp.go +++ b/plugins/outputs/influxdb/udp.go @@ -115,7 +115,7 @@ func (c *udpClient) Write(ctx context.Context, metrics []telegraf.Metric) error return nil } -func (c *udpClient) CreateDatabase(ctx context.Context, database string) error { +func (c *udpClient) CreateDatabase(_ context.Context, _ string) error { return nil } diff --git a/plugins/outputs/influxdb/udp_test.go b/plugins/outputs/influxdb/udp_test.go index 2e60c586c7a03..1c5696cf10fe5 100644 --- a/plugins/outputs/influxdb/udp_test.go +++ b/plugins/outputs/influxdb/udp_test.go @@ -62,7 +62,7 @@ type MockDialer struct { DialContextF func(network, address string) (influxdb.Conn, error) } -func (d *MockDialer) DialContext(ctx context.Context, network string, address string) (influxdb.Conn, error) { +func (d *MockDialer) DialContext(_ context.Context, network string, address string) (influxdb.Conn, error) { return d.DialContextF(network, address) } diff --git a/plugins/outputs/influxdb_v2/influxdb_test.go b/plugins/outputs/influxdb_v2/influxdb_test.go index 90a3823915a5b..b16fd944d28db 100644 --- a/plugins/outputs/influxdb_v2/influxdb_test.go +++ b/plugins/outputs/influxdb_v2/influxdb_test.go @@ -94,7 +94,7 @@ func TestConnect(t *testing.T) { } } -func TestUnused(t *testing.T) { +func TestUnused(_ *testing.T) { thing := influxdb.InfluxDB{} thing.Close() thing.Description() diff --git a/plugins/outputs/kafka/kafka.go b/plugins/outputs/kafka/kafka.go index dde2c8e62e4d0..5aad62f48e408 100644 --- a/plugins/outputs/kafka/kafka.go +++ b/plugins/outputs/kafka/kafka.go @@ -1,7 +1,6 @@ package kafka import ( - "crypto/tls" "fmt" "log" "strings" @@ -44,8 +43,6 @@ type Kafka struct { Log telegraf.Logger `toml:"-"` - tlsConfig tls.Config - producerFunc func(addrs []string, config *sarama.Config) (sarama.SyncProducer, error) producer sarama.SyncProducer diff --git a/plugins/outputs/kafka/kafka_test.go b/plugins/outputs/kafka/kafka_test.go index 52b020813975b..2d786013c9a24 100644 --- a/plugins/outputs/kafka/kafka_test.go +++ b/plugins/outputs/kafka/kafka_test.go @@ -179,7 +179,7 @@ func (p *MockProducer) Close() error { return nil } -func NewMockProducer(addrs []string, config *sarama.Config) (sarama.SyncProducer, error) { +func NewMockProducer(_ []string, _ *sarama.Config) (sarama.SyncProducer, error) { return &MockProducer{}, nil } diff --git a/plugins/outputs/newrelic/newrelic_test.go b/plugins/outputs/newrelic/newrelic_test.go index 1eedc63f44116..2d679bf3cecbc 100644 --- a/plugins/outputs/newrelic/newrelic_test.go +++ b/plugins/outputs/newrelic/newrelic_test.go @@ -31,9 +31,6 @@ func TestBasic(t *testing.T) { } func TestNewRelic_Write(t *testing.T) { - type args struct { - metrics []telegraf.Metric - } tests := []struct { name string metrics []telegraf.Metric diff --git a/plugins/outputs/prometheus_client/v2/collector.go b/plugins/outputs/prometheus_client/v2/collector.go index b28a4deab1cc9..5c569685de5cb 100644 --- a/plugins/outputs/prometheus_client/v2/collector.go +++ b/plugins/outputs/prometheus_client/v2/collector.go @@ -59,7 +59,7 @@ func NewCollector(expire time.Duration, stringsAsLabel bool, exportTimestamp boo } } -func (c *Collector) Describe(ch chan<- *prometheus.Desc) { +func (c *Collector) Describe(_ chan<- *prometheus.Desc) { // Sending no descriptor at all marks the Collector as "unchecked", // i.e. no checks will be performed at registration time, and the // Collector may yield any Metric it sees fit in its Collect method. diff --git a/plugins/outputs/signalfx/signalfx.go b/plugins/outputs/signalfx/signalfx.go index 87285750735c5..b5552ee0e3830 100644 --- a/plugins/outputs/signalfx/signalfx.go +++ b/plugins/outputs/signalfx/signalfx.go @@ -6,8 +6,6 @@ import ( "fmt" "strings" - "sync" - "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/outputs" "github.com/signalfx/golib/v3/datapoint" @@ -37,7 +35,6 @@ type SignalFx struct { ctx context.Context cancel context.CancelFunc - wg sync.WaitGroup } var sampleConfig = ` diff --git a/plugins/outputs/signalfx/signalfx_test.go b/plugins/outputs/signalfx/signalfx_test.go index 3c04c1ef100e2..3f081a16cbbd8 100644 --- a/plugins/outputs/signalfx/signalfx_test.go +++ b/plugins/outputs/signalfx/signalfx_test.go @@ -21,11 +21,11 @@ type sink struct { evs []*event.Event } -func (s *sink) AddDatapoints(ctx context.Context, points []*datapoint.Datapoint) error { +func (s *sink) AddDatapoints(_ context.Context, points []*datapoint.Datapoint) error { s.dps = append(s.dps, points...) return nil } -func (s *sink) AddEvents(ctx context.Context, events []*event.Event) error { +func (s *sink) AddEvents(_ context.Context, events []*event.Event) error { s.evs = append(s.evs, events...) return nil } @@ -35,10 +35,10 @@ type errorsink struct { evs []*event.Event } -func (e *errorsink) AddDatapoints(ctx context.Context, points []*datapoint.Datapoint) error { +func (e *errorsink) AddDatapoints(_ context.Context, _ []*datapoint.Datapoint) error { return errors.New("not sending datapoints") } -func (e *errorsink) AddEvents(ctx context.Context, events []*event.Event) error { +func (e *errorsink) AddEvents(_ context.Context, _ []*event.Event) error { return errors.New("not sending events") } func TestSignalFx_SignalFx(t *testing.T) { diff --git a/plugins/outputs/sumologic/sumologic.go b/plugins/outputs/sumologic/sumologic.go index da86eadfae585..22b64a8e6a114 100644 --- a/plugins/outputs/sumologic/sumologic.go +++ b/plugins/outputs/sumologic/sumologic.go @@ -3,7 +3,6 @@ package sumologic import ( "bytes" "compress/gzip" - "context" "log" "net/http" "time" @@ -139,13 +138,13 @@ func (s *SumoLogic) SetSerializer(serializer serializers.Serializer) { s.serializer = serializer } -func (s *SumoLogic) createClient(ctx context.Context) (*http.Client, error) { +func (s *SumoLogic) createClient() *http.Client { return &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, Timeout: s.Timeout.Duration, - }, nil + } } func (s *SumoLogic) Connect() error { @@ -157,12 +156,7 @@ func (s *SumoLogic) Connect() error { s.Timeout.Duration = defaultClientTimeout } - client, err := s.createClient(context.Background()) - if err != nil { - return err - } - - s.client = client + s.client = s.createClient() return nil } diff --git a/plugins/outputs/sumologic/sumologic_test.go b/plugins/outputs/sumologic/sumologic_test.go index 48450ab450f3e..d6fe2731fcd3e 100644 --- a/plugins/outputs/sumologic/sumologic_test.go +++ b/plugins/outputs/sumologic/sumologic_test.go @@ -39,7 +39,8 @@ func getMetric(t *testing.T) telegraf.Metric { return m } -func getMetrics(t *testing.T, count int) []telegraf.Metric { +func getMetrics(t *testing.T) []telegraf.Metric { + const count = 100 var metrics = make([]telegraf.Metric, count) for i := 0; i < count; i++ { @@ -450,8 +451,6 @@ func TestMaxRequestBodySize(t *testing.T) { u, err := url.Parse(fmt.Sprintf("http://%s", ts.Listener.Addr().String())) require.NoError(t, err) - const count = 100 - testcases := []struct { name string plugin func() *SumoLogic @@ -479,7 +478,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.URL = u.String() return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 1, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -494,7 +493,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 43_749 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 2, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -507,7 +506,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 10_000 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 5, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -520,7 +519,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 5_000 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 10, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -533,7 +532,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 2_500 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 20, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -546,7 +545,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 1_000 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 50, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -559,7 +558,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 500 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 100, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 @@ -572,7 +571,7 @@ func TestMaxRequestBodySize(t *testing.T) { s.MaxRequstBodySize = 300 return s }, - metrics: getMetrics(t, count), + metrics: getMetrics(t), expectedError: false, expectedRequestCount: 100, expectedMetricLinesCount: 500, // count (100) metrics, 5 lines per each (steal, idle, system, user, temp) = 500 diff --git a/plugins/outputs/warp10/warp10.go b/plugins/outputs/warp10/warp10.go index 2e601fc16f29a..1988bc6e1963f 100644 --- a/plugins/outputs/warp10/warp10.go +++ b/plugins/outputs/warp10/warp10.go @@ -214,10 +214,6 @@ func boolToString(inputBool bool) string { return strconv.FormatBool(inputBool) } -func uIntToString(inputNum uint64) string { - return strconv.FormatUint(inputNum, 10) -} - func floatToString(inputNum float64) string { return strconv.FormatFloat(inputNum, 'f', 6, 64) } diff --git a/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring_test.go b/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring_test.go index db62358777c9a..a3a7ea04d60d4 100644 --- a/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring_test.go +++ b/plugins/outputs/yandex_cloud_monitoring/yandex_cloud_monitoring_test.go @@ -14,12 +14,12 @@ import ( ) func TestWrite(t *testing.T) { - readBody := func(r *http.Request) (yandexCloudMonitoringMessage, error) { + readBody := func(r *http.Request) yandexCloudMonitoringMessage { decoder := json.NewDecoder(r.Body) var message yandexCloudMonitoringMessage err := decoder.Decode(&message) require.NoError(t, err) - return message, nil + return message } testMetadataHTTPServer := httptest.NewServer( @@ -67,8 +67,7 @@ func TestWrite(t *testing.T) { ), }, handler: func(t *testing.T, w http.ResponseWriter, r *http.Request) { - message, err := readBody(r) - require.NoError(t, err) + message := readBody(r) require.Len(t, message.Metrics, 1) require.Equal(t, "cpu", message.Metrics[0].Name) require.Equal(t, 42.0, message.Metrics[0].Value) diff --git a/plugins/parsers/csv/parser.go b/plugins/parsers/csv/parser.go index 3f370b507dc4f..9b3219a0580fb 100644 --- a/plugins/parsers/csv/parser.go +++ b/plugins/parsers/csv/parser.go @@ -80,7 +80,7 @@ func (p *Parser) SetTimeFunc(fn TimeFunc) { p.TimeFunc = fn } -func (p *Parser) compile(r io.Reader) (*csv.Reader, error) { +func (p *Parser) compile(r io.Reader) *csv.Reader { csvReader := csv.NewReader(r) // ensures that the reader reads records of different lengths without an error csvReader.FieldsPerRecord = -1 @@ -91,15 +91,12 @@ func (p *Parser) compile(r io.Reader) (*csv.Reader, error) { csvReader.Comment = []rune(p.Comment)[0] } csvReader.TrimLeadingSpace = p.TrimSpace - return csvReader, nil + return csvReader } func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) { r := bytes.NewReader(buf) - csvReader, err := p.compile(r) - if err != nil { - return nil, err - } + csvReader := p.compile(r) // skip first rows for i := 0; i < p.SkipRows; i++ { _, err := csvReader.Read() @@ -163,11 +160,7 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) { // it will also not skip any rows func (p *Parser) ParseLine(line string) (telegraf.Metric, error) { r := bytes.NewReader([]byte(line)) - csvReader, err := p.compile(r) - if err != nil { - return nil, err - } - + csvReader := p.compile(r) // if there is nothing in DataColumns, ParseLine will fail if len(p.ColumnNames) == 0 { return nil, fmt.Errorf("[parsers.csv] data columns must be specified") diff --git a/plugins/parsers/dropwizard/parser.go b/plugins/parsers/dropwizard/parser.go index 179de7dd77e37..43b8c139f3220 100644 --- a/plugins/parsers/dropwizard/parser.go +++ b/plugins/parsers/dropwizard/parser.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "log" - "strings" "time" "github.com/influxdata/telegraf" @@ -14,16 +13,12 @@ import ( "github.com/tidwall/gjson" ) -var fieldEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"") -var keyEscaper = strings.NewReplacer(" ", "\\ ", ",", "\\,", "=", "\\=") - type TimeFunc func() time.Time // Parser parses json inputs containing dropwizard metrics, // either top-level or embedded inside a json field. // This parser is using gjson for retrieving paths within the json file. type parser struct { - // an optional json path containing the metric registry object // if left empty, the whole json object is parsed as a metric registry MetricRegistryPath string diff --git a/plugins/parsers/influx/handler.go b/plugins/parsers/influx/handler.go index ae08d5a7c0870..efd7329ca9c29 100644 --- a/plugins/parsers/influx/handler.go +++ b/plugins/parsers/influx/handler.go @@ -12,7 +12,6 @@ import ( // MetricHandler implements the Handler interface and produces telegraf.Metric. type MetricHandler struct { - err error timePrecision time.Duration timeFunc TimeFunc metric telegraf.Metric diff --git a/plugins/parsers/influx/machine_test.go b/plugins/parsers/influx/machine_test.go index de5353da0c446..735b5b9114ddd 100644 --- a/plugins/parsers/influx/machine_test.go +++ b/plugins/parsers/influx/machine_test.go @@ -169,35 +169,35 @@ func (h *TestingHandler) Results() []Result { type BenchmarkingHandler struct { } -func (h *BenchmarkingHandler) SetMeasurement(name []byte) error { +func (h *BenchmarkingHandler) SetMeasurement(_ []byte) error { return nil } -func (h *BenchmarkingHandler) AddTag(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddTag(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) AddInt(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddInt(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) AddUint(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddUint(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) AddFloat(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddFloat(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) AddString(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddString(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) AddBool(key []byte, value []byte) error { +func (h *BenchmarkingHandler) AddBool(_ []byte, _ []byte) error { return nil } -func (h *BenchmarkingHandler) SetTimestamp(tm []byte) error { +func (h *BenchmarkingHandler) SetTimestamp(_ []byte) error { return nil } @@ -1832,7 +1832,7 @@ func BenchmarkMachine(b *testing.B) { } } -func TestMachineProcstat(t *testing.T) { +func TestMachineProcstat(_ *testing.T) { input := []byte("procstat,exe=bash,process_name=bash voluntary_context_switches=42i,memory_rss=5103616i,rlimit_memory_data_hard=2147483647i,cpu_time_user=0.02,rlimit_file_locks_soft=2147483647i,pid=29417i,cpu_time_nice=0,rlimit_memory_locked_soft=65536i,read_count=259i,rlimit_memory_vms_hard=2147483647i,memory_swap=0i,rlimit_num_fds_soft=1024i,rlimit_nice_priority_hard=0i,cpu_time_soft_irq=0,cpu_time=0i,rlimit_memory_locked_hard=65536i,realtime_priority=0i,signals_pending=0i,nice_priority=20i,cpu_time_idle=0,memory_stack=139264i,memory_locked=0i,rlimit_memory_stack_soft=8388608i,cpu_time_iowait=0,cpu_time_guest=0,cpu_time_guest_nice=0,rlimit_memory_data_soft=2147483647i,read_bytes=0i,rlimit_cpu_time_soft=2147483647i,involuntary_context_switches=2i,write_bytes=106496i,cpu_time_system=0,cpu_time_irq=0,cpu_usage=0,memory_vms=21659648i,memory_data=1576960i,rlimit_memory_stack_hard=2147483647i,num_threads=1i,rlimit_memory_rss_soft=2147483647i,rlimit_realtime_priority_soft=0i,num_fds=4i,write_count=35i,rlimit_signals_pending_soft=78994i,cpu_time_steal=0,rlimit_num_fds_hard=4096i,rlimit_file_locks_hard=2147483647i,rlimit_cpu_time_hard=2147483647i,rlimit_signals_pending_hard=78994i,rlimit_nice_priority_soft=0i,rlimit_memory_rss_hard=2147483647i,rlimit_memory_vms_soft=2147483647i,rlimit_realtime_priority_hard=0i 1517620624000000000") handler := &TestingHandler{} fsm := influx.NewMachine(handler) diff --git a/plugins/parsers/nagios/parser_test.go b/plugins/parsers/nagios/parser_test.go index 7f5b5937ec0c9..d269debd62ce7 100644 --- a/plugins/parsers/nagios/parser_test.go +++ b/plugins/parsers/nagios/parser_test.go @@ -65,14 +65,6 @@ func (b *metricBuilder) n(v string) *metricBuilder { return b } -func (b *metricBuilder) t(k, v string) *metricBuilder { - if b.tags == nil { - b.tags = make(map[string]string) - } - b.tags[k] = v - return b -} - func (b *metricBuilder) f(k string, v interface{}) *metricBuilder { if b.fields == nil { b.fields = make(map[string]interface{}) @@ -81,11 +73,6 @@ func (b *metricBuilder) f(k string, v interface{}) *metricBuilder { return b } -func (b *metricBuilder) ts(v time.Time) *metricBuilder { - b.timestamp = v - return b -} - func (b *metricBuilder) b() telegraf.Metric { m, err := metric.New(b.name, b.tags, b.fields, b.timestamp) if err != nil { diff --git a/plugins/parsers/prometheus/parser_test.go b/plugins/parsers/prometheus/parser_test.go index 8b8a4ad2ff7b0..f53b926bda4a5 100644 --- a/plugins/parsers/prometheus/parser_test.go +++ b/plugins/parsers/prometheus/parser_test.go @@ -24,9 +24,6 @@ cadvisor_version_info{cadvisorRevision="",cadvisorVersion="",dockerVersion="1.8. get_token_fail_count 0 ` - validUniqueLine = `# HELP get_token_fail_count Counter of failed Token() requests to the alternate token source -` - validUniqueSummary = `# HELP http_request_duration_microseconds The HTTP request latencies in microseconds. # TYPE http_request_duration_microseconds summary http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 552048.506 diff --git a/plugins/parsers/wavefront/element.go b/plugins/parsers/wavefront/element.go index 86fd166ffc8c3..4afa199663733 100644 --- a/plugins/parsers/wavefront/element.go +++ b/plugins/parsers/wavefront/element.go @@ -30,9 +30,6 @@ type LoopedParser struct { wrappedParser ElementParser wsParser *WhiteSpaceParser } -type LiteralParser struct { - literal string -} func (ep *NameParser) parse(p *PointParser, pt *Point) error { //Valid characters are: a-z, A-Z, 0-9, hyphen ("-"), underscore ("_"), dot ("."). @@ -168,7 +165,7 @@ func (ep *TagParser) parse(p *PointParser, pt *Point) error { return nil } -func (ep *WhiteSpaceParser) parse(p *PointParser, pt *Point) error { +func (ep *WhiteSpaceParser) parse(p *PointParser, _ *Point) error { tok := Ws for tok != EOF && tok == Ws { tok, _ = p.scan() @@ -184,18 +181,6 @@ func (ep *WhiteSpaceParser) parse(p *PointParser, pt *Point) error { return nil } -func (ep *LiteralParser) parse(p *PointParser, pt *Point) error { - l, err := parseLiteral(p) - if err != nil { - return err - } - - if l != ep.literal { - return fmt.Errorf("found %s, expected %s", l, ep.literal) - } - return nil -} - func parseQuotedLiteral(p *PointParser) (string, error) { p.writeBuf.Reset() diff --git a/plugins/parsers/wavefront/scanner.go b/plugins/parsers/wavefront/scanner.go index 5d22c53896762..70558e604dbb8 100644 --- a/plugins/parsers/wavefront/scanner.go +++ b/plugins/parsers/wavefront/scanner.go @@ -24,11 +24,6 @@ func (s *PointScanner) read() rune { return ch } -// unread places the previously read rune back on the reader. -func (s *PointScanner) unread() { - _ = s.r.UnreadRune() -} - // Scan returns the next token and literal value. func (s *PointScanner) Scan() (Token, string) { // Read the next rune diff --git a/plugins/processors/aws/ec2/ec2.go b/plugins/processors/aws/ec2/ec2.go index 8d22a65305ccd..7126214152a51 100644 --- a/plugins/processors/aws/ec2/ec2.go +++ b/plugins/processors/aws/ec2/ec2.go @@ -113,7 +113,7 @@ func (r *AwsEc2Processor) Description() string { return "Attach AWS EC2 metadata to metrics" } -func (r *AwsEc2Processor) Add(metric telegraf.Metric, acc telegraf.Accumulator) error { +func (r *AwsEc2Processor) Add(metric telegraf.Metric, _ telegraf.Accumulator) error { r.parallel.Enqueue(metric) return nil } diff --git a/plugins/processors/dedup/dedup_test.go b/plugins/processors/dedup/dedup_test.go index cae2bf1a529ed..b2fc9ca1fc546 100644 --- a/plugins/processors/dedup/dedup_test.go +++ b/plugins/processors/dedup/dedup_test.go @@ -11,8 +11,10 @@ import ( "github.com/influxdata/telegraf/metric" ) -func createMetric(name string, value int64, when time.Time) telegraf.Metric { - m, _ := metric.New(name, +const metricName = "m1" + +func createMetric(value int64, when time.Time) telegraf.Metric { + m, _ := metric.New(metricName, map[string]string{"tag": "tag_value"}, map[string]interface{}{"value": value}, when, @@ -70,7 +72,7 @@ func assertMetricPassed(t *testing.T, target []telegraf.Metric, source telegraf. // target is not empty require.NotEqual(t, 0, len(target)) // target has metric with proper name - require.Equal(t, "m1", target[0].Name()) + require.Equal(t, metricName, target[0].Name()) // target metric has proper field tValue, present := target[0].GetField("value") require.True(t, present) @@ -80,14 +82,14 @@ func assertMetricPassed(t *testing.T, target []telegraf.Metric, source telegraf. require.Equal(t, target[0].Time(), source.Time()) } -func assertMetricSuppressed(t *testing.T, target []telegraf.Metric, source telegraf.Metric) { +func assertMetricSuppressed(t *testing.T, target []telegraf.Metric) { // target is empty require.Equal(t, 0, len(target)) } func TestProcRetainsMetric(t *testing.T) { deduplicate := createDedup(time.Now()) - source := createMetric("m1", 1, time.Now()) + source := createMetric(1, time.Now()) target := deduplicate.Apply(source) assertCacheRefresh(t, &deduplicate, source) @@ -97,21 +99,21 @@ func TestProcRetainsMetric(t *testing.T) { func TestSuppressRepeatedValue(t *testing.T) { deduplicate := createDedup(time.Now()) // Create metric in the past - source := createMetric("m1", 1, time.Now().Add(-1*time.Second)) + source := createMetric(1, time.Now().Add(-1*time.Second)) target := deduplicate.Apply(source) - source = createMetric("m1", 1, time.Now()) + source = createMetric(1, time.Now()) target = deduplicate.Apply(source) assertCacheHit(t, &deduplicate, source) - assertMetricSuppressed(t, target, source) + assertMetricSuppressed(t, target) } func TestPassUpdatedValue(t *testing.T) { deduplicate := createDedup(time.Now()) // Create metric in the past - source := createMetric("m1", 1, time.Now().Add(-1*time.Second)) + source := createMetric(1, time.Now().Add(-1*time.Second)) target := deduplicate.Apply(source) - source = createMetric("m1", 2, time.Now()) + source = createMetric(2, time.Now()) target = deduplicate.Apply(source) assertCacheRefresh(t, &deduplicate, source) @@ -121,9 +123,9 @@ func TestPassUpdatedValue(t *testing.T) { func TestPassAfterCacheExpire(t *testing.T) { deduplicate := createDedup(time.Now()) // Create metric in the past - source := createMetric("m1", 1, time.Now().Add(-1*time.Hour)) + source := createMetric(1, time.Now().Add(-1*time.Hour)) target := deduplicate.Apply(source) - source = createMetric("m1", 1, time.Now()) + source = createMetric(1, time.Now()) target = deduplicate.Apply(source) assertCacheRefresh(t, &deduplicate, source) @@ -133,12 +135,12 @@ func TestPassAfterCacheExpire(t *testing.T) { func TestCacheRetainsMetrics(t *testing.T) { deduplicate := createDedup(time.Now()) // Create metric in the past 3sec - source := createMetric("m1", 1, time.Now().Add(-3*time.Hour)) + source := createMetric(1, time.Now().Add(-3*time.Hour)) deduplicate.Apply(source) // Create metric in the past 2sec - source = createMetric("m1", 1, time.Now().Add(-2*time.Hour)) + source = createMetric(1, time.Now().Add(-2*time.Hour)) deduplicate.Apply(source) - source = createMetric("m1", 1, time.Now()) + source = createMetric(1, time.Now()) deduplicate.Apply(source) assertCacheRefresh(t, &deduplicate, source) @@ -148,7 +150,7 @@ func TestCacheShrink(t *testing.T) { // Time offset is more than 2 * DedupInterval deduplicate := createDedup(time.Now().Add(-2 * time.Hour)) // Time offset is more than 1 * DedupInterval - source := createMetric("m1", 1, time.Now().Add(-1*time.Hour)) + source := createMetric(1, time.Now().Add(-1*time.Hour)) deduplicate.Apply(source) require.Equal(t, 0, len(deduplicate.Cache)) diff --git a/plugins/processors/execd/execd.go b/plugins/processors/execd/execd.go index 3d11bac4969fe..992452561db29 100644 --- a/plugins/processors/execd/execd.go +++ b/plugins/processors/execd/execd.go @@ -94,7 +94,7 @@ func (e *Execd) Start(acc telegraf.Accumulator) error { return nil } -func (e *Execd) Add(m telegraf.Metric, acc telegraf.Accumulator) error { +func (e *Execd) Add(m telegraf.Metric, _ telegraf.Accumulator) error { b, err := e.serializer.Serialize(m) if err != nil { return fmt.Errorf("metric serializing error: %w", err) diff --git a/plugins/processors/ifname/ifname.go b/plugins/processors/ifname/ifname.go index d6c696b75bcf1..10cf38a3cec8a 100644 --- a/plugins/processors/ifname/ifname.go +++ b/plugins/processors/ifname/ifname.go @@ -226,7 +226,7 @@ func (d *IfName) Start(acc telegraf.Accumulator) error { return nil } -func (d *IfName) Add(metric telegraf.Metric, acc telegraf.Accumulator) error { +func (d *IfName) Add(metric telegraf.Metric, _ telegraf.Accumulator) error { d.parallel.Enqueue(metric) return nil } diff --git a/plugins/processors/reverse_dns/rdnscache_test.go b/plugins/processors/reverse_dns/rdnscache_test.go index e8466c27fd315..97cc8abdbdff8 100644 --- a/plugins/processors/reverse_dns/rdnscache_test.go +++ b/plugins/processors/reverse_dns/rdnscache_test.go @@ -125,12 +125,12 @@ func TestLookupTimeout(t *testing.T) { type timeoutResolver struct{} -func (r *timeoutResolver) LookupAddr(ctx context.Context, addr string) (names []string, err error) { +func (r *timeoutResolver) LookupAddr(_ context.Context, _ string) (names []string, err error) { return nil, errors.New("timeout") } type localResolver struct{} -func (r *localResolver) LookupAddr(ctx context.Context, addr string) (names []string, err error) { +func (r *localResolver) LookupAddr(_ context.Context, _ string) (names []string, err error) { return []string{"localhost"}, nil } diff --git a/plugins/processors/reverse_dns/reversedns.go b/plugins/processors/reverse_dns/reversedns.go index 616294fc5e54d..966748420bc8d 100644 --- a/plugins/processors/reverse_dns/reversedns.go +++ b/plugins/processors/reverse_dns/reversedns.go @@ -104,7 +104,7 @@ func (r *ReverseDNS) Stop() error { return nil } -func (r *ReverseDNS) Add(metric telegraf.Metric, acc telegraf.Accumulator) error { +func (r *ReverseDNS) Add(metric telegraf.Metric, _ telegraf.Accumulator) error { r.parallel.Enqueue(metric) return nil } diff --git a/plugins/processors/starlark/builtins.go b/plugins/processors/starlark/builtins.go index 53e31fb3a988c..8537c92f34953 100644 --- a/plugins/processors/starlark/builtins.go +++ b/plugins/processors/starlark/builtins.go @@ -9,7 +9,7 @@ import ( "go.starlark.net/starlark" ) -func newMetric(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { +func newMetric(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var name starlark.String if err := starlark.UnpackPositionalArgs("Metric", args, kwargs, 1, &name); err != nil { return nil, err @@ -23,7 +23,7 @@ func newMetric(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple return &Metric{metric: m}, nil } -func deepcopy(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { +func deepcopy(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { var sm *Metric if err := starlark.UnpackPositionalArgs("deepcopy", args, kwargs, 1, &sm); err != nil { return nil, err @@ -71,12 +71,6 @@ func builtinAttrNames(methods map[string]builtinMethod) []string { return names } -// nameErr returns an error message of the form "name: msg" -// where name is b.Name() and msg is a string or error. -func nameErr(b *starlark.Builtin, msg interface{}) error { - return fmt.Errorf("%s: %v", b.Name(), msg) -} - // --- dictionary methods --- // https://github.com/google/starlark-go/blob/master/doc/spec.md#dict·clear diff --git a/plugins/processors/starlark/logging.go b/plugins/processors/starlark/logging.go index 35ba65d1db80f..35efa6a7effba 100644 --- a/plugins/processors/starlark/logging.go +++ b/plugins/processors/starlark/logging.go @@ -12,7 +12,7 @@ import ( // Builds a module that defines all the supported logging functions which will log using the provided logger func LogModule(logger telegraf.Logger) *starlarkstruct.Module { var logFunc = func(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { - return log(t, b, args, kwargs, logger) + return log(b, args, kwargs, logger) } return &starlarkstruct.Module{ Name: "log", @@ -26,7 +26,7 @@ func LogModule(logger telegraf.Logger) *starlarkstruct.Module { } // Logs the provided message according to the level chosen -func log(t *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple, logger telegraf.Logger) (starlark.Value, error) { +func log(b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple, logger telegraf.Logger) (starlark.Value, error) { var msg starlark.String if err := starlark.UnpackPositionalArgs(b.Name(), args, kwargs, 1, &msg); err != nil { return starlark.None, fmt.Errorf("%s: %v", b.Name(), err) diff --git a/plugins/processors/starlark/starlark.go b/plugins/processors/starlark/starlark.go index 64666398d2e50..ffd13680f88e5 100644 --- a/plugins/processors/starlark/starlark.go +++ b/plugins/processors/starlark/starlark.go @@ -61,7 +61,7 @@ func (s *Starlark) Init() error { s.thread = &starlark.Thread{ Print: func(_ *starlark.Thread, msg string) { s.Log.Debug(msg) }, Load: func(thread *starlark.Thread, module string) (starlark.StringDict, error) { - return loadFunc(thread, module, s.Log) + return loadFunc(module, s.Log) }, } @@ -136,7 +136,7 @@ func (s *Starlark) Description() string { return description } -func (s *Starlark) Start(acc telegraf.Accumulator) error { +func (s *Starlark) Start(_ telegraf.Accumulator) error { return nil } @@ -242,7 +242,7 @@ func init() { }) } -func loadFunc(thread *starlark.Thread, module string, logger telegraf.Logger) (starlark.StringDict, error) { +func loadFunc(module string, logger telegraf.Logger) (starlark.StringDict, error) { switch module { case "json.star": return starlark.StringDict{ diff --git a/plugins/processors/topk/topk_test.go b/plugins/processors/topk/topk_test.go index 858859de6261b..79c6b81db4f38 100644 --- a/plugins/processors/topk/topk_test.go +++ b/plugins/processors/topk/topk_test.go @@ -9,6 +9,8 @@ import ( "github.com/influxdata/telegraf/testutil" ) +var oneSecondDuration = internal.Duration{Duration: time.Second} + // Key, value pair that represents a telegraf.Metric Field type field struct { key string @@ -117,10 +119,6 @@ func equalSets(l1 []telegraf.Metric, l2 []telegraf.Metric) bool { return subSet(l1, l2) && subSet(l2, l1) } -func createDuration(t int) internal.Duration { - return internal.Duration{Duration: time.Second * time.Duration(t)} -} - func runAndCompare(topk *TopK, metrics []telegraf.Metric, answer []telegraf.Metric, testID string, t *testing.T) { // Sleep for `period`, otherwise the processor will only // cache the metrics, but it will not process them @@ -142,7 +140,7 @@ func TestTopkAggregatorsSmokeTests(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.Fields = []string{"a"} topk.GroupBy = []string{"tag_name"} @@ -164,7 +162,7 @@ func TestTopkMeanAddAggregateFields(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.Aggregation = "mean" topk.AddAggregateFields = []string{"a"} topk.Fields = []string{"a"} @@ -193,7 +191,7 @@ func TestTopkSumAddAggregateFields(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.Aggregation = "sum" topk.AddAggregateFields = []string{"a"} topk.Fields = []string{"a"} @@ -222,7 +220,7 @@ func TestTopkMaxAddAggregateFields(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.Aggregation = "max" topk.AddAggregateFields = []string{"a"} topk.Fields = []string{"a"} @@ -251,7 +249,7 @@ func TestTopkMinAddAggregateFields(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.Aggregation = "min" topk.AddAggregateFields = []string{"a"} topk.Fields = []string{"a"} @@ -280,7 +278,7 @@ func TestTopkGroupby1(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 3 topk.Aggregation = "sum" topk.AddAggregateFields = []string{"value"} @@ -305,7 +303,7 @@ func TestTopkGroupby2(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 3 topk.Aggregation = "mean" topk.AddAggregateFields = []string{"value"} @@ -334,7 +332,7 @@ func TestTopkGroupby3(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 1 topk.Aggregation = "min" topk.AddAggregateFields = []string{"value"} @@ -360,7 +358,7 @@ func TestTopkGroupbyFields1(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 4 // This settings generate less than 3 groups topk.Aggregation = "mean" topk.AddAggregateFields = []string{"A"} @@ -387,7 +385,7 @@ func TestTopkGroupbyFields2(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 2 topk.Aggregation = "sum" topk.AddAggregateFields = []string{"B", "C"} @@ -415,7 +413,7 @@ func TestTopkGroupbyMetricName1(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 1 topk.Aggregation = "sum" topk.AddAggregateFields = []string{"value"} @@ -441,7 +439,7 @@ func TestTopkGroupbyMetricName2(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 2 topk.Aggregation = "sum" topk.AddAggregateFields = []string{"A", "value"} @@ -469,7 +467,7 @@ func TestTopkBottomk(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 3 topk.Aggregation = "sum" topk.GroupBy = []string{"tag1", "tag3"} @@ -495,7 +493,7 @@ func TestTopkGroupByKeyTag(t *testing.T) { // Build the processor var topk TopK topk = *New() - topk.Period = createDuration(1) + topk.Period = oneSecondDuration topk.K = 3 topk.Aggregation = "sum" topk.GroupBy = []string{"tag1", "tag3"} diff --git a/plugins/serializers/splunkmetric/splunkmetric.go b/plugins/serializers/splunkmetric/splunkmetric.go index f3a3ecebc5c1c..fc9ffe61ecfe4 100644 --- a/plugins/serializers/splunkmetric/splunkmetric.go +++ b/plugins/serializers/splunkmetric/splunkmetric.go @@ -2,7 +2,6 @@ package splunkmetric import ( "encoding/json" - "fmt" "log" "github.com/influxdata/telegraf" @@ -40,22 +39,15 @@ func NewSerializer(splunkmetricHecRouting bool, splunkmetricMultimetric bool) (* } func (s *serializer) Serialize(metric telegraf.Metric) ([]byte, error) { - m, err := s.createObject(metric) - if err != nil { - return nil, fmt.Errorf("D! [serializer.splunkmetric] Dropping invalid metric: %s", metric.Name()) - } - - return m, nil + return s.createObject(metric), nil } func (s *serializer) SerializeBatch(metrics []telegraf.Metric) ([]byte, error) { var serialized []byte for _, metric := range metrics { - m, err := s.createObject(metric) - if err != nil { - return nil, fmt.Errorf("D! [serializer.splunkmetric] Dropping invalid metric: %s", metric.Name()) - } else if m != nil { + m := s.createObject(metric) + if m != nil { serialized = append(serialized, m...) } } @@ -157,7 +149,7 @@ func (s *serializer) createSingle(metric telegraf.Metric, dataGroup HECTimeSerie return metricGroup, nil } -func (s *serializer) createObject(metric telegraf.Metric) (metricGroup []byte, err error) { +func (s *serializer) createObject(metric telegraf.Metric) (metricGroup []byte) { /* Splunk supports one metric json object, and does _not_ support an array of JSON objects. ** Splunk has the following required names for the metric store: ** metric_name: The name of the metric @@ -194,7 +186,7 @@ func (s *serializer) createObject(metric telegraf.Metric) (metricGroup []byte, e } // Return the metric group regardless of if it's multimetric or single metric. - return metricGroup, nil + return metricGroup } func verifyValue(v interface{}) (value interface{}, valid bool) { diff --git a/plugins/serializers/wavefront/wavefront.go b/plugins/serializers/wavefront/wavefront.go index 2538d402298de..0abcf799d2a0f 100755 --- a/plugins/serializers/wavefront/wavefront.go +++ b/plugins/serializers/wavefront/wavefront.go @@ -49,7 +49,7 @@ func NewSerializer(prefix string, useStrict bool, sourceOverride []string) (*Wav return s, nil } -func (s *WavefrontSerializer) serialize(buf *buffer, m telegraf.Metric) { +func (s *WavefrontSerializer) serialize(m telegraf.Metric) { const metricSeparator = "." for fieldName, value := range m.Fields() { @@ -90,7 +90,7 @@ func (s *WavefrontSerializer) serialize(buf *buffer, m telegraf.Metric) { func (s *WavefrontSerializer) Serialize(m telegraf.Metric) ([]byte, error) { s.mu.Lock() s.scratch.Reset() - s.serialize(&s.scratch, m) + s.serialize(m) out := s.scratch.Copy() s.mu.Unlock() return out, nil @@ -100,7 +100,7 @@ func (s *WavefrontSerializer) SerializeBatch(metrics []telegraf.Metric) ([]byte, s.mu.Lock() s.scratch.Reset() for _, m := range metrics { - s.serialize(&s.scratch, m) + s.serialize(m) } out := s.scratch.Copy() s.mu.Unlock() diff --git a/selfstat/stat.go b/selfstat/stat.go index e1905baf57878..4ca12a0557dce 100644 --- a/selfstat/stat.go +++ b/selfstat/stat.go @@ -9,7 +9,6 @@ type stat struct { measurement string field string tags map[string]string - key uint64 } func (s *stat) Incr(v int64) { diff --git a/selfstat/timingStat.go b/selfstat/timingStat.go index 13f8400bc7a48..e6184dc05c582 100644 --- a/selfstat/timingStat.go +++ b/selfstat/timingStat.go @@ -8,7 +8,6 @@ type timingStat struct { measurement string field string tags map[string]string - key uint64 v int64 prev int64 count int64 diff --git a/testutil/accumulator.go b/testutil/accumulator.go index c09857d15f3e2..baf09f60f1234 100644 --- a/testutil/accumulator.go +++ b/testutil/accumulator.go @@ -196,7 +196,7 @@ func (a *Accumulator) AddMetric(m telegraf.Metric) { a.addFields(m.Name(), m.Tags(), m.Fields(), m.Type(), m.Time()) } -func (a *Accumulator) WithTracking(maxTracked int) telegraf.TrackingAccumulator { +func (a *Accumulator) WithTracking(_ int) telegraf.TrackingAccumulator { return a } @@ -234,7 +234,7 @@ func (a *Accumulator) AddError(err error) { a.Unlock() } -func (a *Accumulator) SetPrecision(precision time.Duration) { +func (a *Accumulator) SetPrecision(_ time.Duration) { return } @@ -728,17 +728,17 @@ func (a *Accumulator) BoolField(measurement string, field string) (bool, bool) { // telegraf accumulator machinery. type NopAccumulator struct{} -func (n *NopAccumulator) AddFields(measurement string, fields map[string]interface{}, tags map[string]string, t ...time.Time) { +func (n *NopAccumulator) AddFields(_ string, _ map[string]interface{}, _ map[string]string, _ ...time.Time) { } -func (n *NopAccumulator) AddGauge(measurement string, fields map[string]interface{}, tags map[string]string, t ...time.Time) { +func (n *NopAccumulator) AddGauge(_ string, _ map[string]interface{}, _ map[string]string, _ ...time.Time) { } -func (n *NopAccumulator) AddCounter(measurement string, fields map[string]interface{}, tags map[string]string, t ...time.Time) { +func (n *NopAccumulator) AddCounter(_ string, _ map[string]interface{}, _ map[string]string, _ ...time.Time) { } -func (n *NopAccumulator) AddSummary(measurement string, fields map[string]interface{}, tags map[string]string, t ...time.Time) { +func (n *NopAccumulator) AddSummary(_ string, _ map[string]interface{}, _ map[string]string, _ ...time.Time) { } -func (n *NopAccumulator) AddHistogram(measurement string, fields map[string]interface{}, tags map[string]string, t ...time.Time) { +func (n *NopAccumulator) AddHistogram(_ string, _ map[string]interface{}, _ map[string]string, _ ...time.Time) { } -func (n *NopAccumulator) AddMetric(telegraf.Metric) {} -func (n *NopAccumulator) SetPrecision(precision time.Duration) {} -func (n *NopAccumulator) AddError(err error) {} -func (n *NopAccumulator) WithTracking(maxTracked int) telegraf.TrackingAccumulator { return nil } +func (n *NopAccumulator) AddMetric(telegraf.Metric) {} +func (n *NopAccumulator) SetPrecision(_ time.Duration) {} +func (n *NopAccumulator) AddError(_ error) {} +func (n *NopAccumulator) WithTracking(_ int) telegraf.TrackingAccumulator { return nil }