@cryptotaxi247 / netdata-1 / commits / 1ddf37071

chore(go): go fix (#22133)

Ilya Mashchenko committed Apr 3, 2026 at 23:37 UTC 1ddf37071849969e4ca3b9137029663ff5ec5bf4
190 files changed +445 -666
src/go/cmd/godplugin/main.go
+3 -3
@@ -50,7 +50,7 @@ func init() {
50 }
51
52 func main() {
53 - _, _ = maxprocs.Set(maxprocs.Logger(func(s string, args ...interface{}) {}))
53 + _, _ = maxprocs.Set(maxprocs.Logger(func(s string, args ...any) {}))
54
55 opts := parseCLI()
56
@@ -250,8 +250,8 @@ func readFunctionPayload(raw string) ([]byte, time.Duration, error) {
250
251 var data []byte
252 var err error
253 - if strings.HasPrefix(raw, "@") {
254 - data, err = os.ReadFile(strings.TrimPrefix(raw, "@"))
253 + if after, ok := strings.CutPrefix(raw, "@"); ok {
254 + data, err = os.ReadFile(after)
255 } else {
256 data = []byte(raw)
257 }
src/go/cmd/ibmdplugin/main.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package main
6
src/go/cmd/internal/agenthost/host.go
+2 -4
@@ -51,12 +51,10 @@ func Run(a *agent.Agent) {
51
52 ctx, cancel := context.WithCancel(context.Background())
53 runDone := make(chan struct{})
54 - wg.Add(1)
55 - go func() {
56 - defer wg.Done()
54 + wg.Go(func() {
55 defer close(runDone)
56 a.RunContext(ctx)
59 - }()
57 + })
58
59 select {
60 case sig := <-ch:
src/go/cmd/scriptsdplugin/main.go
+1 -1
@@ -37,7 +37,7 @@ func init() {
37 }
38
39 func main() {
40 - _, _ = maxprocs.Set(maxprocs.Logger(func(string, ...interface{}) {}))
40 + _, _ = maxprocs.Set(maxprocs.Logger(func(string, ...any) {}))
41
42 opts := parseCLI()
43
src/go/logger/ratelimit_test.go
+4 -6
@@ -17,7 +17,7 @@ func TestLimitUsesFixedWindow(t *testing.T) {
17 now := time.Unix(100, 0)
18 l.rl.now = func() time.Time { return now }
19
20 - for i := 0; i < 3; i++ {
20 + for range 3 {
21 l.Limit("k", 2, 5*time.Second).Info("msg")
22 }
23 assert.Equal(t, 2, h.count())
@@ -159,12 +159,10 @@ func TestOnceConcurrentLogsOnlyOnce(t *testing.T) {
159
160 l, h := newTestLogger(slog.LevelDebug)
161 var wg sync.WaitGroup
162 - for i := 0; i < 100; i++ {
163 - wg.Add(1)
164 - go func() {
165 - defer wg.Done()
162 + for range 100 {
163 + wg.Go(func() {
164 l.Once("concurrent").Info("x")
167 - }()
165 + })
166 }
167 wg.Wait()
168
src/go/pkg/confopt/autobool.go
+3 -3
@@ -90,7 +90,7 @@ func AutoBoolFromBool(value bool) AutoBool {
90 }
91
92 // MarshalYAML ensures we always emit the canonical lower-case string.
93 -func (a AutoBool) MarshalYAML() (interface{}, error) {
93 +func (a AutoBool) MarshalYAML() (any, error) {
94 return a.String(), nil
95 }
96
@@ -98,13 +98,13 @@ func (a AutoBool) MarshalYAML() (interface{}, error) {
98 // defaults to auto when empty. Any other value results in an error to ensure
99 // early feedback. The signature matches the yaml.v2 marshaler interface so the
100 // same implementation works for both yaml.v2 and yaml.v3 consumers.
101 -func (a *AutoBool) UnmarshalYAML(unmarshal func(interface{}) error) error {
101 +func (a *AutoBool) UnmarshalYAML(unmarshal func(any) error) error {
102 if unmarshal == nil {
103 *a = AutoBoolAuto
104 return nil
105 }
106
107 - var raw interface{}
107 + var raw any
108 if err := unmarshal(&raw); err != nil {
109 return err
110 }
src/go/pkg/matcher/simple_patterns.go
+1 -1
@@ -20,7 +20,7 @@ type (
20 func NewSimplePatternsMatcher(expr string) (Matcher, error) {
21 ps := simplePatternsMatcher{}
22
23 - for _, pattern := range strings.Fields(expr) {
23 + for pattern := range strings.FieldsSeq(expr) {
24 if err := ps.add(pattern); err != nil {
25 return nil, err
26 }
src/go/pkg/metrix/collector_store.go
+3 -6
@@ -4,6 +4,7 @@ package metrix
4
5 import (
6 "fmt"
7 + "maps"
8 "math"
9 "sort"
10 "strings"
@@ -262,9 +263,7 @@ func (c *storeCycleController) CommitCycleSuccess() {
263 byName: nil,
264 }
265
265 - for k, s := range oldSnap.series {
266 - next.series[k] = s
267 - }
266 + maps.Copy(next.series, oldSnap.series)
267
268 for key, staged := range c.core.active.gauges {
269 series := getOrCreateCommitSeries(oldSnap, next, key, staged.name, staged.labels, staged.labelsKey, staged.desc)
@@ -694,9 +693,7 @@ func cloneStateMap(in map[string]bool) map[string]bool {
693 return nil
694 }
695 out := make(map[string]bool, len(in))
697 - for k, v := range in {
698 - out[k] = v
699 - }
696 + maps.Copy(out, in)
697 return out
698 }
699
src/go/pkg/metrix/collector_store_concurrency_test.go
+3 -5
@@ -27,19 +27,17 @@ func TestCollectorStoreConcurrencyScenarios(t *testing.T) {
27 var writerWG sync.WaitGroup
28 var readerWG sync.WaitGroup
29
30 - writerWG.Add(1)
31 - go func() {
32 - defer writerWG.Done()
30 + writerWG.Go(func() {
31 for i := 1; i <= cycles; i++ {
32 cc.BeginCycle()
33 g.Observe(SampleValue(i))
34 cc.CommitCycleSuccess()
35 }
36 writeDone.Store(true)
39 - }()
37 + })
38
39 readerWG.Add(readers)
42 - for i := 0; i < readers; i++ {
40 + for range readers {
41 go func() {
42 defer readerWG.Done()
43 for !writeDone.Load() {
src/go/pkg/metrix/reader.go
+2 -3
@@ -3,6 +3,7 @@
3 package metrix
4
5 import (
6 + "maps"
7 "math"
8 "sort"
9 "sync"
@@ -659,9 +660,7 @@ func materializeRuntimeSeries(snap *readSnapshot) map[string]*committedSeries {
660 // Chain is leaf->root; root map gives the best starting capacity hint.
661 series := make(map[string]*committedSeries, len(chain[len(chain)-1].series))
662 for i := len(chain) - 1; i >= 0; i-- {
662 - for key, s := range chain[i].series {
663 - series[key] = s
664 - }
663 + maps.Copy(series, chain[i].series)
664 }
665 return series
666 }
src/go/pkg/metrix/retention.go
+1 -1
@@ -40,7 +40,7 @@ func evictOldestSeries[T cmp.Ordered](
40 })
41
42 evictCount := len(series) - maxSeries
43 - for i := 0; i < evictCount; i++ {
43 + for i := range evictCount {
44 key := candidates[i].key
45 delete(series, key)
46 if onEvict != nil {
src/go/pkg/metrix/runtime_store_test.go
+2 -2
@@ -177,10 +177,10 @@ func TestRuntimeStoreScenarios(t *testing.T) {
177
178 var wg sync.WaitGroup
179 wg.Add(workers)
180 - for i := 0; i < workers; i++ {
180 + for range workers {
181 go func() {
182 defer wg.Done()
183 - for j := 0; j < perWorker; j++ {
183 + for range perWorker {
184 c.Add(1)
185 }
186 }()
src/go/pkg/metrix/selector/selector_test.go
+2 -3
@@ -3,6 +3,7 @@
3 package selector
4
5 import (
6 + "maps"
7 "sort"
8 "testing"
9
@@ -35,9 +36,7 @@ func (m mapLabelView) Range(fn func(key, value string) bool) {
36
37 func (m mapLabelView) CloneMap() map[string]string {
38 out := make(map[string]string, len(m))
38 - for key, value := range m {
39 - out[key] = value
40 - }
39 + maps.Copy(out, m)
40 return out
41 }
42
src/go/pkg/metrix/summary.go
+1 -4
@@ -265,10 +265,7 @@ func newSummaryQuantileSketch(capacity int, seed uint64) *summaryQuantileSketch
265 if seed == 0 {
266 seed = 1
267 }
268 - initCap := capacity
269 - if initCap > initialSummaryReservoirCapacity {
270 - initCap = initialSummaryReservoirCapacity
271 - }
268 + initCap := min(capacity, initialSummaryReservoirCapacity)
269 return &summaryQuantileSketch{
270 capacity: capacity,
271 rng: seed,
src/go/pkg/metrix/summary_bench_test.go
+1 -1
@@ -151,7 +151,7 @@ func benchmarkCycleController(b *testing.B, s CollectorStore) CycleController {
151 func benchmarkSummaryValues(n int) []SampleValue {
152 vals := make([]SampleValue, n)
153 var x uint64 = 0x9e3779b97f4a7c15
154 - for i := 0; i < n; i++ {
154 + for i := range n {
155 // Deterministic pseudo-random in [0,1).
156 x ^= x >> 12
157 x ^= x << 25
src/go/pkg/metrix/summary_store_test.go
+1 -1
@@ -195,7 +195,7 @@ func TestSummaryStoreScenarios(t *testing.T) {
195 WithSummaryReservoirSize(8),
196 )
197 cc.BeginCycle()
198 - for i := 0; i < 100; i++ {
198 + for i := range 100 {
199 sum.Observe(SampleValue(i))
200 }
201 cc.CommitCycleSuccess()
src/go/pkg/metrix/vec_store_test.go
+2 -3
@@ -115,11 +115,10 @@ func TestVecStoreScenarios(t *testing.T) {
115 cc.BeginCycle()
116 var wg sync.WaitGroup
117 wg.Add(workers)
118 - for worker := 0; worker < workers; worker++ {
119 - worker := worker
118 + for worker := range workers {
119 go func() {
120 defer wg.Done()
122 - for i := 0; i < iterations; i++ {
121 + for i := range iterations {
122 label := strconv.Itoa((worker*iterations + i) % distinct)
123 vec.WithLabelValues(label).Observe(SampleValue(i))
124 }
src/go/pkg/prometheus/client_test.go
+3 -3
@@ -104,7 +104,7 @@ func TestPrometheusGzip(t *testing.T) {
104 req := web.RequestConfig{URL: ts.URL + "/metrics"}
105 prom := New(http.DefaultClient, req)
106
107 - for i := 0; i < 2; i++ {
107 + for range 2 {
108 res, err := prom.ScrapeSeries()
109 assert.NoError(t, err)
110 verifyTestData(t, res)
@@ -116,7 +116,7 @@ func TestPrometheusReadFromFile(t *testing.T) {
116
117 prom := NewWithSelector(http.DefaultClient, req, nil)
118
119 - for i := 0; i < 2; i++ {
119 + for range 2 {
120 res, err := prom.ScrapeSeries()
121 assert.NoError(t, err)
122 verifyTestData(t, res)
@@ -124,7 +124,7 @@ func TestPrometheusReadFromFile(t *testing.T) {
124
125 prom = New(http.DefaultClient, req)
126
127 - for i := 0; i < 2; i++ {
127 + for range 2 {
128 res, err := prom.ScrapeSeries()
129 assert.NoError(t, err)
130 verifyTestData(t, res)
src/go/pkg/prometheus/parse_test.go
+2 -2
@@ -1345,7 +1345,7 @@ func TestPromTextParser_parseToMetricFamilies(t *testing.T) {
1345 t.Run(name, func(t *testing.T) {
1346 var p promTextParser
1347
1348 - for i := 0; i < 10; i++ {
1348 + for i := range 10 {
1349 t.Run(fmt.Sprintf("parse num %d", i+1), func(t *testing.T) {
1350 mfs, err := p.parseToMetricFamilies(test.input)
1351 if len(test.want) > 0 {
@@ -1622,7 +1622,7 @@ test_histogram_no_meta_1_duration_seconds_count{label1="value1"} 6
1622 t.Run(name, func(t *testing.T) {
1623 var p promTextParser
1624
1625 - for i := 0; i < 10; i++ {
1625 + for i := range 10 {
1626 t.Run(fmt.Sprintf("parse num %d", i+1), func(t *testing.T) {
1627 series, err := p.parseToSeries(test.input)
1628
src/go/pkg/stm/stm.go
+1 -1
@@ -43,7 +43,7 @@ func toMap(value reflect.Value, rv map[string]int64, key string, mul, div int) {
43 }
44 }
45 switch value.Kind() {
46 - case reflect.Ptr:
46 + case reflect.Pointer:
47 convertPtr(value, rv, key, mul, div)
48 case reflect.Struct:
49 convertStruct(value, rv, key)
src/go/pkg/ticker/ticket_test.go
+2 -3
@@ -11,8 +11,7 @@ import (
11 var allowedDelta = 500 * time.Millisecond
12
13 func TestTickerParallel(t *testing.T) {
14 - for i := 0; i < 100; i++ {
15 - i := i
14 + for i := range 100 {
15 go func() {
16 time.Sleep(time.Second / 100 * time.Duration(i))
17 TestTicker(t)
@@ -25,7 +24,7 @@ func TestTicker(t *testing.T) {
24 tk := New(time.Second)
25 defer tk.Stop()
26 prev := time.Now()
28 - for i := 0; i < 3; i++ {
27 + for i := range 3 {
28 <-tk.C
29 now := time.Now()
30 diff := abs(now.Round(time.Second).Sub(now))
src/go/pkg/web/request_config.go
+2 -3
@@ -6,6 +6,7 @@ import (
6 "encoding/base64"
7 "fmt"
8 "io"
9 + "maps"
10 "net/http"
11 "net/url"
12 "os"
@@ -59,9 +60,7 @@ func (r RequestConfig) Copy() RequestConfig {
60 }
61
62 headers := make(map[string]string, len(r.Headers))
62 - for k, v := range r.Headers {
63 - headers[k] = v
64 - }
63 + maps.Copy(headers, r.Headers)
64 r.Headers = headers
65 return r
66 }
src/go/pkg/web/request_config_test.go
+3 -3
@@ -413,10 +413,10 @@ func parseBasicAuth(auth string) (username, password string, ok bool) {
413 }
414
415 decodedStr := string(decoded)
416 - idx := strings.IndexByte(decodedStr, ':')
417 - if idx < 0 {
416 + before, after, ok0 := strings.Cut(decodedStr, ":")
417 + if !ok0 {
418 return "", "", false
419 }
420
421 - return decodedStr[:idx], decodedStr[idx+1:], true
421 + return before, after, true
422 }
src/go/plugin/agent/agent.go
+3 -6
@@ -259,14 +259,11 @@ func (a *Agent) run(ctx context.Context) {
259 in := make(chan []*confgroup.Group)
260 var wg sync.WaitGroup
261
262 - wg.Add(1)
263 - go func() { defer wg.Done(); fnMgr.Run(ctx, a.quitCh) }()
262 + wg.Go(func() { fnMgr.Run(ctx, a.quitCh) })
263
265 - wg.Add(1)
266 - go func() { defer wg.Done(); jobMgr.Run(ctx, in) }()
264 + wg.Go(func() { jobMgr.Run(ctx, in) })
265
268 - wg.Add(1)
269 - go func() { defer wg.Done(); discMgr.Run(ctx, in) }()
266 + wg.Go(func() { discMgr.Run(ctx, in) })
267
268 wg.Wait()
269 <-ctx.Done()
src/go/plugin/agent/agent_test.go
+1 -3
@@ -137,8 +137,7 @@ func TestAgent_Run(t *testing.T) {
137 ctx, cancel := context.WithCancel(context.Background())
138 var wg sync.WaitGroup
139
140 - wg.Add(1)
141 - go func() { defer wg.Done(); a.run(ctx) }()
140 + wg.Go(func() { a.run(ctx) })
141
142 time.Sleep(time.Second * 2)
143 cancel()
@@ -160,7 +159,6 @@ func TestAgent_Run(t *testing.T) {
159 func prepareRegistry(mux *sync.Mutex, stats map[string]int, names ...string) collectorapi.Registry {
160 reg := collectorapi.Registry{}
161 for _, name := range names {
163 - name := name
162 reg.Register(name, collectorapi.Creator{
163 Create: func() collectorapi.CollectorV1 {
164 return prepareMockModule(name, mux, stats)
src/go/plugin/agent/discovery/manager.go
+2 -4
@@ -64,11 +64,9 @@ func (m *Manager) Run(ctx context.Context, in chan<- []*confgroup.Group) {
64 }(d)
65 }
66
67 - wg.Add(1)
68 - go func() {
69 - defer wg.Done()
67 + wg.Go(func() {
68 m.sendLoop(ctx, in)
71 - }()
69 + })
70
71 wg.Wait()
72 <-ctx.Done()
src/go/plugin/agent/discovery/manager_test.go
+2 -2
@@ -166,11 +166,11 @@ func TestManager_Run(t *testing.T) {
166 func prepareMockDiscoverer(source string, groups, configs int) mockDiscoverer {
167 d := mockDiscoverer{}
168
169 - for i := 0; i < groups; i++ {
169 + for i := range groups {
170 group := confgroup.Group{
171 Source: fmt.Sprintf("%s_group_%d", source, i+1),
172 }
173 - for j := 0; j < configs; j++ {
173 + for j := range configs {
174 group.Configs = append(group.Configs,
175 confgroup.Config{"name": fmt.Sprintf("%s_group_%d_target_%d", source, i+1, j+1)})
176 }
src/go/plugin/agent/discovery/sd/discoverer_types_test.go
+2 -2
@@ -26,10 +26,10 @@ type testK8sConfig struct {
26 Namespaces []string `json:"namespaces,omitempty" yaml:"namespaces,omitempty"`
27 Selector struct {
28 Label string `json:"label,omitempty" yaml:"label,omitempty"`
29 - } `json:"selector,omitempty" yaml:"selector,omitempty"`
29 + } `json:"selector" yaml:"selector,omitempty"`
30 Pod struct {
31 LocalMode bool `json:"local_mode,omitempty" yaml:"local_mode,omitempty"`
32 - } `json:"pod,omitempty" yaml:"pod,omitempty"`
32 + } `json:"pod" yaml:"pod,omitempty"`
33 }
34
35 type testSNMPConfig struct {
src/go/plugin/agent/discovery/sd/dyncfg_cache.go
+2 -2
@@ -191,8 +191,8 @@ func sourceTypeFromPath(path string) string {
191
192 func configNameFromSource(source string) string {
193 base := filepath.Base(strings.TrimSpace(source))
194 - if strings.HasSuffix(base, ".conf") {
195 - base = strings.TrimSuffix(base, ".conf")
194 + if before, ok := strings.CutSuffix(base, ".conf"); ok {
195 + base = before
196 }
197 return base
198 }
src/go/plugin/agent/discovery/sd/dyncfg_test.go
+1 -1
@@ -186,7 +186,7 @@ func (s *dyncfgSim) run(t *testing.T) {
186
187 // Filter and normalize dyncfg output (same approach as jobmgr sim_test.go)
188 var lines []string
189 - for _, line := range strings.Split(buf.String(), "\n") {
189 + for line := range strings.SplitSeq(buf.String(), "\n") {
190 // Skip template CONFIG lines (registered on startup)
191 if strings.HasPrefix(line, "CONFIG") && strings.Contains(line, " template ") {
192 continue
src/go/plugin/agent/discovery/sd/pipeline/config.go
+1 -1
@@ -21,7 +21,7 @@ type Config struct {
21 Name string `yaml:"name" json:"name"`
22
23 // Canonical format: discoverer: { <type>: <config> }
24 - Discoverer DiscovererPayload `yaml:"discoverer,omitempty" json:"discoverer,omitempty"`
24 + Discoverer DiscovererPayload `yaml:"discoverer,omitempty" json:"discoverer"`
25
26 // New single-step format for service rules:
27 Services []ServiceRuleConfig `yaml:"services,omitempty" json:"services,omitempty"`
src/go/plugin/agent/discovery/sd/pipeline/funcmap.go
+2 -3
@@ -3,6 +3,7 @@
3 package pipeline
4
5 import (
6 + "maps"
7 "regexp"
8 "strconv"
9 "text/template"
@@ -27,9 +28,7 @@ func newFuncMap() template.FuncMap {
28 },
29 }
30
30 - for name, fn := range extra {
31 - fm[name] = fn
32 - }
31 + maps.Copy(fm, extra)
32
33 return fm
34 }
src/go/plugin/agent/discovery/sd/pipeline/selector.go
+1 -1
@@ -66,7 +66,7 @@ func parseSelector(line string) (sr selector, err error) {
66
67 func parseOrSelectorWord(orWord string) (sr selector, err error) {
68 var srs []selector
69 - for _, word := range strings.Split(orWord, "|") {
69 + for word := range strings.SplitSeq(orWord, "|") {
70 if sr, err = parseSingleSelectorWord(word); err != nil {
71 return nil, err
72 }
src/go/plugin/agent/discovery/sd/pipeline_manager.go
+2 -3
@@ -5,6 +5,7 @@ package sd
5 import (
6 "context"
7 "fmt"
8 + "maps"
9 "sync"
10 "time"
11
@@ -415,8 +416,6 @@ func (m *PipelineManager) processGracePeriodRemovals(ctx context.Context) {
416
417 func copySourcesMap(src map[string]struct{}) map[string]struct{} {
418 dst := make(map[string]struct{}, len(src))
418 - for k, v := range src {
419 - dst[k] = v
420 - }
419 + maps.Copy(dst, src)
420 return dst
421 }
src/go/plugin/agent/discovery/sd/pipeline_manager_test.go
+16 -28
@@ -49,8 +49,7 @@ func TestPipelineManager_Start(t *testing.T) {
49
50 for name, tc := range tests {
51 t.Run(name, func(t *testing.T) {
52 - ctx, cancel := context.WithCancel(context.Background())
53 - defer cancel()
52 + ctx := t.Context()
53
54 var sentGroups []*confgroup.Group
55 var mu sync.Mutex
@@ -83,8 +82,7 @@ func TestPipelineManager_Start(t *testing.T) {
82
83 func TestPipelineManager_Stop(t *testing.T) {
84 t.Run("stop sends removal for tracked sources", func(t *testing.T) {
86 - ctx, cancel := context.WithCancel(context.Background())
87 - defer cancel()
85 + ctx := t.Context()
86
87 var sentGroups []*confgroup.Group
88 var mu sync.Mutex
@@ -146,8 +144,7 @@ func TestPipelineManager_Stop(t *testing.T) {
144
145 func TestPipelineManager_Restart(t *testing.T) {
146 t.Run("restart uses grace period for overlapping sources", func(t *testing.T) {
149 - ctx, cancel := context.WithCancel(context.Background())
150 - defer cancel()
147 + ctx := t.Context()
148
149 var sentGroups []*confgroup.Group
150 var mu sync.Mutex
@@ -226,8 +223,7 @@ func TestPipelineManager_Restart(t *testing.T) {
223 })
224
225 t.Run("restart with invalid config keeps old pipeline", func(t *testing.T) {
229 - ctx, cancel := context.WithCancel(context.Background())
230 - defer cancel()
226 + ctx := t.Context()
227
228 callCount := 0
229 m := NewPipelineManager(
@@ -258,8 +254,7 @@ func TestPipelineManager_Restart(t *testing.T) {
254
255 func TestPipelineManager_StopAll(t *testing.T) {
256 t.Run("stops all pipelines and sends removals", func(t *testing.T) {
261 - ctx, cancel := context.WithCancel(context.Background())
262 - defer cancel()
257 + ctx := t.Context()
258
259 var sentGroups []*confgroup.Group
260 var mu sync.Mutex
@@ -300,8 +295,7 @@ func TestPipelineManager_StopAll(t *testing.T) {
295
296 func TestPipelineManager_RunGracePeriodCleanup(t *testing.T) {
297 t.Run("expired pending removals are cleaned up", func(t *testing.T) {
303 - ctx, cancel := context.WithCancel(context.Background())
304 - defer cancel()
298 + ctx := t.Context()
299
300 var sentGroups []*confgroup.Group
301 var mu sync.Mutex
@@ -349,8 +343,7 @@ func TestPipelineManager_RunGracePeriodCleanup(t *testing.T) {
343 })
344
345 t.Run("non-expired pending removals are preserved", func(t *testing.T) {
352 - ctx, cancel := context.WithCancel(context.Background())
353 - defer cancel()
346 + ctx := t.Context()
347
348 var sentGroups []*confgroup.Group
349 var mu sync.Mutex
@@ -398,8 +391,7 @@ func TestPipelineManager_RunGracePeriodCleanup(t *testing.T) {
391 }
392
393 func TestPipelineManager_IsRunning(t *testing.T) {
401 - ctx, cancel := context.WithCancel(context.Background())
402 - defer cancel()
394 + ctx := t.Context()
395
396 m := NewPipelineManager(
397 logger.New(),
@@ -418,8 +410,7 @@ func TestPipelineManager_IsRunning(t *testing.T) {
410 }
411
412 func TestPipelineManager_Keys(t *testing.T) {
421 - ctx, cancel := context.WithCancel(context.Background())
422 - defer cancel()
413 + ctx := t.Context()
414
415 m := NewPipelineManager(
416 logger.New(),
@@ -442,8 +433,7 @@ func TestPipelineManager_ConcurrentOperations(t *testing.T) {
433 // happen in production (ServiceDiscovery.run() processes events sequentially).
434 // This test verifies concurrent operations on DIFFERENT keys work correctly.
435
445 - ctx, cancel := context.WithCancel(context.Background())
446 - defer cancel()
436 + ctx := t.Context()
437
438 // Track created and stopped pipelines to detect leaks
439 var created, stopped atomic.Int64
@@ -462,7 +452,7 @@ func TestPipelineManager_ConcurrentOperations(t *testing.T) {
452 var wg sync.WaitGroup
453
454 // Concurrent starts for different keys
465 - for i := 0; i < 10; i++ {
455 + for i := range 10 {
456 wg.Add(1)
457 go func(i int) {
458 defer wg.Done()
@@ -472,7 +462,7 @@ func TestPipelineManager_ConcurrentOperations(t *testing.T) {
462 }
463
464 // Concurrent IsRunning checks
475 - for i := 0; i < 10; i++ {
465 + for i := range 10 {
466 wg.Add(1)
467 go func(i int) {
468 defer wg.Done()
@@ -481,19 +471,17 @@ func TestPipelineManager_ConcurrentOperations(t *testing.T) {
471 }
472
473 // Concurrent Keys checks
484 - for i := 0; i < 10; i++ {
485 - wg.Add(1)
486 - go func() {
487 - defer wg.Done()
474 + for range 10 {
475 + wg.Go(func() {
476 _ = m.Keys()
489 - }()
477 + })
478 }
479
480 wg.Wait()
481
482 // Should have 10 pipelines running (one per unique key)
483 assert.Len(t, m.Keys(), 10)
496 - for i := 0; i < 10; i++ {
484 + for i := range 10 {
485 assert.True(t, m.IsRunning(fmt.Sprintf("pipeline-%d", i)))
486 }
487
src/go/plugin/agent/discovery/sd/sd.go
+3 -6
@@ -161,14 +161,11 @@ func (d *ServiceDiscovery) Run(ctx context.Context, in chan<- []*confgroup.Group
161
162 var wg sync.WaitGroup
163
164 - wg.Add(1)
165 - go func() { defer wg.Done(); d.confProv.run(ctx) }()
164 + wg.Go(func() { d.confProv.run(ctx) })
165
167 - wg.Add(1)
168 - go func() { defer wg.Done(); d.run(ctx) }()
166 + wg.Go(func() { d.run(ctx) })
167
170 - wg.Add(1)
171 - go func() { defer wg.Done(); d.mgr.RunGracePeriodCleanup(ctx) }()
168 + wg.Go(func() { d.mgr.RunGracePeriodCleanup(ctx) })
169
170 wg.Wait()
171
src/go/plugin/agent/jobmgr/dyncfg_collector_helpers.go
+3 -3
@@ -79,11 +79,11 @@ func (m *Manager) extractModuleJobName(id string) (mn string, jn string, ok bool
79
80 func (m *Manager) extractModuleName(id string) (string, bool) {
81 id = strings.TrimPrefix(id, m.dyncfgCollectorPrefixValue())
82 - i := strings.IndexByte(id, ':')
83 - if i == -1 {
82 + before, _, ok := strings.Cut(id, ":")
83 + if !ok {
84 return id, id != ""
85 }
86 - return id[:i], true
86 + return before, true
87 }
88
89 func extractJobName(id string) (string, bool) {
src/go/plugin/agent/jobmgr/funcctl/controller_test.go
+2 -2
@@ -195,7 +195,7 @@ func TestModuleFuncRegistry_Concurrency(t *testing.T) {
195 done := make(chan bool)
196
197 go func() {
198 - for i := 0; i < 100; i++ {
198 + for range 100 {
199 job := newTestRuntimeJob("postgres", "job", true)
200 r.addJob("postgres", "job", job)
201 r.removeJob("postgres", "job")
@@ -204,7 +204,7 @@ func TestModuleFuncRegistry_Concurrency(t *testing.T) {
204 }()
205
206 go func() {
207 - for i := 0; i < 100; i++ {
207 + for range 100 {
208 _ = r.getJobNames("postgres")
209 _ = r.getMethods("postgres")
210 _, _ = r.getJob("postgres", "job")
src/go/plugin/agent/jobmgr/funcctl/dispatch.go
+3 -12
@@ -96,10 +96,7 @@ func (c *Controller) executeMethodRequest(in methodExecutionInput) {
96 return
97 }
98
99 - updateEvery := 1
100 - if in.methodCfg.UpdateEvery > 1 {
101 - updateEvery = in.methodCfg.UpdateEvery
102 - }
99 + updateEvery := max(in.methodCfg.UpdateEvery, 1)
100
101 in.respond(dataResp, methodParams, updateEvery)
102 }
@@ -185,10 +182,7 @@ func (c *Controller) handleMethodFuncInfo(moduleName, methodID string, fn functi
182 help = fmt.Sprintf("%s %s data function", moduleName, methodID)
183 }
184
188 - updateEvery := 1
189 - if methodCfg.UpdateEvery > 1 {
190 - updateEvery = methodCfg.UpdateEvery
191 - }
185 + updateEvery := max(methodCfg.UpdateEvery, 1)
186
187 c.respondJSON(fn, map[string]any{
188 "v": 3,
@@ -456,10 +450,7 @@ func (c *Controller) handleJobMethodFuncInfo(moduleName, jobName, methodID strin
450 help = fmt.Sprintf("%s %s data function", moduleName, methodID)
451 }
452
459 - updateEvery := 1
460 - if methodCfg.UpdateEvery > 1 {
461 - updateEvery = methodCfg.UpdateEvery
462 - }
453 + updateEvery := max(methodCfg.UpdateEvery, 1)
454
455 c.respondJSON(fn, map[string]any{
456 "v": 3,
src/go/plugin/agent/jobmgr/manager.go
+4 -8
@@ -265,17 +265,13 @@ func (m *Manager) Run(ctx context.Context, in chan []*confgroup.Group) {
265
266 var wg sync.WaitGroup
267
268 - wg.Add(1)
269 - go func() { defer wg.Done(); m.runFileStatusPersistence() }()
268 + wg.Go(func() { m.runFileStatusPersistence() })
269
271 - wg.Add(1)
272 - go func() { defer wg.Done(); m.runProcessConfGroups(in) }()
270 + wg.Go(func() { m.runProcessConfGroups(in) })
271
274 - wg.Add(1)
275 - go func() { defer wg.Done(); m.run() }()
272 + wg.Go(func() { m.run() })
273
277 - wg.Add(1)
278 - go func() { defer wg.Done(); m.runNotifyRunningJobs() }()
274 + wg.Go(func() { m.runNotifyRunningJobs() })
275
276 close(m.started)
277
src/go/plugin/agent/jobmgr/secretstore_deps_test.go
+2 -3
@@ -5,6 +5,7 @@ package jobmgr
5 import (
6 "bytes"
7 "context"
8 + "maps"
9 "testing"
10
11 "github.com/stretchr/testify/assert"
@@ -59,9 +60,7 @@ func TestExtractSecretStoreKeys(t *testing.T) {
60 for name, tc := range tests {
61 t.Run(name, func(t *testing.T) {
62 cfg := prepareUserCfg("mod", "job")
62 - for k, v := range tc.cfg {
63 - cfg[k] = v
64 - }
63 + maps.Copy(cfg, tc.cfg)
64 got := extractSecretStoreKeys(cfg)
65 assert.Equal(t, tc.want, got)
66 })
src/go/plugin/agent/jobmgr/sim_test.go
+1 -1
@@ -131,7 +131,7 @@ func (s *runSim) run(t *testing.T) {
131
132 var lines []string
133 skipNextEmpty := false
134 - for _, s := range strings.Split(out.String(), "\n") {
134 + for s := range strings.SplitSeq(out.String(), "\n") {
135 if strings.HasPrefix(s, "CONFIG") && strings.Contains(s, " template ") {
136 skipNextEmpty = false
137 continue
src/go/plugin/agent/runtimechartemit/job.go
+1 -3
@@ -378,9 +378,7 @@ func applyEffectiveChartSet(known map[string]chartengine.ChartMeta, plan charten
378 delete(out, v.ChartID)
379 }
380 }
381 - for chartID, meta := range createCharts {
382 - out[chartID] = meta
383 - }
381 + maps.Copy(out, createCharts)
382 for chartID, meta := range dimensionOnlyCharts {
383 if _, ok := out[chartID]; ok {
384 continue
src/go/plugin/agent/secrets/secretstore/service_hardening_test.go
+6 -10
@@ -251,10 +251,8 @@ func TestServiceConcurrentResolveAndMutation(t *testing.T) {
251 var wg sync.WaitGroup
252 errCh := make(chan error, 32)
253
254 - wg.Add(1)
255 - go func() {
256 - defer wg.Done()
257 - for i := 0; i < 100; i++ {
254 + wg.Go(func() {
255 + for range 100 {
256 snapshot := svc.Capture()
257 val, err := svc.Resolve(context.Background(), snapshot, "vault:vault_prod:secret/data/app#key", "${store:vault:vault_prod:secret/data/app#key}")
258 if err != nil {
@@ -266,12 +264,10 @@ func TestServiceConcurrentResolveAndMutation(t *testing.T) {
264 return
265 }
266 }
269 - }()
267 + })
268
271 - wg.Add(1)
272 - go func() {
273 - defer wg.Done()
274 - for i := 0; i < 100; i++ {
269 + wg.Go(func() {
270 + for i := range 100 {
271 updateCfg := baseCfg
272 if i%2 == 0 {
273 updateCfg.Auth = map[string]any{
@@ -284,7 +280,7 @@ func TestServiceConcurrentResolveAndMutation(t *testing.T) {
280 return
281 }
282 }
287 - }()
283 + })
284
285 wg.Wait()
286 close(errCh)
src/go/plugin/agent/secrets/secretstore/service_impl.go
+4 -5
@@ -5,7 +5,8 @@ package secretstore
5 import (
6 "context"
7 "fmt"
8 - "sort"
8 + "maps"
9 + "slices"
10 "sync"
11 "sync/atomic"
12 "time"
@@ -305,7 +306,7 @@ func newCreatorRegistry(creators ...Creator) creatorRegistry {
306 for kind := range reg.byKind {
307 reg.kinds = append(reg.kinds, kind)
308 }
308 - sort.Slice(reg.kinds, func(i, j int) bool { return reg.kinds[i] < reg.kinds[j] })
309 + slices.Sort(reg.kinds)
310 return reg
311 }
312
@@ -348,9 +349,7 @@ func (s *inMemoryService) prepareConfig(ctx context.Context, cfg Config) (prepar
349 return preparedStore{}, fmt.Errorf("store '%s': marshaling raw config: %w", key, err)
350 }
351 if len(resolvedPayload) != 0 {
351 - for k, v := range resolvedPayload {
352 - raw[k] = v
353 - }
352 + maps.Copy(raw, resolvedPayload)
353 bs, err = yaml.Marshal(raw)
354 if err != nil {
355 return preparedStore{}, fmt.Errorf("store '%s': marshaling resolved config: %w", key, err)
src/go/plugin/agent/secrets/secretstore/service_impl_test.go
-1
@@ -171,7 +171,6 @@ func TestProviderBackedAddAcrossKinds(t *testing.T) {
171 svc := secretstore.NewService(backends.Creators()...)
172
173 for _, entry := range providerBackedConfigs() {
174 - entry := entry
174 t.Run(string(entry.kind), func(t *testing.T) {
175 err := svc.Add(context.Background(), newStoreFromConfig(t, svc, entry.kind, entry.config))
176 require.NoError(t, err)
src/go/plugin/agent/secrets/secretstore/snapshot.go
+5 -4
@@ -2,7 +2,10 @@
2
3 package secretstore
4
5 -import "time"
5 +import (
6 + "maps"
7 + "time"
8 +)
9
10 type publishedRecord struct {
11 published PublishedStore
@@ -55,8 +58,6 @@ func clonePublishedRecords(in map[string]publishedRecord) map[string]publishedRe
58 return map[string]publishedRecord{}
59 }
60 out := make(map[string]publishedRecord, len(in))
58 - for id, store := range in {
59 - out[id] = store
60 - }
61 + maps.Copy(out, in)
62 return out
63 }
src/go/plugin/framework/chartengine/planner.go
+1 -4
@@ -324,10 +324,7 @@ func (e *Engine) preparePlanBuildContext(
324 dimCapHints[chartID] = n
325 }
326 }
327 - chartsCap := e.state.hints.chartsByID
328 - if chartsCap < len(materialized.charts) {
329 - chartsCap = len(materialized.charts)
330 - }
327 + chartsCap := max(e.state.hints.chartsByID, len(materialized.charts))
328 seenInferCap := e.state.hints.seenInfer
329 return &planBuildContext{
330 out: out,
src/go/plugin/framework/chartengine/planner_bench_test.go
+1 -1
@@ -67,7 +67,7 @@ func benchmarkCollectorReader(b *testing.B, seriesCount int) metrix.Reader {
67 g := meter.Gauge("bench_metric")
68
69 cc.BeginCycle()
70 - for i := 0; i < seriesCount; i++ {
70 + for i := range seriesCount {
71 g.Observe(metrix.SampleValue(i), meter.LabelSet(
72 metrix.Label{Key: "id", Value: strconv.Itoa(i)},
73 ))
src/go/plugin/framework/chartengine/template_parse_test.go
-1
@@ -44,7 +44,6 @@ func TestParseTemplateLiteralOnly(t *testing.T) {
44 }
45
46 for name, tc := range tests {
47 - tc := tc
47 t.Run(name, func(t *testing.T) {
48 t.Parallel()
49
src/go/plugin/framework/dyncfg/function.go
+1 -1
@@ -87,7 +87,7 @@ func (f Function) User() string {
87 // Source format is "key1=value1,key2=value2,...".
88 func (f Function) SourceValue(key string) string {
89 prefix := key + "="
90 - for _, part := range strings.Split(f.fn.Source, ",") {
90 + for part := range strings.SplitSeq(f.fn.Source, ",") {
91 if v, ok := strings.CutPrefix(part, prefix); ok {
92 return strings.TrimSpace(v)
93 }
src/go/plugin/framework/functions/manager.go
+2 -3
@@ -7,6 +7,7 @@ import (
7 "errors"
8 "fmt"
9 "log/slog"
10 + "maps"
11 "strconv"
12 "strings"
13 "sync"
@@ -620,9 +621,7 @@ func (m *Manager) snapshotFunction(name string) (functionSnapshot, bool) {
621 snap.direct = fs.direct
622 if len(fs.prefixes) > 0 {
623 snap.prefixes = make(map[string]func(Function), len(fs.prefixes))
623 - for prefix, handler := range fs.prefixes {
624 - snap.prefixes[prefix] = handler
625 - }
624 + maps.Copy(snap.prefixes, fs.prefixes)
625 }
626 }
627 m.mux.Unlock()
src/go/plugin/framework/jobruntime/job_v1.go
+1 -1
@@ -759,7 +759,7 @@ func getChartType(chart *collectorapi.Chart, j *Job) string {
759 }
760 if chart.OverModule != "" {
761 cachedType := chart.CachedType()
762 - if v := strings.TrimPrefix(cachedType, j.ModuleName()); v != cachedType {
762 + if v, ok := strings.CutPrefix(cachedType, j.ModuleName()); ok {
763 chart.SetCachedType(chart.OverModule + v)
764 }
765 }
src/go/plugin/framework/jobruntime/job_v1_test.go
+3 -3
@@ -89,14 +89,14 @@ func TestJob_RetryAutoDetection(t *testing.T) {
89
90 assert.True(t, job.RetryAutoDetection())
91 assert.Equal(t, infTries, job.AutoDetectTries)
92 - for i := 0; i < 1000; i++ {
92 + for range 1000 {
93 _ = job.check()
94 }
95 assert.True(t, job.RetryAutoDetection())
96 assert.Equal(t, infTries, job.AutoDetectTries)
97
98 job.AutoDetectTries = 10
99 - for i := 0; i < 10; i++ {
99 + for range 10 {
100 _ = job.check()
101 }
102 assert.False(t, job.RetryAutoDetection())
@@ -304,7 +304,7 @@ func TestJob_MainLoop_Panic(t *testing.T) {
304
305 func TestJob_Tick(t *testing.T) {
306 job := newTestJob()
307 - for i := 0; i < 3; i++ {
307 + for i := range 3 {
308 job.Tick(i)
309 }
310 }
src/go/plugin/framework/jobruntime/job_v2.go
+2 -3
@@ -8,6 +8,7 @@ import (
8 "fmt"
9 "io"
10 "log/slog"
11 + "maps"
12 "runtime/debug"
13 "sync"
14 "sync/atomic"
@@ -522,9 +523,7 @@ func cloneLabels(in map[string]string) map[string]string {
523 return nil
524 }
525 out := make(map[string]string, len(in))
525 - for k, v := range in {
526 - out[k] = v
527 - }
526 + maps.Copy(out, in)
527 return out
528 }
529
src/go/plugin/framework/jobruntime/job_v2_host_state.go
+1 -3
@@ -139,9 +139,7 @@ func (s *jobV2HostState) commitSuccessfulEmission(plan chartengine.Plan, decisio
139 }
140 }
141
142 - for chartID, meta := range createCharts {
143 - s.cleanupCharts[chartID] = meta
144 - }
142 + maps.Copy(s.cleanupCharts, createCharts)
143 for chartID, meta := range dimensionOnlyCharts {
144 if _, ok := s.cleanupCharts[chartID]; ok {
145 continue
src/go/plugin/framework/jobruntime/job_v2_test.go
+1 -1
@@ -675,7 +675,7 @@ END`, chartengine.Priority, chartengine.Priority))
675 close(done)
676 }()
677
678 - for i := 0; i < 3; i++ {
678 + for i := range 3 {
679 job.Tick(i + 1)
680 time.Sleep(10 * time.Millisecond)
681 }
src/go/plugin/framework/metricsaudit/capture.go
+2 -3
@@ -5,6 +5,7 @@ package metricsaudit
5 import (
6 "encoding/json"
7 "fmt"
8 + "maps"
9 "os"
10 "path/filepath"
11 "sort"
@@ -418,9 +419,7 @@ func cloneIntMetrics(mx map[string]int64) map[string]int64 {
419 return map[string]int64{}
420 }
421 out := make(map[string]int64, len(mx))
421 - for k, v := range mx {
422 - out[k] = v
423 - }
422 + maps.Copy(out, mx)
423 return out
424 }
425
src/go/plugin/framework/metricsaudit/report.go
+12 -31
@@ -4,6 +4,8 @@ package metricsaudit
4
5 import (
6 "fmt"
7 + "maps"
8 + "slices"
9 "sort"
10 "strings"
11 "time"
@@ -130,13 +132,7 @@ func (da *Auditor) PrintSummary() {
132
133 // Update label keys and dimension names if needed
134 for _, label := range ca.Chart.Labels {
133 - found := false
134 - for _, key := range contextMap[ctx].labelKeys {
135 - if key == label.Key {
136 - found = true
137 - break
138 - }
139 - }
135 + found := slices.Contains(contextMap[ctx].labelKeys, label.Key)
136 if !found {
137 contextMap[ctx].labelKeys = append(contextMap[ctx].labelKeys, label.Key)
138 sort.Strings(contextMap[ctx].labelKeys)
@@ -148,13 +144,7 @@ func (da *Auditor) PrintSummary() {
144 if dimName == "" {
145 dimName = dim.ID
146 }
151 - found := false
152 - for _, name := range contextMap[ctx].dimNames {
153 - if name == dimName {
154 - found = true
155 - break
156 - }
157 - }
147 + found := slices.Contains(contextMap[ctx].dimNames, dimName)
148 if !found {
149 contextMap[ctx].dimNames = append(contextMap[ctx].dimNames, dimName)
150 sort.Strings(contextMap[ctx].dimNames)
@@ -536,9 +526,7 @@ func cloneJobAnalysis(src *JobAnalysis) JobAnalysis {
526 AllSeenMetrics: make(map[string]bool, len(src.AllSeenMetrics)),
527 Charts: make([]ChartAnalysis, len(src.Charts)),
528 }
539 - for metricID, seen := range src.AllSeenMetrics {
540 - dst.AllSeenMetrics[metricID] = seen
541 - }
529 + maps.Copy(dst.AllSeenMetrics, src.AllSeenMetrics)
530 for i := range src.Charts {
531 dst.Charts[i] = cloneChartAnalysis(src.Charts[i])
532 }
@@ -555,9 +543,7 @@ func cloneChartAnalysis(src ChartAnalysis) ChartAnalysis {
543 for id, values := range src.CollectedValues {
544 dst.CollectedValues[id] = append([]int64(nil), values...)
545 }
558 - for id, seen := range src.SeenDimensions {
559 - dst.SeenDimensions[id] = seen
560 - }
546 + maps.Copy(dst.SeenDimensions, src.SeenDimensions)
547 return dst
548 }
549
@@ -1064,7 +1050,7 @@ func (da *Auditor) printContextAnalysis(ctxInfo *contextInfo, isLast bool) []str
1050 if len(values) > 5 {
1051 // Show first 3 and last 2 values for long series
1052 firstVals := []string{}
1067 - for i := 0; i < 3; i++ {
1053 + for i := range 3 {
1054 firstVals = append(firstVals, fmt.Sprintf("%d", values[i]))
1055 }
1056 lastVals := []string{}
@@ -1111,12 +1097,7 @@ func (da *Auditor) printContextAnalysis(ctxInfo *contextInfo, isLast bool) []str
1097 }
1098
1099 func contains(slice []string, item string) bool {
1114 - for _, s := range slice {
1115 - if s == item {
1116 - return true
1117 - }
1118 - }
1119 - return false
1100 + return slices.Contains(slice, item)
1101 }
1102
1103 // analyzeMetricDimensionMatching performs comprehensive analysis of dimension/metric matching
@@ -1256,8 +1237,8 @@ func (da *Auditor) analyzeFamilyStructureForJob(job *JobAnalysis, contextIssues
1237
1238 // Extract top-level family
1239 topLevel := family
1259 - if idx := strings.Index(family, "/"); idx != -1 {
1260 - topLevel = family[:idx]
1240 + if before, _, ok := strings.Cut(family, "/"); ok {
1241 + topLevel = before
1242 }
1243 topLevelFamilies[topLevel] = true
1244
@@ -1406,8 +1387,8 @@ func (da *Auditor) analyzeFamilyStructureForJob(job *JobAnalysis, contextIssues
1387 for family := range families {
1388 // Check only the base family name (before /)
1389 baseName := family
1409 - if idx := strings.Index(family, "/"); idx != -1 {
1410 - baseName = family[:idx]
1390 + if before, _, ok := strings.Cut(family, "/"); ok {
1391 + baseName = before
1392 }
1393
1394 if genericFamilies[strings.ToLower(baseName)] {
src/go/plugin/go.d/collector/adaptecraid/collect.go
+3 -3
@@ -20,9 +20,9 @@ func (c *Collector) collect() (map[string]int64, error) {
20 }
21
22 func getColonSepValue(line string) string {
23 - i := strings.IndexByte(line, ':')
24 - if i == -1 {
23 + _, after, ok := strings.Cut(line, ":")
24 + if !ok {
25 return ""
26 }
27 - return strings.TrimSpace(line[i+1:])
27 + return strings.TrimSpace(after)
28 }
src/go/plugin/go.d/collector/adaptecraid/collect_pd.go
+2 -2
@@ -92,8 +92,8 @@ func parsePhysDevInfo(bs []byte) (map[string]*physicalDevice, error) {
92 for sc.Scan() {
93 line := strings.TrimSpace(sc.Text())
94
95 - if strings.HasPrefix(line, "Device #") {
96 - num := strings.TrimPrefix(line, "Device #")
95 + if after, ok := strings.CutPrefix(line, "Device #"); ok {
96 + num := after
97 pd = &physicalDevice{number: num}
98 devices[num] = pd
99 continue
src/go/plugin/go.d/collector/apache/collect.go
+1 -1
@@ -111,7 +111,7 @@ func parseScoreboard(line string) *scoreboard {
111 // “I” Idle cleanup of worker
112 // “.” Open slot with no current process
113 var sb scoreboard
114 - for _, s := range strings.Split(line, "") {
114 + for s := range strings.SplitSeq(line, "") {
115 switch s {
116 case "_":
117 sb.Waiting++
src/go/plugin/go.d/collector/apcupsd/collect.go
+1 -1
@@ -50,7 +50,7 @@ func (c *Collector) collectStatus(mx map[string]int64, resp []byte) error {
50 for _, v := range upsStatuses {
51 mx["status_"+v] = 0
52 }
53 - for _, v := range strings.Fields(st.status) {
53 + for v := range strings.FieldsSeq(st.status) {
54 mx["status_"+v] = 1
55 }
56
src/go/plugin/go.d/collector/azure_monitor/azureprofiles/profile.go
+1 -1
@@ -37,7 +37,7 @@ type Profile struct {
37 ResourceType string `yaml:"resource_type" json:"resource_type,omitempty"`
38 MetricNamespace string `yaml:"metric_namespace,omitempty" json:"metric_namespace,omitempty"`
39 Metrics []Metric `yaml:"metrics" json:"metrics,omitempty"`
40 - Template charttpl.Group `yaml:"template" json:"template,omitempty"`
40 + Template charttpl.Group `yaml:"template" json:"template"`
41 }
42
43 type Metric struct {
src/go/plugin/go.d/collector/azure_monitor/query_executor.go
+2 -8
@@ -45,19 +45,13 @@ func (e *queryExecutor) reset() {
45 }
46
47 func (e *queryExecutor) runQueryBatches(ctx context.Context, batches []queryBatch, queryNow time.Time, queryOffsetSeconds int) []queryBatchResult {
48 - workers := e.maxConcurrency
49 - if workers < 1 {
50 - workers = 1
51 - }
52 - if workers > len(batches) {
53 - workers = len(batches)
54 - }
48 + workers := min(max(e.maxConcurrency, 1), len(batches))
49
50 input := make(chan queryBatch)
51 output := make(chan queryBatchResult, len(batches))
52
53 var wg sync.WaitGroup
60 - for i := 0; i < workers; i++ {
54 + for range workers {
55 wg.Go(func() {
56 for batch := range input {
57 samples, err := e.executeQueryBatch(ctx, batch, queryNow, queryOffsetSeconds)
src/go/plugin/go.d/collector/beanstalk/collect.go
+2 -3
@@ -5,6 +5,7 @@ package beanstalk
5 import (
6 "context"
7 "fmt"
8 + "maps"
9 "slices"
10 "time"
11
@@ -38,9 +39,7 @@ func (c *Collector) collectStats(mx map[string]int64) error {
39 if err != nil {
40 return err
41 }
41 - for k, v := range stm.ToMap(stats) {
42 - mx[k] = v
43 - }
42 + maps.Copy(mx, stm.ToMap(stats))
43 return nil
44 }
45
src/go/plugin/go.d/collector/couchdb/collect.go
+6 -11
@@ -8,6 +8,7 @@ import (
8 "errors"
9 "fmt"
10 "io"
11 + "maps"
12 "math"
13 "net/http"
14 "strings"
@@ -61,9 +62,7 @@ func (c *Collector) collectSystemStats(collected map[string]int64, ms *cdbMetric
62 return
63 }
64
64 - for metric, value := range stm.ToMap(ms.NodeSystem) {
65 - collected[metric] = value
66 - }
65 + maps.Copy(collected, stm.ToMap(ms.NodeSystem))
66
67 collected["peak_msg_queue"] = findMaxMQSize(ms.NodeSystem.MessageQueues)
68 }
@@ -101,18 +100,14 @@ func (c *Collector) scrapeCouchDB() *cdbMetrics {
100 ms := &cdbMetrics{}
101 wg := &sync.WaitGroup{}
102
104 - wg.Add(1)
105 - go func() { defer wg.Done(); c.scrapeNodeStats(ms) }()
103 + wg.Go(func() { c.scrapeNodeStats(ms) })
104
107 - wg.Add(1)
108 - go func() { defer wg.Done(); c.scrapeSystemStats(ms) }()
105 + wg.Go(func() { c.scrapeSystemStats(ms) })
106
110 - wg.Add(1)
111 - go func() { defer wg.Done(); c.scrapeActiveTasks(ms) }()
107 + wg.Go(func() { c.scrapeActiveTasks(ms) })
108
109 if len(c.databases) > 0 {
114 - wg.Add(1)
115 - go func() { defer wg.Done(); c.scrapeDBStats(ms) }()
110 + wg.Go(func() { c.scrapeDBStats(ms) })
111 }
112
113 wg.Wait()
src/go/plugin/go.d/collector/couchdb/collector_test.go
+1 -1
@@ -359,7 +359,7 @@ func TestCollector_Collect(t *testing.T) {
359 defer cleanup()
360
361 var mx map[string]int64
362 - for i := 0; i < 10; i++ {
362 + for range 10 {
363 mx = collr.Collect(context.Background())
364 }
365
src/go/plugin/go.d/collector/dcgm/collector_test.go
+2 -2
@@ -651,9 +651,9 @@ func TestClassifier_AllKnownFieldsAvoidOtherContexts(t *testing.T) {
651 }
652
653 func TestClassifier_NIDLInterconnectAndVGPUSplits(t *testing.T) {
654 - lines := strings.Split(string(dataAllFieldsList), "\n")
654 + lines := strings.SplitSeq(string(dataAllFieldsList), "\n")
655
656 - for _, line := range lines {
656 + for line := range lines {
657 name := strings.TrimSpace(line)
658 if name == "" || strings.HasPrefix(name, "#") {
659 continue
src/go/plugin/go.d/collector/dnsdist/collect.go
+2 -3
@@ -3,6 +3,7 @@
3 package dnsdist
4
5 import (
6 + "maps"
7 "net/url"
8
9 "github.com/netdata/netdata/go/plugins/pkg/stm"
@@ -26,9 +27,7 @@ func (c *Collector) collect() (map[string]int64, error) {
27 }
28
29 func (c *Collector) collectStatistic(collected map[string]int64, statistics *statisticMetrics) {
29 - for metric, value := range stm.ToMap(statistics) {
30 - collected[metric] = value
31 - }
30 + maps.Copy(collected, stm.ToMap(statistics))
31 }
32
33 func (c *Collector) scrapeStatistics() (*statisticMetrics, error) {
src/go/plugin/go.d/collector/dnsmasq/init.go
+2 -6
@@ -5,6 +5,7 @@ package dnsmasq
5 import (
6 "errors"
7 "fmt"
8 + "slices"
9
10 "github.com/netdata/netdata/go/plugins/plugin/framework/collectorapi"
11 )
@@ -28,12 +29,7 @@ func (c *Collector) initCharts() (*collectorapi.Charts, error) {
29 }
30
31 func isProtocolValid(protocol string) bool {
31 - for _, v := range validProtocols {
32 - if protocol == v {
33 - return true
34 - }
35 - }
36 - return false
32 + return slices.Contains(validProtocols, protocol)
33 }
34
35 var validProtocols = []string{
src/go/plugin/go.d/collector/docker_engine/collector_test.go
+1 -1
@@ -251,7 +251,7 @@ func TestCollector_Collect(t *testing.T) {
251 pulsar, srv := test.prepare(t)
252 defer srv.Close()
253
254 - for i := 0; i < 10; i++ {
254 + for range 10 {
255 _ = pulsar.Collect(context.Background())
256 }
257 mx := pulsar.Collect(context.Background())
src/go/plugin/go.d/collector/dockerhub/collect.go
+1 -1
@@ -23,7 +23,7 @@ func (c *Collector) collect() (map[string]int64, error) {
23 pullSum int
24 )
25
26 - for i := 0; i < reposNum; i++ {
26 + for range reposNum {
27 repo := <-ch
28 if repo == nil {
29 continue
src/go/plugin/go.d/collector/elasticsearch/collect.go
+4 -8
@@ -135,20 +135,16 @@ func (c *Collector) scrapeElasticsearch() *esMetrics {
135 wg := &sync.WaitGroup{}
136
137 if c.DoNodeStats {
138 - wg.Add(1)
139 - go func() { defer wg.Done(); c.scrapeNodesStats(ms) }()
138 + wg.Go(func() { c.scrapeNodesStats(ms) })
139 }
140 if c.DoClusterHealth {
142 - wg.Add(1)
143 - go func() { defer wg.Done(); c.scrapeClusterHealth(ms) }()
141 + wg.Go(func() { c.scrapeClusterHealth(ms) })
142 }
143 if c.DoClusterStats {
146 - wg.Add(1)
147 - go func() { defer wg.Done(); c.scrapeClusterStats(ms) }()
144 + wg.Go(func() { c.scrapeClusterStats(ms) })
145 }
146 if !c.ClusterMode && c.DoIndicesStats {
150 - wg.Add(1)
151 - go func() { defer wg.Done(); c.scrapeLocalIndicesStats(ms) }()
147 + wg.Go(func() { c.scrapeLocalIndicesStats(ms) })
148 }
149 wg.Wait()
150
src/go/plugin/go.d/collector/elasticsearch/collector_test.go
+1 -1
@@ -633,7 +633,7 @@ func TestCollector_Collect(t *testing.T) {
633 defer cleanup()
634
635 var mx map[string]int64
636 - for i := 0; i < 10; i++ {
636 + for range 10 {
637 mx = collr.Collect(context.Background())
638 }
639
src/go/plugin/go.d/collector/ethtool/collect.go
+1 -1
@@ -9,7 +9,7 @@ import (
9 func (c *Collector) collect() (map[string]int64, error) {
10 mx := make(map[string]int64)
11
12 - for _, iface := range strings.Fields(c.OpticInterfaces) {
12 + for iface := range strings.FieldsSeq(c.OpticInterfaces) {
13 if c.ignoredOpticIfaces[iface] {
14 continue
15 }
src/go/plugin/go.d/collector/hpssa/parse.go
+3 -3
@@ -356,9 +356,9 @@ func parsePhysicalDriveSectionLine(line string, pd *hpssaPhysicalDrive) {
356 }
357
358 func getColonSepValue(line string) string {
359 - i := strings.IndexByte(line, ':')
360 - if i == -1 {
359 + _, after, ok := strings.Cut(line, ":")
360 + if !ok {
361 return ""
362 }
363 - return strings.TrimSpace(line[i+1:])
363 + return strings.TrimSpace(after)
364 }
src/go/plugin/go.d/collector/httpcheck/collector_test.go
+1 -1
@@ -464,7 +464,7 @@ func TestCollector_Collect(t *testing.T) {
464
465 var mx map[string]int64
466
467 - for i := 0; i < 2; i++ {
467 + for range 2 {
468 mx = collr.Collect(context.Background())
469 time.Sleep(time.Duration(collr.UpdateEvery) * time.Second)
470 }
src/go/plugin/go.d/collector/k8s_state/collect.go
+2 -4
@@ -70,11 +70,9 @@ func (c *Collector) collect() (map[string]int64, error) {
70 c.startTime = time.Now()
71 in := make(chan resource)
72
73 - c.wg.Add(1)
74 - go func() { defer c.wg.Done(); c.runUpdateState(in) }()
73 + c.wg.Go(func() { c.runUpdateState(in) })
74
76 - c.wg.Add(1)
77 - go func() { defer c.wg.Done(); c.discoverer.run(c.ctx, in) }()
75 + c.wg.Go(func() { c.discoverer.run(c.ctx, in) })
76
77 c.kubeClusterID = c.getKubeClusterID()
78 c.kubeClusterName = c.getKubeClusterName()
src/go/plugin/go.d/collector/k8s_state/discover_kubernetes.go
+1 -2
@@ -58,8 +58,7 @@ func (d *kubeDiscovery) run(ctx context.Context, in chan<- resource) {
58 go func(dd discoverer) { defer wg.Done(); dd.run(ctx, updates) }(dd)
59 }
60
61 - wg.Add(1)
62 - go func() { defer wg.Done(); d.runDiscover(ctx, updates, in) }()
61 + wg.Go(func() { d.runDiscover(ctx, updates, in) })
62
63 close(d.readyCh)
64 wg.Wait()
src/go/plugin/go.d/collector/k8s_state/update_state.go
+3 -3
@@ -2,6 +2,8 @@
2
3 package k8s_state
4
5 +import "maps"
6 +
7 func (c *Collector) runUpdateState(in <-chan resource) {
8 for {
9 select {
@@ -27,9 +29,7 @@ func (c *Collector) runUpdateState(in <-chan resource) {
29 }
30
31 func copyLabels(dst, src map[string]string) {
30 - for k, v := range src {
31 - dst[k] = v
32 - }
32 + maps.Copy(dst, src)
33 }
34
35 func ptr[T any](v T) *T {
src/go/plugin/go.d/collector/lighttpd/status.go
+1 -1
@@ -103,7 +103,7 @@ func parseScoreboard(value string) *scoreboard {
103 // “_” Waiting for Connection (NOTE: not sure, copied the description from apache score board)
104
105 var sb scoreboard
106 - for _, s := range strings.Split(value, "") {
106 + for s := range strings.SplitSeq(value, "") {
107 switch s {
108 case "_":
109 sb.Waiting++
src/go/plugin/go.d/collector/megacli/collect.go
+6 -6
@@ -33,18 +33,18 @@ func writeInt(mx map[string]int64, key, value string) {
33 }
34
35 func getColonSepValue(line string) string {
36 - i := strings.IndexByte(line, ':')
37 - if i == -1 {
36 + _, after, ok := strings.Cut(line, ":")
37 + if !ok {
38 return ""
39 }
40 - return strings.TrimSpace(line[i+1:])
40 + return strings.TrimSpace(after)
41 }
42
43 func getColonSepNumValue(line string) string {
44 v := getColonSepValue(line)
45 - i := strings.IndexByte(v, ' ')
46 - if i == -1 {
45 + before, _, ok := strings.Cut(v, " ")
46 + if !ok {
47 return v
48 }
49 - return v[:i]
49 + return before
50 }
src/go/plugin/go.d/collector/memcached/collect.go
+3 -3
@@ -113,9 +113,9 @@ func (c *Collector) establishConn() (memcachedConn, error) {
113
114 func getStatKeyValue(line string) (string, string) {
115 line = strings.TrimPrefix(line, "STAT ")
116 - i := strings.IndexByte(line, ' ')
117 - if i < 0 {
116 + before, after, ok := strings.Cut(line, " ")
117 + if !ok {
118 return "", ""
119 }
120 - return line[:i], line[i+1:]
120 + return before, after
121 }
src/go/plugin/go.d/collector/mongodb/collect_serverstatus.go
+2 -3
@@ -4,6 +4,7 @@ package mongo
4
5 import (
6 "fmt"
7 + "maps"
8 "reflect"
9
10 "github.com/netdata/netdata/go/plugins/pkg/stm"
@@ -22,9 +23,7 @@ func (c *Collector) collectServerStatus(mx map[string]int64) error {
23
24 c.addOptionalCharts(s)
25
25 - for k, v := range stm.ToMap(s) {
26 - mx[k] = v
27 - }
26 + maps.Copy(mx, stm.ToMap(s))
27
28 if s.Transactions != nil && s.Transactions.CommitTypes != nil {
29 px := "txn_commit_types_"
src/go/plugin/go.d/collector/mysql/mysqlfunc/deadlock_info_test.go
+2 -2
@@ -312,7 +312,7 @@ func TestFuncDeadlockInfo_Handle_CleanupConcurrent(t *testing.T) {
312
313 go func() {
314 defer wg.Done()
315 - for i := 0; i < iterations; i++ {
315 + for range iterations {
316 resp := handler.Handle(context.Background(), deadlockInfoMethodID, nil)
317 require.NotNil(t, resp)
318 }
@@ -320,7 +320,7 @@ func TestFuncDeadlockInfo_Handle_CleanupConcurrent(t *testing.T) {
320
321 go func() {
322 defer wg.Done()
323 - for i := 0; i < iterations; i++ {
323 + for range iterations {
324 deps.cleanup()
325 }
326 }()
src/go/plugin/go.d/collector/mysql/mysqlfunc/error_info_test.go
+2 -2
@@ -42,7 +42,7 @@ func TestFuncErrorInfo_Handle_CleanupConcurrent(t *testing.T) {
42
43 go func() {
44 defer wg.Done()
45 - for i := 0; i < iterations; i++ {
45 + for range iterations {
46 resp := handler.Handle(context.Background(), errorInfoMethodID, nil)
47 require.NotNil(t, resp)
48 }
@@ -50,7 +50,7 @@ func TestFuncErrorInfo_Handle_CleanupConcurrent(t *testing.T) {
50
51 go func() {
52 defer wg.Done()
53 - for i := 0; i < iterations; i++ {
53 + for range iterations {
54 deps.cleanup()
55 }
56 }()
src/go/plugin/go.d/collector/nginxplus/nginx_http_api_query.go
+1 -3
@@ -152,10 +152,8 @@ func (c *Collector) queryMetrics() *nginxMetrics {
152 {do: c.endpoints.streamUpstreams, fn: c.queryStreamUpstreams},
153 {do: c.endpoints.resolvers, fn: c.queryResolvers},
154 } {
155 - task := task
155 if task.do {
157 - wg.Add(1)
158 - go func() { task.fn(ms); wg.Done() }()
156 + wg.Go(func() { task.fn(ms) })
157 }
158 }
159
src/go/plugin/go.d/collector/nvidia_smi/collect.go
+1 -1
@@ -79,7 +79,7 @@ func (c *Collector) collectGPUInfo(mx map[string]int64) error {
79 addMetric(mx, px+"mem_clock", gpu.Clocks.MemClock, 0)
80 addGPUPowerMetricsSwitch(mx, px, gpu)
81 addMetric(mx, px+"voltage", gpu.Voltage.GraphicsVolt, 0)
82 - for i := 0; i < 16; i++ {
82 + for i := range 16 {
83 s := "P" + strconv.Itoa(i)
84 mx[px+"performance_state_"+s] = oldmetrix.Bool(gpu.PerformanceState == s)
85 }
src/go/plugin/go.d/collector/nvidia_smi/exec.go
+1 -4
@@ -110,10 +110,7 @@ func (e *nvidiaSmiLoopExec) queryGPUInfo() ([]byte, error) {
110 }
111
112 func (e *nvidiaSmiLoopExec) run() error {
113 - secs := 5
114 - if e.updateEvery < secs {
115 - secs = e.updateEvery
116 - }
113 + secs := min(e.updateEvery, 5)
114
115 ndrunPath := filepath.Join(buildinfo.NetdataBinDir, "nd-run")
116 cmd := exec.Command(ndrunPath, e.binPath, "-q", "-x", "-l", strconv.Itoa(secs))
src/go/plugin/go.d/collector/pihole/collect.go
+2 -3
@@ -5,6 +5,7 @@ package pihole
5 import (
6 "errors"
7 "fmt"
8 + "maps"
9 "time"
10
11 "github.com/netdata/netdata/go/plugins/pkg/stm"
@@ -61,9 +62,7 @@ func (c *Collector) collectMetrics(mx map[string]int64) error {
62 return fmt.Errorf("unexpected response from %s", req.URL)
63 }
64
64 - for k, v := range stm.ToMap(resp) {
65 - mx[k] = v
66 - }
65 + maps.Copy(mx, stm.ToMap(resp))
66
67 // 0 if unknown
68 if resp.Gravity.LastUpdate != 0 {
src/go/plugin/go.d/collector/ping/collect.go
-1
@@ -78,7 +78,6 @@ func (c *Collector) collectSamples(updateJitterState bool) []hostSample {
78 )
79
80 for _, host := range c.Hosts {
81 - host := host
81 wg.Go(func() {
82 stats, err := c.prober.Ping(host)
83 if err != nil {
src/go/plugin/go.d/collector/postgres/do_query_replication.go
+1 -4
@@ -39,10 +39,7 @@ func (c *Collector) doQueryReplStandbyAppWALDelta() error {
39 // TODO: delta calculation was changed in https://github.com/netdata/netdata/go/plugins/plugin/go.d/pull/1039
40 // - 'replay_delta' (probably other deltas too?) can be negative
41 // - Also, WAL delta != WAL lag after that PR
42 - v := parseInt(value)
43 - if v < 0 {
44 - v = 0
45 - }
42 + v := max(parseInt(value), 0)
43 switch column {
44 case "sent_delta":
45 c.getReplAppMetrics(app).walSentDelta += v
src/go/plugin/go.d/collector/postgres/func_top_queries.go
+2 -2
@@ -530,8 +530,8 @@ func (f *funcTopQueries) buildAvailableColumns(availableCols map[string]bool, so
530
531 // Strip array_to_string wrapper FIRST (before table prefix removal)
532 // e.g., "array_to_string(s.relations, ', ')" -> "s.relations"
533 - if strings.HasPrefix(colName, "array_to_string(") {
534 - colName = strings.TrimPrefix(colName, "array_to_string(")
533 + if after, ok := strings.CutPrefix(colName, "array_to_string("); ok {
534 + colName = after
535 if idx := strings.Index(colName, ","); idx != -1 {
536 colName = colName[:idx]
537 }
src/go/plugin/go.d/collector/powerstore/client/client.go
+2 -3
@@ -5,6 +5,7 @@ package client
5 import (
6 "encoding/json"
7 "fmt"
8 + "maps"
9 "net/http"
10 "net/http/cookiejar"
11 "net/url"
@@ -277,9 +278,7 @@ func doGetAllPages[T any](c *Client, urlPath string, params url.Values) ([]T, er
278
279 for {
280 reqParams := make(url.Values)
280 - for k, v := range params {
281 - reqParams[k] = v
282 - }
281 + maps.Copy(reqParams, params)
282 if offset > 0 {
283 reqParams.Set("offset", strconv.Itoa(offset))
284 }
src/go/plugin/go.d/collector/prometheus/collector_test.go
+1 -1
@@ -588,7 +588,7 @@ test_gauge_no_meta_metric_1{label1="value2"} 12
588
589 var mx map[string]int64
590
591 - for i := 0; i < maxNotSeenTimes+1; i++ {
591 + for range maxNotSeenTimes + 1 {
592 mx = collr.Collect(context.Background())
593 }
594
src/go/plugin/go.d/collector/pulsar/collector_test.go
+1 -1
@@ -169,7 +169,7 @@ func TestCollector_Collect(t *testing.T) {
169 collr, srv := test.prepare(t)
170 defer srv.Close()
171
172 - for i := 0; i < 10; i++ {
172 + for range 10 {
173 _ = collr.Collect(context.Background())
174 }
175 mx := collr.Collect(context.Background())
src/go/plugin/go.d/collector/rabbitmq/collect_overview.go
+2 -3
@@ -4,6 +4,7 @@ package rabbitmq
4
5 import (
6 "fmt"
7 + "maps"
8
9 "github.com/netdata/netdata/go/plugins/pkg/stm"
10 "github.com/netdata/netdata/go/plugins/pkg/web"
@@ -21,9 +22,7 @@ func (c *Collector) collectOverview(mx map[string]int64) error {
22 return err
23 }
24
24 - for k, v := range stm.ToMap(resp) {
25 - mx[k] = v
26 - }
25 + maps.Copy(mx, stm.ToMap(resp))
26
27 return nil
28 }
src/go/plugin/go.d/collector/redis/collect_info.go
+3 -3
@@ -164,11 +164,11 @@ func convertBgSaveStatus(status string) string {
164 }
165
166 func parseProperty(prop string) (field, value string, ok bool) {
167 - i := strings.IndexByte(prop, ':')
168 - if i == -1 {
167 + before, after, ok0 := strings.Cut(prop, ":")
168 + if !ok0 {
169 return "", "", false
170 }
171 - field, value = prop[:i], prop[i+1:]
171 + field, value = before, after
172 return field, value, field != "" && value != ""
173 }
174
src/go/plugin/go.d/collector/smartctl/collect.go
-1
@@ -76,7 +76,6 @@ func (c *Collector) collectDevicesConcurrently(mx map[string]int64) error {
76 resultsChan := make(chan deviceInfoResult, len(c.scannedDevices))
77
78 for _, dev := range c.scannedDevices {
79 - dev := dev
79 p.Go(func() {
80 resp, err := c.exec.deviceInfo(dev.name, dev.typ, c.NoCheckPowerMode)
81 resultsChan <- deviceInfoResult{
src/go/plugin/go.d/collector/smartctl/collector_test.go
+1 -1
@@ -597,7 +597,7 @@ func TestCollector_Collect(t *testing.T) {
597 collr.PollDevicesEvery = confopt.Duration(time.Microsecond * 1)
598
599 var mx map[string]int64
600 - for i := 0; i < 10; i++ {
600 + for range 10 {
601 mx = collr.Collect(context.Background())
602 }
603
src/go/plugin/go.d/collector/snmp/ddsnmp/ddprofiledefinition/metadata.go
+1 -1
@@ -32,7 +32,7 @@ func (c MetadataResourceConfig) Clone() MetadataResourceConfig {
32
33 // MetadataField holds configs for a metadata field
34 type MetadataField struct {
35 - Symbol SymbolConfig `yaml:"symbol,omitempty" json:"symbol,omitempty"`
35 + Symbol SymbolConfig `yaml:"symbol,omitempty" json:"symbol"`
36 Symbols []SymbolConfig `yaml:"symbols,omitempty" json:"symbols,omitempty"`
37 Value string `yaml:"value,omitempty" json:"value,omitempty"`
38 }
src/go/plugin/go.d/collector/snmp/ddsnmp/ddprofiledefinition/metrics.go
+5 -5
@@ -48,10 +48,10 @@ type MetricsConfig struct {
48 MIB string `yaml:"MIB,omitempty" json:"MIB,omitempty"`
49
50 // Symbol configs
51 - Symbol SymbolConfig `yaml:"symbol,omitempty" json:"symbol,omitempty"`
51 + Symbol SymbolConfig `yaml:"symbol,omitempty" json:"symbol"`
52
53 // Table the table OID
54 - Table SymbolConfig `yaml:"table,omitempty" json:"table,omitempty"`
54 + Table SymbolConfig `yaml:"table,omitempty" json:"table"`
55 // Table configs
56 Symbols []SymbolConfig `yaml:"symbols,omitempty" json:"symbols,omitempty"`
57
@@ -59,7 +59,7 @@ type MetricsConfig struct {
59 StaticTags []StaticMetricTagConfig `yaml:"static_tags,omitempty" json:"-"`
60 MetricTags MetricTagConfigList `yaml:"metric_tags,omitempty" json:"metric_tags,omitempty"`
61
62 - Options MetricsConfigOption `yaml:"options,omitempty" json:"options,omitempty"`
62 + Options MetricsConfigOption `yaml:"options,omitempty" json:"options"`
63
64 // DEPRECATED: Use .Symbol instead
65 OID string `yaml:"OID,omitempty" json:"OID,omitempty" jsonschema:"-"`
@@ -135,7 +135,7 @@ type SymbolConfig struct {
135 // Deprecated types: `counter` (use `rate` instead), percent (use `scale_factor` instead)
136 MetricType ProfileMetricType `yaml:"metric_type,omitempty" json:"metric_type,omitempty"`
137
138 - ChartMeta ChartMeta `yaml:"chart_meta,omitempty" json:"chart_meta,omitempty"`
138 + ChartMeta ChartMeta `yaml:"chart_meta,omitempty" json:"chart_meta"`
139
140 Mapping map[string]string `yaml:"mapping,omitempty" json:"mapping,omitempty"`
141 Transform string `yaml:"transform,omitempty" json:"transform,omitempty"`
@@ -174,7 +174,7 @@ type MetricTagConfig struct {
174 // set .Tag to specify the tag name. If a serialized Symbol is a string
175 // instead of an object, it will be treated like {name: <value>}; this use
176 // pattern is deprecated
177 - Symbol SymbolConfigCompat `yaml:"symbol,omitempty" json:"symbol,omitempty"`
177 + Symbol SymbolConfigCompat `yaml:"symbol,omitempty" json:"symbol"`
178
179 IndexTransform []MetricIndexTransform `yaml:"index_transform,omitempty" json:"index_transform,omitempty"`
180
src/go/plugin/go.d/collector/snmp/ddsnmp/ddprofiledefinition/selector.go
+2 -2
@@ -10,8 +10,8 @@ type (
10 SelectorSpec []SelectorRule
11
12 SelectorRule struct {
13 - SysObjectID SelectorIncludeExclude `yaml:"sysobjectid,omitempty" json:"sysobjectid,omitempty"`
14 - SysDescr SelectorIncludeExclude `yaml:"sysdescr,omitempty" json:"sysdescr,omitempty"`
13 + SysObjectID SelectorIncludeExclude `yaml:"sysobjectid,omitempty" json:"sysobjectid"`
14 + SysDescr SelectorIncludeExclude `yaml:"sysdescr,omitempty" json:"sysdescr"`
15 }
16
17 SelectorIncludeExclude struct {
src/go/plugin/go.d/collector/snmp/ddsnmp/ddprofiledefinition/yaml_utils.go
+3 -3
@@ -11,7 +11,7 @@ package ddprofiledefinition
11 type StringArray []string
12
13 // UnmarshalYAML unmarshalls StringArray
14 -func (a *StringArray) UnmarshalYAML(unmarshal func(interface{}) error) error {
14 +func (a *StringArray) UnmarshalYAML(unmarshal func(any) error) error {
15 var multi []string
16 err := unmarshal(&multi)
17 if err != nil {
@@ -28,7 +28,7 @@ func (a *StringArray) UnmarshalYAML(unmarshal func(interface{}) error) error {
28 }
29
30 // UnmarshalYAML unmarshalls SymbolConfig
31 -func (a *SymbolConfigCompat) UnmarshalYAML(unmarshal func(interface{}) error) error {
31 +func (a *SymbolConfigCompat) UnmarshalYAML(unmarshal func(any) error) error {
32 var symbol SymbolConfig
33 err := unmarshal(&symbol)
34 if err != nil {
@@ -45,7 +45,7 @@ func (a *SymbolConfigCompat) UnmarshalYAML(unmarshal func(interface{}) error) er
45 }
46
47 // UnmarshalYAML unmarshalls MetricTagConfigList
48 -func (mtcl *MetricTagConfigList) UnmarshalYAML(unmarshal func(interface{}) error) error {
48 +func (mtcl *MetricTagConfigList) UnmarshalYAML(unmarshal func(any) error) error {
49 var multi []MetricTagConfig
50 err := unmarshal(&multi)
51 if err != nil {
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/collector.go
-1
@@ -35,7 +35,6 @@ func New(cfg Config) *Collector {
35 }
36
37 for _, prof := range cfg.Profiles {
38 - prof := prof
38 handleCrossTableTagsWithoutMetrics(prof)
39 coll.profiles[prof.SourceFile] = &profileState{profile: prof}
40 }
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/collector_scalar_test.go
+5 -5
@@ -643,7 +643,7 @@ func TestScalarCollector_Collect(t *testing.T) {
643 profile: func() *ddsnmp.Profile {
644 // Create a profile with many metrics to force chunking
645 var metrics []ddprofiledefinition.MetricsConfig
646 - for i := 0; i < 25; i++ {
646 + for i := range 25 {
647 metrics = append(metrics, createScalarMetric(
648 fmt.Sprintf("1.3.6.1.2.1.1.%02d.0", i),
649 fmt.Sprintf("metric%d", i),
@@ -660,21 +660,21 @@ func TestScalarCollector_Collect(t *testing.T) {
660 // Expect 3 chunks (10 + 10 + 5)
661 chunk1OIDs := make([]string, 10)
662 chunk1PDUs := make([]gosnmp.SnmpPDU, 10)
663 - for i := 0; i < 10; i++ {
663 + for i := range 10 {
664 chunk1OIDs[i] = fmt.Sprintf("1.3.6.1.2.1.1.%02d.0", i)
665 chunk1PDUs[i] = createIntegerPDU(chunk1OIDs[i], i*100)
666 }
667
668 chunk2OIDs := make([]string, 10)
669 chunk2PDUs := make([]gosnmp.SnmpPDU, 10)
670 - for i := 0; i < 10; i++ {
670 + for i := range 10 {
671 chunk2OIDs[i] = fmt.Sprintf("1.3.6.1.2.1.1.%02d.0", i+10)
672 chunk2PDUs[i] = createIntegerPDU(chunk2OIDs[i], (i+10)*100)
673 }
674
675 chunk3OIDs := make([]string, 5)
676 chunk3PDUs := make([]gosnmp.SnmpPDU, 5)
677 - for i := 0; i < 5; i++ {
677 + for i := range 5 {
678 chunk3OIDs[i] = fmt.Sprintf("1.3.6.1.2.1.1.%02d.0", i+20)
679 chunk3PDUs[i] = createIntegerPDU(chunk3OIDs[i], (i+20)*100)
680 }
@@ -686,7 +686,7 @@ func TestScalarCollector_Collect(t *testing.T) {
686 expectedResult: func() []ddsnmp.Metric {
687 // Generate expected metrics
688 var metrics []ddsnmp.Metric
689 - for i := 0; i < 25; i++ {
689 + for i := range 25 {
690 metrics = append(metrics, ddsnmp.Metric{
691 Name: fmt.Sprintf("metric%d", i),
692 Value: int64(i * 100),
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/collector_table.go
+5 -8
@@ -5,6 +5,7 @@ package ddsnmpcollector
5 import (
6 "errors"
7 "fmt"
8 + "maps"
9 "slices"
10 "strings"
11
@@ -413,8 +414,8 @@ func (tc *tableCollector) organizePDUsByRow(ctx *tableProcessingContext) (rows m
414
415 for oid, pdu := range ctx.pdus {
416 for _, columnOID := range allColumnOIDs {
416 - if strings.HasPrefix(oid, columnOID+".") {
417 - index := strings.TrimPrefix(oid, columnOID+".")
417 + if after, ok := strings.CutPrefix(oid, columnOID+"."); ok {
418 + index := after
419
420 if rows[index] == nil {
421 rows[index] = make(map[string]gosnmp.SnmpPDU)
@@ -465,9 +466,7 @@ func (tc *tableCollector) processRows(ctx *tableProcessingContext, stats *ddsnmp
466 }
467
468 // Copy processed tags to cache
468 - for k, v := range row.tags {
469 - ctx.tagCache[index][k] = v
470 - }
469 + maps.Copy(ctx.tagCache[index], row.tags)
470
471 metrics = append(metrics, rowMetrics...)
472 }
@@ -521,9 +520,7 @@ func (tc *tableCollector) buildMetricsFromCache(ctx *cacheProcessingContext, sta
520 // Get cached tags for this row
521 rowTags := make(map[string]string)
522 if tags, ok := ctx.cachedTags[index]; ok {
524 - for k, v := range tags {
525 - rowTags[k] = v
526 - }
523 + maps.Copy(rowTags, tags)
524 }
525
526 // Process each metric column
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/collector_vmetrics_test.go
+2 -2
@@ -364,7 +364,7 @@ func TestVirtualMetricsCollector_Collect(t *testing.T) {
364 collectedMetrics: func() []ddsnmp.Metric {
365 // Simulate 1000 interfaces
366 metrics := make([]ddsnmp.Metric, 0, 1000)
367 - for i := 0; i < 1000; i++ {
367 + for i := range 1000 {
368 metrics = append(metrics, ddsnmp.Metric{
369 Name: "ifHCInOctets",
370 Value: int64(i * 100),
@@ -1607,7 +1607,7 @@ var (
1607
1608 func makeTags(n int) map[string]string {
1609 t := make(map[string]string, n)
1610 - for i := 0; i < n; i++ {
1610 + for i := range n {
1611 t["label"+strconv.Itoa(i)] = "v" + strconv.Itoa(i)
1612 }
1613 return t
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/common_test.go
+1 -1
@@ -78,7 +78,7 @@ func expectSNMPWalkError(mockHandler *snmpmock.MockHandler, version gosnmp.SnmpV
78 }
79 }
80
81 -func createPDU(name string, pduType gosnmp.Asn1BER, value interface{}) gosnmp.SnmpPDU {
81 +func createPDU(name string, pduType gosnmp.Asn1BER, value any) gosnmp.SnmpPDU {
82 return gosnmp.SnmpPDU{
83 Name: name,
84 Type: pduType,
src/go/plugin/go.d/collector/snmp/ddsnmp/ddsnmpcollector/table_cache.go
+3 -6
@@ -3,6 +3,7 @@
3 package ddsnmpcollector
4
5 import (
6 + "maps"
7 "math/rand"
8 "sort"
9 "strings"
@@ -119,18 +120,14 @@ func (tc *tableCache) cacheData(cfg ddprofiledefinition.MetricsConfig, oidMap ma
120 oidsCopy := make(map[string]map[string]string, len(oidMap))
121 for index, columns := range oidMap {
122 columnsCopy := make(map[string]string, len(columns))
122 - for colOID, fullOID := range columns {
123 - columnsCopy[colOID] = fullOID
124 - }
123 + maps.Copy(columnsCopy, columns)
124 oidsCopy[index] = columnsCopy
125 }
126
127 tagsCopy := make(map[string]map[string]string, len(tagValues))
128 for index, tags := range tagValues {
129 tagCopy := make(map[string]string, len(tags))
131 - for name, value := range tags {
132 - tagCopy[name] = value
133 - }
130 + maps.Copy(tagCopy, tags)
131 tagsCopy[index] = tagCopy
132 }
133
src/go/plugin/go.d/collector/snmp/ddsnmp/profile_test.go
+2 -2
@@ -1018,7 +1018,7 @@ func TestSortProfilesBySpecificity_Stable(t *testing.T) {
1018 profiles := make([]*Profile, numProfiles)
1019 matchedOIDs := make(map[*Profile]string)
1020
1021 - for i := 0; i < numProfiles; i++ {
1021 + for i := range numProfiles {
1022 profiles[i] = &Profile{
1023 SourceFile: fmt.Sprintf("profile-%03d.yaml", i),
1024 }
@@ -1028,7 +1028,7 @@ func TestSortProfilesBySpecificity_Stable(t *testing.T) {
1028 sortProfilesBySpecificity(profiles, matchedOIDs)
1029
1030 // Verify order is preserved (lexicographic due to same OID)
1031 - for i := 0; i < numProfiles; i++ {
1031 + for i := range numProfiles {
1032 expected := fmt.Sprintf("profile-%03d.yaml", i)
1033 assert.Equal(t, expected, profiles[i].SourceFile)
1034 }
src/go/plugin/go.d/collector/snmp/ddsnmp/transform.go
+4 -5
@@ -5,6 +5,7 @@ package ddsnmp
5 import (
6 "errors"
7 "fmt"
8 + "maps"
9 "math"
10 "net"
11 "strconv"
@@ -70,7 +71,7 @@ func newMetricTransformFuncMap() template.FuncMap {
71 fm := sprig.TxtFuncMap()
72
73 extra := map[string]any{
73 - "deleteTag": func(m *Metric, key string) interface{} {
74 + "deleteTag": func(m *Metric, key string) any {
75 delete(m.Tags, key)
76 return nil
77 },
@@ -176,7 +177,7 @@ func newMetricTransformFuncMap() template.FuncMap {
177 sensorPrecision := m.Tags["rm:sensor_precision"]
178
179 famPrefix := "Hardware/Sensor/"
179 - config := map[string]map[string]interface{}{
180 + config := map[string]map[string]any{
181 "1": {"name": "unspecified", "family": "Generic", "desc": "Unspecified or vendor-specific sensor"},
182 "2": {"name": "unknown", "family": "Unknown", "desc": "Unknown sensor type"},
183 "3": {"name": "voltage_ac", "unit": "V", "family": "Voltage/AC", "desc": "AC voltage"},
@@ -322,9 +323,7 @@ func newMetricTransformFuncMap() template.FuncMap {
323 },
324 }
325
325 - for name, fn := range extra {
326 - fm[name] = fn
327 - }
326 + maps.Copy(fm, extra)
327
328 return fm
329 }
src/go/plugin/go.d/collector/sql/collect.go
+2 -2
@@ -315,8 +315,8 @@ func redactDSN(dsn string) string {
315 }
316
317 // If there's a colon, treat text before first ':' as user and the rest as password.
318 - if colon := strings.IndexByte(userinfo, ':'); colon >= 0 {
319 - user := userinfo[:colon]
318 + if before, _, ok := strings.Cut(userinfo, ":"); ok {
319 + user := before
320 // Keep user, redact password
321 redacted := user + ":****"
322 return dsn[:authStart] + redacted + dsn[at:]
src/go/plugin/go.d/collector/sql/func_table_test.go
+1 -1
@@ -340,7 +340,7 @@ func TestFuncTable_Handle(t *testing.T) {
340 functionID: "test",
341 prepareMock: func(m sqlmock.Sqlmock) {
342 rows := sqlmock.NewRows([]string{"n"})
343 - for i := 0; i < 150; i++ {
343 + for i := range 150 {
344 rows.AddRow(i)
345 }
346 m.ExpectQuery("SELECT n").WillReturnRows(rows)
src/go/plugin/go.d/collector/squidlog/collect.go
+2 -2
@@ -111,8 +111,8 @@ func (c *Collector) collectCacheCode() {
111 }
112 cntr.Inc()
113
114 - tags := strings.Split(c.line.cacheCode, "_")
115 - for _, tag := range tags {
114 + tags := strings.SplitSeq(c.line.cacheCode, "_")
115 + for tag := range tags {
116 c.collectCacheCodeTag(tag)
117 }
118 }
src/go/plugin/go.d/collector/storcli/collect_drives.go
+3 -3
@@ -224,11 +224,11 @@ func getDriveAttrs(driveDetailedInfo map[string]json.RawMessage, id string) (*dr
224
225 func getTemperature(temp string) string {
226 // ' 28C (82.40 F)' (drive) or '33C' (bbu)
227 - i := strings.IndexByte(temp, 'C')
228 - if i == -1 {
227 + before, _, ok := strings.Cut(temp, "C")
228 + if !ok {
229 return ""
230 }
231 - return strings.TrimSpace(temp[:i])
231 + return strings.TrimSpace(before)
232 }
233
234 func parseInt(s string) (int64, bool) {
src/go/plugin/go.d/collector/testrandom/charts.go
+2 -2
@@ -34,7 +34,7 @@ func newChart(num, ctx, labels int, typ collectorapi.ChartType) *collectorapi.Ch
34 if ctx > 0 {
35 chart.Ctx += fmt.Sprintf("_%d", ctx)
36 }
37 - for i := 0; i < labels; i++ {
37 + for i := range labels {
38 chart.Labels = append(chart.Labels, collectorapi.Label{
39 Key: fmt.Sprintf("random_name_%d", i),
40 Value: fmt.Sprintf("random_value_%d_%d", num, i),
@@ -50,7 +50,7 @@ func newHiddenChart(num, ctx, labels int, typ collectorapi.ChartType) *collector
50 if ctx > 0 {
51 chart.Ctx += fmt.Sprintf("_%d", ctx)
52 }
53 - for i := 0; i < labels; i++ {
53 + for i := range labels {
54 chart.Labels = append(chart.Labels, collectorapi.Label{
55 Key: fmt.Sprintf("random_name_%d", i),
56 Value: fmt.Sprintf("random_value_%d_%d", num, i),
src/go/plugin/go.d/collector/tor/collector_test.go
+1 -1
@@ -316,7 +316,7 @@ func (m *mockTorDaemon) handleGetInfo(conn io.Writer, keywords string) error {
316
317 keywords = strings.Trim(keywords, "\"")
318
319 - for _, k := range strings.Fields(keywords) {
319 + for k := range strings.FieldsSeq(keywords) {
320 s := fmt.Sprintf("250-%s=%d\n", k, 100)
321
322 if _, err := conn.Write([]byte(s)); err != nil {
src/go/plugin/go.d/collector/typesense/collect.go
+2 -3
@@ -5,6 +5,7 @@ package typesense
5 import (
6 "encoding/json"
7 "fmt"
8 + "maps"
9 "net/http"
10 "strings"
11
@@ -108,9 +109,7 @@ func (c *Collector) collectStats(mx map[string]int64) error {
109
110 c.once.Do(c.addStatsCharts)
111
111 - for k, v := range stm.ToMap(resp) {
112 - mx[k] = v
113 - }
112 + maps.Copy(mx, stm.ToMap(resp))
113
114 return nil
115 }
src/go/plugin/go.d/collector/upsd/client.go
+2 -2
@@ -137,8 +137,8 @@ func (c *upsdClient) sendCommand(cmd string) ([]string, error) {
137 line := string(bytes)
138 resp = append(resp, line)
139
140 - if strings.HasPrefix(line, "ERR ") {
141 - errMsg = strings.TrimPrefix(line, "ERR ")
140 + if after, ok := strings.CutPrefix(line, "ERR "); ok {
141 + errMsg = after
142 }
143
144 return line != endLine && errMsg == "", nil
src/go/plugin/go.d/collector/upsd/collect.go
+1 -1
@@ -161,7 +161,7 @@ func writeUpsStatus(mx map[string]int64, ups upsUnit) {
161 }
162 mx[px+"other"] = 0
163
164 - for _, st := range strings.Split(ups.vars[varUpsStatus], " ") {
164 + for st := range strings.SplitSeq(ups.vars[varUpsStatus], " ") {
165 if _, ok := upsStatuses[st]; ok {
166 mx[px+st] = 1
167 } else {
src/go/plugin/go.d/collector/vcsa/collect.go
+1 -3
@@ -67,10 +67,8 @@ func (c *Collector) scrapeHealth(status *vcsaHealthStatus) {
67 func() { scrape(c.client.Swap, &status.Swap) },
68 func() { scrape(c.client.SoftwarePackages, &status.SoftwarePackages) },
69 } {
70 - fn := fn
70
72 - wg.Add(1)
73 - go func() { defer wg.Done(); fn() }()
71 + wg.Go(func() { fn() })
72 }
73
74 wg.Wait()
src/go/plugin/go.d/collector/vernemq/collect.go
+6 -5
@@ -137,8 +137,8 @@ func (c *Collector) getNodesStats(mfs prometheus.MetricFamilies) map[string]*nod
137 func (c *Collector) getMetricNamespace(mfs prometheus.MetricFamilies) (string, error) {
138 want := metricPUBLISHError
139 for _, mf := range mfs {
140 - if strings.HasSuffix(mf.Name(), want) {
141 - s := strings.TrimSuffix(mf.Name(), want)
140 + if before, ok := strings.CutSuffix(mf.Name(), want); ok {
141 + s := before
142 s = strings.TrimSuffix(s, "_")
143 return s, nil
144 }
@@ -152,9 +152,10 @@ func isSchedulerUtilizationMetric(name string) bool {
152 }
153
154 func join(a, b string, rest ...string) string {
155 - s := a + "_" + b
155 + var s strings.Builder
156 + s.WriteString(a + "_" + b)
157 for _, v := range rest {
157 - s += "_" + v
158 + s.WriteString("_" + v)
159 }
159 - return s
160 + return s.String()
161 }
src/go/plugin/go.d/collector/vsphere/collect.go
+1 -4
@@ -204,10 +204,7 @@ func writeDatastoreMetrics(mx map[string]int64, ds *rs.Datastore) {
204 if ds.Accessible {
205 capacity = ds.Capacity
206 freeSpace = ds.FreeSpace
207 - used = capacity - freeSpace
208 - if used < 0 {
209 - used = 0
210 - }
207 + used = max(capacity-freeSpace, 0)
208 }
209
210 mx[fmt.Sprintf("%s_capacity", ds.ID)] = capacity
src/go/plugin/go.d/collector/vsphere/collector_test.go
+2 -2
@@ -484,7 +484,7 @@ func TestCollector_Collect_RemoveHostsVMsInRuntime(t *testing.T) {
484 require.NoError(t, collr.discoverOnce())
485
486 numOfRuns := 5
487 - for i := 0; i < numOfRuns; i++ {
487 + for range numOfRuns {
488 collr.Collect(context.Background())
489 }
490
@@ -534,7 +534,7 @@ func TestCollector_Collect_Run(t *testing.T) {
534 require.NoError(t, collr.Check(context.Background()))
535
536 runs := 20
537 - for i := 0; i < runs; i++ {
537 + for i := range runs {
538 assert.True(t, len(collr.Collect(context.Background())) > 0)
539 if i < 6 {
540 time.Sleep(time.Second)
src/go/plugin/go.d/collector/vsphere/scrape/scrape.go
+1 -4
@@ -123,10 +123,7 @@ func (s *Scraper) scrape(metrics *[]performance.EntityMetric, lock *sync.Mutex,
123
124 func chunkify(pqs []types.PerfQuerySpec, chunkSize int) (chunks [][]types.PerfQuerySpec) {
125 for i := 0; i < len(pqs); i += chunkSize {
126 - end := i + chunkSize
127 - if end > len(pqs) {
128 - end = len(pqs)
129 - }
126 + end := min(i+chunkSize, len(pqs))
127 chunks = append(chunks, pqs[i:end])
128 }
129 return chunks
src/go/plugin/go.d/collector/vsphere/scrape/throttled_caller.go
+2 -4
@@ -17,15 +17,13 @@ func newThrottledCaller(limit int) *throttledCaller {
17 }
18
19 func (t *throttledCaller) call(job func()) {
20 - t.wg.Add(1)
21 - go func() {
22 - defer t.wg.Done()
20 + t.wg.Go(func() {
21 t.limit <- struct{}{}
22 defer func() {
23 <-t.limit
24 }()
25 job()
28 - }()
26 + })
27 }
28
29 func (t *throttledCaller) wait() {
src/go/plugin/go.d/collector/vsphere/scrape/throttled_caller_test.go
+1 -1
@@ -20,7 +20,7 @@ func Test_throttledCaller(t *testing.T) {
20 n := 10000
21 tc := newThrottledCaller(limit)
22
23 - for i := 0; i < n; i++ {
23 + for range n {
24 job := func() {
25 atomic.AddInt64(&total, 1)
26 atomic.AddInt64(&current, 1)
src/go/plugin/go.d/discovery/sdext/discoverer/dockersd/sim_test.go
+4 -8
@@ -45,15 +45,11 @@ func (sim *discoverySim) run(t *testing.T) {
45 in := make(chan []model.TargetGroup)
46 var wg sync.WaitGroup
47
48 - wg.Add(1)
49 - go func() {
50 - defer wg.Done()
48 + wg.Go(func() {
49 d.Discover(ctx, in)
52 - }()
50 + })
51
54 - wg.Add(1)
55 - go func() {
56 - defer wg.Done()
52 + wg.Go(func() {
53 for {
54 select {
55 case <-ctx.Done():
@@ -64,7 +60,7 @@ func (sim *discoverySim) run(t *testing.T) {
60 }
61 }
62 }
67 - }()
63 + })
64
65 done := make(chan struct{})
66 go func() {
src/go/plugin/go.d/discovery/sdext/discoverer/k8ssd/config.go
+2 -2
@@ -15,10 +15,10 @@ type Config struct {
15 Selector struct {
16 Label string `yaml:"label,omitempty" json:"label,omitempty"`
17 Field string `yaml:"field,omitempty" json:"field,omitempty"`
18 - } `yaml:"selector,omitempty" json:"selector,omitempty"`
18 + } `yaml:"selector,omitempty" json:"selector"`
19 Pod struct {
20 LocalMode bool `yaml:"local_mode,omitempty" json:"local_mode,omitempty"`
21 - } `yaml:"pod,omitempty" json:"pod,omitempty"`
21 + } `yaml:"pod,omitempty" json:"pod"`
22 }
23
24 func validateConfig(cfg Config) error {
src/go/plugin/go.d/discovery/sdext/discoverer/netlistensd/netlisteners.go
-1
@@ -267,7 +267,6 @@ func (d *Discoverer) parseLocalListeners(bs []byte) ([]model.Target, error) {
267 var n int
268
269 for _, tgt := range targets {
270 - tgt := tgt
270
271 proto := strings.TrimSuffix(tgt.Protocol, "6")
272 key := tgt.Protocol + ":" + tgt.Address
src/go/plugin/go.d/discovery/sdext/discoverer/netlistensd/sim_test.go
+4 -8
@@ -46,15 +46,11 @@ func (sim *discoverySim) run(t *testing.T) {
46 in := make(chan []model.TargetGroup)
47 var wg sync.WaitGroup
48
49 - wg.Add(1)
50 - go func() {
51 - defer wg.Done()
49 + wg.Go(func() {
50 d.Discover(ctx, in)
53 - }()
51 + })
52
55 - wg.Add(1)
56 - go func() {
57 - defer wg.Done()
53 + wg.Go(func() {
54 for {
55 select {
56 case <-ctx.Done():
@@ -65,7 +61,7 @@ func (sim *discoverySim) run(t *testing.T) {
61 }
62 }
63 }
68 - }()
64 + })
65
66 done := make(chan struct{})
67 go func() {
src/go/plugin/go.d/discovery/sdext/discoverer/snmpsd/discoverer.go
-1
@@ -163,7 +163,6 @@ func (d *Discoverer) discoverNetworks(ctx context.Context, in chan<- []model.Tar
163
164 p := pool.New()
165 for _, sub := range d.subnets {
166 - sub := sub
166 p.Go(func() { d.discoverNetwork(ctx, in, sub, doProbing) })
167 }
168 p.Wait()
src/go/plugin/go.d/discovery/sdext/discoverer/snmpsd/sim_test.go
+4 -8
@@ -45,15 +45,11 @@ func (sim *discoverySim) run(t *testing.T) {
45 in := make(chan []model.TargetGroup)
46 var wg sync.WaitGroup
47
48 - wg.Add(1)
49 - go func() {
50 - defer wg.Done()
48 + wg.Go(func() {
49 d.Discover(ctx, in)
52 - }()
50 + })
51
54 - wg.Add(1)
55 - go func() {
56 - defer wg.Done()
52 + wg.Go(func() {
53 for {
54 select {
55 case <-ctx.Done():
@@ -64,7 +60,7 @@ func (sim *discoverySim) run(t *testing.T) {
60 }
61 }
62 }
67 - }()
63 + })
64
65 done := make(chan struct{})
66 go func() {
src/go/plugin/go.d/pkg/cloudauth/provider.go
+1 -1
@@ -35,7 +35,7 @@ func (p Provider) MarshalYAML() (any, error) {
35 return p.marshalValue(), nil
36 }
37
38 -func (p *Provider) UnmarshalYAML(unmarshal func(interface{}) error) error {
38 +func (p *Provider) UnmarshalYAML(unmarshal func(any) error) error {
39 var raw string
40 if err := unmarshal(&raw); err != nil {
41 return err
src/go/plugin/go.d/pkg/cloudauth/token_provider.go
+3 -4
@@ -6,6 +6,7 @@ import (
6 "context"
7 "errors"
8 "fmt"
9 + "slices"
10 "sync"
11 "time"
12
@@ -35,10 +36,8 @@ func NewTokenProvider(cred azcore.TokenCredential, scopes []string, refreshMargi
36 if len(scopes) == 0 {
37 return nil, errors.New("token scopes are required")
38 }
38 - for _, scope := range scopes {
39 - if scope == "" {
40 - return nil, errors.New("token scopes contain an empty value")
41 - }
39 + if slices.Contains(scopes, "") {
40 + return nil, errors.New("token scopes contain an empty value")
41 }
42 if refreshMargin <= 0 {
43 refreshMargin = DefaultTokenRefreshMargin
src/go/plugin/go.d/pkg/iprange/pool_test.go
+1 -1
@@ -460,7 +460,7 @@ func TestPool_Ranges(t *testing.T) {
460 func BenchmarkPool_Contains(b *testing.B) {
461 // Create a pool with multiple ranges
462 pool := NewPool()
463 - for i := 0; i < 10; i++ {
463 + for i := range 10 {
464 start := fmt.Sprintf("192.0.%d.0", i)
465 end := fmt.Sprintf("192.0.%d.255", i)
466 r, _ := ParseRange(fmt.Sprintf("%s-%s", start, end))
src/go/plugin/go.d/pkg/logs/reader_test.go
+3 -3
@@ -24,7 +24,7 @@ func TestReader_Read(t *testing.T) {
24 numLogs := 5
25 var sum int
26
27 - for i := 0; i < 10; i++ {
27 + for i := range 10 {
28 appendLogs(t, filename, time.Millisecond*10, numLogs)
29 n, err := r.readUntilEOF()
30 sum += n
@@ -187,7 +187,7 @@ func (r *testReader) readUntilEOF() (n int, err error) {
187
188 func (r *testReader) readUntilEOFTimes(times int) (sum int, err error) {
189 var n int
190 - for i := 0; i < times; i++ {
190 + for range times {
191 n, err = r.readUntilEOF()
192 if err != io.EOF {
193 break
@@ -237,7 +237,7 @@ func appendLogs(t *testing.T, filename string, interval time.Duration, numOfLogs
237 require.NotNil(t, file)
238 defer func() { _ = file.Close() }()
239
240 - for i := 0; i < numOfLogs; i++ {
240 + for i := range numOfLogs {
241 _, err = fmt.Fprintln(file, "line", i, "filename", base)
242 require.NoError(t, err)
243 time.Sleep(interval)
src/go/plugin/go.d/pkg/ndexec/resource_usage.go
-1
@@ -1,5 +1,4 @@
1 //go:build !windows
2 -// +build !windows
2
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
src/go/plugin/go.d/pkg/ndexec/resource_usage_windows.go
-1
@@ -1,5 +1,4 @@
1 //go:build windows
2 -// +build windows
2
3 // SPDX-License-Identifier: GPL-3.0-or-later
4
src/go/plugin/go.d/pkg/oldmetrix/histogram.go
+3 -2
@@ -4,6 +4,7 @@ package oldmetrix
4
5 import (
6 "fmt"
7 + "slices"
8 "sort"
9
10 "github.com/netdata/netdata/go/plugins/pkg/stm"
@@ -93,7 +94,7 @@ func NewHistogram(buckets []float64) Histogram {
94 if len(buckets) == 0 {
95 buckets = DefBuckets
96 } else {
96 - sort.Slice(buckets, func(i, j int) bool { return buckets[i] < buckets[j] })
97 + slices.Sort(buckets)
98 }
99
100 return &histogram{
@@ -108,7 +109,7 @@ func NewHistogramWithRangeBuckets(buckets []float64) Histogram {
109 if len(buckets) == 0 {
110 buckets = DefBuckets
111 } else {
111 - sort.Slice(buckets, func(i, j int) bool { return buckets[i] < buckets[j] })
112 + slices.Sort(buckets)
113 }
114
115 return &histogram{
src/go/plugin/go.d/pkg/snmputils/overrides_test.go
-4
@@ -44,7 +44,6 @@ func TestOverrides_OnUnknownOID(t *testing.T) {
44 }
45
46 for name, tc := range cases {
47 - tc := tc
47 t.Run(name, func(t *testing.T) {
48 defer withOverrides(t, tc.overrides)()
49
@@ -65,7 +64,6 @@ func TestOrgToVendorMapping(t *testing.T) {
64 }
65
66 for name, tc := range cases {
68 - tc := tc
67 t.Run(name, func(t *testing.T) {
68 rawOrg := lookupEnterpriseNumber(tc.oid)
69 if rawOrg == "" {
@@ -104,7 +102,6 @@ func TestLookupEnterpriseNumber(t *testing.T) {
102 }
103
104 for name, tc := range cases {
107 - tc := tc
105 t.Run(name, func(t *testing.T) {
106 got := lookupEnterpriseNumber(tc.oid)
107 if tc.wantNonEmpty {
@@ -141,7 +138,6 @@ func TestPduToString(t *testing.T) {
138 }
139
140 for name, tc := range cases {
144 - tc := tc
141 t.Run(name, func(t *testing.T) {
142 got, err := PduToString(tc.pdu)
143 if tc.wantErr {
src/go/plugin/go.d/pkg/socket/server.go
+4 -8
@@ -64,11 +64,9 @@ func (t *tcpServer) handleConnections() (err error) {
64 }
65 return fmt.Errorf("could not accept connection: %v", err)
66 }
67 - t.wg.Add(1)
68 - go func() {
69 - defer t.wg.Done()
67 + t.wg.Go(func() {
68 t.handleConnection(conn)
71 - }()
69 + })
70 }
71 }
72 }
@@ -225,11 +223,9 @@ func (u *unixServer) handleConnections() error {
223 continue
224 }
225
228 - u.wg.Add(1)
229 - go func() {
230 - defer u.wg.Done()
226 + u.wg.Go(func() {
227 u.handleConnection(conn)
232 - }()
228 + })
229 }
230 }
231 }
src/go/plugin/ibm.d/docgen/config_parser.go
+16 -16
@@ -22,7 +22,7 @@ import (
22
23 // parseConfigFromGoFile parses a Go config file to extract configuration fields
24 // and the defaults supplied by defaultConfig().
25 -func (g *DocGenerator) parseConfigFromGoFile() ([]ConfigField, map[string]interface{}, error) {
25 +func (g *DocGenerator) parseConfigFromGoFile() ([]ConfigField, map[string]any, error) {
26 fset := token.NewFileSet()
27 node, err := parser.ParseFile(fset, g.ConfigFile, nil, parser.ParseComments)
28 if err != nil {
@@ -502,8 +502,8 @@ func parseUIOptions(tag string) map[string]string {
502 if tag == "" {
503 return result
504 }
505 - parts := strings.Split(tag, ",")
506 - for _, part := range parts {
505 + parts := strings.SplitSeq(tag, ",")
506 + for part := range parts {
507 part = strings.TrimSpace(part)
508 if part == "" {
509 continue
@@ -558,7 +558,7 @@ func toStringSlice(values []confopt.AutoBool) []string {
558 return result
559 }
560
561 -func normalizeDefaultValue(field ConfigField, value interface{}) interface{} {
561 +func normalizeDefaultValue(field ConfigField, value any) any {
562 if !isAutoBoolType(field.GoType) {
563 return value
564 }
@@ -599,7 +599,7 @@ func normalizeAutoBoolLiteral(value string) string {
599
600 // parseDefaultsFromInitFile parses init.go to find the defaultConfig() function
601 // and extract default values from the returned Config struct
602 -func (g *DocGenerator) parseDefaultsFromInitFile() map[string]interface{} {
602 +func (g *DocGenerator) parseDefaultsFromInitFile() map[string]any {
603 // Construct path to init.go
604 dir := filepath.Dir(g.ConfigFile)
605 initFile := filepath.Join(dir, "init.go")
@@ -617,7 +617,7 @@ func (g *DocGenerator) parseDefaultsFromInitFile() map[string]interface{} {
617 return nil
618 }
619
620 - defaults := make(map[string]interface{})
620 + defaults := make(map[string]any)
621 foundDefaultConfig := false
622
623 // Find the defaultConfig function
@@ -665,7 +665,7 @@ func (g *DocGenerator) parseDefaultsFromInitFile() map[string]interface{} {
665 }
666
667 // extractDefaultsFromLiteral extracts field values from a Config{} literal
668 -func (g *DocGenerator) extractDefaultsFromLiteral(lit *ast.CompositeLit, defaults map[string]interface{}) {
668 +func (g *DocGenerator) extractDefaultsFromLiteral(lit *ast.CompositeLit, defaults map[string]any) {
669 for _, elt := range lit.Elts {
670 if kv, ok := elt.(*ast.KeyValueExpr); ok {
671 if ident, ok := kv.Key.(*ast.Ident); ok {
@@ -673,7 +673,7 @@ func (g *DocGenerator) extractDefaultsFromLiteral(lit *ast.CompositeLit, default
673 switch val := kv.Value.(type) {
674 case *ast.CompositeLit:
675 if isArrayLiteral(val) {
676 - values := make([]interface{}, 0, len(val.Elts))
676 + values := make([]any, 0, len(val.Elts))
677 for _, elt := range val.Elts {
678 if value := g.extractValue(elt); value != nil {
679 values = append(values, value)
@@ -682,7 +682,7 @@ func (g *DocGenerator) extractDefaultsFromLiteral(lit *ast.CompositeLit, default
682 defaults[fieldName] = values
683 continue
684 }
685 - nested := make(map[string]interface{})
685 + nested := make(map[string]any)
686 g.extractDefaultsFromLiteral(val, nested)
687 // Flatten nested composite literals for embedded configs such as framework.Config.
688 if fieldName == "Config" {
@@ -711,7 +711,7 @@ func (g *DocGenerator) extractDefaultsFromLiteral(lit *ast.CompositeLit, default
711 }
712
713 // extractValue converts an AST expression to a Go value
714 -func (g *DocGenerator) extractValue(expr ast.Expr) interface{} {
714 +func (g *DocGenerator) extractValue(expr ast.Expr) any {
715 switch v := expr.(type) {
716 case *ast.BasicLit:
717 switch v.Kind {
@@ -810,8 +810,8 @@ func isArrayLiteral(lit *ast.CompositeLit) bool {
810 return false
811 }
812
813 -func (g *DocGenerator) extractConstValues(file *ast.File) map[string]interface{} {
814 - consts := make(map[string]interface{})
813 +func (g *DocGenerator) extractConstValues(file *ast.File) map[string]any {
814 + consts := make(map[string]any)
815 if file == nil {
816 return consts
817 }
@@ -833,7 +833,7 @@ func (g *DocGenerator) extractConstValues(file *ast.File) map[string]interface{}
833 if name == nil || name.Name == "_" {
834 continue
835 }
836 - var value interface{}
836 + var value any
837 if len(vs.Values) > i {
838 value = g.extractValue(vs.Values[i])
839 } else if len(vs.Values) > 0 {
@@ -850,7 +850,7 @@ func (g *DocGenerator) extractConstValues(file *ast.File) map[string]interface{}
850 return consts
851 }
852
853 -func evalBinaryExpr(op token.Token, left, right interface{}) (interface{}, bool) {
853 +func evalBinaryExpr(op token.Token, left, right any) (any, bool) {
854 if li, lok := toInt64(left); lok {
855 if ri, rok := toInt64(right); rok {
856 switch op {
@@ -906,7 +906,7 @@ func evalBinaryExpr(op token.Token, left, right interface{}) (interface{}, bool)
906 return res, true
907 }
908
909 -func toInt64(v interface{}) (int64, bool) {
909 +func toInt64(v any) (int64, bool) {
910 switch val := v.(type) {
911 case int:
912 return int64(val), true
@@ -939,7 +939,7 @@ func toInt64(v interface{}) (int64, bool) {
939 return 0, false
940 }
941
942 -func toFloat64(v interface{}) (float64, bool) {
942 +func toFloat64(v any) (float64, bool) {
943 switch val := v.(type) {
944 case int:
945 return float64(val), true
src/go/plugin/ibm.d/docgen/main.go
+17 -17
@@ -62,7 +62,7 @@ type ConfigField struct {
62 Title string
63 ItemsType string
64 Required bool
65 - Default interface{}
65 + Default any
66 Description string
67 Format string
68 Minimum *int
@@ -112,7 +112,7 @@ type DocGenerator struct {
112 ConfigFile string
113 OutputDir string
114 ModuleInfo string
115 - consts map[string]interface{}
115 + consts map[string]any
116 hasHTTPConfig bool
117 }
118
@@ -222,7 +222,7 @@ func (g *DocGenerator) parseConfig() ([]ConfigField, error) {
222 }
223
224 // Ensure standard fields are present even if they come from embedded structs
225 - ensureField := func(name string, desc string, defaultKey string, fallback interface{}, fieldType string, uiGroup string, uiWidget string, min *int, max *int) {
225 + ensureField := func(name string, desc string, defaultKey string, fallback any, fieldType string, uiGroup string, uiWidget string, min *int, max *int) {
226 for _, f := range fields {
227 if f.JSONName == name {
228 return
@@ -388,22 +388,22 @@ func (g *DocGenerator) generateMetadata(contexts *Config, moduleInfo *ModuleInfo
388
389 func (g *DocGenerator) generateConfigSchema(fields []ConfigField) error {
390 // Create schema manually to avoid template issues
391 - schema := map[string]interface{}{
392 - "jsonSchema": map[string]interface{}{
391 + schema := map[string]any{
392 + "jsonSchema": map[string]any{
393 "$schema": "http://json-schema.org/draft-07/schema#",
394 "title": fmt.Sprintf("%s collector configuration", g.ModuleName),
395 "type": "object",
396 },
397 }
398
399 - properties := make(map[string]interface{})
399 + properties := make(map[string]any)
400 var required []string
401 groupOrder := make([]string, 0)
402 groupFields := make(map[string][]string)
403 - fieldUIOptions := make(map[string]map[string]interface{})
403 + fieldUIOptions := make(map[string]map[string]any)
404
405 for _, field := range fields {
406 - prop := map[string]interface{}{
406 + prop := map[string]any{
407 "title": field.Title,
408 "type": field.Type,
409 }
@@ -416,7 +416,7 @@ func (g *DocGenerator) generateConfigSchema(fields []ConfigField) error {
416 if itemsType == "" {
417 itemsType = "string"
418 }
419 - prop["items"] = map[string]interface{}{
419 + prop["items"] = map[string]any{
420 "type": itemsType,
421 }
422 }
@@ -462,7 +462,7 @@ func (g *DocGenerator) generateConfigSchema(fields []ConfigField) error {
462
463 opts, exists := fieldUIOptions[field.JSONName]
464 if !exists {
465 - opts = make(map[string]interface{})
465 + opts = make(map[string]any)
466 }
467 if field.UIWidget != "" {
468 opts["ui:widget"] = field.UIWidget
@@ -481,32 +481,32 @@ func (g *DocGenerator) generateConfigSchema(fields []ConfigField) error {
481 }
482 }
483
484 - schema["jsonSchema"].(map[string]interface{})["properties"] = properties
484 + schema["jsonSchema"].(map[string]any)["properties"] = properties
485 if len(required) > 0 {
486 - schema["jsonSchema"].(map[string]interface{})["required"] = required
486 + schema["jsonSchema"].(map[string]any)["required"] = required
487 }
488
489 - uiSchema := map[string]interface{}{
490 - "uiOptions": map[string]interface{}{
489 + uiSchema := map[string]any{
490 + "uiOptions": map[string]any{
491 "fullPage": true,
492 },
493 }
494 uiSchema["ui:flavour"] = "tabs"
495
496 if len(groupOrder) > 0 {
497 - tabs := make([]map[string]interface{}, 0, len(groupOrder))
497 + tabs := make([]map[string]any, 0, len(groupOrder))
498 for _, group := range groupOrder {
499 fieldsForGroup := groupFields[group]
500 if len(fieldsForGroup) == 0 {
501 continue
502 }
503 - tabs = append(tabs, map[string]interface{}{
503 + tabs = append(tabs, map[string]any{
504 "title": group,
505 "fields": fieldsForGroup,
506 })
507 }
508 if len(tabs) > 0 {
509 - uiSchema["ui:options"] = map[string]interface{}{
509 + uiSchema["ui:options"] = map[string]any{
510 "tabs": tabs,
511 }
512 }
src/go/plugin/ibm.d/framework/batch.go
+3 -6
@@ -8,10 +8,7 @@ func Batch[T any](items []T, size int) <-chan []T {
8 defer close(ch)
9
10 for i := 0; i < len(items); i += size {
11 - end := i + size
12 - if end > len(items) {
13 - end = len(items)
14 - }
11 + end := min(i+size, len(items))
12
13 ch <- items[i:end]
14 }
@@ -40,7 +37,7 @@ func ParallelBatch[T any](items []T, batchSize int, workers int, fn func([]T) er
37 results := make(chan result, workers)
38
39 // Start workers
43 - for i := 0; i < workers; i++ {
40 + for range workers {
41 go func() {
42 for batch := range work {
43 results <- result{err: fn(batch)}
@@ -59,7 +56,7 @@ func ParallelBatch[T any](items []T, batchSize int, workers int, fn func([]T) er
56 // Collect results
57 var firstErr error
58 batchCount := (len(items) + batchSize - 1) / batchSize
62 - for i := 0; i < batchCount; i++ {
59 + for range batchCount {
60 res := <-results
61 if res.err != nil && firstErr == nil {
62 firstErr = res.err
src/go/plugin/ibm.d/framework/collector.go
+6 -6
@@ -13,8 +13,8 @@ type Collector struct {
13
14 Config Config
15 State *CollectorState
16 - registeredContexts []interface{} // All contexts from generated code
17 - contextMap map[string]interface{}
16 + registeredContexts []any // All contexts from generated code
17 + contextMap map[string]any
18 charts *collectorapi.Charts
19 impl CollectorImpl // The actual collector implementation
20 globalLabels []collectorapi.Label // Job-level labels applied to all charts
@@ -26,7 +26,7 @@ func (c *Collector) Init(ctx context.Context) error {
26 // Initialize state
27 c.State = NewCollectorState()
28 c.State.collector = &c.Base // Set logger reference
29 - c.contextMap = make(map[string]interface{})
29 + c.contextMap = make(map[string]any)
30 c.charts = &collectorapi.Charts{}
31 c.globalLabels = make([]collectorapi.Label, 0)
32 c.instanceCharts = make(map[string]struct{})
@@ -216,7 +216,7 @@ func cleanLabelValue(value string) string {
216 }
217
218 // createChartFromContext creates a go.d chart from a Context[T]
219 -func (c *Collector) createChartFromContext(ctx interface{}, instanceID string, instance *Instance) *collectorapi.Chart {
219 +func (c *Collector) createChartFromContext(ctx any, instanceID string, instance *Instance) *collectorapi.Chart {
220 // Use reflection to extract context metadata
221 contextMeta := extractContextMetadata(ctx)
222 if contextMeta == nil {
@@ -308,11 +308,11 @@ func (c *Collector) markChartsObsolete(instanceKey string) {
308 }
309
310 // Helper method for collectors to register generated contexts
311 -func (c *Collector) RegisterContexts(contexts ...interface{}) {
311 +func (c *Collector) RegisterContexts(contexts ...any) {
312 c.registeredContexts = append(c.registeredContexts, contexts...)
313 // Build context map for quick lookup
314 if c.contextMap == nil {
315 - c.contextMap = make(map[string]interface{})
315 + c.contextMap = make(map[string]any)
316 }
317 for _, ctx := range contexts {
318 name := extractContextName(ctx)
src/go/plugin/ibm.d/framework/protocols.go
+9 -12
@@ -36,23 +36,23 @@ func (p *ProtocolClient) MarkConnected() {
36 }
37
38 // Debugf logs a debug message prefixed with the protocol name
39 -func (p *ProtocolClient) Debugf(format string, args ...interface{}) {
40 - p.state.Debugf("[%s] "+format, append([]interface{}{p.name}, args...)...)
39 +func (p *ProtocolClient) Debugf(format string, args ...any) {
40 + p.state.Debugf("[%s] "+format, append([]any{p.name}, args...)...)
41 }
42
43 // Warningf logs a warning message prefixed with the protocol name
44 -func (p *ProtocolClient) Warningf(format string, args ...interface{}) {
45 - p.state.Warningf("[%s] "+format, append([]interface{}{p.name}, args...)...)
44 +func (p *ProtocolClient) Warningf(format string, args ...any) {
45 + p.state.Warningf("[%s] "+format, append([]any{p.name}, args...)...)
46 }
47
48 // Errorf logs an error message prefixed with the protocol name
49 -func (p *ProtocolClient) Errorf(format string, args ...interface{}) {
50 - p.state.Errorf("[%s] "+format, append([]interface{}{p.name}, args...)...)
49 +func (p *ProtocolClient) Errorf(format string, args ...any) {
50 + p.state.Errorf("[%s] "+format, append([]any{p.name}, args...)...)
51 }
52
53 // Infof logs an info message prefixed with the protocol name
54 -func (p *ProtocolClient) Infof(format string, args ...interface{}) {
55 - p.state.Infof("[%s] "+format, append([]interface{}{p.name}, args...)...)
54 +func (p *ProtocolClient) Infof(format string, args ...any) {
55 + p.state.Infof("[%s] "+format, append([]any{p.name}, args...)...)
56 }
57
58 // IsReconnect returns true if this is the same iteration as when connected
@@ -182,10 +182,7 @@ func NewExponentialBackoff() *ExponentialBackoff {
182 // NextInterval returns the next backoff interval
183 func (b *ExponentialBackoff) NextInterval() time.Duration {
184 defer func() {
185 - b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier)
186 - if b.currentInterval > b.MaxInterval {
187 - b.currentInterval = b.MaxInterval
188 - }
185 + b.currentInterval = min(time.Duration(float64(b.currentInterval)*b.Multiplier), b.MaxInterval)
186 b.attempt++
187 }()
188
src/go/plugin/ibm.d/framework/state.go
+15 -15
@@ -20,7 +20,7 @@ func NewCollectorState() *CollectorState {
20 }
21
22 // GetInstance returns or creates an instance for the given context and labels
23 -func (s *CollectorState) GetInstance(ctx interface{}, labels interface{}) *Instance {
23 +func (s *CollectorState) GetInstance(ctx any, labels any) *Instance {
24 // Extract context metadata including label order
25 contextMeta := extractContextMetadata(ctx)
26 if contextMeta == nil {
@@ -70,14 +70,14 @@ func (s *CollectorState) GetInstance(ctx interface{}, labels interface{}) *Insta
70 // SetMetricsForGeneratedCode is ONLY for use by code generated by metricgen.
71 // DO NOT call this method directly in hand-written code.
72 // Use the type-safe Set() methods on generated context types instead.
73 -func (s *CollectorState) SetMetricsForGeneratedCode(ctx interface{}, labels interface{}, values map[string]int64) {
73 +func (s *CollectorState) SetMetricsForGeneratedCode(ctx any, labels any, values map[string]int64) {
74 s.set(ctx, labels, values)
75 }
76
77 // SetUpdateEveryOverrideForGeneratedCode is ONLY for use by code generated by metricgen.
78 // DO NOT call this method directly in hand-written code.
79 // Use the type-safe SetUpdateEvery() methods on generated context types instead.
80 -func (s *CollectorState) SetUpdateEveryOverrideForGeneratedCode(ctx interface{}, labels interface{}, updateEvery int) {
80 +func (s *CollectorState) SetUpdateEveryOverrideForGeneratedCode(ctx any, labels any, updateEvery int) {
81 instance := s.GetInstance(ctx, labels)
82 if instance != nil {
83 instance.UpdateEveryOverride = updateEvery
@@ -87,7 +87,7 @@ func (s *CollectorState) SetUpdateEveryOverrideForGeneratedCode(ctx interface{},
87 // set stores multiple metric values for an instance
88 // This method is unexported to prevent direct usage by modules.
89 // Use the type-safe Set() methods on generated context types instead.
90 -func (s *CollectorState) set(ctx interface{}, labels interface{}, values map[string]int64) {
90 +func (s *CollectorState) set(ctx any, labels any, values map[string]int64) {
91 instance := s.GetInstance(ctx, labels)
92
93 // Get context metadata
@@ -197,10 +197,10 @@ func (s *CollectorState) GetIteration() int64 {
197
198 // Helper functions
199
200 -func extractContextName(ctx interface{}) string {
200 +func extractContextName(ctx any) string {
201 // Use reflection to get the Name field from Context[T]
202 v := reflect.ValueOf(ctx)
203 - if v.Kind() == reflect.Ptr {
203 + if v.Kind() == reflect.Pointer {
204 v = v.Elem()
205 }
206
@@ -216,7 +216,7 @@ func extractContextName(ctx interface{}) string {
216 return ""
217 }
218
219 -func structToMap(labels interface{}) map[string]string {
219 +func structToMap(labels any) map[string]string {
220 result := make(map[string]string)
221
222 if labels == nil {
@@ -228,7 +228,7 @@ func structToMap(labels interface{}) map[string]string {
228 t := reflect.TypeOf(labels)
229
230 // Handle pointer types
231 - if v.Kind() == reflect.Ptr {
231 + if v.Kind() == reflect.Pointer {
232 if v.IsNil() {
233 return result
234 }
@@ -301,15 +301,15 @@ func generateInstanceKeyWithOrder(contextName string, labelKeys []string, labels
301 return contextName
302 }
303
304 -func getContextMetadata(ctx interface{}) *ContextMetadata {
304 +func getContextMetadata(ctx any) *ContextMetadata {
305 // Extract metadata from Context[T] using reflection
306 return extractContextMetadata(ctx)
307 }
308
309 // extractContextMetadata extracts metadata from a Context[T] pointer
310 -func extractContextMetadata(ctx interface{}) *ContextMetadata {
310 +func extractContextMetadata(ctx any) *ContextMetadata {
311 v := reflect.ValueOf(ctx)
312 - if v.Kind() == reflect.Ptr {
312 + if v.Kind() == reflect.Pointer {
313 v = v.Elem()
314 }
315
@@ -395,28 +395,28 @@ func getContextUpdateInterval(contextName string) int {
395 }
396
397 // Debugf logs a debug message (delegate to collector's logger)
398 -func (s *CollectorState) Debugf(format string, args ...interface{}) {
398 +func (s *CollectorState) Debugf(format string, args ...any) {
399 if s.collector != nil {
400 s.collector.Debugf(format, args...)
401 }
402 }
403
404 // Warningf logs a warning message (delegate to collector's logger)
405 -func (s *CollectorState) Warningf(format string, args ...interface{}) {
405 +func (s *CollectorState) Warningf(format string, args ...any) {
406 if s.collector != nil {
407 s.collector.Warningf(format, args...)
408 }
409 }
410
411 // Errorf logs an error message (delegate to collector's logger)
412 -func (s *CollectorState) Errorf(format string, args ...interface{}) {
412 +func (s *CollectorState) Errorf(format string, args ...any) {
413 if s.collector != nil {
414 s.collector.Errorf(format, args...)
415 }
416 }
417
418 // Infof logs an info message (delegate to collector's logger)
419 -func (s *CollectorState) Infof(format string, args ...interface{}) {
419 +func (s *CollectorState) Infof(format string, args ...any) {
420 if s.collector != nil {
421 s.collector.Infof(format, args...)
422 }
src/go/plugin/ibm.d/framework/types.go
+4 -4
@@ -7,10 +7,10 @@ import (
7
8 // Logger interface for logging functionality
9 type Logger interface {
10 - Debugf(format string, args ...interface{})
11 - Warningf(format string, args ...interface{})
12 - Errorf(format string, args ...interface{})
13 - Infof(format string, args ...interface{})
10 + Debugf(format string, args ...any)
11 + Warningf(format string, args ...any)
12 + Errorf(format string, args ...any)
13 + Infof(format string, args ...any)
14 }
15
16 // Context represents a metric collection context with compile-time type safety
src/go/plugin/ibm.d/modules/mq/collect_queues.go
+1 -4
@@ -208,10 +208,7 @@ func (c *Collector) collectQueueMetrics() error {
208 return filtered[i].Name < filtered[j].Name
209 })
210
211 - limit := c.Config.MaxQueues
212 - if limit < 0 {
213 - limit = 0
214 - }
211 + limit := max(c.Config.MaxQueues, 0)
212
213 aggregated := make(map[string]*queueGroupAggregate)
214 overflowTotals := &queueGroupAggregate{}
src/go/plugin/ibm.d/modules/mq/collector.go
+1 -1
@@ -30,7 +30,7 @@ type Collector struct {
30
31 const warnThrottleInterval = 10 * time.Minute
32
33 -func (c *Collector) warnOnce(key string, format string, args ...interface{}) {
33 +func (c *Collector) warnOnce(key string, format string, args ...any) {
34 c.warnMu.Lock()
35 defer c.warnMu.Unlock()
36
src/go/plugin/ibm.d/modules/websphere/jmx/collector.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package jmx
4
src/go/plugin/ibm.d/modules/websphere/jmx/collector_test.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package jmx
4
src/go/plugin/ibm.d/modules/websphere/jmx/init.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package jmx
4
src/go/plugin/ibm.d/modules/websphere/jmx/module.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package jmx
4
src/go/plugin/ibm.d/modules/websphere/mp/collector.go
+3 -13
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package mp
4
@@ -238,10 +237,7 @@ func (c *Collector) exportCoreMetrics(agg map[string]int64) {
237
238 used := agg["heap_used"]
239 committed := agg["heap_committed"]
241 - free := committed - used
242 - if free < 0 {
243 - free = 0
244 - }
240 + free := max(committed-used, 0)
241 contexts.JVM.HeapUsage.Set(c.State, labels, contexts.JVMHeapUsageValues{
242 Used: used,
243 Free: free,
@@ -259,10 +255,7 @@ func (c *Collector) exportCoreMetrics(agg map[string]int64) {
255
256 totalThreads := agg["thread_total"]
257 daemon := agg["thread_daemon"]
262 - other := totalThreads - daemon
263 - if other < 0 {
264 - other = 0
265 - }
258 + other := max(totalThreads-daemon, 0)
259 contexts.JVM.ThreadsCurrent.Set(c.State, labels, contexts.JVMThreadsCurrentValues{
260 Daemon: daemon,
261 Other: other,
@@ -277,10 +270,7 @@ func (c *Collector) exportCoreMetrics(agg map[string]int64) {
270
271 active := agg["threadpool_active"]
272 size := agg["threadpool_size"]
280 - idle := size - active
281 - if idle < 0 {
282 - idle = 0
283 - }
273 + idle := max(size-active, 0)
274 contexts.Vendor.ThreadPoolUsage.Set(c.State, labels, contexts.VendorThreadPoolUsageValues{
275 Active: active,
276 Idle: idle,
src/go/plugin/ibm.d/modules/websphere/mp/init.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package mp
4
src/go/plugin/ibm.d/modules/websphere/mp/module.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package mp
4
src/go/plugin/ibm.d/modules/websphere/pmi/collector.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package pmi
4
src/go/plugin/ibm.d/modules/websphere/pmi/collector_coverage_test.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package pmi
4
src/go/plugin/ibm.d/modules/websphere/pmi/collector_test.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package pmi
4
src/go/plugin/ibm.d/modules/websphere/pmi/init.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package pmi
4
src/go/plugin/ibm.d/modules/websphere/pmi/module.go
-1
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package pmi
4
src/go/plugin/ibm.d/protocols/jmxbridge/client.go
+6 -6
@@ -34,15 +34,15 @@ type Config struct {
34 }
35
36 // Command represents a JSON command sent to the helper.
37 -type Command map[string]interface{}
37 +type Command map[string]any
38
39 // Response represents a generic helper response.
40 type Response struct {
41 - Status string `json:"status"`
42 - Message string `json:"message,omitempty"`
43 - Details string `json:"details,omitempty"`
44 - Recoverable bool `json:"recoverable,omitempty"`
45 - Data map[string]interface{} `json:"data,omitempty"`
41 + Status string `json:"status"`
42 + Message string `json:"message,omitempty"`
43 + Details string `json:"details,omitempty"`
44 + Recoverable bool `json:"recoverable,omitempty"`
45 + Data map[string]any `json:"data,omitempty"`
46 }
47
48 // Option configures a Client.
src/go/plugin/ibm.d/protocols/jmxbridge/client_test.go
+8 -8
@@ -26,10 +26,10 @@ type fakeProcess struct {
26 stderrR *io.PipeReader
27 stderrW *io.PipeWriter
28 done chan struct{}
29 - handler func(map[string]interface{}) Response
29 + handler func(map[string]any) Response
30 }
31
32 -func newFakeProcess(handler func(map[string]interface{}) Response) *fakeProcess {
32 +func newFakeProcess(handler func(map[string]any) Response) *fakeProcess {
33 stdinR, stdinW := io.Pipe()
34 stdoutR, stdoutW := io.Pipe()
35 stderrR, stderrW := io.Pipe()
@@ -57,7 +57,7 @@ func (p *fakeProcess) run() {
57 scanner := bufio.NewScanner(p.stdinR)
58 for scanner.Scan() {
59 line := scanner.Text()
60 - var cmd map[string]interface{}
60 + var cmd map[string]any
61 if err := json.Unmarshal([]byte(line), &cmd); err != nil {
62 continue
63 }
@@ -74,12 +74,12 @@ func (p *fakeProcess) Wait() error { <-p.done; return nil }
74
75 func TestClientStartAndSend(t *testing.T) {
76 var call int
77 - handler := func(cmd map[string]interface{}) Response {
77 + handler := func(cmd map[string]any) Response {
78 call++
79 if call == 1 {
80 return Response{Status: "OK"}
81 }
82 - return Response{Status: "OK", Data: map[string]interface{}{"value": 123}}
82 + return Response{Status: "OK", Data: map[string]any{"value": 123}}
83 }
84
85 var procMu sync.Mutex
@@ -115,7 +115,7 @@ func TestClientStartAndSend(t *testing.T) {
115
116 func TestClientErrorStatus(t *testing.T) {
117 var call int
118 - handler := func(cmd map[string]interface{}) Response {
118 + handler := func(cmd map[string]any) Response {
119 call++
120 if call == 1 {
121 return Response{Status: "OK"}
@@ -144,7 +144,7 @@ func TestClientErrorStatus(t *testing.T) {
144 }
145
146 func TestClientCancellation(t *testing.T) {
147 - handler := func(cmd map[string]interface{}) Response {
147 + handler := func(cmd map[string]any) Response {
148 time.Sleep(200 * time.Millisecond)
149 return Response{Status: "OK"}
150 }
@@ -178,7 +178,7 @@ func TestClientWritesJar(t *testing.T) {
178 if _, err := os.Stat(jarPath); err != nil {
179 t.Fatalf("jar file not written: %v", err)
180 }
181 - return newFakeProcess(func(cmd map[string]interface{}) Response { return Response{Status: "OK"} }), nil
181 + return newFakeProcess(func(cmd map[string]any) Response { return Response{Status: "OK"} }), nil
182 }))
183 if err != nil {
184 t.Fatalf("NewClient failed: %v", err)
src/go/plugin/ibm.d/protocols/pcf/channel_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/client_core.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/connection.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/constants.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/list_parser.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/listener_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/pcf_ibm_transport.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/qmgr_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/queue_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/reset_queue_stats.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/resource_monitor_ibm.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/statistics_queue.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/stub.go
+1 -1
@@ -196,7 +196,7 @@ func (c *Client) GetResourcePublications() (*ResourcePublicationsResult, error)
196 return nil, errors.New("PCF protocol requires CGO support")
197 }
198
199 -func (c *Client) GetResourceMonitorData() (map[string]interface{}, error) {
199 +func (c *Client) GetResourceMonitorData() (map[string]any, error) {
200 return nil, errors.New("PCF protocol requires CGO support")
201 }
202
src/go/plugin/ibm.d/protocols/pcf/subscription_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/topic_commands.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/types.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/pcf/utils.go
-1
@@ -1,7 +1,6 @@
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 //go:build cgo && ibm_mq
4 -// +build cgo,ibm_mq
4
5 package pcf
6
src/go/plugin/ibm.d/protocols/websphere/jmx/client.go
+18 -19
@@ -2,7 +2,6 @@
2 // SPDX-License-Identifier: GPL-3.0-or-later
3
4 //go:build cgo
5 -// +build cgo
5
6 package jmx
7
@@ -178,13 +177,13 @@ func (c *Client) FetchThreadPools(ctx context.Context, maxItems int) ([]ThreadPo
177 }
178
179 var pools []ThreadPool
181 - items, ok := payload["threadPools"].([]interface{})
180 + items, ok := payload["threadPools"].([]any)
181 if !ok {
182 return pools, nil
183 }
184
185 for _, item := range items {
187 - poolMap, ok := item.(map[string]interface{})
186 + poolMap, ok := item.(map[string]any)
187 if !ok {
188 continue
189 }
@@ -220,13 +219,13 @@ func (c *Client) FetchJDBCPools(ctx context.Context, maxItems int) ([]JDBCPool,
219 }
220
221 var pools []JDBCPool
223 - items, ok := payload["jdbcPools"].([]interface{})
222 + items, ok := payload["jdbcPools"].([]any)
223 if !ok {
224 return pools, nil
225 }
226
227 for _, item := range items {
229 - poolMap, ok := item.(map[string]interface{})
228 + poolMap, ok := item.(map[string]any)
229 if !ok {
230 continue
231 }
@@ -267,13 +266,13 @@ func (c *Client) FetchJCAPools(ctx context.Context, maxItems int) ([]JCAPool, er
266 }
267
268 var pools []JCAPool
270 - items, ok := payload["jcaPools"].([]interface{})
269 + items, ok := payload["jcaPools"].([]any)
270 if !ok {
271 return pools, nil
272 }
273
274 for _, item := range items {
276 - poolMap, ok := item.(map[string]interface{})
275 + poolMap, ok := item.(map[string]any)
276 if !ok {
277 continue
278 }
@@ -314,13 +313,13 @@ func (c *Client) FetchJMSDestinations(ctx context.Context, maxItems int) ([]JMSD
313 }
314
315 var dests []JMSDestination
317 - items, ok := payload["jmsDestinations"].([]interface{})
316 + items, ok := payload["jmsDestinations"].([]any)
317 if !ok {
318 return dests, nil
319 }
320
321 for _, item := range items {
323 - destMap, ok := item.(map[string]interface{})
322 + destMap, ok := item.(map[string]any)
323 if !ok {
324 continue
325 }
@@ -362,13 +361,13 @@ func (c *Client) FetchApplications(ctx context.Context, maxItems int, includeSes
361 }
362
363 var metrics []ApplicationMetric
365 - items, ok := payload["applications"].([]interface{})
364 + items, ok := payload["applications"].([]any)
365 if !ok {
366 return metrics, nil
367 }
368
369 for _, item := range items {
371 - appMap, ok := item.(map[string]interface{})
370 + appMap, ok := item.(map[string]any)
371 if !ok {
372 continue
373 }
@@ -396,7 +395,7 @@ func (c *Client) FetchApplications(ctx context.Context, maxItems int, includeSes
395 return metrics, nil
396 }
397
399 -func (c *Client) send(ctx context.Context, cmd jmxbridge.Command) (map[string]interface{}, error) {
398 +func (c *Client) send(ctx context.Context, cmd jmxbridge.Command) (map[string]any, error) {
399 if !c.started {
400 return nil, errors.New("websphere jmx protocol: client not started")
401 }
@@ -419,18 +418,18 @@ func (c *Client) send(ctx context.Context, cmd jmxbridge.Command) (map[string]in
418 return resp.Data, nil
419 }
420
422 -func mapValue(m map[string]interface{}, key string) map[string]interface{} {
421 +func mapValue(m map[string]any, key string) map[string]any {
422 if m == nil {
424 - return map[string]interface{}{}
423 + return map[string]any{}
424 }
426 - val, _ := m[key].(map[string]interface{})
425 + val, _ := m[key].(map[string]any)
426 if val == nil {
428 - return map[string]interface{}{}
427 + return map[string]any{}
428 }
429 return val
430 }
431
433 -func stringValue(m map[string]interface{}, key string) string {
432 +func stringValue(m map[string]any, key string) string {
433 if m == nil {
434 return ""
435 }
@@ -440,14 +439,14 @@ func stringValue(m map[string]interface{}, key string) string {
439 return ""
440 }
441
443 -func floatValue(m map[string]interface{}, key string) float64 {
442 +func floatValue(m map[string]any, key string) float64 {
443 if m == nil {
444 return 0
445 }
446 return toFloat(m[key])
447 }
448
450 -func toFloat(v interface{}) float64 {
449 +func toFloat(v any) float64 {
450 switch value := v.(type) {
451 case nil:
452 return 0
src/go/plugin/ibm.d/protocols/websphere/jmx/client_test.go
+21 -22
@@ -1,5 +1,4 @@
1 //go:build cgo
2 -// +build cgo
2
3 package jmx
4
@@ -38,7 +37,7 @@ func (f *fakeBridge) Send(ctx context.Context, cmd jmxbridge.Command) (*jmxbridg
37 }
38 resp := f.responses[target]
39 if resp == nil {
41 - return &jmxbridge.Response{Status: "OK", Data: map[string]interface{}{}}, nil
40 + return &jmxbridge.Response{Status: "OK", Data: map[string]any{}}, nil
41 }
42 return resp, nil
43 }
@@ -52,31 +51,31 @@ func TestClientFetchJVM(t *testing.T) {
51 responses: map[string]*jmxbridge.Response{
52 "JVM": {
53 Status: "OK",
55 - Data: map[string]interface{}{
56 - "heap": map[string]interface{}{
54 + Data: map[string]any{
55 + "heap": map[string]any{
56 "used": 512.0,
57 "committed": 1024.0,
58 "max": 2048.0,
59 },
61 - "nonheap": map[string]interface{}{
60 + "nonheap": map[string]any{
61 "used": 128.0,
62 "committed": 256.0,
63 },
65 - "gc": map[string]interface{}{
64 + "gc": map[string]any{
65 "count": 12.0,
66 "time": 345.0,
67 },
69 - "threads": map[string]interface{}{
68 + "threads": map[string]any{
69 "count": 44.0,
70 "daemon": 30.0,
71 "peak": 60.0,
72 "totalStarted": 100.0,
73 },
75 - "classes": map[string]interface{}{
74 + "classes": map[string]any{
75 "loaded": 5000.0,
76 "unloaded": 200.0,
77 },
79 - "cpu": map[string]interface{}{
78 + "cpu": map[string]any{
79 "processCpuUsage": 0.42,
80 },
81 "uptime": 900.0,
@@ -118,15 +117,15 @@ func TestClientFetchThreadPools(t *testing.T) {
117 responses: map[string]*jmxbridge.Response{
118 "THREADPOOLS": {
119 Status: "OK",
121 - Data: map[string]interface{}{
122 - "threadPools": []interface{}{
123 - map[string]interface{}{
120 + Data: map[string]any{
121 + "threadPools": []any{
122 + map[string]any{
123 "name": "Default",
124 "poolSize": 50.0,
125 "activeCount": 5.0,
126 "maximumPoolSize": 75.0,
127 },
129 - map[string]interface{}{
128 + map[string]any{
129 "name": "WebContainer",
130 "poolSize": 80.0,
131 "activeCount": 12.0,
@@ -168,9 +167,9 @@ func TestClientFetchJDBCPools(t *testing.T) {
167 responses: map[string]*jmxbridge.Response{
168 "JDBC": {
169 Status: "OK",
171 - Data: map[string]interface{}{
172 - "jdbcPools": []interface{}{
173 - map[string]interface{}{
170 + Data: map[string]any{
171 + "jdbcPools": []any{
172 + map[string]any{
173 "name": "DefaultDS",
174 "poolSize": 40.0,
175 "numConnectionsUsed": 5.0,
@@ -218,9 +217,9 @@ func TestClientFetchJMSDestinations(t *testing.T) {
217 responses: map[string]*jmxbridge.Response{
218 "JMS": {
219 Status: "OK",
221 - Data: map[string]interface{}{
222 - "jmsDestinations": []interface{}{
223 - map[string]interface{}{
220 + Data: map[string]any{
221 + "jmsDestinations": []any{
222 + map[string]any{
223 "name": "Queue1",
224 "type": "queue",
225 "messagesCurrentCount": 12.0,
@@ -265,9 +264,9 @@ func TestClientFetchApplications(t *testing.T) {
264 responses: map[string]*jmxbridge.Response{
265 "APPLICATIONS": {
266 Status: "OK",
268 - Data: map[string]interface{}{
269 - "applications": []interface{}{
270 - map[string]interface{}{
267 + Data: map[string]any{
268 + "applications": []any{
269 + map[string]any{
270 "name": "sample-app",
271 "module": "moduleA",
272 "requestCount": 120.0,
src/go/plugin/scripts.d/collector/nagios/exec_env.go
+2 -3
@@ -4,6 +4,7 @@ package nagios
4
5 import (
6 "fmt"
7 + "maps"
8 "os"
9 "os/user"
10 "runtime"
@@ -15,9 +16,7 @@ func buildRunEnv(workingDir string, jobEnv map[string]string, macroEnv map[strin
16 for k, v := range jobEnv {
17 merged[k] = replaceMacro(v, macroEnv)
18 }
18 - for k, v := range macroEnv {
19 - merged[k] = v
20 - }
19 + maps.Copy(merged, macroEnv)
20
21 keys := make([]string, 0, len(merged))
22 for k := range merged {
src/go/plugin/scripts.d/collector/nagios/job_config_test.go
+1 -1
@@ -32,7 +32,7 @@ func TestJobConfigValidate(t *testing.T) {
32 "arg_values over limit": {
33 cfg: func() JobConfig {
34 cfg := JobConfig{Name: "sample", Plugin: "/bin/true"}
35 - for i := 0; i < maxArgMacros+1; i++ {
35 + for range maxArgMacros + 1 {
36 cfg.ArgValues = append(cfg.ArgValues, "value")
37 }
38 return cfg
src/go/plugin/scripts.d/collector/nagios/macros.go
+2 -3
@@ -4,6 +4,7 @@ package nagios
4
5 import (
6 "fmt"
7 + "maps"
8 "strings"
9 "time"
10
@@ -78,9 +79,7 @@ func vnodeInfoFromVirtualNode(vn *vnodes.VirtualNode, fallbackHostname string) v
79 if vn.Hostname != "" {
80 info.Hostname = vn.Hostname
81 }
81 - for k, v := range vn.Labels {
82 - info.Labels[k] = v
83 - }
82 + maps.Copy(info.Labels, vn.Labels)
83 return info
84 }
85
src/go/plugin/scripts.d/pkg/timeperiod/compile.go
+1 -1
@@ -299,7 +299,7 @@ func (p *Period) NextAllowed(t time.Time) time.Time {
299 if p == nil {
300 return t
301 }
302 - for i := 0; i < 60*24*90; i++ { // search up to ~90 days
302 + for range 60 * 24 * 90 { // search up to ~90 days
303 if p.Allows(t) {
304 return t
305 }