diff --git a/plugins/processors/aws/ec2/ec2.go b/plugins/processors/aws/ec2/ec2.go index 088ec09c8..012cad92d 100644 --- a/plugins/processors/aws/ec2/ec2.go +++ b/plugins/processors/aws/ec2/ec2.go @@ -26,13 +26,13 @@ type AwsEc2Processor struct { Timeout config.Duration `toml:"timeout"` Ordered bool `toml:"ordered"` MaxParallelCalls int `toml:"max_parallel_calls"` + Log telegraf.Logger `toml:"-"` - Log telegraf.Logger `toml:"-"` - imdsClient *imds.Client `toml:"-"` - imdsTags map[string]struct{} `toml:"-"` - ec2Client *ec2.Client `toml:"-"` - parallel parallel.Parallel `toml:"-"` - instanceID string `toml:"-"` + imdsClient *imds.Client + imdsTagsMap map[string]struct{} + ec2Client *ec2.Client + parallel parallel.Parallel + instanceID string } const sampleConfig = ` @@ -128,9 +128,9 @@ func (r *AwsEc2Processor) Init() error { if len(tag) == 0 || !isImdsTagAllowed(tag) { return fmt.Errorf("not allowed metadata tag specified in configuration: %s", tag) } - r.imdsTags[tag] = struct{}{} + r.imdsTagsMap[tag] = struct{}{} } - if len(r.imdsTags) == 0 && len(r.EC2Tags) == 0 { + if len(r.imdsTagsMap) == 0 && len(r.EC2Tags) == 0 { return errors.New("no allowed metadata tags specified in configuration") } @@ -186,7 +186,7 @@ func (r *AwsEc2Processor) Start(acc telegraf.Accumulator) error { func (r *AwsEc2Processor) Stop() error { if r.parallel == nil { - return errors.New("Trying to stop unstarted AWS EC2 Processor") + return errors.New("trying to stop unstarted AWS EC2 Processor") } r.parallel.Stop() return nil @@ -197,7 +197,7 @@ func (r *AwsEc2Processor) asyncAdd(metric telegraf.Metric) []telegraf.Metric { defer cancel() // Add IMDS Instance Identity Document tags. - if len(r.imdsTags) > 0 { + if len(r.imdsTagsMap) > 0 { iido, err := r.imdsClient.GetInstanceIdentityDocument( ctx, &imds.GetInstanceIdentityDocumentInput{}, @@ -207,7 +207,7 @@ func (r *AwsEc2Processor) asyncAdd(metric telegraf.Metric) []telegraf.Metric { return []telegraf.Metric{metric} } - for tag := range r.imdsTags { + for tag := range r.imdsTagsMap { if v := getTagFromInstanceIdentityDocument(iido, tag); v != "" { metric.AddTag(tag, v) } @@ -244,7 +244,7 @@ func newAwsEc2Processor() *AwsEc2Processor { return &AwsEc2Processor{ MaxParallelCalls: DefaultMaxParallelCalls, Timeout: config.Duration(DefaultTimeout), - imdsTags: make(map[string]struct{}), + imdsTagsMap: make(map[string]struct{}), } } diff --git a/plugins/processors/clone/clone_test.go b/plugins/processors/clone/clone_test.go index 20bec925e..1ef85f6e9 100644 --- a/plugins/processors/clone/clone_test.go +++ b/plugins/processors/clone/clone_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/stretchr/testify/assert" ) func createTestMetric() telegraf.Metric { @@ -18,8 +19,8 @@ func createTestMetric() telegraf.Metric { return m } -func calculateProcessedTags(processor Clone, metric telegraf.Metric) map[string]string { - processed := processor.Apply(metric) +func calculateProcessedTags(processor Clone, m telegraf.Metric) map[string]string { + processed := processor.Apply(m) return processed[0].Tags() } @@ -29,8 +30,8 @@ func TestRetainsTags(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["metric_tag"] - assert.True(t, present, "Tag of metric was not present") - assert.Equal(t, "from_metric", value, "Value of Tag was changed") + require.True(t, present, "Tag of metric was not present") + require.Equal(t, "from_metric", value, "Value of Tag was changed") } func TestAddTags(t *testing.T) { @@ -39,9 +40,9 @@ func TestAddTags(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["added_tag"] - assert.True(t, present, "Additional Tag of metric was not present") - assert.Equal(t, "from_config", value, "Value of Tag was changed") - assert.Equal(t, 3, len(tags), "Should have one previous and two added tags.") + require.True(t, present, "Additional Tag of metric was not present") + require.Equal(t, "from_config", value, "Value of Tag was changed") + require.Equal(t, 3, len(tags), "Should have one previous and two added tags.") } func TestOverwritesPresentTagValues(t *testing.T) { @@ -50,9 +51,9 @@ func TestOverwritesPresentTagValues(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["metric_tag"] - assert.True(t, present, "Tag of metric was not present") - assert.Equal(t, 1, len(tags), "Should only have one tag.") - assert.Equal(t, "from_config", value, "Value of Tag was not changed") + require.True(t, present, "Tag of metric was not present") + require.Equal(t, 1, len(tags), "Should only have one tag.") + require.Equal(t, "from_config", value, "Value of Tag was not changed") } func TestOverridesName(t *testing.T) { @@ -60,8 +61,8 @@ func TestOverridesName(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") - assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") + require.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") + require.Equal(t, "m1", processed[1].Name(), "Original metric was modified") } func TestNamePrefix(t *testing.T) { @@ -69,8 +70,8 @@ func TestNamePrefix(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") - assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") + require.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") + require.Equal(t, "m1", processed[1].Name(), "Original metric was modified") } func TestNameSuffix(t *testing.T) { @@ -78,6 +79,6 @@ func TestNameSuffix(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") - assert.Equal(t, "m1", processed[1].Name(), "Original metric was modified") + require.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") + require.Equal(t, "m1", processed[1].Name(), "Original metric was modified") } diff --git a/plugins/processors/converter/converter.go b/plugins/processors/converter/converter.go index fd56cc4d9..042b7d8f2 100644 --- a/plugins/processors/converter/converter.go +++ b/plugins/processors/converter/converter.go @@ -328,7 +328,7 @@ func (p *Converter) convertFields(metric telegraf.Metric) { } } -func toBool(v interface{}) (bool, bool) { +func toBool(v interface{}) (val bool, ok bool) { switch value := v.(type) { case int64: return value != 0, true diff --git a/plugins/processors/date/date_test.go b/plugins/processors/date/date_test.go index aa7efc64e..83df86b3e 100644 --- a/plugins/processors/date/date_test.go +++ b/plugins/processors/date/date_test.go @@ -4,12 +4,12 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric { @@ -53,9 +53,9 @@ func TestMonthTag(t *testing.T) { m2 := MustMetric("bar", nil, nil, currentTime) m3 := MustMetric("baz", nil, nil, currentTime) monthApply := dateFormatMonth.Apply(m1, m2, m3) - assert.Equal(t, map[string]string{"month": month}, monthApply[0].Tags(), "should add tag 'month'") - assert.Equal(t, map[string]string{"month": month}, monthApply[1].Tags(), "should add tag 'month'") - assert.Equal(t, map[string]string{"month": month}, monthApply[2].Tags(), "should add tag 'month'") + require.Equal(t, map[string]string{"month": month}, monthApply[0].Tags(), "should add tag 'month'") + require.Equal(t, map[string]string{"month": month}, monthApply[1].Tags(), "should add tag 'month'") + require.Equal(t, map[string]string{"month": month}, monthApply[2].Tags(), "should add tag 'month'") } func TestMonthField(t *testing.T) { @@ -74,9 +74,9 @@ func TestMonthField(t *testing.T) { m2 := MustMetric("bar", nil, nil, currentTime) m3 := MustMetric("baz", nil, nil, currentTime) monthApply := dateFormatMonth.Apply(m1, m2, m3) - assert.Equal(t, map[string]interface{}{"month": month}, monthApply[0].Fields(), "should add field 'month'") - assert.Equal(t, map[string]interface{}{"month": month}, monthApply[1].Fields(), "should add field 'month'") - assert.Equal(t, map[string]interface{}{"month": month}, monthApply[2].Fields(), "should add field 'month'") + require.Equal(t, map[string]interface{}{"month": month}, monthApply[0].Fields(), "should add field 'month'") + require.Equal(t, map[string]interface{}{"month": month}, monthApply[1].Fields(), "should add field 'month'") + require.Equal(t, map[string]interface{}{"month": month}, monthApply[2].Fields(), "should add field 'month'") } func TestOldDateTag(t *testing.T) { @@ -90,7 +90,7 @@ func TestOldDateTag(t *testing.T) { m7 := MustMetric("foo", nil, nil, time.Date(1993, 05, 27, 0, 0, 0, 0, time.UTC)) customDateApply := dateFormatYear.Apply(m7) - assert.Equal(t, map[string]string{"year": "1993"}, customDateApply[0].Tags(), "should add tag 'year'") + require.Equal(t, map[string]string{"year": "1993"}, customDateApply[0].Tags(), "should add tag 'year'") } func TestFieldUnix(t *testing.T) { @@ -107,7 +107,7 @@ func TestFieldUnix(t *testing.T) { m8 := MustMetric("foo", nil, nil, currentTime) unixApply := dateFormatUnix.Apply(m8) - assert.Equal(t, map[string]interface{}{"unix": unixTime}, unixApply[0].Fields(), "should add unix time in s as field 'unix'") + require.Equal(t, map[string]interface{}{"unix": unixTime}, unixApply[0].Fields(), "should add unix time in s as field 'unix'") } func TestFieldUnixNano(t *testing.T) { @@ -124,7 +124,7 @@ func TestFieldUnixNano(t *testing.T) { m9 := MustMetric("foo", nil, nil, currentTime) unixNanoApply := dateFormatUnixNano.Apply(m9) - assert.Equal(t, map[string]interface{}{"unix_ns": unixNanoTime}, unixNanoApply[0].Fields(), "should add unix time in ns as field 'unix_ns'") + require.Equal(t, map[string]interface{}{"unix_ns": unixNanoTime}, unixNanoApply[0].Fields(), "should add unix time in ns as field 'unix_ns'") } func TestFieldUnixMillis(t *testing.T) { @@ -141,7 +141,7 @@ func TestFieldUnixMillis(t *testing.T) { m10 := MustMetric("foo", nil, nil, currentTime) unixMillisApply := dateFormatUnixMillis.Apply(m10) - assert.Equal(t, map[string]interface{}{"unix_ms": unixMillisTime}, unixMillisApply[0].Fields(), "should add unix time in ms as field 'unix_ms'") + require.Equal(t, map[string]interface{}{"unix_ms": unixMillisTime}, unixMillisApply[0].Fields(), "should add unix time in ms as field 'unix_ms'") } func TestFieldUnixMicros(t *testing.T) { @@ -158,7 +158,7 @@ func TestFieldUnixMicros(t *testing.T) { m11 := MustMetric("foo", nil, nil, currentTime) unixMicrosApply := dateFormatUnixMicros.Apply(m11) - assert.Equal(t, map[string]interface{}{"unix_us": unixMicrosTime}, unixMicrosApply[0].Fields(), "should add unix time in us as field 'unix_us'") + require.Equal(t, map[string]interface{}{"unix_us": unixMicrosTime}, unixMicrosApply[0].Fields(), "should add unix time in us as field 'unix_us'") } func TestDateOffset(t *testing.T) { @@ -171,7 +171,7 @@ func TestDateOffset(t *testing.T) { err := plugin.Init() require.NoError(t, err) - metric := testutil.MustMetric( + m := testutil.MustMetric( "cpu", map[string]string{}, map[string]interface{}{ @@ -193,6 +193,6 @@ func TestDateOffset(t *testing.T) { ), } - actual := plugin.Apply(metric) + actual := plugin.Apply(m) testutil.RequireMetricsEqual(t, expected, actual) } diff --git a/plugins/processors/dedup/dedup_test.go b/plugins/processors/dedup/dedup_test.go index 4f3d10934..d5cc83192 100644 --- a/plugins/processors/dedup/dedup_test.go +++ b/plugins/processors/dedup/dedup_test.go @@ -77,6 +77,7 @@ func assertMetricPassed(t *testing.T, target []telegraf.Metric, source telegraf. tValue, present := target[0].GetField("value") require.True(t, present) sValue, present := source.GetField("value") + require.True(t, present) require.Equal(t, tValue, sValue) // target metric has proper timestamp require.Equal(t, target[0].Time(), source.Time()) @@ -100,9 +101,9 @@ func TestSuppressRepeatedValue(t *testing.T) { deduplicate := createDedup(time.Now()) // Create metric in the past source := createMetric(1, time.Now().Add(-1*time.Second)) - target := deduplicate.Apply(source) + _ = deduplicate.Apply(source) source = createMetric(1, time.Now()) - target = deduplicate.Apply(source) + target := deduplicate.Apply(source) assertCacheHit(t, &deduplicate, source) assertMetricSuppressed(t, target) @@ -113,9 +114,10 @@ func TestPassUpdatedValue(t *testing.T) { // Create metric in the past source := createMetric(1, time.Now().Add(-1*time.Second)) target := deduplicate.Apply(source) + assertMetricPassed(t, target, source) + source = createMetric(2, time.Now()) target = deduplicate.Apply(source) - assertCacheRefresh(t, &deduplicate, source) assertMetricPassed(t, target, source) } @@ -125,9 +127,10 @@ func TestPassAfterCacheExpire(t *testing.T) { // Create metric in the past source := createMetric(1, time.Now().Add(-1*time.Hour)) target := deduplicate.Apply(source) + assertMetricPassed(t, target, source) + source = createMetric(1, time.Now()) target = deduplicate.Apply(source) - assertCacheRefresh(t, &deduplicate, source) assertMetricPassed(t, target, source) } diff --git a/plugins/processors/defaults/defaults.go b/plugins/processors/defaults/defaults.go index eaffdf81a..5d6522fad 100644 --- a/plugins/processors/defaults/defaults.go +++ b/plugins/processors/defaults/defaults.go @@ -1,9 +1,10 @@ package defaults import ( + "strings" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/processors" - "strings" ) const sampleConfig = ` @@ -58,10 +59,10 @@ func (def *Defaults) Apply(inputMetrics ...telegraf.Metric) []telegraf.Metric { } func maybeTrimmedString(v interface{}) (string, bool) { - switch value := v.(type) { - case string: + if value, ok := v.(string); ok { return strings.TrimSpace(value), true } + return "", false } diff --git a/plugins/processors/defaults/defaults_test.go b/plugins/processors/defaults/defaults_test.go index c0e930fc6..5d6808f4f 100644 --- a/plugins/processors/defaults/defaults_test.go +++ b/plugins/processors/defaults/defaults_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" ) func TestDefaults(t *testing.T) { @@ -124,7 +125,7 @@ func TestDefaults(t *testing.T) { defaults := scenario.defaults resultMetrics := defaults.Apply(scenario.input) - assert.Len(t, resultMetrics, 1) + require.Len(t, resultMetrics, 1) testutil.RequireMetricsEqual(t, scenario.expected, resultMetrics) }) } diff --git a/plugins/processors/enum/enum_test.go b/plugins/processors/enum/enum_test.go index 53603ae01..4addf32b0 100644 --- a/plugins/processors/enum/enum_test.go +++ b/plugins/processors/enum/enum_test.go @@ -4,10 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func createTestMetric() telegraf.Metric { @@ -19,7 +19,7 @@ func createTestMetric() telegraf.Metric { map[string]interface{}{ "string_value": "test", "duplicate_string_value": "test", - "int_value": int(200), + "int_value": 200, "uint_value": uint(500), "float_value": float64(3.14), "true_value": true, @@ -29,26 +29,26 @@ func createTestMetric() telegraf.Metric { return m } -func calculateProcessedValues(mapper EnumMapper, metric telegraf.Metric) map[string]interface{} { - processed := mapper.Apply(metric) +func calculateProcessedValues(mapper EnumMapper, m telegraf.Metric) map[string]interface{} { + processed := mapper.Apply(m) return processed[0].Fields() } -func calculateProcessedTags(mapper EnumMapper, metric telegraf.Metric) map[string]string { - processed := mapper.Apply(metric) +func calculateProcessedTags(mapper EnumMapper, m telegraf.Metric) map[string]string { + processed := mapper.Apply(m) return processed[0].Tags() } func assertFieldValue(t *testing.T, expected interface{}, field string, fields map[string]interface{}) { value, present := fields[field] - assert.True(t, present, "value of field '"+field+"' was not present") - assert.EqualValues(t, expected, value) + require.True(t, present, "value of field '"+field+"' was not present") + require.EqualValues(t, expected, value) } func assertTagValue(t *testing.T, expected interface{}, tag string, tags map[string]string) { value, present := tags[tag] - assert.True(t, present, "value of tag '"+tag+"' was not present") - assert.EqualValues(t, expected, value) + require.True(t, present, "value of tag '"+tag+"' was not present") + require.EqualValues(t, expected, value) } func TestRetainsMetric(t *testing.T) { @@ -65,9 +65,9 @@ func TestRetainsMetric(t *testing.T) { assertFieldValue(t, 500, "uint_value", fields) assertFieldValue(t, float64(3.14), "float_value", fields) assertFieldValue(t, true, "true_value", fields) - assert.Equal(t, "m1", target.Name()) - assert.Equal(t, source.Tags(), target.Tags()) - assert.Equal(t, source.Time(), target.Time()) + require.Equal(t, "m1", target.Name()) + require.Equal(t, source.Tags(), target.Tags()) + require.Equal(t, source.Time(), target.Time()) } func TestMapsSingleStringValueTag(t *testing.T) { @@ -118,7 +118,7 @@ func TestMappings(t *testing.T) { for index := range mapping["target_value"] { mapper := EnumMapper{Mappings: []Mapping{{Field: fieldName, ValueMappings: map[string]interface{}{mapping["target_value"][index].(string): mapping["mapped_value"][index]}}}} err := mapper.Init() - assert.Nil(t, err) + require.Nil(t, err) fields := calculateProcessedValues(mapper, createTestMetric()) assertFieldValue(t, mapping["expected_value"][index], fieldName, fields) } @@ -171,7 +171,7 @@ func TestDoNotWriteToDestinationWithoutDefaultOrDefinedMapping(t *testing.T) { assertFieldValue(t, "test", "string_value", fields) _, present := fields[field] - assert.False(t, present, "value of field '"+field+"' was present") + require.False(t, present, "value of field '"+field+"' was present") } func TestFieldGlobMatching(t *testing.T) { diff --git a/plugins/processors/execd/execd_test.go b/plugins/processors/execd/execd_test.go index c226725e1..26af72013 100644 --- a/plugins/processors/execd/execd_test.go +++ b/plugins/processors/execd/execd_test.go @@ -7,13 +7,13 @@ import ( "testing" "time" - "github.com/influxdata/telegraf" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf/config" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/parsers/influx" "github.com/influxdata/telegraf/plugins/serializers" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" ) func TestExternalProcessorWorks(t *testing.T) { @@ -32,7 +32,6 @@ func TestExternalProcessorWorks(t *testing.T) { now := time.Now() orig := now - metrics := []telegraf.Metric{} for i := 0; i < 10; i++ { m := metric.New("test", map[string]string{ @@ -43,17 +42,16 @@ func TestExternalProcessorWorks(t *testing.T) { "count": 1, }, now) - metrics = append(metrics, m) now = now.Add(1) - e.Add(m, acc) + require.NoError(t, e.Add(m, acc)) } acc.Wait(1) require.NoError(t, e.Stop()) acc.Wait(9) - metrics = acc.GetTelegrafMetrics() + metrics := acc.GetTelegrafMetrics() m := metrics[0] expected := testutil.MustMetric("test", @@ -105,7 +103,7 @@ func TestParseLinesWithNewLines(t *testing.T) { }, now) - e.Add(m, acc) + require.NoError(t, e.Add(m, acc)) acc.Wait(1) require.NoError(t, e.Stop()) @@ -144,40 +142,51 @@ func runCountMultiplierProgram() { serializer, _ := serializers.NewInfluxSerializer() for { - metric, err := parser.Next() + m, err := parser.Next() if err != nil { if err == influx.EOF { return // stream ended } if parseErr, isParseError := err.(*influx.ParseError); isParseError { + //nolint:errcheck,revive // Test will fail anyway fmt.Fprintf(os.Stderr, "parse ERR %v\n", parseErr) + //nolint:revive // os.Exit called intentionally os.Exit(1) } + //nolint:errcheck,revive // Test will fail anyway fmt.Fprintf(os.Stderr, "ERR %v\n", err) + //nolint:revive // os.Exit called intentionally os.Exit(1) } - c, found := metric.GetField("count") + c, found := m.GetField("count") if !found { + //nolint:errcheck,revive // Test will fail anyway fmt.Fprintf(os.Stderr, "metric has no count field\n") + //nolint:revive // os.Exit called intentionally os.Exit(1) } switch t := c.(type) { case float64: t *= 2 - metric.AddField("count", t) + m.AddField("count", t) case int64: t *= 2 - metric.AddField("count", t) + m.AddField("count", t) default: + //nolint:errcheck,revive // Test will fail anyway fmt.Fprintf(os.Stderr, "count is not an unknown type, it's a %T\n", c) + //nolint:revive // os.Exit called intentionally os.Exit(1) } - b, err := serializer.Serialize(metric) + b, err := serializer.Serialize(m) if err != nil { + //nolint:errcheck,revive // Test will fail anyway fmt.Fprintf(os.Stderr, "ERR %v\n", err) + //nolint:revive // os.Exit called intentionally os.Exit(1) } + //nolint:errcheck,revive // Test will fail anyway fmt.Fprint(os.Stdout, string(b)) } } diff --git a/plugins/processors/ifname/ifname.go b/plugins/processors/ifname/ifname.go index eb3fb2333..228124e7b 100644 --- a/plugins/processors/ifname/ifname.go +++ b/plugins/processors/ifname/ifname.go @@ -80,7 +80,7 @@ type valType = nameMap type mapFunc func(agent string) (nameMap, error) type makeTableFunc func(string) (*si.Table, error) -type sigMap map[string](chan struct{}) +type sigMap map[string]chan struct{} type IfName struct { SourceTag string `toml:"tag"` @@ -96,24 +96,24 @@ type IfName struct { Log telegraf.Logger `toml:"-"` - ifTable *si.Table `toml:"-"` - ifXTable *si.Table `toml:"-"` + ifTable *si.Table + ifXTable *si.Table - lock sync.Mutex `toml:"-"` - cache *TTLCache `toml:"-"` + lock sync.Mutex + cache *TTLCache - parallel parallel.Parallel `toml:"-"` - acc telegraf.Accumulator `toml:"-"` + parallel parallel.Parallel + acc telegraf.Accumulator - getMapRemote mapFunc `toml:"-"` - makeTable makeTableFunc `toml:"-"` + getMapRemote mapFunc + makeTable makeTableFunc - gsBase snmp.GosnmpWrapper `toml:"-"` + gsBase snmp.GosnmpWrapper - sigs sigMap `toml:"-"` + sigs sigMap } -const minRetry time.Duration = 5 * time.Minute +const minRetry = 5 * time.Minute func (d *IfName) SampleConfig() string { return sampleConfig diff --git a/plugins/processors/ifname/ifname_test.go b/plugins/processors/ifname/ifname_test.go index 4052818f7..161390738 100644 --- a/plugins/processors/ifname/ifname_test.go +++ b/plugins/processors/ifname/ifname_test.go @@ -18,15 +18,16 @@ func TestTable(t *testing.T) { t.Skip("Skipping test due to connect failures") d := IfName{} - d.Init() + err := d.Init() + require.NoError(t, err) tab, err := d.makeTable("IF-MIB::ifTable") require.NoError(t, err) - config := snmp.ClientConfig{ + clientConfig := snmp.ClientConfig{ Version: 2, Timeout: config.Duration(5 * time.Second), // Doesn't work with 0 timeout } - gs, err := snmp.NewWrapper(config) + gs, err := snmp.NewWrapper(clientConfig) require.NoError(t, err) err = gs.SetAgent("127.0.0.1") require.NoError(t, err) diff --git a/plugins/processors/override/override_test.go b/plugins/processors/override/override_test.go index 5e3c118e8..74e228d2e 100644 --- a/plugins/processors/override/override_test.go +++ b/plugins/processors/override/override_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/stretchr/testify/assert" ) func createTestMetric() telegraf.Metric { @@ -18,8 +19,8 @@ func createTestMetric() telegraf.Metric { return m } -func calculateProcessedTags(processor Override, metric telegraf.Metric) map[string]string { - processed := processor.Apply(metric) +func calculateProcessedTags(processor Override, m telegraf.Metric) map[string]string { + processed := processor.Apply(m) return processed[0].Tags() } @@ -29,8 +30,8 @@ func TestRetainsTags(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["metric_tag"] - assert.True(t, present, "Tag of metric was not present") - assert.Equal(t, "from_metric", value, "Value of Tag was changed") + require.True(t, present, "Tag of metric was not present") + require.Equal(t, "from_metric", value, "Value of Tag was changed") } func TestAddTags(t *testing.T) { @@ -39,9 +40,9 @@ func TestAddTags(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["added_tag"] - assert.True(t, present, "Additional Tag of metric was not present") - assert.Equal(t, "from_config", value, "Value of Tag was changed") - assert.Equal(t, 3, len(tags), "Should have one previous and two added tags.") + require.True(t, present, "Additional Tag of metric was not present") + require.Equal(t, "from_config", value, "Value of Tag was changed") + require.Equal(t, 3, len(tags), "Should have one previous and two added tags.") } func TestOverwritesPresentTagValues(t *testing.T) { @@ -50,9 +51,9 @@ func TestOverwritesPresentTagValues(t *testing.T) { tags := calculateProcessedTags(processor, createTestMetric()) value, present := tags["metric_tag"] - assert.True(t, present, "Tag of metric was not present") - assert.Equal(t, 1, len(tags), "Should only have one tag.") - assert.Equal(t, "from_config", value, "Value of Tag was not changed") + require.True(t, present, "Tag of metric was not present") + require.Equal(t, 1, len(tags), "Should only have one tag.") + require.Equal(t, "from_config", value, "Value of Tag was not changed") } func TestOverridesName(t *testing.T) { @@ -60,7 +61,7 @@ func TestOverridesName(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") + require.Equal(t, "overridden", processed[0].Name(), "Name was not overridden") } func TestNamePrefix(t *testing.T) { @@ -68,7 +69,7 @@ func TestNamePrefix(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") + require.Equal(t, "Pre-m1", processed[0].Name(), "Prefix was not applied") } func TestNameSuffix(t *testing.T) { @@ -76,5 +77,5 @@ func TestNameSuffix(t *testing.T) { processed := processor.Apply(createTestMetric()) - assert.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") + require.Equal(t, "m1-suff", processed[0].Name(), "Suffix was not applied") } diff --git a/plugins/processors/rename/rename_test.go b/plugins/processors/rename/rename_test.go index 36e8aaeed..b917e486b 100644 --- a/plugins/processors/rename/rename_test.go +++ b/plugins/processors/rename/rename_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/stretchr/testify/assert" ) func newMetric(name string, tags map[string]string, fields map[string]interface{}) telegraf.Metric { @@ -31,9 +32,9 @@ func TestMeasurementRename(t *testing.T) { m2 := newMetric("bar", nil, nil) m3 := newMetric("baz", nil, nil) results := r.Apply(m1, m2, m3) - assert.Equal(t, "bar", results[0].Name(), "Should change name from 'foo' to 'bar'") - assert.Equal(t, "bar", results[1].Name(), "Should not name from 'bar'") - assert.Equal(t, "quux", results[2].Name(), "Should change name from 'baz' to 'quux'") + require.Equal(t, "bar", results[0].Name(), "Should change name from 'foo' to 'bar'") + require.Equal(t, "bar", results[1].Name(), "Should not name from 'bar'") + require.Equal(t, "quux", results[2].Name(), "Should change name from 'baz' to 'quux'") } func TestTagRename(t *testing.T) { @@ -45,7 +46,7 @@ func TestTagRename(t *testing.T) { m := newMetric("foo", map[string]string{"hostname": "localhost", "region": "east-1"}, nil) results := r.Apply(m) - assert.Equal(t, map[string]string{"host": "localhost", "region": "east-1"}, results[0].Tags(), "should change tag 'hostname' to 'host'") + require.Equal(t, map[string]string{"host": "localhost", "region": "east-1"}, results[0].Tags(), "should change tag 'hostname' to 'host'") } func TestFieldRename(t *testing.T) { @@ -57,5 +58,5 @@ func TestFieldRename(t *testing.T) { m := newMetric("foo", nil, map[string]interface{}{"time_msec": int64(1250), "snakes": true}) results := r.Apply(m) - assert.Equal(t, map[string]interface{}{"time": int64(1250), "snakes": true}, results[0].Fields(), "should change field 'time_msec' to 'time'") + require.Equal(t, map[string]interface{}{"time": int64(1250), "snakes": true}, results[0].Fields(), "should change field 'time_msec' to 'time'") } diff --git a/plugins/processors/reverse_dns/rdnscache.go b/plugins/processors/reverse_dns/rdnscache.go index cc9574552..c027fc132 100644 --- a/plugins/processors/reverse_dns/rdnscache.go +++ b/plugins/processors/reverse_dns/rdnscache.go @@ -104,10 +104,7 @@ func (d *ReverseDNSCache) Lookup(ip string) ([]string, error) { if len(ip) == 0 { return nil, nil } - return d.lookup(ip) -} -func (d *ReverseDNSCache) lookup(ip string) ([]string, error) { // check if the value is cached d.rwLock.RLock() result, found := d.lockedGetFromCache(ip) @@ -298,12 +295,6 @@ func (d *ReverseDNSCache) cleanup() { } } -// blockAllWorkers is a test function that eats up all the worker pool space to -// make sure workers are done running and there's no room to acquire a new worker. -func (d *ReverseDNSCache) blockAllWorkers() { - d.sem.Acquire(context.Background(), int64(d.maxWorkers)) -} - func (d *ReverseDNSCache) Stats() RDNSCacheStats { stats := RDNSCacheStats{} stats.CacheHit = atomic.LoadUint64(&d.stats.CacheHit) diff --git a/plugins/processors/reverse_dns/rdnscache_test.go b/plugins/processors/reverse_dns/rdnscache_test.go index 97cc8abdb..b717e64ef 100644 --- a/plugins/processors/reverse_dns/rdnscache_test.go +++ b/plugins/processors/reverse_dns/rdnscache_test.go @@ -18,7 +18,8 @@ func TestSimpleReverseDNSLookup(t *testing.T) { answer, err := d.Lookup("127.0.0.1") require.NoError(t, err) require.Equal(t, []string{"localhost"}, answer) - d.blockAllWorkers() + err = blockAllWorkers(d) + require.NoError(t, err) // do another request with no workers available. // it should read from cache instantly. @@ -134,3 +135,9 @@ type localResolver struct{} func (r *localResolver) LookupAddr(_ context.Context, _ string) (names []string, err error) { return []string{"localhost"}, nil } + +// blockAllWorkers is a test function that eats up all the worker pool space to +// make sure workers are done running and there's no room to acquire a new worker. +func blockAllWorkers(d *ReverseDNSCache) error { + return d.sem.Acquire(context.Background(), int64(d.maxWorkers)) +} diff --git a/plugins/processors/reverse_dns/reversedns_test.go b/plugins/processors/reverse_dns/reversedns_test.go index 5fcce5fb4..6db0b2ce5 100644 --- a/plugins/processors/reverse_dns/reversedns_test.go +++ b/plugins/processors/reverse_dns/reversedns_test.go @@ -33,9 +33,12 @@ func TestSimpleReverseLookup(t *testing.T) { }, } acc := &testutil.Accumulator{} - dns.Start(acc) - dns.Add(m, acc) - dns.Stop() + err := dns.Start(acc) + require.NoError(t, err) + err = dns.Add(m, acc) + require.NoError(t, err) + err = dns.Stop() + require.NoError(t, err) // should be processed now. require.Len(t, acc.GetTelegrafMetrics(), 1) diff --git a/plugins/processors/starlark/starlark_test.go b/plugins/processors/starlark/starlark_test.go index 3a1f955a8..df3e53f6c 100644 --- a/plugins/processors/starlark/starlark_test.go +++ b/plugins/processors/starlark/starlark_test.go @@ -9,15 +9,16 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + starlarktime "go.starlark.net/lib/time" + "go.starlark.net/starlark" + "go.starlark.net/starlarkstruct" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/config" common "github.com/influxdata/telegraf/plugins/common/starlark" "github.com/influxdata/telegraf/plugins/parsers" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/require" - starlarktime "go.starlark.net/lib/time" - "go.starlark.net/starlark" - "go.starlark.net/starlarkstruct" ) // Tests for runtime errors in the processors Init function. @@ -2674,11 +2675,11 @@ func buildPlugin(configContent string) (*Starlark, error) { return nil, err } if len(c.Processors) != 1 { - return nil, errors.New("Only one processor was expected") + return nil, errors.New("only one processor was expected") } plugin, ok := (c.Processors[0].Processor).(*Starlark) if !ok { - return nil, errors.New("Only a Starlark processor was expected") + return nil, errors.New("only a Starlark processor was expected") } plugin.Log = testutil.Logger{} return plugin, nil @@ -3199,7 +3200,8 @@ def apply(metric): b.ResetTimer() for n := 0; n < b.N; n++ { for _, m := range tt.input { - plugin.Add(m, &acc) + err = plugin.Add(m, &acc) + require.NoError(b, err) } } @@ -3213,7 +3215,7 @@ func TestAllScriptTestData(t *testing.T) { // can be run from multiple folders paths := []string{"testdata", "plugins/processors/starlark/testdata"} for _, testdataPath := range paths { - filepath.Walk(testdataPath, func(path string, info os.FileInfo, err error) error { + err := filepath.Walk(testdataPath, func(path string, info os.FileInfo, err error) error { if info == nil || info.IsDir() { return nil } @@ -3252,6 +3254,7 @@ func TestAllScriptTestData(t *testing.T) { }) return nil }) + require.NoError(t, err) } } @@ -3316,7 +3319,7 @@ func testLoadFunc(module string, logger telegraf.Logger) (starlark.StringDict, e return result, nil } -func testNow(thread *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) { +func testNow(_ *starlark.Thread, _ *starlark.Builtin, _ starlark.Tuple, _ []starlark.Tuple) (starlark.Value, error) { return starlarktime.Time(time.Date(2021, 4, 15, 12, 0, 0, 999, time.UTC)), nil } diff --git a/plugins/processors/strings/strings_test.go b/plugins/processors/strings/strings_test.go index c42011884..26c3e85a9 100644 --- a/plugins/processors/strings/strings_test.go +++ b/plugins/processors/strings/strings_test.go @@ -4,11 +4,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func newM1() telegraf.Metric { @@ -318,6 +318,7 @@ func TestFieldKeyConversions(t *testing.T) { check: func(t *testing.T, actual telegraf.Metric) { fv, ok := actual.GetField("Request") require.False(t, ok) + require.Nil(t, fv) fv, ok = actual.GetField("REQUEST") require.True(t, ok) @@ -686,7 +687,7 @@ func TestTagKeyConversions(t *testing.T) { require.True(t, ok) require.Equal(t, "GET", tv) - tv, ok = actual.GetTag("S-ComputerName") + _, ok = actual.GetTag("S-ComputerName") require.False(t, ok) tv, ok = actual.GetTag("s-computername") @@ -708,7 +709,7 @@ func TestTagKeyConversions(t *testing.T) { require.True(t, ok) require.Equal(t, "GET", tv) - tv, ok = actual.GetTag("S-ComputerName") + _, ok = actual.GetTag("S-ComputerName") require.False(t, ok) tv, ok = actual.GetTag("S-COMPUTERNAME") @@ -831,8 +832,8 @@ func TestMultipleConversions(t *testing.T) { "bar": "y", } - assert.Equal(t, expectedFields, processed[0].Fields()) - assert.Equal(t, expectedTags, processed[0].Tags()) + require.Equal(t, expectedFields, processed[0].Fields()) + require.Equal(t, expectedTags, processed[0].Tags()) } func TestReadmeExample(t *testing.T) { @@ -888,8 +889,8 @@ func TestReadmeExample(t *testing.T) { "resp_bytes": int64(270), } - assert.Equal(t, expectedFields, processed[0].Fields()) - assert.Equal(t, expectedTags, processed[0].Tags()) + require.Equal(t, expectedFields, processed[0].Fields()) + require.Equal(t, expectedTags, processed[0].Tags()) } func newMetric(name string) telegraf.Metric { @@ -915,9 +916,9 @@ func TestMeasurementReplace(t *testing.T) { newMetric("average_cpu_usage"), } results := plugin.Apply(metrics...) - assert.Equal(t, "foo:some-value:bar", results[0].Name(), "`_` was not changed to `-`") - assert.Equal(t, "average:cpu:usage", results[1].Name(), "Input name should have been unchanged") - assert.Equal(t, "average-cpu-usage", results[2].Name(), "All instances of `_` should have been changed to `-`") + require.Equal(t, "foo:some-value:bar", results[0].Name(), "`_` was not changed to `-`") + require.Equal(t, "average:cpu:usage", results[1].Name(), "Input name should have been unchanged") + require.Equal(t, "average-cpu-usage", results[2].Name(), "All instances of `_` should have been changed to `-`") } func TestMeasurementCharDeletion(t *testing.T) { @@ -936,9 +937,9 @@ func TestMeasurementCharDeletion(t *testing.T) { newMetric("barbarbar"), } results := plugin.Apply(metrics...) - assert.Equal(t, ":bar:baz", results[0].Name(), "Should have deleted the initial `foo`") - assert.Equal(t, "foofoofoo", results[1].Name(), "Should have refused to delete the whole string") - assert.Equal(t, "barbarbar", results[2].Name(), "Should not have changed the input") + require.Equal(t, ":bar:baz", results[0].Name(), "Should have deleted the initial `foo`") + require.Equal(t, "foofoofoo", results[1].Name(), "Should have refused to delete the whole string") + require.Equal(t, "barbarbar", results[2].Name(), "Should not have changed the input") } func TestBase64Decode(t *testing.T) { diff --git a/plugins/processors/tag_limit/tag_limit.go b/plugins/processors/tag_limit/tag_limit.go index 1b48739a1..ef2e86c81 100644 --- a/plugins/processors/tag_limit/tag_limit.go +++ b/plugins/processors/tag_limit/tag_limit.go @@ -2,9 +2,9 @@ package taglimit import ( "fmt" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/processors" - "log" ) const sampleConfig = ` @@ -16,8 +16,9 @@ const sampleConfig = ` ` type TagLimit struct { - Limit int `toml:"limit"` - Keep []string `toml:"keep"` + Limit int `toml:"limit"` + Keep []string `toml:"keep"` + Log telegraf.Logger `toml:"-"` init bool keepTags map[string]string } @@ -49,7 +50,7 @@ func (d *TagLimit) initOnce() error { func (d *TagLimit) Apply(in ...telegraf.Metric) []telegraf.Metric { err := d.initOnce() if err != nil { - log.Printf("E! [processors.tag_limit] could not create tag_limit processor: %v", err) + d.Log.Errorf("Could not create tag_limit processor: %v", err) return in } for _, point := range in { diff --git a/plugins/processors/tag_limit/tag_limit_test.go b/plugins/processors/tag_limit/tag_limit_test.go index d9c361ed0..3b2894d8a 100644 --- a/plugins/processors/tag_limit/tag_limit_test.go +++ b/plugins/processors/tag_limit/tag_limit_test.go @@ -4,9 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" - "github.com/stretchr/testify/assert" ) func MustMetric(name string, tags map[string]string, fields map[string]interface{}, metricTime time.Time) telegraf.Metric { @@ -46,8 +47,8 @@ func TestUnderLimit(t *testing.T) { m1 := MustMetric("foo", oneTags, nil, currentTime) m2 := MustMetric("bar", tenTags, nil, currentTime) limitApply := tagLimitConfig.Apply(m1, m2) - assert.Equal(t, oneTags, limitApply[0].Tags(), "one tag") - assert.Equal(t, tenTags, limitApply[1].Tags(), "ten tags") + require.Equal(t, oneTags, limitApply[0].Tags(), "one tag") + require.Equal(t, tenTags, limitApply[1].Tags(), "ten tags") } func TestTrim(t *testing.T) { @@ -78,9 +79,9 @@ func TestTrim(t *testing.T) { m1 := MustMetric("foo", threeTags, nil, currentTime) m2 := MustMetric("bar", tenTags, nil, currentTime) limitApply := tagLimitConfig.Apply(m1, m2) - assert.Equal(t, threeTags, limitApply[0].Tags(), "three tags") + require.Equal(t, threeTags, limitApply[0].Tags(), "three tags") trimmedTags := limitApply[1].Tags() - assert.Equal(t, 3, len(trimmedTags), "ten tags") - assert.Equal(t, "foo", trimmedTags["a"], "preserved: a") - assert.Equal(t, "bar", trimmedTags["b"], "preserved: b") + require.Equal(t, 3, len(trimmedTags), "ten tags") + require.Equal(t, "foo", trimmedTags["a"], "preserved: a") + require.Equal(t, "bar", trimmedTags["b"], "preserved: b") } diff --git a/plugins/processors/template/template_test.go b/plugins/processors/template/template_test.go index f43d69795..c3f25742d 100644 --- a/plugins/processors/template/template_test.go +++ b/plugins/processors/template/template_test.go @@ -4,10 +4,10 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestName(t *testing.T) { @@ -90,7 +90,7 @@ func TestMetricMissingTagsIsNotLost(t *testing.T) { // assert // make sure no metrics are lost when a template process fails - assert.Equal(t, 2, len(actual), "Number of metrics input should equal number of metrics output") + require.Equal(t, 2, len(actual), "Number of metrics input should equal number of metrics output") } func TestTagAndFieldConcatenate(t *testing.T) {