diff --git a/.golangci.yml b/.golangci.yml index e4c5b52b3e0..4386eebb341 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -18,6 +18,8 @@ issues: text: "exitAfterDefer" - linters: [gocritic] text: "appendAssign" + - linters: [perfsprint] + text: "fmt.Sprintf can be replaced" exclude-dirs-use-default: false exclude-dirs: - mocks @@ -96,6 +98,9 @@ linters: # Reports ill-formed or insufficient nolint directives. - nolintlint + # Checks that fmt.Sprintf can be replaced with a faster alternative. + - perfsprint + # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. - revive @@ -153,6 +158,17 @@ linters-settings: - fieldalignment # Disable shadow - shadow + perfsprint: + # Optimizes even if it requires an int or uint type cast. + int-conversion: false + # Optimizes into `err.Error()` even if it is only equivalent for non-nil errors. + err-error: true + # Optimizes `fmt.Errorf`. + errorf: true + # Optimizes `fmt.Sprintf` with only one argument. + sprintf1: false + # Optimizes into strings concatenation. + strconcat: false revive: ignore-generated-header: true severity: error diff --git a/cmd/agent/app/agent_test.go b/cmd/agent/app/agent_test.go index e11e88e2769..0cd3cb08d48 100644 --- a/cmd/agent/app/agent_test.go +++ b/cmd/agent/app/agent_test.go @@ -44,9 +44,7 @@ func TestAgentSamplingEndpoint(t *testing.T) { } select { case err := <-errorch: - if err != nil { - t.Fatalf("error from agent: %s", err) - } + require.NoError(t, err, "error from agent") break wait_loop default: time.Sleep(time.Millisecond) @@ -155,9 +153,7 @@ func TestStartStopRace(t *testing.T) { // Before the bug was fixed this test was failing as expected when // run with -race flag. - if err := agent.Run(); err != nil { - t.Fatalf("error from agent.Run(): %s", err) - } + require.NoError(t, agent.Run()) t.Log("stopping agent") agent.Stop() @@ -192,9 +188,7 @@ func TestStartStopWithSocketBufferSet(t *testing.T) { agent, err := cfg.CreateAgent(fakeCollectorProxy{}, zap.NewNop(), metricsFactory) require.NoError(t, err) - if err := agent.Run(); err != nil { - t.Fatalf("error from agent.Run(): %s", err) - } + require.NoError(t, agent.Run()) t.Log("stopping agent") agent.Stop() diff --git a/cmd/anonymizer/app/uiconv/reader.go b/cmd/anonymizer/app/uiconv/reader.go index 749ea461a24..e9f2ae12686 100644 --- a/cmd/anonymizer/app/uiconv/reader.go +++ b/cmd/anonymizer/app/uiconv/reader.go @@ -6,6 +6,7 @@ package uiconv import ( "bufio" "encoding/json" + "errors" "fmt" "os" @@ -14,7 +15,7 @@ import ( uimodel "github.com/jaegertracing/jaeger/model/json" ) -var errNoMoreSpans = fmt.Errorf("no more spans") +var errNoMoreSpans = errors.New("no more spans") // spanReader loads previously captured spans from a file. type spanReader struct { @@ -53,7 +54,7 @@ func (r *spanReader) NextSpan() (*uimodel.Span, error) { } if b != '[' { r.eofReached = true - return nil, fmt.Errorf("file must begin with '['") + return nil, errors.New("file must begin with '['") } } s, err := r.reader.ReadString('\n') diff --git a/cmd/collector/app/handler/http_thrift_handler_test.go b/cmd/collector/app/handler/http_thrift_handler_test.go index 7048c4efbb4..08fa4d516dc 100644 --- a/cmd/collector/app/handler/http_thrift_handler_test.go +++ b/cmd/collector/app/handler/http_thrift_handler_test.go @@ -7,7 +7,7 @@ package handler import ( "bytes" "context" - "fmt" + "errors" "io" "net/http" "net/http/httptest" @@ -79,7 +79,7 @@ func TestThriftFormat(t *testing.T) { assert.EqualValues(t, http.StatusAccepted, statusCode) assert.EqualValues(t, "", resBodyStr) - handler.jaegerBatchesHandler.(*mockJaegerHandler).err = fmt.Errorf("Bad times ahead") + handler.jaegerBatchesHandler.(*mockJaegerHandler).err = errors.New("Bad times ahead") statusCode, resBodyStr, err = postBytes("application/vnd.apache.thrift.binary", server.URL+`/api/traces`, someBytes) require.NoError(t, err) assert.EqualValues(t, http.StatusInternalServerError, statusCode) @@ -161,7 +161,7 @@ func TestCannotReadBodyFromRequest(t *testing.T) { type errReader struct{} func (*errReader) Read([]byte) (int, error) { - return 0, fmt.Errorf("Simulated error reading body") + return 0, errors.New("Simulated error reading body") } type dummyResponseWriter struct { diff --git a/cmd/collector/app/span_processor_test.go b/cmd/collector/app/span_processor_test.go index fd76bfdc1a6..c57f73b4bd8 100644 --- a/cmd/collector/app/span_processor_test.go +++ b/cmd/collector/app/span_processor_test.go @@ -6,6 +6,7 @@ package app import ( "context" + "errors" "fmt" "io" "reflect" @@ -250,7 +251,7 @@ func TestSpanProcessor(t *testing.T) { func TestSpanProcessorErrors(t *testing.T) { logger, logBuf := testutils.NewLogger() w := &fakeSpanWriter{ - err: fmt.Errorf("some-error"), + err: errors.New("some-error"), } mb := metricstest.NewFactory(time.Hour) defer mb.Backend.Stop() diff --git a/cmd/es-index-cleaner/main.go b/cmd/es-index-cleaner/main.go index 9efbdee874a..a0ea71775c2 100644 --- a/cmd/es-index-cleaner/main.go +++ b/cmd/es-index-cleaner/main.go @@ -5,6 +5,7 @@ package main import ( "encoding/base64" + "errors" "fmt" "log" "net/http" @@ -33,7 +34,7 @@ func main() { Long: "Jaeger es-index-cleaner removes Jaeger indices", RunE: func(_ *cobra.Command, args []string) error { if len(args) != 2 { - return fmt.Errorf("wrong number of arguments") + return errors.New("wrong number of arguments") } numOfDays, err := strconv.Atoi(args[0]) if err != nil { diff --git a/cmd/es-rollover/app/init/action.go b/cmd/es-rollover/app/init/action.go index d44e28e850e..4651aba3ece 100644 --- a/cmd/es-rollover/app/init/action.go +++ b/cmd/es-rollover/app/init/action.go @@ -49,7 +49,7 @@ func (c Action) Do() error { } if c.Config.UseILM { if version < ilmVersionSupport { - return fmt.Errorf("ILM is supported only for ES version 7+") + return errors.New("ILM is supported only for ES version 7+") } policyExist, err := c.ILMClient.Exists(c.Config.ILMPolicyName) if err != nil { diff --git a/cmd/jaeger/internal/extension/jaegerquery/server_test.go b/cmd/jaeger/internal/extension/jaegerquery/server_test.go index e17875a707a..6fd95566e9f 100644 --- a/cmd/jaeger/internal/extension/jaegerquery/server_test.go +++ b/cmd/jaeger/internal/extension/jaegerquery/server_test.go @@ -5,6 +5,7 @@ package jaegerquery import ( "context" + "errors" "fmt" "net/http" "testing" @@ -42,28 +43,28 @@ type fakeFactory struct { func (ff fakeFactory) CreateDependencyReader() (dependencystore.Reader, error) { if ff.name == "need-dependency-reader-error" { - return nil, fmt.Errorf("test-error") + return nil, errors.New("test-error") } return &depsmocks.Reader{}, nil } func (ff fakeFactory) CreateSpanReader() (spanstore.Reader, error) { if ff.name == "need-span-reader-error" { - return nil, fmt.Errorf("test-error") + return nil, errors.New("test-error") } return &spanstoremocks.Reader{}, nil } func (ff fakeFactory) CreateSpanWriter() (spanstore.Writer, error) { if ff.name == "need-span-writer-error" { - return nil, fmt.Errorf("test-error") + return nil, errors.New("test-error") } return &spanstoremocks.Writer{}, nil } func (ff fakeFactory) Initialize(metrics.Factory, *zap.Logger) error { if ff.name == "need-initialize-error" { - return fmt.Errorf("test-error") + return errors.New("test-error") } return nil } @@ -75,14 +76,14 @@ type fakeMetricsFactory struct { // Initialize implements storage.MetricsFactory. func (fmf fakeMetricsFactory) Initialize(*zap.Logger) error { if fmf.name == "need-initialize-error" { - return fmt.Errorf("test-error") + return errors.New("test-error") } return nil } func (fmf fakeMetricsFactory) CreateMetricsReader() (metricsstore.Reader, error) { if fmf.name == "need-metrics-reader-error" { - return nil, fmt.Errorf("test-error") + return nil, errors.New("test-error") } return &metricsstoremocks.Reader{}, nil } diff --git a/cmd/jaeger/internal/extension/jaegerstorage/config.go b/cmd/jaeger/internal/extension/jaegerstorage/config.go index 0ae2a59895b..5f5189841df 100644 --- a/cmd/jaeger/internal/extension/jaegerstorage/config.go +++ b/cmd/jaeger/internal/extension/jaegerstorage/config.go @@ -4,6 +4,7 @@ package jaegerstorage import ( + "errors" "fmt" "reflect" "time" @@ -96,7 +97,7 @@ func (cfg *Backend) Unmarshal(conf *confmap.Conf) error { func (cfg *Config) Validate() error { if len(cfg.Backends) == 0 { - return fmt.Errorf("at least one storage is required") + return errors.New("at least one storage is required") } for name, b := range cfg.Backends { empty := Backend{} diff --git a/cmd/jaeger/internal/extension/jaegerstorage/extension_test.go b/cmd/jaeger/internal/extension/jaegerstorage/extension_test.go index deac35b2b02..8b49292a600 100644 --- a/cmd/jaeger/internal/extension/jaegerstorage/extension_test.go +++ b/cmd/jaeger/internal/extension/jaegerstorage/extension_test.go @@ -6,7 +6,7 @@ package jaegerstorage import ( "context" "encoding/json" - "fmt" + "errors" "net/http" "net/http/httptest" "testing" @@ -88,7 +88,7 @@ func TestStorageExtensionType(t *testing.T) { } func TestStorageFactoryBadShutdownError(t *testing.T) { - shutdownError := fmt.Errorf("shutdown error") + shutdownError := errors.New("shutdown error") ext := storageExt{ factories: map[string]storage.Factory{ "foo": errorFactory{closeErr: shutdownError}, diff --git a/cmd/jaeger/internal/integration/storagecleaner/extension_test.go b/cmd/jaeger/internal/integration/storagecleaner/extension_test.go index 5a2224535dd..d9783fd636c 100644 --- a/cmd/jaeger/internal/integration/storagecleaner/extension_test.go +++ b/cmd/jaeger/internal/integration/storagecleaner/extension_test.go @@ -5,6 +5,7 @@ package storagecleaner import ( "context" + "errors" "fmt" "net" "net/http" @@ -79,7 +80,7 @@ func TestStorageCleanerExtension(t *testing.T) { }, { name: "good storage with error", - factory: &PurgerFactory{err: fmt.Errorf("error")}, + factory: &PurgerFactory{err: errors.New("error")}, status: http.StatusInternalServerError, }, { diff --git a/cmd/query/app/apiv3/grpc_handler_test.go b/cmd/query/app/apiv3/grpc_handler_test.go index 808007fa8d8..bb3c08d9b59 100644 --- a/cmd/query/app/apiv3/grpc_handler_test.go +++ b/cmd/query/app/apiv3/grpc_handler_test.go @@ -5,7 +5,7 @@ package apiv3 import ( "context" - "fmt" + "errors" "net" "testing" @@ -105,7 +105,7 @@ func TestGetTrace(t *testing.T) { func TestGetTraceStorageError(t *testing.T) { tsc := newTestServerClient(t) tsc.reader.On("GetTrace", matchContext, matchTraceID).Return( - nil, fmt.Errorf("storage_error")).Once() + nil, errors.New("storage_error")).Once() getTraceStream, err := tsc.client.GetTrace(context.Background(), &api_v3.GetTraceRequest{ TraceId: "156", @@ -186,7 +186,7 @@ func TestFindTracesQueryNil(t *testing.T) { func TestFindTracesStorageError(t *testing.T) { tsc := newTestServerClient(t) tsc.reader.On("FindTraces", matchContext, mock.AnythingOfType("*spanstore.TraceQueryParameters")).Return( - nil, fmt.Errorf("storage_error"), nil).Once() + nil, errors.New("storage_error"), nil).Once() responseStream, err := tsc.client.FindTraces(context.Background(), &api_v3.FindTracesRequest{ Query: &api_v3.TraceQueryParameters{ @@ -215,7 +215,7 @@ func TestGetServices(t *testing.T) { func TestGetServicesStorageError(t *testing.T) { tsc := newTestServerClient(t) tsc.reader.On("GetServices", matchContext).Return( - nil, fmt.Errorf("storage_error")).Once() + nil, errors.New("storage_error")).Once() response, err := tsc.client.GetServices(context.Background(), &api_v3.GetServicesRequest{}) require.ErrorContains(t, err, "storage_error") @@ -243,7 +243,7 @@ func TestGetOperations(t *testing.T) { func TestGetOperationsStorageError(t *testing.T) { tsc := newTestServerClient(t) tsc.reader.On("GetOperations", matchContext, mock.AnythingOfType("spanstore.OperationQueryParameters")).Return( - nil, fmt.Errorf("storage_error")).Once() + nil, errors.New("storage_error")).Once() response, err := tsc.client.GetOperations(context.Background(), &api_v3.GetOperationsRequest{}) require.ErrorContains(t, err, "storage_error") diff --git a/cmd/query/app/flags.go b/cmd/query/app/flags.go index c3fd2e0cdab..df40f502ff2 100644 --- a/cmd/query/app/flags.go +++ b/cmd/query/app/flags.go @@ -161,7 +161,7 @@ func stringSliceAsHeader(slice []string) (http.Header, error) { header, err := tp.ReadMIMEHeader() if err != nil && !errors.Is(err, io.EOF) { - return nil, fmt.Errorf("failed to parse headers") + return nil, errors.New("failed to parse headers") } return http.Header(header), nil diff --git a/cmd/query/app/grpc_handler_test.go b/cmd/query/app/grpc_handler_test.go index b95acf2187c..18b18972808 100644 --- a/cmd/query/app/grpc_handler_test.go +++ b/cmd/query/app/grpc_handler_test.go @@ -7,7 +7,6 @@ package app import ( "context" "errors" - "fmt" "net" "testing" "time" @@ -418,7 +417,7 @@ func TestFindTracesMissingQuery_GRPC(t *testing.T) { func TestFindTracesFailure_GRPC(t *testing.T) { t.Parallel() withServerAndClient(t, func(server *grpcServer, client *grpcClient) { - mockErrorGRPC := fmt.Errorf("whatsamattayou") + mockErrorGRPC := errors.New("whatsamattayou") server.spanReader.On("FindTraces", mock.AnythingOfType("*context.valueCtx"), mock.AnythingOfType("*spanstore.TraceQueryParameters")). Return(nil, mockErrorGRPC).Once() diff --git a/cmd/query/app/http_handler_test.go b/cmd/query/app/http_handler_test.go index 753313f015d..9058a71aa4c 100644 --- a/cmd/query/app/http_handler_test.go +++ b/cmd/query/app/http_handler_test.go @@ -217,7 +217,7 @@ func TestLogOnServerError(t *testing.T) { type httpResponseErrWriter struct{} func (*httpResponseErrWriter) Write([]byte) (int, error) { - return 0, fmt.Errorf("failed to write") + return 0, errors.New("failed to write") } func (*httpResponseErrWriter) WriteHeader(int /* statusCode */) {} func (*httpResponseErrWriter) Header() http.Header { @@ -485,7 +485,7 @@ func TestSearchDBFailure(t *testing.T) { t.Parallel() ts := initializeTestServer(t) ts.spanReader.On("FindTraces", mock.AnythingOfType("*context.valueCtx"), mock.AnythingOfType("*spanstore.TraceQueryParameters")). - Return(nil, fmt.Errorf("whatsamattayou")).Once() + Return(nil, errors.New("whatsamattayou")).Once() var response structuredResponse err := getJSON(ts.server.URL+`/api/traces?service=service&start=0&end=0&operation=operation&limit=200&minDuration=20ms`, &response) diff --git a/cmd/query/app/static_handler_test.go b/cmd/query/app/static_handler_test.go index f7f4b73a72e..fa644ebad9b 100644 --- a/cmd/query/app/static_handler_test.go +++ b/cmd/query/app/static_handler_test.go @@ -6,6 +6,7 @@ package app import ( "encoding/json" + "errors" "fmt" "io" "net/http" @@ -309,7 +310,7 @@ type fakeFile struct { } func (*fakeFile) Read([]byte) (n int, err error) { - return 0, fmt.Errorf("read error") + return 0, errors.New("read error") } func TestLoadIndexHTMLReadError(t *testing.T) { diff --git a/crossdock/services/tracehandler.go b/crossdock/services/tracehandler.go index e2eb54c60bb..a1f29686722 100644 --- a/crossdock/services/tracehandler.go +++ b/crossdock/services/tracehandler.go @@ -174,7 +174,7 @@ func validateAdaptiveSamplingTraces(expected *traceRequest, actual []*ui.Trace) return fmt.Errorf("%s tag value should be '%s'", samplerTypeKey, jaeger.SamplerTypeProbabilistic) } if isDefaultProbability(probability) { - return fmt.Errorf("adaptive sampling probability not used") + return errors.New("adaptive sampling probability not used") } } return nil @@ -201,7 +201,7 @@ func (h *TraceHandler) createAndRetrieveTraces(service string, request *traceReq } traces := h.getTraces(service, request.Operation, request.Tags) if len(traces) == 0 { - return nil, fmt.Errorf("could not retrieve traces from query service") + return nil, errors.New("could not retrieve traces from query service") } return traces, nil } @@ -261,7 +261,7 @@ func validateTraces(expected *traceRequest, actual []*ui.Trace) error { } tags := convertTagsIntoMap(trace.Spans[0].Tags) if !expectedTagsExist(expected.Tags, tags) { - return fmt.Errorf("expected tags not found") + return errors.New("expected tags not found") } } return nil diff --git a/internal/metrics/prometheus/factory_test.go b/internal/metrics/prometheus/factory_test.go index 6acede6b73f..e4531d12a3e 100644 --- a/internal/metrics/prometheus/factory_test.go +++ b/internal/metrics/prometheus/factory_test.go @@ -401,9 +401,7 @@ func findMetric(t *testing.T, snapshot []*promModel.MetricFamily, name string, t continue } for _, m := range mf.GetMetric() { - if len(m.GetLabel()) != len(tags) { - t.Fatalf("Mismatching labels for metric %v: want %v, have %v", name, tags, m.GetLabel()) - } + require.Lenf(t, m.GetLabel(), len(tags), "Mismatching labels for metric %v: want %v, have %v", name, tags, m.GetLabel()) match := true for _, l := range m.GetLabel() { if v, ok := tags[l.GetName()]; !ok || v != l.GetValue() { diff --git a/internal/tracegen/config.go b/internal/tracegen/config.go index 0df7705ba35..560740184e2 100644 --- a/internal/tracegen/config.go +++ b/internal/tracegen/config.go @@ -4,8 +4,8 @@ package tracegen import ( + "errors" "flag" - "fmt" "sync" "sync/atomic" "time" @@ -54,7 +54,7 @@ func Run(c *Config, tracers []trace.Tracer, logger *zap.Logger) error { if c.Duration > 0 { c.Traces = 0 } else if c.Traces <= 0 { - return fmt.Errorf("either `traces` or `duration` must be greater than 0") + return errors.New("either `traces` or `duration` must be greater than 0") } wg := sync.WaitGroup{} diff --git a/model/ids.go b/model/ids.go index 76c51020048..27c7d3846b0 100644 --- a/model/ids.go +++ b/model/ids.go @@ -7,6 +7,7 @@ package model import ( "encoding/base64" "encoding/binary" + "errors" "fmt" "strconv" @@ -76,19 +77,19 @@ func TraceIDFromBytes(data []byte) (TraceID, error) { case len(data) == traceIDShortBytesLen: t.Low = binary.BigEndian.Uint64(data) default: - return TraceID{}, fmt.Errorf("invalid length for TraceID") + return TraceID{}, errors.New("invalid length for TraceID") } return t, nil } // MarshalText is called by encoding/json, which we do not want people to use. func (TraceID) MarshalText() ([]byte, error) { - return nil, fmt.Errorf("unsupported method TraceID.MarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") + return nil, errors.New("unsupported method TraceID.MarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") } // UnmarshalText is called by encoding/json, which we do not want people to use. func (*TraceID) UnmarshalText([]byte /* text */) error { - return fmt.Errorf("unsupported method TraceID.UnmarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") + return errors.New("unsupported method TraceID.UnmarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") } // Size returns the size of this datum in protobuf. It is always 16 bytes. @@ -113,7 +114,7 @@ func (t *TraceID) Unmarshal(data []byte) error { func marshalBytes(dst []byte, src []byte) (n int, err error) { if len(dst) < len(src) { - return 0, fmt.Errorf("buffer is too short") + return 0, errors.New("buffer is too short") } return copy(dst, src), nil } @@ -170,19 +171,19 @@ func SpanIDFromString(s string) (SpanID, error) { // SpanIDFromBytes creates a SpandID from list of bytes func SpanIDFromBytes(data []byte) (SpanID, error) { if len(data) != traceIDShortBytesLen { - return SpanID(0), fmt.Errorf("invalid length for SpanID") + return SpanID(0), errors.New("invalid length for SpanID") } return NewSpanID(binary.BigEndian.Uint64(data)), nil } // MarshalText is called by encoding/json, which we do not want people to use. func (SpanID) MarshalText() ([]byte, error) { - return nil, fmt.Errorf("unsupported method SpanID.MarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") + return nil, errors.New("unsupported method SpanID.MarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") } // UnmarshalText is called by encoding/json, which we do not want people to use. func (*SpanID) UnmarshalText([]byte /* text */) error { - return fmt.Errorf("unsupported method SpanID.UnmarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") + return errors.New("unsupported method SpanID.UnmarshalText; please use github.com/gogo/protobuf/jsonpb for marshalling") } // Size returns the size of this datum in protobuf. It is always 8 bytes. diff --git a/pkg/bearertoken/grpc.go b/pkg/bearertoken/grpc.go index 2be9c7c3860..dd01a95d213 100644 --- a/pkg/bearertoken/grpc.go +++ b/pkg/bearertoken/grpc.go @@ -5,7 +5,7 @@ package bearertoken import ( "context" - "fmt" + "errors" "google.golang.org/grpc" "google.golang.org/grpc/metadata" @@ -34,7 +34,7 @@ func ValidTokenFromGRPCMetadata(ctx context.Context, bearerHeader string) (strin return "", nil } if len(tokens) > 1 { - return "", fmt.Errorf("malformed token: multiple tokens found") + return "", errors.New("malformed token: multiple tokens found") } return tokens[0], nil } diff --git a/pkg/config/tlscfg/options.go b/pkg/config/tlscfg/options.go index 4251eaf076b..4604313e157 100644 --- a/pkg/config/tlscfg/options.go +++ b/pkg/config/tlscfg/options.go @@ -6,6 +6,7 @@ package tlscfg import ( "crypto/tls" "crypto/x509" + "errors" "fmt" "io" "os" @@ -64,7 +65,7 @@ func (o *Options) Config(logger *zap.Logger) (*tls.Config, error) { if o.MinVersion != "" && o.MaxVersion != "" { if minVersionId > maxVersionId { - return nil, fmt.Errorf("minimum tls version can't be greater than maximum tls version") + return nil, errors.New("minimum tls version can't be greater than maximum tls version") } } @@ -94,7 +95,7 @@ func (o *Options) Config(logger *zap.Logger) (*tls.Config, error) { o.certWatcher = certWatcher if (o.CertPath == "" && o.KeyPath != "") || (o.CertPath != "" && o.KeyPath == "") { - return nil, fmt.Errorf("for client auth via TLS, either both client certificate and key must be supplied, or neither") + return nil, errors.New("for client auth via TLS, either both client certificate and key must be supplied, or neither") } if o.CertPath != "" && o.KeyPath != "" { tlsCfg.GetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) { diff --git a/pkg/config/tlscfg/options_test.go b/pkg/config/tlscfg/options_test.go index e301879d764..4a1d5d46555 100644 --- a/pkg/config/tlscfg/options_test.go +++ b/pkg/config/tlscfg/options_test.go @@ -6,7 +6,7 @@ package tlscfg import ( "crypto/tls" "crypto/x509" - "fmt" + "errors" "path/filepath" "testing" "time" @@ -148,7 +148,7 @@ func TestOptionsToConfig(t *testing.T) { if test.fakeSysPool { saveSystemCertPool := systemCertPool systemCertPool = func() (*x509.CertPool, error) { - return nil, fmt.Errorf("fake system pool") + return nil, errors.New("fake system pool") } defer func() { systemCertPool = saveSystemCertPool diff --git a/pkg/es/config/config.go b/pkg/es/config/config.go index 872a1b5834a..f5104a4691b 100644 --- a/pkg/es/config/config.go +++ b/pkg/es/config/config.go @@ -464,7 +464,7 @@ func (c *Configuration) getConfigOptions(logger *zap.Logger) ([]elastic.ClientOp options = append(options, elastic.SetHttpClient(httpClient)) if c.Authentication.BasicAuthentication.Password != "" && c.Authentication.BasicAuthentication.PasswordFilePath != "" { - return nil, fmt.Errorf("both Password and PasswordFilePath are set") + return nil, errors.New("both Password and PasswordFilePath are set") } if c.Authentication.BasicAuthentication.PasswordFilePath != "" { passwordFromFile, err := loadTokenFromFile(c.Authentication.BasicAuthentication.PasswordFilePath) diff --git a/pkg/es/errors_test.go b/pkg/es/errors_test.go index e57ec1403b2..f6d8dfb436c 100644 --- a/pkg/es/errors_test.go +++ b/pkg/es/errors_test.go @@ -4,7 +4,7 @@ package es import ( - "fmt" + "errors" "testing" "github.com/olivere/elastic" @@ -12,7 +12,7 @@ import ( ) func TestDetailedError(t *testing.T) { - require.ErrorContains(t, fmt.Errorf("some err"), "some err", "no panic") + require.ErrorContains(t, errors.New("some err"), "some err", "no panic") esErr := &elastic.Error{ Status: 400, diff --git a/pkg/gogocodec/codec_test.go b/pkg/gogocodec/codec_test.go index 9349e74c62f..5b9d3c5741a 100644 --- a/pkg/gogocodec/codec_test.go +++ b/pkg/gogocodec/codec_test.go @@ -97,9 +97,7 @@ func BenchmarkCodecUnmarshal25Spans(b *testing.B) { for i := 0; i < b.N; i++ { var trace model.Trace err := c.Unmarshal(bytes, &trace) - if err != nil { - b.Fatal(err) - } + require.NoError(b, err) } } diff --git a/plugin/storage/es/factory.go b/plugin/storage/es/factory.go index a204ccd6bc4..2ce06af5fc9 100644 --- a/plugin/storage/es/factory.go +++ b/plugin/storage/es/factory.go @@ -218,7 +218,7 @@ func createSpanReader( tp trace.TracerProvider, ) (spanstore.Reader, error) { if cfg.UseILM && !cfg.UseReadWriteAliases { - return nil, fmt.Errorf("--es.use-ilm must always be used in conjunction with --es.use-aliases to ensure ES writers and readers refer to the single index mapping") + return nil, errors.New("--es.use-ilm must always be used in conjunction with --es.use-aliases to ensure ES writers and readers refer to the single index mapping") } return esSpanStore.NewSpanReader(esSpanStore.SpanReaderParams{ Client: clientFn, @@ -247,7 +247,7 @@ func createSpanWriter( var tags []string var err error if cfg.UseILM && !cfg.UseReadWriteAliases { - return nil, fmt.Errorf("--es.use-ilm must always be used in conjunction with --es.use-aliases to ensure ES writers and readers refer to the single index mapping") + return nil, errors.New("--es.use-ilm must always be used in conjunction with --es.use-aliases to ensure ES writers and readers refer to the single index mapping") } if tags, err = cfg.TagKeysAsFields(); err != nil { logger.Error("failed to get tag keys", zap.Error(err)) diff --git a/plugin/storage/es/samplingstore/storage.go b/plugin/storage/es/samplingstore/storage.go index 2450e80eb37..0fd2d0db0c2 100644 --- a/plugin/storage/es/samplingstore/storage.go +++ b/plugin/storage/es/samplingstore/storage.go @@ -6,6 +6,7 @@ package samplingstore import ( "context" "encoding/json" + "errors" "fmt" "time" @@ -165,7 +166,7 @@ func getLatestIndices(indexPrefix, indexDateLayout string, clientFn es.Client, r return []string{currentIndex}, nil } if currentIndex == earliestIndex { - return nil, fmt.Errorf("falied to find latest index") + return nil, errors.New("falied to find latest index") } now = now.Add(rollover) // rollover is negative } diff --git a/plugin/storage/es/spanstore/dbmodel/to_domain_test.go b/plugin/storage/es/spanstore/dbmodel/to_domain_test.go index 648bd41c185..f97beae72e1 100644 --- a/plugin/storage/es/spanstore/dbmodel/to_domain_test.go +++ b/plugin/storage/es/spanstore/dbmodel/to_domain_test.go @@ -7,6 +7,7 @@ package dbmodel import ( "bytes" "encoding/json" + "errors" "fmt" "math" "os" @@ -313,7 +314,7 @@ func TestTagsMap(t *testing.T) { {fieldTags: map[string]any{"float:float": float64(123)}, expected: []model.KeyValue{model.Float64("float.float", float64(123))}}, {fieldTags: map[string]any{"json_number:int": json.Number("123")}, expected: []model.KeyValue{model.Int64("json_number.int", 123)}}, {fieldTags: map[string]any{"json_number:float": json.Number("123.0")}, expected: []model.KeyValue{model.Float64("json_number.float", float64(123.0))}}, - {fieldTags: map[string]any{"json_number:err": json.Number("foo")}, err: fmt.Errorf("invalid tag type in foo: strconv.ParseFloat: parsing \"foo\": invalid syntax")}, + {fieldTags: map[string]any{"json_number:err": json.Number("foo")}, err: errors.New("invalid tag type in foo: strconv.ParseFloat: parsing \"foo\": invalid syntax")}, {fieldTags: map[string]any{"str": "foo"}, expected: []model.KeyValue{model.String("str", "foo")}}, {fieldTags: map[string]any{"str:str": "foo"}, expected: []model.KeyValue{model.String("str.str", "foo")}}, {fieldTags: map[string]any{"binary": []byte("foo")}, expected: []model.KeyValue{model.Binary("binary", []byte("foo"))}}, diff --git a/plugin/storage/factory_test.go b/plugin/storage/factory_test.go index 42e91a0a1b0..c09f8e7504c 100644 --- a/plugin/storage/factory_test.go +++ b/plugin/storage/factory_test.go @@ -8,7 +8,6 @@ import ( "errors" "expvar" "flag" - "fmt" "io" "reflect" "strings" @@ -73,7 +72,7 @@ func TestNewFactory(t *testing.T) { func TestClose(t *testing.T) { storageType := "foo" - err := fmt.Errorf("some error") + err := errors.New("some error") f := Factory{ factories: map[string]storage.Factory{ storageType: &errorFactory{closeErr: err}, diff --git a/plugin/storage/grpc/factory.go b/plugin/storage/grpc/factory.go index b5ceac8a3aa..07daea2e569 100644 --- a/plugin/storage/grpc/factory.go +++ b/plugin/storage/grpc/factory.go @@ -121,7 +121,7 @@ func (f *Factory) newRemoteStorage( ) (*ClientPluginServices, error) { c := f.config if c.Auth != nil { - return nil, fmt.Errorf("authenticator is not supported") + return nil, errors.New("authenticator is not supported") } unaryInterceptors := []grpc.UnaryClientInterceptor{ bearertoken.NewUnaryClientInterceptor(), diff --git a/plugin/storage/grpc/shared/grpc_handler_test.go b/plugin/storage/grpc/shared/grpc_handler_test.go index a6fd5079143..6fe228387c7 100644 --- a/plugin/storage/grpc/shared/grpc_handler_test.go +++ b/plugin/storage/grpc/shared/grpc_handler_test.go @@ -5,7 +5,7 @@ package shared import ( "context" - "fmt" + "errors" "io" "testing" "time" @@ -226,7 +226,7 @@ func TestGRPCServerWriteSpanStream(t *testing.T) { stream.On("SendAndClose", &storage_v1.WriteSpanResponse{}).Return(nil) stream.On("Context").Return(context.Background()) r.impl.streamWriter.On("WriteSpan", context.Background(), &mockTraceSpans[0]). - Return(fmt.Errorf("some error")).Once(). + Return(errors.New("some error")).Once(). On("WriteSpan", context.Background(), &mockTraceSpans[0]). Return(nil) @@ -315,7 +315,7 @@ func TestGRPCServerGetArchiveTrace_Error(t *testing.T) { traceSteam.On("Context").Return(context.Background()) r.impl.archiveReader.On("GetTrace", mock.Anything, mockTraceID). - Return(nil, fmt.Errorf("some error")) + Return(nil, errors.New("some error")) err := r.server.GetArchiveTrace(&storage_v1.GetTraceRequest{ TraceID: mockTraceID, @@ -330,7 +330,7 @@ func TestGRPCServerGetArchiveTrace_NoImpl(t *testing.T) { traceSteam := new(grpcMocks.SpanReaderPlugin_GetTraceServer) r.impl.archiveReader.On("GetTrace", mock.Anything, mockTraceID). - Return(nil, fmt.Errorf("some error")) + Return(nil, errors.New("some error")) err := r.server.GetArchiveTrace(&storage_v1.GetTraceRequest{ TraceID: mockTraceID, @@ -344,7 +344,7 @@ func TestGRPCServerGetArchiveTrace_StreamError(t *testing.T) { traceSteam := new(grpcMocks.SpanReaderPlugin_GetTraceServer) traceSteam.On("Context").Return(context.Background()) traceSteam.On("Send", &storage_v1.SpansResponseChunk{Spans: mockTraceSpans}). - Return(fmt.Errorf("some error")) + Return(errors.New("some error")) var traceSpans []*model.Span for i := range mockTraceSpans { @@ -387,7 +387,7 @@ func TestGRPCServerWriteArchiveSpan(t *testing.T) { func TestGRPCServerWriteArchiveSpan_Error(t *testing.T) { withGRPCServer(func(r *grpcServerTest) { r.impl.archiveWriter.On("WriteSpan", mock.Anything, &mockTraceSpans[0]). - Return(fmt.Errorf("some error")) + Return(errors.New("some error")) _, err := r.server.WriteArchiveSpan(context.Background(), &storage_v1.WriteSpanRequest{ Span: &mockTraceSpans[0], diff --git a/plugin/storage/grpc/shared/streaming_writer.go b/plugin/storage/grpc/shared/streaming_writer.go index 0b12db4a165..b186404afdd 100644 --- a/plugin/storage/grpc/shared/streaming_writer.go +++ b/plugin/storage/grpc/shared/streaming_writer.go @@ -67,7 +67,7 @@ func (s *streamingSpanWriter) getStream(ctx context.Context) (storage_v1.Streami if ok { return st, nil } - return nil, fmt.Errorf("plugin is closed") + return nil, errors.New("plugin is closed") default: return s.client.WriteSpanStream(ctx) } diff --git a/plugin/storage/integration/elasticsearch_test.go b/plugin/storage/integration/elasticsearch_test.go index 57b0d8a1ed8..5aae3614262 100644 --- a/plugin/storage/integration/elasticsearch_test.go +++ b/plugin/storage/integration/elasticsearch_test.go @@ -156,9 +156,7 @@ func healthCheck() error { func testElasticsearchStorage(t *testing.T, allTagsAsFields bool) { SkipUnlessEnv(t, "elasticsearch", "opensearch") - if err := healthCheck(); err != nil { - t.Fatal(err) - } + require.NoError(t, healthCheck()) s := &ESStorageIntegration{ StorageIntegration: StorageIntegration{ Fixtures: LoadAndParseQueryTestCases(t, "fixtures/queries_es.json"), @@ -182,9 +180,7 @@ func TestElasticsearchStorage_AllTagsAsObjectFields(t *testing.T) { func TestElasticsearchStorage_IndexTemplates(t *testing.T) { SkipUnlessEnv(t, "elasticsearch", "opensearch") - if err := healthCheck(); err != nil { - t.Fatal(err) - } + require.NoError(t, healthCheck()) s := &ESStorageIntegration{} s.initializeES(t, true) esVersion, err := s.getVersion()