From 0906f2eafa3506d411f2053ecba160a6c5ca0387 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Wed, 8 Jun 2022 10:47:52 +0200 Subject: [PATCH] refactor (promql): move from github.com/pkg/errors to 'errors' and 'fmt' (#10817) Signed-off-by: Matthieu MOREL Co-authored-by: Matthieu MOREL --- promql/engine.go | 42 ++++++++++++++++++------------------- promql/functions.go | 14 ++++++------- promql/fuzz.go | 3 ++- promql/parser/ast.go | 5 ++--- promql/parser/parse.go | 6 +++--- promql/parser/parse_test.go | 5 +++-- promql/test.go | 37 +++++++++++++++++--------------- promql/value.go | 3 +-- 8 files changed, 59 insertions(+), 56 deletions(-) diff --git a/promql/engine.go b/promql/engine.go index 7711223d6a..3cb1c95683 100644 --- a/promql/engine.go +++ b/promql/engine.go @@ -17,6 +17,7 @@ import ( "bytes" "container/heap" "context" + "errors" "fmt" "math" "reflect" @@ -29,7 +30,6 @@ import ( "github.com/go-kit/log" "github.com/go-kit/log/level" "github.com/grafana/regexp" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/common/model" "go.opentelemetry.io/otel" @@ -208,10 +208,10 @@ func contextDone(ctx context.Context, env string) error { } func contextErr(err error, env string) error { - switch err { - case context.Canceled: + switch { + case errors.Is(err, context.Canceled): return ErrQueryCanceled(env) - case context.DeadlineExceeded: + case errors.Is(err, context.DeadlineExceeded): return ErrQueryTimeout(env) default: return err @@ -416,7 +416,7 @@ func (ng *Engine) NewRangeQuery(q storage.Queryable, opts *QueryOpts, qs string, return nil, err } if expr.Type() != parser.ValueTypeVector && expr.Type() != parser.ValueTypeScalar { - return nil, errors.Errorf("invalid expression type %q for range query, must be Scalar or instant Vector", parser.DocumentedType(expr.Type())) + return nil, fmt.Errorf("invalid expression type %q for range query, must be Scalar or instant Vector", parser.DocumentedType(expr.Type())) } qry, err := ng.newQuery(q, opts, expr, start, end, interval) if err != nil { @@ -597,7 +597,7 @@ func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, ws storag return nil, nil, s(ctx) } - panic(errors.Errorf("promql.Engine.exec: unhandled statement of type %T", q.Statement())) + panic(fmt.Errorf("promql.Engine.exec: unhandled statement of type %T", q.Statement())) } func timeMilliseconds(t time.Time) int64 { @@ -657,7 +657,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.Eval case String: return result, warnings, nil default: - panic(errors.Errorf("promql.Engine.exec: invalid expression type %q", val.Type())) + panic(fmt.Errorf("promql.Engine.exec: invalid expression type %q", val.Type())) } query.matrix = mat @@ -676,7 +676,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.Eval case parser.ValueTypeMatrix: return mat, warnings, nil default: - panic(errors.Errorf("promql.Engine.exec: unexpected expression type %q", s.Expr.Type())) + panic(fmt.Errorf("promql.Engine.exec: unexpected expression type %q", s.Expr.Type())) } } @@ -701,7 +701,7 @@ func (ng *Engine) execEvalStmt(ctx context.Context, query *query, s *parser.Eval mat, ok := val.(Matrix) if !ok { - panic(errors.Errorf("promql.Engine.exec: invalid expression type %q", val.Type())) + panic(fmt.Errorf("promql.Engine.exec: invalid expression type %q", val.Type())) } query.matrix = mat @@ -928,7 +928,7 @@ type evaluator struct { // errorf causes a panic with the input formatted into an error. func (ev *evaluator) errorf(format string, args ...interface{}) { - ev.error(errors.Errorf(format, args...)) + ev.error(fmt.Errorf(format, args...)) } // error causes a panic with the given error. @@ -950,7 +950,7 @@ func (ev *evaluator) recover(ws *storage.Warnings, errp *error) { buf = buf[:runtime.Stack(buf, false)] level.Error(ev.logger).Log("msg", "runtime panic in parser", "err", e, "stacktrace", string(buf)) - *errp = errors.Wrap(err, "unexpected error") + *errp = fmt.Errorf("unexpected error: %w", err) case errWithWarnings: *errp = err.err *ws = append(*ws, err.warnings...) @@ -1344,7 +1344,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { ws, err := checkAndExpandSeriesSet(ev.ctx, sel) warnings = append(warnings, ws...) if err != nil { - ev.error(errWithWarnings{errors.Wrap(err, "expanding series"), warnings}) + ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), warnings}) } mat := make(Matrix, 0, len(selVS.Series)) // Output matrix. offset := durationMilliseconds(selVS.Offset) @@ -1541,7 +1541,7 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { case *parser.VectorSelector: ws, err := checkAndExpandSeriesSet(ev.ctx, e) if err != nil { - ev.error(errWithWarnings{errors.Wrap(err, "expanding series"), ws}) + ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), ws}) } mat := make(Matrix, 0, len(e.Series)) it := storage.NewMemoizedEmptyIterator(durationMilliseconds(ev.lookbackDelta)) @@ -1657,11 +1657,11 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { // with changed timestamps. mat, ok := res.(Matrix) if !ok { - panic(errors.Errorf("unexpected result in StepInvariantExpr evaluation: %T", expr)) + panic(fmt.Errorf("unexpected result in StepInvariantExpr evaluation: %T", expr)) } for i := range mat { if len(mat[i].Points) != 1 { - panic(errors.Errorf("unexpected number of samples")) + panic(fmt.Errorf("unexpected number of samples")) } for ts := ev.startTimestamp + ev.interval; ts <= ev.endTimestamp; ts = ts + ev.interval { mat[i].Points = append(mat[i].Points, Point{ @@ -1678,14 +1678,14 @@ func (ev *evaluator) eval(expr parser.Expr) (parser.Value, storage.Warnings) { return res, ws } - panic(errors.Errorf("unhandled expression of type: %T", expr)) + panic(fmt.Errorf("unhandled expression of type: %T", expr)) } // vectorSelector evaluates a *parser.VectorSelector expression. func (ev *evaluator) vectorSelector(node *parser.VectorSelector, ts int64) (Vector, storage.Warnings) { ws, err := checkAndExpandSeriesSet(ev.ctx, node) if err != nil { - ev.error(errWithWarnings{errors.Wrap(err, "expanding series"), ws}) + ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), ws}) } vec := make(Vector, 0, len(node.Series)) it := storage.NewMemoizedEmptyIterator(durationMilliseconds(ev.lookbackDelta)) @@ -1769,7 +1769,7 @@ func (ev *evaluator) matrixSelector(node *parser.MatrixSelector) (Matrix, storag ) ws, err := checkAndExpandSeriesSet(ev.ctx, node) if err != nil { - ev.error(errWithWarnings{errors.Wrap(err, "expanding series"), ws}) + ev.error(errWithWarnings{fmt.Errorf("expanding series: %w", err), ws}) } series := vs.Series @@ -2181,7 +2181,7 @@ func scalarBinop(op parser.ItemType, lhs, rhs float64) float64 { case parser.ATAN2: return math.Atan2(lhs, rhs) } - panic(errors.Errorf("operator %q not allowed for Scalar operations", op)) + panic(fmt.Errorf("operator %q not allowed for Scalar operations", op)) } // vectorElemBinop evaluates a binary operation between two Vector elements. @@ -2214,7 +2214,7 @@ func vectorElemBinop(op parser.ItemType, lhs, rhs float64) (float64, bool) { case parser.ATAN2: return math.Atan2(lhs, rhs), true } - panic(errors.Errorf("operator %q not allowed for operations between Vectors", op)) + panic(fmt.Errorf("operator %q not allowed for operations between Vectors", op)) } type groupedAggregation struct { @@ -2423,7 +2423,7 @@ func (ev *evaluator) aggregation(op parser.ItemType, grouping []string, without group.heap = append(group.heap, s) default: - panic(errors.Errorf("expected aggregation operator but got %q", op)) + panic(fmt.Errorf("expected aggregation operator but got %q", op)) } } diff --git a/promql/functions.go b/promql/functions.go index 18c8e63a35..d133fef051 100644 --- a/promql/functions.go +++ b/promql/functions.go @@ -14,6 +14,7 @@ package promql import ( + "fmt" "math" "sort" "strconv" @@ -21,7 +22,6 @@ import ( "time" "github.com/grafana/regexp" - "github.com/pkg/errors" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" @@ -223,10 +223,10 @@ func funcHoltWinters(vals []parser.Value, args parser.Expressions, enh *EvalNode // Sanity check the input. if sf <= 0 || sf >= 1 { - panic(errors.Errorf("invalid smoothing factor. Expected: 0 < sf < 1, got: %f", sf)) + panic(fmt.Errorf("invalid smoothing factor. Expected: 0 < sf < 1, got: %f", sf)) } if tf <= 0 || tf >= 1 { - panic(errors.Errorf("invalid trend factor. Expected: 0 < tf < 1, got: %f", tf)) + panic(fmt.Errorf("invalid trend factor. Expected: 0 < tf < 1, got: %f", tf)) } l := len(samples.Points) @@ -885,10 +885,10 @@ func funcLabelReplace(vals []parser.Value, args parser.Expressions, enh *EvalNod var err error enh.regex, err = regexp.Compile("^(?:" + regexStr + ")$") if err != nil { - panic(errors.Errorf("invalid regular expression in label_replace(): %s", regexStr)) + panic(fmt.Errorf("invalid regular expression in label_replace(): %s", regexStr)) } if !model.LabelNameRE.MatchString(dst) { - panic(errors.Errorf("invalid destination label name in label_replace(): %s", dst)) + panic(fmt.Errorf("invalid destination label name in label_replace(): %s", dst)) } enh.Dmn = make(map[uint64]labels.Labels, len(enh.Out)) } @@ -950,13 +950,13 @@ func funcLabelJoin(vals []parser.Value, args parser.Expressions, enh *EvalNodeHe for i := 3; i < len(args); i++ { src := stringFromArg(args[i]) if !model.LabelName(src).IsValid() { - panic(errors.Errorf("invalid source label name in label_join(): %s", src)) + panic(fmt.Errorf("invalid source label name in label_join(): %s", src)) } srcLabels[i-3] = src } if !model.LabelName(dst).IsValid() { - panic(errors.Errorf("invalid destination label name in label_join(): %s", dst)) + panic(fmt.Errorf("invalid destination label name in label_join(): %s", dst)) } srcVals := make([]string, len(srcLabels)) diff --git a/promql/fuzz.go b/promql/fuzz.go index 6b7c16e2d5..39933378e6 100644 --- a/promql/fuzz.go +++ b/promql/fuzz.go @@ -18,6 +18,7 @@ package promql import ( + "errors" "io" "github.com/prometheus/prometheus/model/textparse" @@ -71,7 +72,7 @@ func fuzzParseMetricWithContentType(in []byte, contentType string) int { break } } - if err == io.EOF { + if errors.Is(err, io.EOF) { err = nil } diff --git a/promql/parser/ast.go b/promql/parser/ast.go index fc144cbbc4..d5a2335abb 100644 --- a/promql/parser/ast.go +++ b/promql/parser/ast.go @@ -15,10 +15,9 @@ package parser import ( "context" + "fmt" "time" - "github.com/pkg/errors" - "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/storage" ) @@ -394,7 +393,7 @@ func Children(node Node) []Node { // nothing to do return []Node{} default: - panic(errors.Errorf("promql.Children: unhandled node type %T", node)) + panic(fmt.Errorf("promql.Children: unhandled node type %T", node)) } } diff --git a/promql/parser/parse.go b/promql/parser/parse.go index 5b60c5ed51..7a0e48464b 100644 --- a/promql/parser/parse.go +++ b/promql/parser/parse.go @@ -14,6 +14,7 @@ package parser import ( + "errors" "fmt" "math" "os" @@ -23,7 +24,6 @@ import ( "sync" "time" - "github.com/pkg/errors" "github.com/prometheus/common/model" "github.com/prometheus/prometheus/model/labels" @@ -224,7 +224,7 @@ func ParseSeriesDesc(input string) (labels labels.Labels, values []SequenceValue // addParseErrf formats the error and appends it to the list of parsing errors. func (p *parser) addParseErrf(positionRange PositionRange, format string, args ...interface{}) { - p.addParseErr(positionRange, errors.Errorf(format, args...)) + p.addParseErr(positionRange, fmt.Errorf(format, args...)) } // addParseErr appends the provided error to the list of parsing errors. @@ -801,7 +801,7 @@ func MustLabelMatcher(mt labels.MatchType, name, val string) *labels.Matcher { func MustGetFunction(name string) *Function { f, ok := getFunction(name) if !ok { - panic(errors.Errorf("function %q does not exist", name)) + panic(fmt.Errorf("function %q does not exist", name)) } return f } diff --git a/promql/parser/parse_test.go b/promql/parser/parse_test.go index 790064d373..548fb5aa92 100644 --- a/promql/parser/parse_test.go +++ b/promql/parser/parse_test.go @@ -14,13 +14,13 @@ package parser import ( + "errors" "fmt" "math" "strings" "testing" "time" - "github.com/pkg/errors" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" @@ -3570,7 +3570,8 @@ func TestParseExpressions(t *testing.T) { require.Error(t, err) require.Contains(t, err.Error(), test.errMsg, "unexpected error on input '%s', expected '%s', got '%s'", test.input, test.errMsg, err.Error()) - errorList, ok := err.(ParseErrors) + var errorList ParseErrors + ok := errors.As(err, &errorList) require.True(t, ok, "unexpected error type") diff --git a/promql/test.go b/promql/test.go index 28bdd05886..22144fe358 100644 --- a/promql/test.go +++ b/promql/test.go @@ -15,6 +15,7 @@ package promql import ( "context" + "errors" "fmt" "math" "os" @@ -23,7 +24,6 @@ import ( "time" "github.com/grafana/regexp" - "github.com/pkg/errors" "github.com/prometheus/common/model" "github.com/stretchr/testify/require" @@ -122,7 +122,7 @@ func (t *Test) ExemplarQueryable() storage.ExemplarQueryable { func raise(line int, format string, v ...interface{}) error { return &parser.ParseErr{ LineOffset: line, - Err: errors.Errorf(format, v...), + Err: fmt.Errorf(format, v...), } } @@ -146,7 +146,8 @@ func parseLoad(lines []string, i int) (int, *loadCmd, error) { } metric, vals, err := parser.ParseSeriesDesc(defLine) if err != nil { - if perr, ok := err.(*parser.ParseErr); ok { + var perr *parser.ParseErr + if errors.As(err, &perr) { perr.LineOffset = i } return i, nil, err @@ -168,7 +169,8 @@ func (t *Test) parseEval(lines []string, i int) (int, *evalCmd, error) { ) _, err := parser.ParseExpr(expr) if err != nil { - if perr, ok := err.(*parser.ParseErr); ok { + var perr *parser.ParseErr + if errors.As(err, &perr) { perr.LineOffset = i posOffset := parser.Pos(strings.Index(lines[i], expr)) perr.PositionRange.Start += posOffset @@ -205,7 +207,8 @@ func (t *Test) parseEval(lines []string, i int) (int, *evalCmd, error) { } metric, vals, err := parser.ParseSeriesDesc(defLine) if err != nil { - if perr, ok := err.(*parser.ParseErr); ok { + var perr *parser.ParseErr + if errors.As(err, &perr) { perr.LineOffset = i } return i, nil, err @@ -388,14 +391,14 @@ func (ev *evalCmd) compareResult(result parser.Value) error { for pos, v := range val { fp := v.Metric.Hash() if _, ok := ev.metrics[fp]; !ok { - return errors.Errorf("unexpected metric %s in result", v.Metric) + return fmt.Errorf("unexpected metric %s in result", v.Metric) } exp := ev.expected[fp] if ev.ordered && exp.pos != pos+1 { - return errors.Errorf("expected metric %s with %v at position %d but was at %d", v.Metric, exp.vals, exp.pos, pos+1) + return fmt.Errorf("expected metric %s with %v at position %d but was at %d", v.Metric, exp.vals, exp.pos, pos+1) } if !almostEqual(exp.vals[0].Value, v.V) { - return errors.Errorf("expected %v for %s but got %v", exp.vals[0].Value, v.Metric, v.V) + return fmt.Errorf("expected %v for %s but got %v", exp.vals[0].Value, v.Metric, v.V) } seen[fp] = true @@ -406,17 +409,17 @@ func (ev *evalCmd) compareResult(result parser.Value) error { for _, ss := range val { fmt.Println(" ", ss.Metric, ss.Point) } - return errors.Errorf("expected metric %s with %v not found", ev.metrics[fp], expVals) + return fmt.Errorf("expected metric %s with %v not found", ev.metrics[fp], expVals) } } case Scalar: if !almostEqual(ev.expected[0].vals[0].Value, val.V) { - return errors.Errorf("expected Scalar %v but got %v", val.V, ev.expected[0].vals[0].Value) + return fmt.Errorf("expected Scalar %v but got %v", val.V, ev.expected[0].vals[0].Value) } default: - panic(errors.Errorf("promql.Test.compareResult: unexpected result type %T", result)) + panic(fmt.Errorf("promql.Test.compareResult: unexpected result type %T", result)) } return nil } @@ -543,14 +546,14 @@ func (t *Test) exec(tc testCommand) error { if cmd.fail { continue } - return errors.Wrapf(res.Err, "error evaluating query %q (line %d)", iq.expr, cmd.line) + return fmt.Errorf("error evaluating query %q (line %d): %w", iq.expr, cmd.line, res.Err) } if res.Err == nil && cmd.fail { - return errors.Errorf("expected error evaluating query %q (line %d) but got none", iq.expr, cmd.line) + return fmt.Errorf("expected error evaluating query %q (line %d) but got none", iq.expr, cmd.line) } err = cmd.compareResult(res.Value) if err != nil { - return errors.Wrapf(err, "error in %s %s", cmd, iq.expr) + return fmt.Errorf("error in %s %s: %w", cmd, iq.expr, err) } // Check query returns same result in range mode, @@ -561,7 +564,7 @@ func (t *Test) exec(tc testCommand) error { } rangeRes := q.Exec(t.context) if rangeRes.Err != nil { - return errors.Wrapf(rangeRes.Err, "error evaluating query %q (line %d) in range mode", iq.expr, cmd.line) + return fmt.Errorf("error evaluating query %q (line %d) in range mode: %w", iq.expr, cmd.line, rangeRes.Err) } defer q.Close() if cmd.ordered { @@ -584,7 +587,7 @@ func (t *Test) exec(tc testCommand) error { err = cmd.compareResult(vec) } if err != nil { - return errors.Wrapf(err, "error in %s %s (line %d) range mode", cmd, iq.expr, cmd.line) + return fmt.Errorf("error in %s %s (line %d) range mode: %w", cmd, iq.expr, cmd.line, err) } } @@ -658,7 +661,7 @@ func parseNumber(s string) (float64, error) { f, err = strconv.ParseFloat(s, 64) } if err != nil { - return 0, errors.Wrap(err, "error parsing number") + return 0, fmt.Errorf("error parsing number: %w", err) } return f, nil } diff --git a/promql/value.go b/promql/value.go index 55cdc44d35..5b0bd8fa82 100644 --- a/promql/value.go +++ b/promql/value.go @@ -15,12 +15,11 @@ package promql import ( "encoding/json" + "errors" "fmt" "strconv" "strings" - "github.com/pkg/errors" - "github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/promql/parser" "github.com/prometheus/prometheus/storage"