fix assorted oddities found by golangci-lint (#1040)

* fix assorted oddities found by golangci-lint

Signed-off-by: Christoph Mewes <christoph@kubermatic.com>

* permanently enable the linters

Signed-off-by: Christoph Mewes <christoph@kubermatic.com>

* post-rebase blues

Signed-off-by: Christoph Mewes <christoph@kubermatic.com>
This commit is contained in:
Christoph Mewes 2022-08-03 06:30:51 +02:00 committed by GitHub
parent c7488be2e4
commit 618194de6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
19 changed files with 111 additions and 246 deletions

View File

@ -8,10 +8,26 @@ output:
linters:
enable:
- deadcode
- depguard
- durationcheck
- errorlint
- exportloopref
- gofmt
- gofumpt
- goimports
- revive
- gosimple
- ineffassign
- misspell
- nolintlint
- predeclared
- revive
- staticcheck
- structcheck
- unconvert
- unused
- varcheck
- wastedassign
issues:
max-same-issues: 0

View File

@ -109,7 +109,7 @@ func (c *httpClient) URL(ep string, args map[string]string) *url.URL {
for arg, val := range args {
arg = ":" + arg
p = strings.Replace(p, arg, val, -1)
p = strings.ReplaceAll(p, arg, val)
}
u := *c.endpoint

View File

@ -856,7 +856,7 @@ func (h *httpAPI) Query(ctx context.Context, query string, ts time.Time, opts ..
}
var qres queryResult
return model.Value(qres.v), warnings, json.Unmarshal(body, &qres)
return qres.v, warnings, json.Unmarshal(body, &qres)
}
func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts ...Option) (model.Value, Warnings, error) {
@ -885,7 +885,7 @@ func (h *httpAPI) QueryRange(ctx context.Context, query string, r Range, opts ..
var qres queryResult
return model.Value(qres.v), warnings, json.Unmarshal(body, &qres)
return qres.v, warnings, json.Unmarshal(body, &qres)
}
func (h *httpAPI) Series(ctx context.Context, matches []string, startTime, endTime time.Time) ([]model.LabelSet, Warnings, error) {

View File

@ -40,10 +40,8 @@ type apiTest struct {
inRes interface{}
reqPath string
reqParam url.Values
reqMethod string
res interface{}
warnings Warnings
err error
}
@ -55,7 +53,7 @@ type apiTestClient struct {
func (c *apiTestClient) URL(ep string, args map[string]string) *url.URL {
path := ep
for k, v := range args {
path = strings.Replace(path, ":"+k, v, -1)
path = strings.ReplaceAll(path, ":"+k, v)
}
u := &url.URL{
Host: "test:9090",
@ -74,25 +72,6 @@ func (c *apiTestClient) Do(_ context.Context, req *http.Request) (*http.Response
c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method)
}
var vals url.Values
switch test.reqMethod {
case http.MethodGet:
if req.URL.RawQuery != "" {
vals = req.URL.Query()
}
case http.MethodPost:
if req.Body != nil {
reqBody, _ := io.ReadAll(req.Body)
vals, _ = url.ParseQuery(string(reqBody))
} else if req.URL.RawQuery != "" {
vals = req.URL.Query()
}
}
if !reflect.DeepEqual(vals, test.reqParam) {
c.Fatalf("unexpected request parameters: want %s, got %s", vals, test.reqParam)
}
b, err := json.Marshal(test.inRes)
if err != nil {
c.Fatal(err)
@ -274,11 +253,6 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
"timeout": []string{(5 * time.Second).String()},
},
res: &model.Scalar{
Value: 2,
Timestamp: model.TimeFromUnix(testTime.Unix()),
@ -290,11 +264,7 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
do: doQuery("2", testTime),
@ -308,10 +278,6 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
},
err: errors.New("server_error: server error: 500"),
},
{
@ -326,10 +292,6 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
},
err: errors.New("client_error: client error: 404"),
},
// Warning only.
@ -346,15 +308,10 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
},
res: &model.Scalar{
Value: 2,
Timestamp: model.TimeFromUnix(testTime.Unix()),
},
warnings: []string{"warning"},
},
// Warning + error.
{
@ -370,12 +327,7 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query",
reqParam: url.Values{
"query": []string{"2"},
"time": []string{formatTime(testTime)},
},
err: errors.New("client_error: client error: 404"),
warnings: []string{"warning"},
},
{
@ -388,14 +340,7 @@ func TestAPIs(t *testing.T) {
reqMethod: "POST",
reqPath: "/api/v1/query_range",
reqParam: url.Values{
"query": []string{"2"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
"step": []string{"60"},
"timeout": []string{(5 * time.Second).String()},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -403,10 +348,6 @@ func TestAPIs(t *testing.T) {
inRes: []string{"val1", "val2"},
reqMethod: "GET",
reqPath: "/api/v1/labels",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: []string{"val1", "val2"},
},
{
@ -415,12 +356,7 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/labels",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: []string{"val1", "val2"},
warnings: []string{"a"},
},
{
@ -428,11 +364,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "GET",
reqPath: "/api/v1/labels",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime),
@ -440,23 +372,13 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/labels",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
warnings: []string{"a"},
err: errors.New("some error"),
},
{
do: doLabelNames([]string{"up"}, testTime.Add(-100*time.Hour), testTime),
inRes: []string{"val1", "val2"},
reqMethod: "GET",
reqPath: "/api/v1/labels",
reqParam: url.Values{
"match[]": {"up"},
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: []string{"val1", "val2"},
},
@ -465,10 +387,6 @@ func TestAPIs(t *testing.T) {
inRes: []string{"val1", "val2"},
reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: model.LabelValues{"val1", "val2"},
},
{
@ -477,12 +395,7 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: model.LabelValues{"val1", "val2"},
warnings: []string{"a"},
},
{
@ -490,11 +403,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime),
@ -502,23 +411,13 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values",
reqParam: url.Values{
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
warnings: []string{"a"},
err: errors.New("some error"),
},
{
do: doLabelValues([]string{"up"}, "mylabel", testTime.Add(-100*time.Hour), testTime),
inRes: []string{"val1", "val2"},
reqMethod: "GET",
reqPath: "/api/v1/label/mylabel/values",
reqParam: url.Values{
"match[]": {"up"},
"start": []string{formatTime(testTime.Add(-100 * time.Hour))},
"end": []string{formatTime(testTime)},
},
res: model.LabelValues{"val1", "val2"},
},
@ -533,11 +432,6 @@ func TestAPIs(t *testing.T) {
},
reqMethod: "GET",
reqPath: "/api/v1/series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
res: []model.LabelSet{
{
"__name__": "up",
@ -559,11 +453,6 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
res: []model.LabelSet{
{
"__name__": "up",
@ -571,7 +460,6 @@ func TestAPIs(t *testing.T) {
"instance": "localhost:9090",
},
},
warnings: []string{"a"},
},
{
@ -579,12 +467,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "GET",
reqPath: "/api/v1/series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
// Series with error and warning.
{
@ -593,13 +476,7 @@ func TestAPIs(t *testing.T) {
inWarnings: []string{"a"},
reqMethod: "GET",
reqPath: "/api/v1/series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
warnings: []string{"a"},
err: errors.New("some error"),
},
{
@ -609,9 +486,6 @@ func TestAPIs(t *testing.T) {
},
reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/snapshot",
reqParam: url.Values{
"skip_head": []string{"true"},
},
res: SnapshotResult{
Name: "20171210T211224Z-2be650b6d019eb54",
},
@ -622,10 +496,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/snapshot",
reqParam: url.Values{
"skip_head": []string{"true"},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -639,7 +510,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/clean_tombstones",
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -653,11 +524,6 @@ func TestAPIs(t *testing.T) {
},
reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/delete_series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
},
{
@ -665,12 +531,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "POST",
reqPath: "/api/v1/admin/tsdb/delete_series",
reqParam: url.Values{
"match[]": []string{"up"},
"start": []string{formatTime(testTime.Add(-time.Minute))},
"end": []string{formatTime(testTime)},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -1129,11 +990,6 @@ func TestAPIs(t *testing.T) {
},
reqMethod: "GET",
reqPath: "/api/v1/targets/metadata",
reqParam: url.Values{
"match_target": []string{"{job=\"prometheus\"}"},
"metric": []string{"go_goroutines"},
"limit": []string{"1"},
},
res: []MetricMetadata{
{
Target: map[string]string{
@ -1152,12 +1008,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "GET",
reqPath: "/api/v1/targets/metadata",
reqParam: url.Values{
"match_target": []string{"{job=\"prometheus\"}"},
"metric": []string{"go_goroutines"},
"limit": []string{"1"},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -1173,10 +1024,6 @@ func TestAPIs(t *testing.T) {
},
reqMethod: "GET",
reqPath: "/api/v1/metadata",
reqParam: url.Values{
"metric": []string{"go_goroutines"},
"limit": []string{"1"},
},
res: map[string][]Metadata{
"go_goroutines": {
{
@ -1193,11 +1040,7 @@ func TestAPIs(t *testing.T) {
inErr: fmt.Errorf("some error"),
reqMethod: "GET",
reqPath: "/api/v1/metadata",
reqParam: url.Values{
"metric": []string{""},
"limit": []string{"1"},
},
err: fmt.Errorf("some error"),
err: errors.New("some error"),
},
{
@ -1308,24 +1151,14 @@ func TestAPIs(t *testing.T) {
do: doQueryExemplars("tns_request_duration_seconds_bucket", testTime.Add(-1*time.Minute), testTime),
reqMethod: "GET",
reqPath: "/api/v1/query_exemplars",
reqParam: url.Values{
"query": []string{"tns_request_duration_seconds_bucket"},
"start": []string{formatTime(testTime.Add(-1 * time.Minute))},
"end": []string{formatTime(testTime)},
},
inErr: fmt.Errorf("some error"),
err: fmt.Errorf("some error"),
inErr: errors.New("some error"),
err: errors.New("some error"),
},
{
do: doQueryExemplars("tns_request_duration_seconds_bucket", testTime.Add(-1*time.Minute), testTime),
reqMethod: "GET",
reqPath: "/api/v1/query_exemplars",
reqParam: url.Values{
"query": []string{"tns_request_duration_seconds_bucket"},
"start": []string{formatTime(testTime.Add(-1 * time.Minute))},
"end": []string{formatTime(testTime)},
},
inRes: []interface{}{
map[string]interface{}{
"seriesLabels": map[string]interface{}{
@ -1395,7 +1228,9 @@ func TestAPIs(t *testing.T) {
if err.Error() != test.err.Error() {
t.Errorf("unexpected error: want %s, got %s", test.err, err)
}
if apiErr, ok := err.(*Error); ok {
apiErr := &Error{}
if ok := errors.As(err, &apiErr); ok {
if apiErr.Detail != test.inRes {
t.Errorf("%q should be %q", apiErr.Detail, test.inRes)
}
@ -1620,10 +1455,14 @@ func TestAPIClientDo(t *testing.T) {
}
if test.expectedErr.Detail != "" {
apiErr := err.(*Error)
apiErr := &Error{}
if errors.As(err, &apiErr) {
if apiErr.Detail != test.expectedErr.Detail {
t.Fatalf("expected error detail :%v, but got:%v", apiErr.Detail, test.expectedErr.Detail)
}
} else {
t.Fatalf("expected v1.Error instance, but got:%T", err)
}
}
return

View File

@ -15,6 +15,7 @@ package prometheus_test
import (
"bytes"
"errors"
"fmt"
"math"
"net/http"
@ -713,7 +714,8 @@ func ExampleAlreadyRegisteredError() {
Help: "The total number of requests served.",
})
if err := prometheus.Register(reqCounter); err != nil {
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
// A counter for that metric has been registered before.
// Use the old counter from now on.
reqCounter = are.ExistingCollector.(prometheus.Counter)

View File

@ -485,7 +485,7 @@ func (m *SequenceMatcher) QuickRatio() float64 {
if m.fullBCount == nil {
m.fullBCount = map[string]int{}
for _, s := range m.b {
m.fullBCount[s] = m.fullBCount[s] + 1
m.fullBCount[s]++
}
}

View File

@ -134,7 +134,7 @@ four`
Context: 3,
}
result, _ := GetUnifiedDiffString(diff)
fmt.Println(strings.Replace(result, "\t", " ", -1))
fmt.Println(strings.ReplaceAll(result, "\t", " "))
// Output:
// --- Original 2005-01-26 23:30:50
// +++ Current 2010-04-02 10:20:52

View File

@ -61,9 +61,9 @@ func RuntimeMetricsToProm(d *metrics.Description) (string, string, string, bool)
// name has - replaced with _ and is concatenated with the unit and
// other data.
name = strings.ReplaceAll(name, "-", "_")
name = name + "_" + unit
name += "_" + unit
if d.Cumulative && d.Kind != metrics.KindFloat64Histogram {
name = name + "_total"
name += "_total"
}
valid := model.IsValidMetricName(model.LabelValue(namespace + "_" + subsystem + "_" + name))

View File

@ -39,7 +39,7 @@ var errInconsistentCardinality = errors.New("inconsistent label cardinality")
func makeInconsistentCardinalityError(fqName string, labels, labelValues []string) error {
return fmt.Errorf(
"%s: %q has %d variable labels named %q but %d values %q were provided",
"%w: %q has %d variable labels named %q but %d values %q were provided",
errInconsistentCardinality, fqName,
len(labels), labels,
len(labelValues), labelValues,
@ -49,7 +49,7 @@ func makeInconsistentCardinalityError(fqName string, labels, labelValues []strin
func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error {
if len(labels) != expectedNumberOfValues {
return fmt.Errorf(
"%s: expected %d label values but got %d in %#v",
"%w: expected %d label values but got %d in %#v",
errInconsistentCardinality, expectedNumberOfValues,
len(labels), labels,
)
@ -67,7 +67,7 @@ func validateValuesInLabels(labels Labels, expectedNumberOfValues int) error {
func validateLabelValues(vals []string, expectedNumberOfValues int) error {
if len(vals) != expectedNumberOfValues {
return fmt.Errorf(
"%s: expected %d label values but got %d in %#v",
"%w: expected %d label values but got %d in %#v",
errInconsistentCardinality, expectedNumberOfValues,
len(vals), vals,
)

View File

@ -153,11 +153,11 @@ func NewPidFileFn(pidFilePath string) func() (int, error) {
return func() (int, error) {
content, err := os.ReadFile(pidFilePath)
if err != nil {
return 0, fmt.Errorf("can't read pid file %q: %+v", pidFilePath, err)
return 0, fmt.Errorf("can't read pid file %q: %w", pidFilePath, err)
}
pid, err := strconv.Atoi(strings.TrimSpace(string(content)))
if err != nil {
return 0, fmt.Errorf("can't parse pid file %q: %+v", pidFilePath, err)
return 0, fmt.Errorf("can't parse pid file %q: %w", pidFilePath, err)
}
return pid, nil

View File

@ -33,6 +33,7 @@ package promhttp
import (
"compress/gzip"
"errors"
"fmt"
"io"
"net/http"
@ -110,7 +111,8 @@ func HandlerForTransactional(reg prometheus.TransactionalGatherer, opts HandlerO
errCnt.WithLabelValues("gathering")
errCnt.WithLabelValues("encoding")
if err := opts.Registry.Register(errCnt); err != nil {
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
errCnt = are.ExistingCollector.(*prometheus.CounterVec)
} else {
panic(err)
@ -250,7 +252,8 @@ func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) ht
cnt.WithLabelValues("500")
cnt.WithLabelValues("503")
if err := reg.Register(cnt); err != nil {
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
cnt = are.ExistingCollector.(*prometheus.CounterVec)
} else {
panic(err)
@ -262,7 +265,8 @@ func InstrumentMetricHandler(reg prometheus.Registerer, handler http.Handler) ht
Help: "Current number of scrapes being served.",
})
if err := reg.Register(gge); err != nil {
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
gge = are.ExistingCollector.(prometheus.Gauge)
} else {
panic(err)

View File

@ -64,7 +64,7 @@ func InstrumentHandlerInFlight(g prometheus.Gauge, next http.Handler) http.Handl
// names are "code" and "method". The function panics otherwise. For the "method"
// label a predefined default label value set is used to filter given values.
// Values besides predefined values will count as `unknown` method.
//`WithExtraMethods` can be used to add more methods to the set. The Observe
// `WithExtraMethods` can be used to add more methods to the set. The Observe
// method of the Observer in the ObserverVec is called with the request duration
// in seconds. Partitioning happens by HTTP status code and/or HTTP method if
// the respective instance label names are present in the ObserverVec. For

View File

@ -146,7 +146,6 @@ func TestLabelCheck(t *testing.T) {
},
append(sc.varLabels, sc.curriedLabels...),
))
//nolint:typecheck // Ignore declared but unused error.
for _, l := range sc.curriedLabels {
c = c.MustCurryWith(prometheus.Labels{l: "dummy"})
o = o.MustCurryWith(prometheus.Labels{l: "dummy"})

View File

@ -15,6 +15,7 @@ package push
import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
@ -200,8 +201,8 @@ func TestPush(t *testing.T) {
Push(); err == nil {
t.Error("push with empty job succeeded")
} else {
if got, want := err, errJobEmpty; got != want {
t.Errorf("got error %q, want %q", got, want)
if want := errJobEmpty; !errors.Is(err, want) {
t.Errorf("got error %q, want %q", err, want)
}
}

View File

@ -15,6 +15,7 @@ package prometheus
import (
"bytes"
"errors"
"fmt"
"os"
"path/filepath"
@ -288,7 +289,7 @@ func (r *Registry) Register(c Collector) error {
// Is the descriptor valid at all?
if desc.err != nil {
return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
return fmt.Errorf("descriptor %s is invalid: %w", desc, desc.err)
}
// Is the descID unique?
@ -602,7 +603,7 @@ func processMetric(
}
dtoMetric := &dto.Metric{}
if err := metric.Write(dtoMetric); err != nil {
return fmt.Errorf("error collecting metric %v: %s", desc, err)
return fmt.Errorf("error collecting metric %v: %w", desc, err)
}
metricFamily, ok := metricFamiliesByName[desc.fqName]
if ok { // Existing name.
@ -724,12 +725,13 @@ func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) {
for i, g := range gs {
mfs, err := g.Gather()
if err != nil {
if multiErr, ok := err.(MultiError); ok {
multiErr := MultiError{}
if errors.As(err, &multiErr) {
for _, err := range multiErr {
errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err))
}
} else {
errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
errs = append(errs, fmt.Errorf("[from Gatherer #%d] %w", i+1, err))
}
}
for _, mf := range mfs {

View File

@ -120,8 +120,8 @@ metric: <
>
`)
externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric:<label:<name:"externalconstname" value:"externalconstvalue" > label:<name:"externallabelname" value:"externalval1" > counter:<value:1 > >
`)
externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric:<label:<name:"externalconstname" value:"externalconstvalue" > label:<name:"externallabelname" value:"externalval1" > counter:<value:1 > >`)
externalMetricFamilyAsProtoCompactText = append(externalMetricFamilyAsProtoCompactText, []byte(" \n")...)
expectedMetricFamily := &dto.MetricFamily{
Name: proto.String("name"),
@ -202,8 +202,8 @@ metric: <
>
`)
expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >
`)
expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >`)
expectedMetricFamilyAsProtoCompactText = append(expectedMetricFamilyAsProtoCompactText, []byte(" \n")...)
externalMetricFamilyWithSameName := &dto.MetricFamily{
Name: proto.String("name"),
@ -228,8 +228,8 @@ metric: <
},
}
expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"different_val" > counter:<value:42 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >
`)
expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"different_val" > counter:<value:42 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val1" > counter:<value:1 > > metric:<label:<name:"constname" value:"constvalue" > label:<name:"labelname" value:"val2" > counter:<value:1 > >`)
expectedMetricFamilyMergedWithExternalAsProtoCompactText = append(expectedMetricFamilyMergedWithExternalAsProtoCompactText, []byte(" \n")...)
externalMetricFamilyWithInvalidLabelValue := &dto.MetricFamily{
Name: proto.String("name"),
@ -850,7 +850,8 @@ func TestAlreadyRegistered(t *testing.T) {
if err = s.reRegisterWith(reg).Register(s.newCollector); err == nil {
t.Fatal("expected error when registering new collector")
}
if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
are := &prometheus.AlreadyRegisteredError{}
if errors.As(err, are) {
if are.ExistingCollector != s.originalCollector {
t.Error("expected original collector but got something else")
}
@ -931,7 +932,7 @@ func TestHistogramVecRegisterGatherConcurrency(t *testing.T) {
return
default:
if err := reg.Register(hv); err != nil {
if _, ok := err.(prometheus.AlreadyRegisteredError); !ok {
if !errors.As(err, &prometheus.AlreadyRegisteredError{}) {
t.Error("Registering failed:", err)
}
}
@ -1162,15 +1163,15 @@ func TestAlreadyRegisteredCollision(t *testing.T) {
// Register should not fail, since each collector has a unique
// set of sub-collectors, determined by their names and const label values.
if err := reg.Register(&collector); err != nil {
alreadyRegErr, ok := err.(prometheus.AlreadyRegisteredError)
if !ok {
are := &prometheus.AlreadyRegisteredError{}
if !errors.As(err, are) {
t.Fatal(err)
}
previous := alreadyRegErr.ExistingCollector.(*collidingCollector)
current := alreadyRegErr.NewCollector.(*collidingCollector)
previous := are.ExistingCollector.(*collidingCollector)
current := are.NewCollector.(*collidingCollector)
t.Errorf("Unexpected registration error: %q\nprevious collector: %s (i=%d)\ncurrent collector %s (i=%d)", alreadyRegErr, previous.name, previous.i, current.name, current.i)
t.Errorf("Unexpected registration error: %q\nprevious collector: %s (i=%d)\ncurrent collector %s (i=%d)", are, previous.name, previous.i, current.name, current.i)
}
}
}
@ -1240,7 +1241,7 @@ func TestNewMultiTRegistry(t *testing.T) {
t.Run("two registries, one with error", func(t *testing.T) {
m := prometheus.NewMultiTRegistry(prometheus.ToTransactionalGatherer(reg), treg)
ret, done, err := m.Gather()
if err != treg.err {
if !errors.Is(err, treg.err) {
t.Error("unexpected error:", err)
}
done()

View File

@ -26,7 +26,7 @@ import (
func CollectAndLint(c prometheus.Collector, metricNames ...string) ([]promlint.Problem, error) {
reg := prometheus.NewPedanticRegistry()
if err := reg.Register(c); err != nil {
return nil, fmt.Errorf("registering collector failed: %s", err)
return nil, fmt.Errorf("registering collector failed: %w", err)
}
return GatherAndLint(reg, metricNames...)
}
@ -37,7 +37,7 @@ func CollectAndLint(c prometheus.Collector, metricNames ...string) ([]promlint.P
func GatherAndLint(g prometheus.Gatherer, metricNames ...string) ([]promlint.Problem, error) {
got, err := g.Gather()
if err != nil {
return nil, fmt.Errorf("gathering metrics failed: %s", err)
return nil, fmt.Errorf("gathering metrics failed: %w", err)
}
if metricNames != nil {
got = filterMetrics(got, metricNames)

View File

@ -15,6 +15,7 @@
package promlint
import (
"errors"
"fmt"
"io"
"regexp"
@ -83,7 +84,7 @@ func (l *Linter) Lint() ([]Problem, error) {
mf := &dto.MetricFamily{}
for {
if err := d.Decode(mf); err != nil {
if err == io.EOF {
if errors.Is(err, io.EOF) {
break
}

View File

@ -126,7 +126,7 @@ func ToFloat64(c prometheus.Collector) float64 {
func CollectAndCount(c prometheus.Collector, metricNames ...string) int {
reg := prometheus.NewPedanticRegistry()
if err := reg.Register(c); err != nil {
panic(fmt.Errorf("registering collector failed: %s", err))
panic(fmt.Errorf("registering collector failed: %w", err))
}
result, err := GatherAndCount(reg, metricNames...)
if err != nil {
@ -142,7 +142,7 @@ func CollectAndCount(c prometheus.Collector, metricNames ...string) int {
func GatherAndCount(g prometheus.Gatherer, metricNames ...string) (int, error) {
got, err := g.Gather()
if err != nil {
return 0, fmt.Errorf("gathering metrics failed: %s", err)
return 0, fmt.Errorf("gathering metrics failed: %w", err)
}
if metricNames != nil {
got = filterMetrics(got, metricNames)
@ -161,7 +161,7 @@ func GatherAndCount(g prometheus.Gatherer, metricNames ...string) (int, error) {
func CollectAndCompare(c prometheus.Collector, expected io.Reader, metricNames ...string) error {
reg := prometheus.NewPedanticRegistry()
if err := reg.Register(c); err != nil {
return fmt.Errorf("registering collector failed: %s", err)
return fmt.Errorf("registering collector failed: %w", err)
}
return GatherAndCompare(reg, expected, metricNames...)
}
@ -182,7 +182,7 @@ func TransactionalGatherAndCompare(g prometheus.TransactionalGatherer, expected
got, done, err := g.Gather()
defer done()
if err != nil {
return fmt.Errorf("gathering metrics failed: %s", err)
return fmt.Errorf("gathering metrics failed: %w", err)
}
if metricNames != nil {
got = filterMetrics(got, metricNames)
@ -190,7 +190,7 @@ func TransactionalGatherAndCompare(g prometheus.TransactionalGatherer, expected
var tp expfmt.TextParser
wantRaw, err := tp.TextToMetricFamilies(expected)
if err != nil {
return fmt.Errorf("parsing expected metrics failed: %s", err)
return fmt.Errorf("parsing expected metrics failed: %w", err)
}
want := internal.NormalizeMetricFamilies(wantRaw)
@ -206,13 +206,13 @@ func compare(got, want []*dto.MetricFamily) error {
enc := expfmt.NewEncoder(&gotBuf, expfmt.FmtText)
for _, mf := range got {
if err := enc.Encode(mf); err != nil {
return fmt.Errorf("encoding gathered metrics failed: %s", err)
return fmt.Errorf("encoding gathered metrics failed: %w", err)
}
}
enc = expfmt.NewEncoder(&wantBuf, expfmt.FmtText)
for _, mf := range want {
if err := enc.Encode(mf); err != nil {
return fmt.Errorf("encoding expected metrics failed: %s", err)
return fmt.Errorf("encoding expected metrics failed: %w", err)
}
}
if diffErr := diff(wantBuf, gotBuf); diffErr != "" {