From 10b4311c41f752e9ac7f2a289fad61e896e033ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20=C5=BBak?= Date: Mon, 11 Nov 2024 11:33:45 +0100 Subject: [PATCH] chore: Fix linter findings for `revive:enforce-slice-style` in `plugins/inputs/[a-d]*` and `plugins/common` (#16161) (cherry picked from commit b4fdd52ff3a3585831ee31a159fd29f98b4e2845) --- plugins/common/jolokia2/client.go | 2 +- plugins/common/jolokia2/gatherer.go | 2 +- plugins/common/jolokia2/gatherer_test.go | 2 +- plugins/common/jolokia2/metric.go | 4 +- .../common/opcua/input/input_client_test.go | 21 ------ plugins/common/opcua/opcua_util.go | 5 +- plugins/common/shim/config.go | 6 +- plugins/common/starlark/starlark.go | 4 +- plugins/common/tls/utils.go | 3 +- plugins/inputs/aliyuncms/aliyuncms.go | 2 +- plugins/inputs/aliyuncms/aliyuncms_test.go | 15 ++-- plugins/inputs/amd_rocm_smi/amd_rocm_smi.go | 2 +- .../azure_monitor/azure_monitor_test.go | 8 +-- plugins/inputs/beanstalkd/beanstalkd_test.go | 9 +-- plugins/inputs/ceph/ceph.go | 4 +- plugins/inputs/clickhouse/clickhouse_test.go | 6 +- plugins/inputs/cloudwatch/cloudwatch.go | 10 +-- plugins/inputs/cloudwatch/cloudwatch_test.go | 4 +- plugins/inputs/couchbase/couchbase.go | 2 +- .../ctrlx_datalayer_subscription.go | 2 +- plugins/inputs/dcos/client.go | 6 +- plugins/inputs/dcos/client_test.go | 2 +- plugins/inputs/dcos/dcos_test.go | 3 +- plugins/inputs/dmcache/dmcache_linux.go | 2 +- plugins/inputs/dmcache/dmcache_linux_test.go | 2 +- plugins/inputs/docker/docker.go | 2 +- plugins/inputs/docker/docker_test.go | 71 ++++++------------- plugins/inputs/docker/docker_testdata.go | 6 +- plugins/inputs/dpdk/dpdk_test.go | 22 ++---- 29 files changed, 77 insertions(+), 152 deletions(-) diff --git a/plugins/common/jolokia2/client.go b/plugins/common/jolokia2/client.go index dfd33a7302962..307ef7fa936da 100644 --- a/plugins/common/jolokia2/client.go +++ b/plugins/common/jolokia2/client.go @@ -221,7 +221,7 @@ func makeReadResponses(jresponses []jolokiaResponse) []ReadResponse { rrequest := ReadRequest{ Mbean: jr.Request.Mbean, Path: jr.Request.Path, - Attributes: []string{}, + Attributes: make([]string, 0), } attrValue := jr.Request.Attribute diff --git a/plugins/common/jolokia2/gatherer.go b/plugins/common/jolokia2/gatherer.go index 447fc602a4db9..ab61a53a4395d 100644 --- a/plugins/common/jolokia2/gatherer.go +++ b/plugins/common/jolokia2/gatherer.go @@ -200,7 +200,7 @@ func makeReadRequests(metrics []Metric) []ReadRequest { if len(metric.Paths) == 0 { requests = append(requests, ReadRequest{ Mbean: metric.Mbean, - Attributes: []string{}, + Attributes: make([]string, 0), }) } else { attributes := make(map[string][]string) diff --git a/plugins/common/jolokia2/gatherer_test.go b/plugins/common/jolokia2/gatherer_test.go index e01c603addaeb..10e12cdc9d981 100644 --- a/plugins/common/jolokia2/gatherer_test.go +++ b/plugins/common/jolokia2/gatherer_test.go @@ -19,7 +19,7 @@ func TestJolokia2_makeReadRequests(t *testing.T) { expected: []ReadRequest{ { Mbean: "test:foo=bar", - Attributes: []string{}, + Attributes: make([]string, 0), }, }, }, { diff --git a/plugins/common/jolokia2/metric.go b/plugins/common/jolokia2/metric.go index 0f438b3c03df0..9d517ce4f81c5 100644 --- a/plugins/common/jolokia2/metric.go +++ b/plugins/common/jolokia2/metric.go @@ -115,13 +115,13 @@ func (m Metric) MatchAttributeAndPath(attribute, innerPath string) bool { func parseMbeanObjectName(name string) (string, []string) { index := strings.Index(name, ":") if index == -1 { - return name, []string{} + return name, nil } domain := name[:index] if index+1 > len(name) { - return domain, []string{} + return domain, nil } return domain, strings.Split(name[index+1:], ",") diff --git a/plugins/common/opcua/input/input_client_test.go b/plugins/common/opcua/input/input_client_test.go index 9ea73d070ceca..99fbd2b809935 100644 --- a/plugins/common/opcua/input/input_client_test.go +++ b/plugins/common/opcua/input/input_client_test.go @@ -126,7 +126,6 @@ func TestValidateOPCTags(t *testing.T) { TagsSlice: [][]string{{"t1", "v1"}, {"t3", "v2"}}, }, }, - Groups: []NodeGroupSettings{}, }, nil, }, @@ -150,7 +149,6 @@ func TestValidateOPCTags(t *testing.T) { TagsSlice: [][]string{{"t1", "bar"}, {"t2", "v2"}}, }, }, - Groups: []NodeGroupSettings{}, }, nil, }, @@ -158,7 +156,6 @@ func TestValidateOPCTags(t *testing.T) { "different metric names", InputClientConfig{ MetricName: "mn", - RootNodes: []NodeSettings{}, Groups: []NodeGroupSettings{ { MetricName: "mn", @@ -208,7 +205,6 @@ func TestValidateOPCTags(t *testing.T) { TagsSlice: [][]string{{"t1", "v1"}, {"t2", "v2"}}, }, }, - Groups: []NodeGroupSettings{}, }, nil, }, @@ -239,7 +235,6 @@ func TestNewNodeMetricMappingTags(t *testing.T) { Namespace: "2", IdentifierType: "s", Identifier: "h", - TagsSlice: [][]string{}, }, groupTags: map[string]string{}, expectedTags: map[string]string{}, @@ -265,7 +260,6 @@ func TestNewNodeMetricMappingTags(t *testing.T) { Namespace: "2", IdentifierType: "s", Identifier: "h", - TagsSlice: [][]string{}, }, groupTags: map[string]string{"t1": "v1"}, expectedTags: map[string]string{"t1": "v1"}, @@ -313,7 +307,6 @@ func TestNewNodeMetricMappingIdStrInstantiated(t *testing.T) { Namespace: "2", IdentifierType: "s", Identifier: "h", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) require.Equal(t, "ns=2;s=h", nmm.idStr) @@ -335,7 +328,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: "s", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -351,7 +343,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: "s", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -367,7 +358,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "", IdentifierType: "s", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -383,7 +373,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: "", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -399,7 +388,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: "j", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -433,7 +421,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: "i", Identifier: "hf", - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -461,7 +448,6 @@ func TestValidateNodeToAdd(t *testing.T) { Namespace: "2", IdentifierType: idT, Identifier: idV, - TagsSlice: [][]string{}, }, map[string]string{}) require.NoError(t, err) return nmm @@ -499,7 +485,6 @@ func TestInitNodeMetricMapping(t *testing.T) { TagsSlice: [][]string{{"t1", "v1"}}, }, }, - Groups: []NodeGroupSettings{}, }, expected: []NodeMetricMapping{ { @@ -543,7 +528,6 @@ func TestInitNodeMetricMapping(t *testing.T) { TagsSlice: [][]string{{"t2", "v2"}}, }, }, - TagsSlice: [][]string{}, }, }, }, @@ -580,7 +564,6 @@ func TestInitNodeMetricMapping(t *testing.T) { config: InputClientConfig{ MetricName: "testmetric", Timestamp: TimestampSourceTelegraf, - RootNodes: []NodeSettings{}, Groups: []NodeGroupSettings{ { MetricName: "groupmetric", @@ -593,7 +576,6 @@ func TestInitNodeMetricMapping(t *testing.T) { TagsSlice: [][]string{{"t2", "v2"}}, }, }, - TagsSlice: [][]string{}, }, }, }, @@ -618,7 +600,6 @@ func TestInitNodeMetricMapping(t *testing.T) { config: InputClientConfig{ MetricName: "testmetric", Timestamp: TimestampSourceTelegraf, - RootNodes: []NodeSettings{}, Groups: []NodeGroupSettings{ { MetricName: "groupmetric", @@ -632,7 +613,6 @@ func TestInitNodeMetricMapping(t *testing.T) { DefaultTags: map[string]string{"t3": "v3"}, }, }, - TagsSlice: [][]string{}, }, }, }, @@ -668,7 +648,6 @@ func TestInitNodeMetricMapping(t *testing.T) { DefaultTags: map[string]string{"t3": "v3"}, }, }, - Groups: []NodeGroupSettings{}, }, expected: []NodeMetricMapping{ { diff --git a/plugins/common/opcua/opcua_util.go b/plugins/common/opcua/opcua_util.go index fc2690ad20561..95414453a263b 100644 --- a/plugins/common/opcua/opcua_util.go +++ b/plugins/common/opcua/opcua_util.go @@ -151,16 +151,15 @@ func pemBlockForKey(priv interface{}) (*pem.Block, error) { } func (o *OpcUAClient) generateClientOpts(endpoints []*ua.EndpointDescription) ([]opcua.Option, error) { - opts := []opcua.Option{} appuri := "urn:telegraf:gopcua:client" appname := "Telegraf" // ApplicationURI is automatically read from the cert so is not required if a cert if provided - opts = append(opts, + opts := []opcua.Option{ opcua.ApplicationURI(appuri), opcua.ApplicationName(appname), opcua.RequestTimeout(time.Duration(o.Config.RequestTimeout)), - ) + } if o.Config.SessionTimeout != 0 { opts = append(opts, opcua.SessionTimeout(time.Duration(o.Config.SessionTimeout))) diff --git a/plugins/common/shim/config.go b/plugins/common/shim/config.go index 69b043d0702cf..f3b29ae3d91b1 100644 --- a/plugins/common/shim/config.go +++ b/plugins/common/shim/config.go @@ -153,17 +153,17 @@ func DefaultImportedPlugins() config { } for name := range inputs.Inputs { log.Println("No config found. Loading default config for plugin", name) - conf.Inputs[name] = []toml.Primitive{} + conf.Inputs[name] = make([]toml.Primitive, 0) return conf } for name := range processors.Processors { log.Println("No config found. Loading default config for plugin", name) - conf.Processors[name] = []toml.Primitive{} + conf.Processors[name] = make([]toml.Primitive, 0) return conf } for name := range outputs.Outputs { log.Println("No config found. Loading default config for plugin", name) - conf.Outputs[name] = []toml.Primitive{} + conf.Outputs[name] = make([]toml.Primitive, 0) return conf } return conf diff --git a/plugins/common/starlark/starlark.go b/plugins/common/starlark/starlark.go index 5b43e19bfa378..d44e99f0a50a8 100644 --- a/plugins/common/starlark/starlark.go +++ b/plugins/common/starlark/starlark.go @@ -35,7 +35,7 @@ func (s *Common) GetState() interface{} { // Return the actual byte-type instead of nil allowing the persister // to guess instantiate variable of the appropriate type if s.state == nil { - return []byte{} + return make([]byte, 0) } // Convert the starlark dict into a golang dictionary for serialization @@ -65,7 +65,7 @@ func (s *Common) GetState() interface{} { var buf bytes.Buffer if err := gob.NewEncoder(&buf).Encode(state); err != nil { s.Log.Errorf("encoding state failed: %v", err) - return []byte{} + return make([]byte, 0) } return buf.Bytes() diff --git a/plugins/common/tls/utils.go b/plugins/common/tls/utils.go index 8d4dc89bb84f1..a6963c8276b33 100644 --- a/plugins/common/tls/utils.go +++ b/plugins/common/tls/utils.go @@ -39,8 +39,7 @@ func Ciphers() (secure, insecure []string) { // ParseCiphers returns a `[]uint16` by received `[]string` key that represents ciphers from crypto/tls. // If some of ciphers in received list doesn't exists ParseCiphers returns nil with error func ParseCiphers(ciphers []string) ([]uint16, error) { - suites := []uint16{} - + suites := make([]uint16, 0) added := make(map[uint16]bool, len(ciphers)) for _, c := range ciphers { // Handle meta-keywords diff --git a/plugins/inputs/aliyuncms/aliyuncms.go b/plugins/inputs/aliyuncms/aliyuncms.go index fb96556d8c458..83286b5722c8b 100644 --- a/plugins/inputs/aliyuncms/aliyuncms.go +++ b/plugins/inputs/aliyuncms/aliyuncms.go @@ -149,7 +149,7 @@ func (s *AliyunCMS) Init() error { continue } metric.dimensionsUdObj = make(map[string]string) - metric.dimensionsUdArr = []map[string]string{} + metric.dimensionsUdArr = make([]map[string]string, 0) // first try to unmarshal as an object if err := json.Unmarshal([]byte(metric.Dimensions), &metric.dimensionsUdObj); err == nil { diff --git a/plugins/inputs/aliyuncms/aliyuncms_test.go b/plugins/inputs/aliyuncms/aliyuncms_test.go index ebd7c8bfb23e2..6995b342c149d 100644 --- a/plugins/inputs/aliyuncms/aliyuncms_test.go +++ b/plugins/inputs/aliyuncms/aliyuncms_test.go @@ -250,8 +250,7 @@ func TestPluginMetricsInitialize(t *testing.T) { accessKeySecret: "dummy", metrics: []*metric{ { - MetricNames: []string{}, - Dimensions: `{"instanceId": "i-abcdefgh123456"}`, + Dimensions: `{"instanceId": "i-abcdefgh123456"}`, }, }, }, @@ -263,8 +262,7 @@ func TestPluginMetricsInitialize(t *testing.T) { accessKeySecret: "dummy", metrics: []*metric{ { - MetricNames: []string{}, - Dimensions: `[{"instanceId": "p-example"},{"instanceId": "q-example"}]`, + Dimensions: `[{"instanceId": "p-example"},{"instanceId": "q-example"}]`, }, }, }, @@ -277,8 +275,7 @@ func TestPluginMetricsInitialize(t *testing.T) { expectedErrorString: `cannot parse dimensions (neither obj, nor array) "[": unexpected end of JSON input`, metrics: []*metric{ { - MetricNames: []string{}, - Dimensions: `[`, + Dimensions: `[`, }, }, }, @@ -344,8 +341,7 @@ func TestGatherMetric(t *testing.T) { } metric := &metric{ - MetricNames: []string{}, - Dimensions: `"instanceId": "i-abcdefgh123456"`, + Dimensions: `"instanceId": "i-abcdefgh123456"`, } tests := []struct { @@ -375,8 +371,7 @@ func TestGatherMetric(t *testing.T) { func TestGather(t *testing.T) { m := &metric{ - MetricNames: []string{}, - Dimensions: `{"instanceId": "i-abcdefgh123456"}`, + Dimensions: `{"instanceId": "i-abcdefgh123456"}`, } plugin := &AliyunCMS{ AccessKeyID: "my_access_key_id", diff --git a/plugins/inputs/amd_rocm_smi/amd_rocm_smi.go b/plugins/inputs/amd_rocm_smi/amd_rocm_smi.go index fbca6246ebd92..b30a8b1b80871 100644 --- a/plugins/inputs/amd_rocm_smi/amd_rocm_smi.go +++ b/plugins/inputs/amd_rocm_smi/amd_rocm_smi.go @@ -180,7 +180,7 @@ func (rsmi *ROCmSMI) pollROCmSMI() ([]byte, error) { } func genTagsFields(gpus map[string]gpu, system map[string]sysInfo) []metric { - metrics := []metric{} + metrics := make([]metric, 0, len(gpus)) for cardID := range gpus { if strings.Contains(cardID, "card") { tags := map[string]string{ diff --git a/plugins/inputs/azure_monitor/azure_monitor_test.go b/plugins/inputs/azure_monitor/azure_monitor_test.go index 5e14e73e4fa94..e51b616baad0b 100644 --- a/plugins/inputs/azure_monitor/azure_monitor_test.go +++ b/plugins/inputs/azure_monitor/azure_monitor_test.go @@ -923,7 +923,7 @@ func TestGather_Success(t *testing.T) { am.receiver, err = receiver.NewAzureMonitorMetricsReceiver( am.SubscriptionID, - receiver.NewTargets(resourceTargets, []*receiver.ResourceGroupTarget{}, []*receiver.Resource{}), + receiver.NewTargets(resourceTargets, nil, nil), azureClients, ) require.NoError(t, err) @@ -1010,7 +1010,7 @@ func TestGather_China_Success(t *testing.T) { am.receiver, err = receiver.NewAzureMonitorMetricsReceiver( am.SubscriptionID, - receiver.NewTargets(resourceTargets, []*receiver.ResourceGroupTarget{}, []*receiver.Resource{}), + receiver.NewTargets(resourceTargets, nil, nil), azureClients, ) require.NoError(t, err) @@ -1043,7 +1043,7 @@ func TestGather_Government_Success(t *testing.T) { am.receiver, err = receiver.NewAzureMonitorMetricsReceiver( am.SubscriptionID, - receiver.NewTargets(resourceTargets, []*receiver.ResourceGroupTarget{}, []*receiver.Resource{}), + receiver.NewTargets(resourceTargets, nil, nil), azureClients, ) require.NoError(t, err) @@ -1076,7 +1076,7 @@ func TestGather_Public_Success(t *testing.T) { am.receiver, err = receiver.NewAzureMonitorMetricsReceiver( am.SubscriptionID, - receiver.NewTargets(resourceTargets, []*receiver.ResourceGroupTarget{}, []*receiver.Resource{}), + receiver.NewTargets(resourceTargets, nil, nil), azureClients, ) require.NoError(t, err) diff --git a/plugins/inputs/beanstalkd/beanstalkd_test.go b/plugins/inputs/beanstalkd/beanstalkd_test.go index 204db8b7063ab..3c65b12ae2c52 100644 --- a/plugins/inputs/beanstalkd/beanstalkd_test.go +++ b/plugins/inputs/beanstalkd/beanstalkd_test.go @@ -26,13 +26,11 @@ func TestBeanstalkd(t *testing.T) { expectedError string }{ { - name: "All tubes stats", - tubesConfig: []string{}, + name: "All tubes stats", expectedTubes: []tubeStats{ {name: "default", fields: defaultTubeFields}, {name: "test", fields: testTubeFields}, }, - notExpectedTubes: []tubeStats{}, }, { name: "Specified tubes stats", @@ -45,9 +43,8 @@ func TestBeanstalkd(t *testing.T) { }, }, { - name: "Unknown tube stats", - tubesConfig: []string{"unknown"}, - expectedTubes: []tubeStats{}, + name: "Unknown tube stats", + tubesConfig: []string{"unknown"}, notExpectedTubes: []tubeStats{ {name: "default", fields: defaultTubeFields}, {name: "test", fields: testTubeFields}, diff --git a/plugins/inputs/ceph/ceph.go b/plugins/inputs/ceph/ceph.go index 2ef13b6788c21..4f8829c3673dd 100644 --- a/plugins/inputs/ceph/ceph.go +++ b/plugins/inputs/ceph/ceph.go @@ -210,7 +210,7 @@ var perfDump = func(binary string, socket *socket) (string, error) { var findSockets = func(c *Ceph) ([]*socket, error) { listing, err := os.ReadDir(c.SocketDir) if err != nil { - return []*socket{}, fmt.Errorf("failed to read socket directory %q: %w", c.SocketDir, err) + return nil, fmt.Errorf("failed to read socket directory %q: %w", c.SocketDir, err) } sockets := make([]*socket, 0, len(listing)) for _, info := range listing { @@ -714,7 +714,7 @@ type osdPoolStats []struct { // decodeOsdPoolStats decodes the output of 'ceph osd pool stats' func decodeOsdPoolStats(acc telegraf.Accumulator, input string) error { - data := osdPoolStats{} + data := make(osdPoolStats, 0) if err := json.Unmarshal([]byte(input), &data); err != nil { return fmt.Errorf("failed to parse json: %q: %w", input, err) } diff --git a/plugins/inputs/clickhouse/clickhouse_test.go b/plugins/inputs/clickhouse/clickhouse_test.go index d63d430c31bad..c68225c75406e 100644 --- a/plugins/inputs/clickhouse/clickhouse_test.go +++ b/plugins/inputs/clickhouse/clickhouse_test.go @@ -23,12 +23,12 @@ func TestClusterIncludeExcludeFilter(t *testing.T) { ch.ClusterInclude = []string{"cluster"} require.Equal(t, "WHERE cluster IN ('cluster') OR cluster NOT IN ('test_cluster')", ch.clusterIncludeExcludeFilter()) - ch.ClusterExclude = []string{} + ch.ClusterExclude = make([]string, 0) ch.ClusterInclude = []string{"cluster1", "cluster2"} require.Equal(t, "WHERE cluster IN ('cluster1', 'cluster2')", ch.clusterIncludeExcludeFilter()) ch.ClusterExclude = []string{"cluster1", "cluster2"} - ch.ClusterInclude = []string{} + ch.ClusterInclude = make([]string, 0) require.Equal(t, "WHERE cluster NOT IN ('cluster1', 'cluster2')", ch.clusterIncludeExcludeFilter()) } @@ -623,7 +623,7 @@ func TestWrongJSONMarshalling(t *testing.T) { enc := json.NewEncoder(w) // wrong data section json err := enc.Encode(result{ - Data: []struct{}{}, + Data: make([]struct{}, 0), }) if err != nil { w.WriteHeader(http.StatusInternalServerError) diff --git a/plugins/inputs/cloudwatch/cloudwatch.go b/plugins/inputs/cloudwatch/cloudwatch.go index f3753542b3b0f..f9caa49f51e63 100644 --- a/plugins/inputs/cloudwatch/cloudwatch.go +++ b/plugins/inputs/cloudwatch/cloudwatch.go @@ -236,12 +236,12 @@ func getFilteredMetrics(c *CloudWatch) ([]filteredMetric, error) { return c.metricCache.metrics, nil } - fMetrics := []filteredMetric{} + fMetrics := make([]filteredMetric, 0) // check for provided metric filter if c.Metrics != nil { for _, m := range c.Metrics { - metrics := []types.Metric{} + metrics := make([]types.Metric, 0) var accounts []string if !hasWildcard(m.Dimensions) { dimensions := make([]types.Dimension, 0, len(m.Dimensions)) @@ -321,11 +321,11 @@ func getFilteredMetrics(c *CloudWatch) ([]filteredMetric, error) { // fetchNamespaceMetrics retrieves available metrics for a given CloudWatch namespace. func (c *CloudWatch) fetchNamespaceMetrics() ([]types.Metric, []string) { - metrics := []types.Metric{} + metrics := make([]types.Metric, 0) var accounts []string for _, namespace := range c.Namespaces { params := &cloudwatch.ListMetricsInput{ - Dimensions: []types.DimensionFilter{}, + Dimensions: make([]types.DimensionFilter, 0), Namespace: aws.String(namespace), IncludeLinkedAccounts: &c.IncludeLinkedAccounts, } @@ -434,7 +434,7 @@ func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) map[string func (c *CloudWatch) gatherMetrics( params *cloudwatch.GetMetricDataInput, ) ([]types.MetricDataResult, error) { - results := []types.MetricDataResult{} + results := make([]types.MetricDataResult, 0) for { resp, err := c.client.GetMetricData(context.Background(), params) diff --git a/plugins/inputs/cloudwatch/cloudwatch_test.go b/plugins/inputs/cloudwatch/cloudwatch_test.go index 283f1e9232b15..4cf11fe5955db 100644 --- a/plugins/inputs/cloudwatch/cloudwatch_test.go +++ b/plugins/inputs/cloudwatch/cloudwatch_test.go @@ -312,7 +312,7 @@ func (m *mockSelectMetricsCloudWatchClient) ListMetrics( _ *cloudwatch.ListMetricsInput, _ ...func(*cloudwatch.Options), ) (*cloudwatch.ListMetricsOutput, error) { - metrics := []types.Metric{} + metrics := make([]types.Metric, 0) // 4 metrics are available metricNames := []string{"Latency", "RequestCount", "HealthyHostCount", "UnHealthyHostCount"} // for 3 ELBs @@ -493,7 +493,7 @@ func TestGenerateStatisticsInputParamsFiltered(t *testing.T) { func TestMetricsCacheTimeout(t *testing.T) { cache := &metricCache{ - metrics: []filteredMetric{}, + metrics: make([]filteredMetric, 0), built: time.Now(), ttl: time.Minute, } diff --git a/plugins/inputs/couchbase/couchbase.go b/plugins/inputs/couchbase/couchbase.go index f8e1489eb3e18..1d8fe62d653f3 100644 --- a/plugins/inputs/couchbase/couchbase.go +++ b/plugins/inputs/couchbase/couchbase.go @@ -49,7 +49,7 @@ func (*Couchbase) SampleConfig() string { } func (cb *Couchbase) Init() error { - f, err := filter.NewIncludeExcludeFilter(cb.BucketStatsIncluded, []string{}) + f, err := filter.NewIncludeExcludeFilter(cb.BucketStatsIncluded, nil) if err != nil { return err } diff --git a/plugins/inputs/ctrlx_datalayer/ctrlx_datalayer_subscription.go b/plugins/inputs/ctrlx_datalayer/ctrlx_datalayer_subscription.go index 3ba6908bc65e8..28edd41f3a9a9 100644 --- a/plugins/inputs/ctrlx_datalayer/ctrlx_datalayer_subscription.go +++ b/plugins/inputs/ctrlx_datalayer/ctrlx_datalayer_subscription.go @@ -152,7 +152,7 @@ func (s *subscription) createRequest(id string) subscriptionRequest { // addressList lists all configured node addresses func (s *subscription) addressList() []string { - addressList := []string{} + addressList := make([]string, 0) for _, node := range s.Nodes { addressList = append(addressList, node.Address) } diff --git a/plugins/inputs/dcos/client.go b/plugins/inputs/dcos/client.go index 608abd62eaaaf..1b1af7d818e69 100644 --- a/plugins/inputs/dcos/client.go +++ b/plugins/inputs/dcos/client.go @@ -212,10 +212,8 @@ func (c *clusterClient) getSummary(ctx context.Context) (*summary, error) { } func (c *clusterClient) getContainers(ctx context.Context, node string) ([]container, error) { - list := []string{} - - path := fmt.Sprintf("/system/v1/agent/%s/metrics/v0/containers", node) - err := c.doGet(ctx, c.toURL(path), &list) + list := make([]string, 0) + err := c.doGet(ctx, c.toURL(fmt.Sprintf("/system/v1/agent/%s/metrics/v0/containers", node)), &list) if err != nil { return nil, err } diff --git a/plugins/inputs/dcos/client_test.go b/plugins/inputs/dcos/client_test.go index f6574fca31f55..d14c72455f32b 100644 --- a/plugins/inputs/dcos/client_test.go +++ b/plugins/inputs/dcos/client_test.go @@ -95,7 +95,7 @@ func TestGetSummary(t *testing.T) { name: "No nodes", responseCode: http.StatusOK, responseBody: `{"cluster": "a", "slaves": []}`, - expectedValue: &summary{Cluster: "a", Slaves: []slave{}}, + expectedValue: &summary{Cluster: "a", Slaves: make([]slave, 0)}, expectedError: nil, }, { diff --git a/plugins/inputs/dcos/dcos_test.go b/plugins/inputs/dcos/dcos_test.go index 63683b9acd45a..4f71f1be2327b 100644 --- a/plugins/inputs/dcos/dcos_test.go +++ b/plugins/inputs/dcos/dcos_test.go @@ -366,7 +366,6 @@ func TestGatherFilterNode(t *testing.T) { GetSummaryF: func() (*summary, error) { return &summary{ Cluster: "a", - Slaves: []slave{}, }, nil }, }, @@ -391,7 +390,7 @@ func TestGatherFilterNode(t *testing.T) { }, nil }, GetContainersF: func() ([]container, error) { - return []container{}, nil + return nil, nil }, GetNodeMetricsF: func() (*metrics, error) { return &metrics{ diff --git a/plugins/inputs/dmcache/dmcache_linux.go b/plugins/inputs/dmcache/dmcache_linux.go index ee82f0da906a8..bd0ef4257c886 100644 --- a/plugins/inputs/dmcache/dmcache_linux.go +++ b/plugins/inputs/dmcache/dmcache_linux.go @@ -179,7 +179,7 @@ func dmSetupStatus() ([]string, error) { return nil, err } if string(out) == "No devices found\n" { - return []string{}, nil + return nil, nil } outString := strings.TrimRight(string(out), "\n") diff --git a/plugins/inputs/dmcache/dmcache_linux_test.go b/plugins/inputs/dmcache/dmcache_linux_test.go index f1ae81ae6652b..26b0a91aa947b 100644 --- a/plugins/inputs/dmcache/dmcache_linux_test.go +++ b/plugins/inputs/dmcache/dmcache_linux_test.go @@ -139,7 +139,7 @@ func TestNoDevicesOutput(t *testing.T) { var plugin = &DMCache{ PerDevice: true, getCurrentStatus: func() ([]string, error) { - return []string{}, nil + return nil, nil }, } diff --git a/plugins/inputs/docker/docker.go b/plugins/inputs/docker/docker.go index b09eb347232c5..0f5471eb11840 100644 --- a/plugins/inputs/docker/docker.go +++ b/plugins/inputs/docker/docker.go @@ -128,7 +128,7 @@ func (d *Docker) Init() error { if choice.Contains("cpu", d.TotalInclude) { d.TotalInclude = []string{"cpu"} } else { - d.TotalInclude = []string{} + d.TotalInclude = make([]string, 0) } } diff --git a/plugins/inputs/docker/docker_test.go b/plugins/inputs/docker/docker_test.go index 14b826a9f0d57..600227e5b1653 100644 --- a/plugins/inputs/docker/docker_test.go +++ b/plugins/inputs/docker/docker_test.go @@ -484,8 +484,6 @@ func TestContainerLabels(t *testing.T) { container: genContainerLabeled(map[string]string{ "a": "x", }), - include: []string{}, - exclude: []string{}, expected: map[string]string{ "a": "x", }, @@ -497,7 +495,6 @@ func TestContainerLabels(t *testing.T) { "b": "y", }), include: []string{"a"}, - exclude: []string{}, expected: map[string]string{ "a": "x", }, @@ -508,7 +505,6 @@ func TestContainerLabels(t *testing.T) { "a": "x", "b": "y", }), - include: []string{}, exclude: []string{"b"}, expected: map[string]string{ "a": "x", @@ -522,7 +518,6 @@ func TestContainerLabels(t *testing.T) { "bb": "z", }), include: []string{"a*"}, - exclude: []string{}, expected: map[string]string{ "aa": "x", "ab": "y", @@ -535,7 +530,6 @@ func TestContainerLabels(t *testing.T) { "ab": "y", "bb": "z", }), - include: []string{}, exclude: []string{"a*"}, expected: map[string]string{ "bb": "z", @@ -616,51 +610,42 @@ func TestContainerNames(t *testing.T) { }, { name: "Empty filters matches all", - include: []string{}, - exclude: []string{}, expected: []string{"etcd", "etcd2", "acme", "acme-test", "foo"}, }, { name: "Match all containers", include: []string{"*"}, - exclude: []string{}, expected: []string{"etcd", "etcd2", "acme", "acme-test", "foo"}, }, { name: "Include prefix match", include: []string{"etc*"}, - exclude: []string{}, expected: []string{"etcd", "etcd2"}, }, { name: "Exact match", include: []string{"etcd"}, - exclude: []string{}, expected: []string{"etcd"}, }, { name: "Star matches zero length", include: []string{"etcd2*"}, - exclude: []string{}, expected: []string{"etcd2"}, }, { name: "Exclude matches all", - include: []string{}, exclude: []string{"etc*"}, expected: []string{"acme", "acme-test", "foo"}, }, { name: "Exclude single", - include: []string{}, exclude: []string{"etcd"}, expected: []string{"etcd2", "acme", "acme-test", "foo"}, }, { - name: "Exclude all", - include: []string{"*"}, - exclude: []string{"*"}, - expected: []string{}, + name: "Exclude all", + include: []string{"*"}, + exclude: []string{"*"}, }, { name: "Exclude item matching include", @@ -721,7 +706,7 @@ func TestContainerNames(t *testing.T) { } func filterMetrics(metrics []telegraf.Metric, f func(telegraf.Metric) bool) []telegraf.Metric { - results := []telegraf.Metric{} + results := make([]telegraf.Metric, 0, len(metrics)) for _, m := range metrics { if f(m) { results = append(results, m) @@ -1406,7 +1391,6 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { args: args{ stat: stats, perDeviceInclude: containerMetricClasses, - totalInclude: []string{}, }, expected: []telegraf.Metric{ metricCPU0, metricCPU1, @@ -1417,20 +1401,16 @@ func Test_parseContainerStatsPerDeviceAndTotal(t *testing.T) { { name: "Total metrics enabled", args: args{ - stat: stats, - perDeviceInclude: []string{}, - totalInclude: containerMetricClasses, + stat: stats, + totalInclude: containerMetricClasses, }, expected: []telegraf.Metric{metricCPUTotal, metricNetworkTotal, metricBlkioTotal}, }, { name: "Per device and total metrics disabled", args: args{ - stat: stats, - perDeviceInclude: []string{}, - totalInclude: []string{}, + stat: stats, }, - expected: []telegraf.Metric{}, }, } @@ -1468,52 +1448,46 @@ func TestDocker_Init(t *testing.T) { wantTotalInclude []string }{ { - "Unsupported perdevice_include setting", - fields{ + name: "Unsupported perdevice_include setting", + fields: fields{ PerDevice: false, PerDeviceInclude: []string{"nonExistentClass"}, Total: false, TotalInclude: []string{"cpu"}, }, - true, - []string{}, - []string{}, + wantErr: true, }, { - "Unsupported total_include setting", - fields{ + name: "Unsupported total_include setting", + fields: fields{ PerDevice: false, PerDeviceInclude: []string{"cpu"}, Total: false, TotalInclude: []string{"nonExistentClass"}, }, - true, - []string{}, - []string{}, + wantErr: true, }, { - "PerDevice true adds network and blkio", - fields{ + name: "PerDevice true adds network and blkio", + fields: fields{ PerDevice: true, PerDeviceInclude: []string{"cpu"}, Total: true, TotalInclude: []string{"cpu"}, }, - false, - []string{"cpu", "network", "blkio"}, - []string{"cpu"}, + wantPerDeviceInclude: []string{"cpu", "network", "blkio"}, + wantTotalInclude: []string{"cpu"}, }, { - "Total false removes network and blkio", - fields{ + name: "Total false removes network and blkio", + fields: fields{ PerDevice: false, PerDeviceInclude: []string{"cpu"}, Total: false, TotalInclude: []string{"cpu", "network", "blkio"}, }, - false, - []string{"cpu"}, - []string{"cpu"}, + wantPerDeviceInclude: []string{"cpu"}, + wantTotalInclude: []string{"cpu"}, }, } for _, tt := range tests { @@ -1552,8 +1526,7 @@ func TestDockerGatherDiskUsage(t *testing.T) { require.NoError(t, acc.GatherError(d.Gather)) - duOpts := types.DiskUsageOptions{Types: []types.DiskUsageObject{}} - d.gatherDiskUsage(&acc, duOpts) + d.gatherDiskUsage(&acc, types.DiskUsageOptions{}) acc.AssertContainsTaggedFields(t, "docker_disk_usage", diff --git a/plugins/inputs/docker/docker_testdata.go b/plugins/inputs/docker/docker_testdata.go index 11027cf00ba60..57be5a8cb1773 100644 --- a/plugins/inputs/docker/docker_testdata.go +++ b/plugins/inputs/docker/docker_testdata.go @@ -40,15 +40,15 @@ var info = system.Info{ IndexConfigs: map[string]*registry.IndexInfo{ "docker.io": { Name: "docker.io", - Mirrors: []string{}, + Mirrors: make([]string, 0), Official: true, Secure: true, }, - }, InsecureRegistryCIDRs: []*registry.NetIPNet{{IP: []byte{127, 0, 0, 0}, Mask: []byte{255, 0, 0, 0}}}, Mirrors: []string{}}, + }, InsecureRegistryCIDRs: []*registry.NetIPNet{{IP: []byte{127, 0, 0, 0}, Mask: []byte{255, 0, 0, 0}}}, Mirrors: make([]string, 0)}, OperatingSystem: "Linux Mint LMDE (containerized)", BridgeNfIptables: true, HTTPSProxy: "", - Labels: []string{}, + Labels: make([]string, 0), MemoryLimit: false, DriverStatus: [][2]string{ {"Pool Name", "docker-8:1-1182287-pool"}, diff --git a/plugins/inputs/dpdk/dpdk_test.go b/plugins/inputs/dpdk/dpdk_test.go index 0781cc862d192..db001c7691bcc 100644 --- a/plugins/inputs/dpdk/dpdk_test.go +++ b/plugins/inputs/dpdk/dpdk_test.go @@ -86,10 +86,9 @@ func Test_Init(t *testing.T) { t.Run("when device_types and additional_commands are empty, then error should be returned", func(t *testing.T) { pathToSocket, _ := createSocketForTest(t, "") dpdk := Dpdk{ - SocketPath: pathToSocket, - DeviceTypes: []string{}, - AdditionalCommands: []string{}, - Log: testutil.Logger{}, + SocketPath: pathToSocket, + DeviceTypes: make([]string, 0), + Log: testutil.Logger{}, } err := dpdk.Init() @@ -481,10 +480,6 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { dpdk.DeviceTypes = []string{"ethdev"} dpdk.ethdevCommands = []string{"/ethdev/stats", "/ethdev/xstats"} - var err error - dpdk.ethdevExcludedCommandsFilter, err = filter.Compile([]string{}) - require.NoError(t, err) - dpdk.AdditionalCommands = []string{} commands := dpdk.gatherCommands(mockAcc, dpdk.connectors[0]) require.ElementsMatch(t, commands, expectedCommands) @@ -500,7 +495,6 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { dpdk.DeviceTypes = []string{"rawdev"} dpdk.rawdevCommands = []string{"/rawdev/xstats"} - dpdk.AdditionalCommands = []string{} commands := dpdk.gatherCommands(mockAcc, dpdk.connectors[0]) require.ElementsMatch(t, commands, expectedCommands) @@ -519,7 +513,6 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { var err error dpdk.ethdevExcludedCommandsFilter, err = filter.Compile([]string{"/ethdev/xstats"}) require.NoError(t, err) - dpdk.AdditionalCommands = []string{} commands := dpdk.gatherCommands(mockAcc, dpdk.connectors[0]) require.ElementsMatch(t, commands, expectedCommands) @@ -533,10 +526,6 @@ func Test_getCommandsAndParamsCombinations(t *testing.T) { dpdk.DeviceTypes = []string{"ethdev"} dpdk.ethdevCommands = []string{"/ethdev/stats", "/ethdev/xstats"} - var err error - dpdk.ethdevExcludedCommandsFilter, err = filter.Compile([]string{}) - require.NoError(t, err) - dpdk.AdditionalCommands = []string{} commands := dpdk.gatherCommands(mockAcc, dpdk.connectors[0]) require.Empty(t, commands) @@ -607,7 +596,7 @@ func Test_Gather(t *testing.T) { mockAcc := &testutil.Accumulator{} dpdk := Dpdk{ Log: testutil.Logger{}, - PluginOptions: []string{}, + PluginOptions: make([]string, 0), } require.NoError(t, dpdk.Init()) @@ -621,7 +610,6 @@ func Test_Gather(t *testing.T) { mockAcc := &testutil.Accumulator{} dpdk := Dpdk{ Log: testutil.Logger{}, - PluginOptions: []string{}, UnreachableSocketBehavior: unreachableSocketBehaviorIgnore, } require.NoError(t, dpdk.Init()) @@ -769,7 +757,6 @@ func Test_Gather(t *testing.T) { MaxOutputLen: 1024, } mockConn, dpdk, mockAcc := prepareEnvironmentWithInitializedMessage(testInitMessage) - dpdk.MetadataFields = []string{} defer mockConn.AssertExpectations(t) dpdk.AdditionalCommands = []string{"/endpoint1"} simulateResponse(mockConn, `{"/endpoint1":"myvalue"}`, nil) @@ -801,7 +788,6 @@ func Test_Gather(t *testing.T) { func Test_Gather_MultiSocket(t *testing.T) { t.Run("Test Gather without Metadata Fields", func(t *testing.T) { mockConns, dpdk, mockAcc := prepareEnvironmentWithMultiSockets() - dpdk.MetadataFields = []string{} defer func() { for _, mockConn := range mockConns { mockConn.AssertExpectations(t)