Skip to content

Commit 19e5c0e

Browse files
fix: handle MetricSlice to Points conversion errors (#24452)
Correctly handle errors in converting MetricSlice elements into model.Points. Add a test to verify error handling.
1 parent c0f467e commit 19e5c0e

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

gather/metrics.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ type MetricsSlice []Metrics
3131

3232
// Points convert the MetricsSlice to model.Points
3333
func (ms MetricsSlice) Points() (models.Points, error) {
34-
ps := make([]models.Point, len(ms))
35-
for mi, m := range ms {
34+
ps := make([]models.Point, 0, len(ms))
35+
for _, m := range ms {
3636
point, err := models.NewPoint(m.Name, models.NewTags(m.Tags), m.Fields, m.Timestamp)
3737
if err != nil {
3838
return ps, err
3939
}
4040

41-
ps[mi] = point
41+
ps = append(ps, point)
4242
}
4343
return ps, nil
4444
}

gather/scheduler_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package gather
33
import (
44
"context"
55
"net/http/httptest"
6+
"strings"
67
"testing"
78
"time"
89

@@ -11,6 +12,7 @@ import (
1112
"github.com/influxdata/influxdb/v2/mock"
1213
"github.com/influxdata/influxdb/v2/models"
1314
influxdbtesting "github.com/influxdata/influxdb/v2/testing"
15+
dto "github.com/prometheus/client_model/go"
1416
"github.com/stretchr/testify/assert"
1517
"github.com/stretchr/testify/require"
1618
"go.uber.org/zap/zaptest"
@@ -77,3 +79,46 @@ const sampleRespSmall = `
7779
# TYPE go_goroutines gauge
7880
go_goroutines 36
7981
`
82+
83+
func TestMetricsToPoints(t *testing.T) {
84+
const overflow = 3
85+
const goodPoints = 2
86+
tags := map[string]string{"one": "first", "two": "second", "three": "third"}
87+
fields := map[string]interface{}{"first_field": 32.2}
88+
89+
ms := MetricsSlice{
90+
{
91+
Name: "a",
92+
Tags: tags,
93+
Fields: fields,
94+
Timestamp: time.Now(),
95+
Type: dto.MetricType_GAUGE,
96+
},
97+
{
98+
Name: "b",
99+
Tags: tags,
100+
Fields: fields,
101+
Timestamp: time.Now(),
102+
Type: dto.MetricType_GAUGE,
103+
}, {
104+
Name: strings.Repeat("c", models.MaxKeyLength+overflow),
105+
Tags: tags,
106+
Fields: fields,
107+
Timestamp: time.Now(),
108+
Type: dto.MetricType_GAUGE,
109+
},
110+
{
111+
Name: "d",
112+
Tags: tags,
113+
Fields: fields,
114+
Timestamp: time.Now(),
115+
Type: dto.MetricType_GAUGE,
116+
},
117+
}
118+
ps, err := ms.Points()
119+
assert.ErrorContains(t, err, "max key length exceeded", "MetricSlice.Points did not have a 'max key length exceeded' error")
120+
assert.Equal(t, goodPoints, len(ps), "wrong number of Points returned from MetricSlice.Points")
121+
for _, p := range ps {
122+
assert.NotNil(t, p, "nil Point object returned from MetricSlice.Points")
123+
}
124+
}

0 commit comments

Comments
 (0)