diff --git a/.golangci.yml b/.golangci.yml index bedb09e6a..7e1953030 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -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 diff --git a/api/client.go b/api/client.go index c91cf0c16..72a01309c 100644 --- a/api/client.go +++ b/api/client.go @@ -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 diff --git a/api/prometheus/v1/api.go b/api/prometheus/v1/api.go index bc89cb4ae..5f0ecef29 100644 --- a/api/prometheus/v1/api.go +++ b/api/prometheus/v1/api.go @@ -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) { diff --git a/api/prometheus/v1/api_test.go b/api/prometheus/v1/api_test.go index 717a0f92d..c933e0cfd 100644 --- a/api/prometheus/v1/api_test.go +++ b/api/prometheus/v1/api_test.go @@ -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,11 +278,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("server_error: server error: 500"), + err: errors.New("server_error: server error: 500"), }, { do: doQuery("2", testTime), @@ -326,11 +292,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"), + 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"}, + err: errors.New("client_error: client error: 404"), }, { @@ -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,11 +348,7 @@ 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"}, + res: []string{"val1", "val2"}, }, { do: doLabelNames(nil, testTime.Add(-100*time.Hour), testTime), @@ -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"}, + res: []string{"val1", "val2"}, }, { @@ -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,24 +372,14 @@ 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"}, + res: []string{"val1", "val2"}, }, { @@ -465,11 +387,7 @@ 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"}, + res: model.LabelValues{"val1", "val2"}, }, { do: doLabelValues(nil, "mylabel", testTime.Add(-100*time.Hour), testTime), @@ -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"}, + res: model.LabelValues{"val1", "val2"}, }, { @@ -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,24 +411,14 @@ 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"}, + 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,9 +1455,13 @@ func TestAPIClientDo(t *testing.T) { } if test.expectedErr.Detail != "" { - apiErr := err.(*Error) - if apiErr.Detail != test.expectedErr.Detail { - t.Fatalf("expected error detail :%v, but got:%v", apiErr.Detail, test.expectedErr.Detail) + 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) } } diff --git a/prometheus/examples_test.go b/prometheus/examples_test.go index a7a8d0c14..a86826281 100644 --- a/prometheus/examples_test.go +++ b/prometheus/examples_test.go @@ -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) diff --git a/prometheus/internal/difflib.go b/prometheus/internal/difflib.go index 12b2d70b4..fd45cadc0 100644 --- a/prometheus/internal/difflib.go +++ b/prometheus/internal/difflib.go @@ -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]++ } } diff --git a/prometheus/internal/difflib_test.go b/prometheus/internal/difflib_test.go index 820bbc6b7..e99c7cbfc 100644 --- a/prometheus/internal/difflib_test.go +++ b/prometheus/internal/difflib_test.go @@ -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 diff --git a/prometheus/internal/go_runtime_metrics.go b/prometheus/internal/go_runtime_metrics.go index 6cbe063a2..97d17d6cb 100644 --- a/prometheus/internal/go_runtime_metrics.go +++ b/prometheus/internal/go_runtime_metrics.go @@ -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)) diff --git a/prometheus/labels.go b/prometheus/labels.go index 2744443ac..6eee198fe 100644 --- a/prometheus/labels.go +++ b/prometheus/labels.go @@ -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, ) diff --git a/prometheus/process_collector.go b/prometheus/process_collector.go index 1245428a7..930272579 100644 --- a/prometheus/process_collector.go +++ b/prometheus/process_collector.go @@ -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 diff --git a/prometheus/promhttp/http.go b/prometheus/promhttp/http.go index a6e4f850c..a4cc9810b 100644 --- a/prometheus/promhttp/http.go +++ b/prometheus/promhttp/http.go @@ -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) diff --git a/prometheus/promhttp/instrument_server.go b/prometheus/promhttp/instrument_server.go index b35d0939a..bfe500987 100644 --- a/prometheus/promhttp/instrument_server.go +++ b/prometheus/promhttp/instrument_server.go @@ -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 diff --git a/prometheus/promhttp/instrument_server_test.go b/prometheus/promhttp/instrument_server_test.go index 421534875..2a2cbf251 100644 --- a/prometheus/promhttp/instrument_server_test.go +++ b/prometheus/promhttp/instrument_server_test.go @@ -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"}) diff --git a/prometheus/push/push_test.go b/prometheus/push/push_test.go index a0e8e9a28..cc061cf64 100644 --- a/prometheus/push/push_test.go +++ b/prometheus/push/push_test.go @@ -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) } } diff --git a/prometheus/registry.go b/prometheus/registry.go index 36fd64ec5..325f665ff 100644 --- a/prometheus/registry.go +++ b/prometheus/registry.go @@ -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 { diff --git a/prometheus/registry_test.go b/prometheus/registry_test.go index 9443ef3d0..f0871ba87 100644 --- a/prometheus/registry_test.go +++ b/prometheus/registry_test.go @@ -120,8 +120,8 @@ metric: < > `) - externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > -`) + externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: >`) + 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: counter: > metric: label: counter: > -`) + expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: >`) + 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: counter: > metric: label: counter: > metric: label: counter: > -`) + expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: >`) + 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() diff --git a/prometheus/testutil/lint.go b/prometheus/testutil/lint.go index 7681877a8..8d2f05500 100644 --- a/prometheus/testutil/lint.go +++ b/prometheus/testutil/lint.go @@ -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) diff --git a/prometheus/testutil/promlint/promlint.go b/prometheus/testutil/promlint/promlint.go index d534f553e..a20f159b7 100644 --- a/prometheus/testutil/promlint/promlint.go +++ b/prometheus/testutil/promlint/promlint.go @@ -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 } diff --git a/prometheus/testutil/testutil.go b/prometheus/testutil/testutil.go index 67d162cbe..cdf1802ca 100644 --- a/prometheus/testutil/testutil.go +++ b/prometheus/testutil/testutil.go @@ -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 != "" {