Skip to content

Commit

Permalink
chore: Fix linter findings for revive:enforce-map-style in `plugins…
Browse files Browse the repository at this point in the history
…/inputs/[a-m]*` (#16042)

(cherry picked from commit 6c48fbb)
  • Loading branch information
zak-pawel authored and srebhan committed Oct 28, 2024
1 parent 27d2a79 commit 6f721e0
Show file tree
Hide file tree
Showing 33 changed files with 80 additions and 89 deletions.
6 changes: 3 additions & 3 deletions plugins/inputs/aliyuncms/aliyuncms.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (s *AliyunCMS) Init() error {
if metric.Dimensions == "" {
continue
}
metric.dimensionsUdObj = map[string]string{}
metric.dimensionsUdObj = make(map[string]string)
metric.dimensionsUdArr = []map[string]string{}

// first try to unmarshal as an object
Expand Down Expand Up @@ -295,9 +295,9 @@ func (s *AliyunCMS) gatherMetric(acc telegraf.Accumulator, metricName string, me

NextDataPoint:
for _, datapoint := range datapoints {
fields := map[string]interface{}{}
fields := make(map[string]interface{}, len(datapoint))
tags := make(map[string]string, len(datapoint))
datapointTime := int64(0)
tags := map[string]string{}
for key, value := range datapoint {
switch key {
case "instanceId", "BucketName":
Expand Down
20 changes: 8 additions & 12 deletions plugins/inputs/aliyuncms/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,6 @@ func newDiscoveryTool(
discoveryInterval time.Duration,
) (*discoveryTool, error) {
var (
dscReq = map[string]discoveryRequest{}
cli = map[string]aliyunSdkClient{}
responseRootKey string
responseObjectIDKey string
err error
Expand All @@ -115,6 +113,8 @@ func newDiscoveryTool(
rateLimit = 1
}

dscReq := make(map[string]discoveryRequest, len(regions))
cli := make(map[string]aliyunSdkClient, len(regions))
for _, region := range regions {
switch project {
case "acs_ecs_dashboard":
Expand Down Expand Up @@ -252,7 +252,7 @@ func newDiscoveryTool(

func (dt *discoveryTool) parseDiscoveryResponse(resp *responses.CommonResponse) (*parsedDResp, error) {
var (
fullOutput = map[string]interface{}{}
fullOutput = make(map[string]interface{})
data []byte
foundDataItem bool
foundRootKey bool
Expand Down Expand Up @@ -335,8 +335,8 @@ func (dt *discoveryTool) getDiscoveryData(cli aliyunSdkClient, req *requests.Com
req.QueryParams["PageNumber"] = strconv.Itoa(pageNumber)

if len(discoveryData) == totalCount { // All data received
// Map data to appropriate shape before return
preparedData := map[string]interface{}{}
// Map data to the appropriate shape before return
preparedData := make(map[string]interface{}, len(discoveryData))

for _, raw := range discoveryData {
elem, ok := raw.(map[string]interface{})
Expand All @@ -353,10 +353,7 @@ func (dt *discoveryTool) getDiscoveryData(cli aliyunSdkClient, req *requests.Com
}

func (dt *discoveryTool) getDiscoveryDataAcrossRegions(lmtr chan bool) (map[string]interface{}, error) {
var (
data map[string]interface{}
resultData = map[string]interface{}{}
)
resultData := make(map[string]interface{})

for region, cli := range dt.cli {
// Building common request, as the code below is the same no matter
Expand All @@ -383,7 +380,7 @@ func (dt *discoveryTool) getDiscoveryDataAcrossRegions(lmtr chan bool) (map[stri
commonRequest.TransToAcsRequest()

// Get discovery data using common request
data, err = dt.getDiscoveryData(cli, commonRequest, lmtr)
data, err := dt.getDiscoveryData(cli, commonRequest, lmtr)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -428,8 +425,7 @@ func (dt *discoveryTool) start() {
}

if !reflect.DeepEqual(data, lastData) {
lastData = nil
lastData = map[string]interface{}{}
lastData = make(map[string]interface{}, len(data))
for k, v := range data {
lastData[k] = v
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/amd_rocm_smi/amd_rocm_smi.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,6 @@ func genTagsFields(gpus map[string]gpu, system map[string]sysInfo) []metric {
tags := map[string]string{
"name": cardID,
}
fields := map[string]interface{}{}

payload := gpus[cardID]
//nolint:errcheck // silently treat as zero if malformed
Expand All @@ -202,6 +201,7 @@ func genTagsFields(gpus map[string]gpu, system map[string]sysInfo) []metric {

setTagIfUsed(tags, "gpu_unique_id", payload.GpuUniqueID)

fields := make(map[string]interface{}, 20)
setIfUsed("int", fields, "driver_version", strings.ReplaceAll(system["system"].DriverVersion, ".", ""))
setIfUsed("int", fields, "fan_speed", payload.GpuFanSpeedPercentage)
setIfUsed("int64", fields, "memory_total", payload.GpuVRAMTotalMemory)
Expand Down
14 changes: 7 additions & 7 deletions plugins/inputs/ceph/ceph.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ func decodeStatusFsmap(acc telegraf.Accumulator, data *status) error {
"up_standby": data.FSMap.NumUpStandby,
"up": data.FSMap.NumUp,
}
acc.AddFields("ceph_fsmap", fields, map[string]string{})
acc.AddFields("ceph_fsmap", fields, make(map[string]string))
return nil
}

Expand All @@ -521,7 +521,7 @@ func decodeStatusHealth(acc telegraf.Accumulator, data *status) error {
"status_code": statusCodes[data.Health.Status],
"status": data.Health.Status,
}
acc.AddFields("ceph_health", fields, map[string]string{})
acc.AddFields("ceph_health", fields, make(map[string]string))
return nil
}

Expand All @@ -530,7 +530,7 @@ func decodeStatusMonmap(acc telegraf.Accumulator, data *status) error {
fields := map[string]interface{}{
"num_mons": data.MonMap.NumMons,
}
acc.AddFields("ceph_monmap", fields, map[string]string{})
acc.AddFields("ceph_monmap", fields, make(map[string]string))
return nil
}

Expand All @@ -555,7 +555,7 @@ func decodeStatusOsdmap(acc telegraf.Accumulator, data *status) error {
}
}

acc.AddFields("ceph_osdmap", fields, map[string]string{})
acc.AddFields("ceph_osdmap", fields, make(map[string]string))
return nil
}

Expand Down Expand Up @@ -586,7 +586,7 @@ func decodeStatusPgmap(acc telegraf.Accumulator, data *status) error {
"write_bytes_sec": data.PGMap.WriteBytesSec,
"write_op_per_sec": data.PGMap.WriteOpPerSec,
}
acc.AddFields("ceph_pgmap", fields, map[string]string{})
acc.AddFields("ceph_pgmap", fields, make(map[string]string))
return nil
}

Expand Down Expand Up @@ -654,14 +654,14 @@ func decodeDf(acc telegraf.Accumulator, input string) error {
"total_used_raw_ratio": data.Stats.TotalUsedRawRatio,
"total_used": data.Stats.TotalUsed, // pre ceph 0.84
}
acc.AddFields("ceph_usage", fields, map[string]string{})
acc.AddFields("ceph_usage", fields, make(map[string]string))

// ceph.stats_by_class: records per device-class usage
for class, stats := range data.StatsbyClass {
tags := map[string]string{
"class": class,
}
fields := map[string]interface{}{}
fields := make(map[string]interface{})
for key, value := range stats {
fields[key] = value
}
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/chrony/chrony.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ func (c *Chrony) gatherActivity(acc telegraf.Accumulator) error {
return fmt.Errorf("got unexpected response type %T while waiting for activity data", r)
}

tags := map[string]string{}
tags := make(map[string]string, 1)
if c.source != "" {
tags["source"] = c.source
}
Expand Down Expand Up @@ -300,7 +300,7 @@ func (c *Chrony) gatherServerStats(acc telegraf.Accumulator) error {
return fmt.Errorf("querying server statistics failed: %w", err)
}

tags := map[string]string{}
tags := make(map[string]string, 1)
if c.source != "" {
tags["source"] = c.source
}
Expand Down
13 changes: 5 additions & 8 deletions plugins/inputs/cloudwatch/cloudwatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,7 @@ func (c *CloudWatch) Gather(acc telegraf.Accumulator) error {
wg := sync.WaitGroup{}
rLock := sync.Mutex{}

results := map[string][]types.MetricDataResult{}

results := make(map[string][]types.MetricDataResult)
for namespace, namespacedQueries := range queries {
var batches [][]types.MetricDataQuery

Expand Down Expand Up @@ -373,9 +372,8 @@ func (c *CloudWatch) getDataQueries(filteredMetrics []filteredMetric) map[string
return c.metricCache.queries
}

c.queryDimensions = map[string]*map[string]string{}

dataQueries := map[string][]types.MetricDataQuery{}
c.queryDimensions = make(map[string]*map[string]string)
dataQueries := make(map[string][]types.MetricDataQuery)
for i, filtered := range filteredMetrics {
for j, singleMetric := range filtered.metrics {
id := strconv.Itoa(j) + "_" + strconv.Itoa(i)
Expand Down Expand Up @@ -460,8 +458,7 @@ func (c *CloudWatch) aggregateMetrics(acc telegraf.Accumulator, metricDataResult
namespace = sanitizeMeasurement(namespace)

for _, result := range results {
tags := map[string]string{}

tags := make(map[string]string)
if dimensions, ok := c.queryDimensions[*result.Id]; ok {
tags = *dimensions
}
Expand Down Expand Up @@ -507,7 +504,7 @@ func snakeCase(s string) string {

// ctod converts cloudwatch dimensions to regular dimensions.
func ctod(cDimensions []types.Dimension) *map[string]string {
dimensions := map[string]string{}
dimensions := make(map[string]string, len(cDimensions))
for i := range cDimensions {
dimensions[snakeCase(*cDimensions[i].Name)] = *cDimensions[i].Value
}
Expand Down
3 changes: 1 addition & 2 deletions plugins/inputs/couchdb/couchdb.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,6 @@ func (c *CouchDB) fetchAndInsertData(accumulator telegraf.Accumulator, host stri
return fmt.Errorf("failed to decode stats from couchdb: HTTP body %q", response.Body)
}

fields := map[string]interface{}{}

// for couchdb 2.0 API changes
requestTime := metaData{
Current: stats.Couchdb.RequestTime.Current,
Expand Down Expand Up @@ -207,6 +205,7 @@ func (c *CouchDB) fetchAndInsertData(accumulator telegraf.Accumulator, host stri
httpdStatusCodesStatus500 = stats.Couchdb.HttpdStatusCodes.Status500
}

fields := make(map[string]interface{}, 31)
// CouchDB meta stats:
c.generateFields(fields, "couchdb_auth_cache_misses", stats.Couchdb.AuthCacheMisses)
c.generateFields(fields, "couchdb_database_writes", stats.Couchdb.DatabaseWrites)
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/directory_monitor/directory_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ func (monitor *DirectoryMonitor) Init() error {
tags := map[string]string{
"directory": monitor.Directory,
}
monitor.filesDropped = selfstat.Register("directory_monitor", "files_dropped", map[string]string{})
monitor.filesDropped = selfstat.Register("directory_monitor", "files_dropped", make(map[string]string))
monitor.filesDroppedDir = selfstat.Register("directory_monitor", "files_dropped_per_dir", tags)
monitor.filesProcessed = selfstat.Register("directory_monitor", "files_processed", map[string]string{})
monitor.filesProcessed = selfstat.Register("directory_monitor", "files_processed", make(map[string]string))
monitor.filesProcessedDir = selfstat.Register("directory_monitor", "files_processed_per_dir", tags)
monitor.filesQueuedDir = selfstat.Register("directory_monitor", "files_queue_per_dir", tags)

Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/diskio/diskio.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (d *DiskIO) Gather(acc telegraf.Accumulator) error {
match = true
}

tags := map[string]string{}
tags := make(map[string]string)
var devLinks []string
tags["name"], devLinks = d.diskName(io.Name)

Expand Down Expand Up @@ -187,7 +187,7 @@ func (d *DiskIO) diskTags(devName string) map[string]string {
return nil
}

tags := map[string]string{}
tags := make(map[string]string, len(d.DeviceTags))
for _, dt := range d.DeviceTags {
if v, ok := di[dt]; ok {
tags[dt] = v
Expand Down
11 changes: 5 additions & 6 deletions plugins/inputs/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,16 +276,15 @@ func (d *Docker) gatherSwarmInfo(acc telegraf.Accumulator) error {
return err
}

running := map[string]int{}
tasksNoShutdown := map[string]uint64{}

activeNodes := make(map[string]struct{})
for _, n := range nodes {
if n.Status.State != swarm.NodeStateDown {
activeNodes[n.ID] = struct{}{}
}
}

tasksNoShutdown := make(map[string]uint64, len(tasks))
running := make(map[string]int, len(tasks))
for _, task := range tasks {
if task.DesiredState != swarm.TaskStateShutdown {
tasksNoShutdown[task.ServiceID]++
Expand All @@ -297,8 +296,8 @@ func (d *Docker) gatherSwarmInfo(acc telegraf.Accumulator) error {
}

for _, service := range services {
tags := map[string]string{}
fields := make(map[string]interface{})
tags := make(map[string]string, 3)
fields := make(map[string]interface{}, 2)
now := time.Now()
tags["service_id"] = service.ID
tags["service_name"] = service.Spec.Name
Expand Down Expand Up @@ -375,7 +374,7 @@ func (d *Docker) gatherInfo(acc telegraf.Accumulator) error {
var (
// "docker_devicemapper" measurement fields
poolName string
deviceMapperFields = map[string]interface{}{}
deviceMapperFields = make(map[string]interface{}, len(info.DriverStatus))
)

for _, rawData := range info.DriverStatus {
Expand Down
8 changes: 4 additions & 4 deletions plugins/inputs/elasticsearch/elasticsearch.go
Original file line number Diff line number Diff line change
Expand Up @@ -548,11 +548,11 @@ func (e *Elasticsearch) gatherIndicesStats(url string, acc telegraf.Accumulator)
now := time.Now()

// Total Shards Stats
shardsStats := map[string]interface{}{}
shardsStats := make(map[string]interface{}, len(indicesStats.Shards))
for k, v := range indicesStats.Shards {
shardsStats[k] = v
}
acc.AddFields("elasticsearch_indices_stats_shards_total", shardsStats, map[string]string{}, now)
acc.AddFields("elasticsearch_indices_stats_shards_total", shardsStats, make(map[string]string), now)

// All Stats
for m, s := range indicesStats.All {
Expand Down Expand Up @@ -603,7 +603,7 @@ func (e *Elasticsearch) gatherIndividualIndicesStats(indices map[string]indexSta
}

func (e *Elasticsearch) categorizeIndices(indices map[string]indexStat) map[string][]string {
categorizedIndexNames := map[string][]string{}
categorizedIndexNames := make(map[string][]string, len(indices))

// If all indices are configured to be gathered, bucket them all together.
if len(e.IndicesInclude) == 0 || e.IndicesInclude[0] == "_all" {
Expand Down Expand Up @@ -768,8 +768,8 @@ func (e *Elasticsearch) gatherJSONData(url string, v interface{}) error {
}

func (e *Elasticsearch) compileIndexMatchers() (map[string]filter.Filter, error) {
indexMatchers := map[string]filter.Filter{}
var err error
indexMatchers := make(map[string]filter.Filter, len(e.IndicesInclude))

// Compile each configured index into a glob matcher.
for _, configuredIndex := range e.IndicesInclude {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/elasticsearch_query/aggregation_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func parseSimpleResult(acc telegraf.Accumulator, measurement string, searchResul
}

func parseAggregationResult(acc telegraf.Accumulator, aggregationQueryList []aggregationQueryData, searchResult *elastic5.SearchResult) error {
measurements := map[string]map[string]string{}
measurements := make(map[string]map[string]string, len(aggregationQueryList))

// organize the aggregation query data by measurement
for _, aggregationQuery := range aggregationQueryList {
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/ethtool/ethtool_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ func (c *CommandEthtool) Interfaces(includeNamespaces bool) ([]NamespacedInterfa
// Handles are only used to create namespaced goroutines. We don't prefill
// with the handle for the initial namespace because we've already created
// its goroutine in Init().
handles := map[string]netns.NsHandle{}
handles := make(map[string]netns.NsHandle)

if includeNamespaces {
namespaces, err := os.ReadDir(namespaceDirectory)
Expand Down
4 changes: 2 additions & 2 deletions plugins/inputs/fibaro/hc2/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func Parse(acc telegraf.Accumulator, sectionBytes, roomBytes, deviecsBytes []byt
return err
}

sections := map[uint16]string{}
sections := make(map[uint16]string, len(tmpSections))
for _, v := range tmpSections {
sections[v.ID] = v.Name
}
Expand All @@ -22,7 +22,7 @@ func Parse(acc telegraf.Accumulator, sectionBytes, roomBytes, deviecsBytes []byt
if err := json.Unmarshal(roomBytes, &tmpRooms); err != nil {
return err
}
rooms := map[uint16]LinkRoomsSections{}
rooms := make(map[uint16]LinkRoomsSections, len(tmpRooms))
for _, v := range tmpRooms {
rooms[v.ID] = LinkRoomsSections{Name: v.Name, SectionID: v.SectionID}
}
Expand Down
2 changes: 1 addition & 1 deletion plugins/inputs/hugepages/hugepages.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ func (h *Hugepages) gatherStatsFromMeminfo(acc telegraf.Accumulator) error {
metrics[metricName] = fieldValue
}

acc.AddFields("hugepages_"+meminfoHugepages, metrics, map[string]string{})
acc.AddFields("hugepages_"+meminfoHugepages, metrics, make(map[string]string))
return nil
}

Expand Down
Loading

0 comments on commit 6f721e0

Please sign in to comment.