diff --git a/.golangci.yml b/.golangci.yml index 6b15a36ad2b..e4c5b52b3e0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -181,9 +181,6 @@ linters-settings: # wtf: "you have exceeded the maximum number of public struct declarations" - name: max-public-structs disabled: true - # probably a good one to enable after cleanup - - name: import-shadowing - disabled: true # TBD - often triggered in tests - name: unhandled-error disabled: true diff --git a/cmd/agent/app/agent.go b/cmd/agent/app/agent.go index 67cebbc78bd..97f6408fa78 100644 --- a/cmd/agent/app/agent.go +++ b/cmd/agent/app/agent.go @@ -29,12 +29,12 @@ type Agent struct { // NewAgent creates the new Agent. func NewAgent( - processors []processors.Processor, + procs []processors.Processor, httpServer *http.Server, logger *zap.Logger, ) *Agent { a := &Agent{ - processors: processors, + processors: procs, httpServer: httpServer, logger: logger, } diff --git a/cmd/agent/app/builder.go b/cmd/agent/app/builder.go index cc1de33026d..efa1b9f8727 100644 --- a/cmd/agent/app/builder.go +++ b/cmd/agent/app/builder.go @@ -95,14 +95,14 @@ func (b *Builder) WithReporter(r ...reporter.Reporter) *Builder { // CreateAgent creates the Agent func (b *Builder) CreateAgent(primaryProxy CollectorProxy, logger *zap.Logger, mFactory metrics.Factory) (*Agent, error) { r := b.getReporter(primaryProxy) - processors, err := b.getProcessors(r, mFactory, logger) + procs, err := b.getProcessors(r, mFactory, logger) if err != nil { return nil, fmt.Errorf("cannot create processors: %w", err) } server := b.HTTPServer.getHTTPServer(primaryProxy.GetManager(), mFactory, logger) b.publishOpts() - return NewAgent(processors, server, logger), nil + return NewAgent(procs, server, logger), nil } func (b *Builder) getReporter(primaryProxy CollectorProxy) reporter.Reporter { @@ -140,11 +140,11 @@ func (b *Builder) getProcessors(rep reporter.Reporter, mFactory metrics.Factory, default: return nil, fmt.Errorf("cannot find agent processor for data model %v", cfg.Model) } - metrics := mFactory.Namespace(metrics.NSOptions{Name: "", Tags: map[string]string{ + metricsNamespace := mFactory.Namespace(metrics.NSOptions{Name: "", Tags: map[string]string{ "protocol": string(cfg.Protocol), "model": string(cfg.Model), }}) - processor, err := cfg.GetThriftProcessor(metrics, protoFactory, handler, logger) + processor, err := cfg.GetThriftProcessor(metricsNamespace, protoFactory, handler, logger) if err != nil { return nil, fmt.Errorf("cannot create Thrift Processor: %w", err) } diff --git a/cmd/agent/app/processors/thrift_processor_test.go b/cmd/agent/app/processors/thrift_processor_test.go index d056df8313b..3d50e507ded 100644 --- a/cmd/agent/app/processors/thrift_processor_test.go +++ b/cmd/agent/app/processors/thrift_processor_test.go @@ -75,8 +75,8 @@ func initCollectorAndReporter(t *testing.T) (*metricstest.Factory, *testutils.Gr require.NoError(t, err) rep := grpcrep.NewReporter(conn, map[string]string{}, zaptest.NewLogger(t)) metricsFactory := metricstest.NewFactory(0) - reporter := reporter.WrapWithMetrics(rep, metricsFactory) - return metricsFactory, grpcCollector, reporter, conn + metricsReporter := reporter.WrapWithMetrics(rep, metricsFactory) + return metricsFactory, grpcCollector, metricsReporter, conn } func TestNewThriftProcessor_ZeroCount(t *testing.T) { @@ -85,11 +85,11 @@ func TestNewThriftProcessor_ZeroCount(t *testing.T) { } func TestProcessorWithCompactZipkin(t *testing.T) { - metricsFactory, collector, reporter, conn := initCollectorAndReporter(t) + metricsFactory, collector, metricsReporter, conn := initCollectorAndReporter(t) defer conn.Close() defer collector.Close() - hostPort, processor := createProcessor(t, metricsFactory, compactFactory, agent.NewAgentProcessor(reporter)) + hostPort, processor := createProcessor(t, metricsFactory, compactFactory, agent.NewAgentProcessor(metricsReporter)) defer processor.Stop() client, clientCloser, err := testutils.NewZipkinThriftUDPClient(hostPort) diff --git a/cmd/agent/app/reporter/client_metrics.go b/cmd/agent/app/reporter/client_metrics.go index 7cd5b8ba349..7b237582a5f 100644 --- a/cmd/agent/app/reporter/client_metrics.go +++ b/cmd/agent/app/reporter/client_metrics.go @@ -175,12 +175,12 @@ func (r *ClientMetricsReporter) updateClientMetrics(batch *jaeger.Batch) { func (s *lastReceivedClientStats) update( batchSeqNo int64, stats *jaeger.ClientStats, - metrics *clientMetrics, + cMetrics *clientMetrics, ) { s.lock.Lock() defer s.lock.Unlock() - metrics.BatchesReceived.Inc(1) + cMetrics.BatchesReceived.Inc(1) if s.batchSeqNo >= batchSeqNo { // Ignore out of order batches. Once we receive a batch with a larger-than-seen number, @@ -191,11 +191,11 @@ func (s *lastReceivedClientStats) update( // do not update counters on the first batch, because it may cause a huge spike in totals // if the client has been running for a while already, but the agent just started. if s.batchSeqNo > 0 { - metrics.BatchesSent.Inc(batchSeqNo - s.batchSeqNo) + cMetrics.BatchesSent.Inc(batchSeqNo - s.batchSeqNo) if stats != nil { - metrics.FailedToEmitSpans.Inc(stats.FailedToEmitSpans - s.failedToEmitSpans) - metrics.TooLargeDroppedSpans.Inc(stats.TooLargeDroppedSpans - s.tooLargeDroppedSpans) - metrics.FullQueueDroppedSpans.Inc(stats.FullQueueDroppedSpans - s.fullQueueDroppedSpans) + cMetrics.FailedToEmitSpans.Inc(stats.FailedToEmitSpans - s.failedToEmitSpans) + cMetrics.TooLargeDroppedSpans.Inc(stats.TooLargeDroppedSpans - s.tooLargeDroppedSpans) + cMetrics.FullQueueDroppedSpans.Inc(stats.FullQueueDroppedSpans - s.fullQueueDroppedSpans) } } diff --git a/cmd/agent/app/reporter/flags.go b/cmd/agent/app/reporter/flags.go index 7890d8dfacd..7ba521b983b 100644 --- a/cmd/agent/app/reporter/flags.go +++ b/cmd/agent/app/reporter/flags.go @@ -33,10 +33,10 @@ type Options struct { } // AddFlags adds flags for Options. -func AddFlags(flags *flag.FlagSet) { - flags.String(reporterType, string(GRPC), fmt.Sprintf("Reporter type to use e.g. %s", string(GRPC))) +func AddFlags(flagSet *flag.FlagSet) { + flagSet.String(reporterType, string(GRPC), fmt.Sprintf("Reporter type to use e.g. %s", string(GRPC))) if !setupcontext.IsAllInOne() { - flags.String(agentTags, "", "One or more tags to be added to the Process tags of all spans passing through this agent. Ex: key1=value1,key2=${envVar:defaultValue}") + flagSet.String(agentTags, "", "One or more tags to be added to the Process tags of all spans passing through this agent. Ex: key1=value1,key2=${envVar:defaultValue}") } } diff --git a/cmd/collector/app/flags/flags.go b/cmd/collector/app/flags/flags.go index bc0918b9a0d..5c68169c881 100644 --- a/cmd/collector/app/flags/flags.go +++ b/cmd/collector/app/flags/flags.go @@ -172,55 +172,55 @@ type GRPCOptions struct { } // AddFlags adds flags for CollectorOptions -func AddFlags(flags *flag.FlagSet) { - flags.Int(flagNumWorkers, DefaultNumWorkers, "The number of workers pulling items from the queue") - flags.Int(flagQueueSize, DefaultQueueSize, "The queue size of the collector") - flags.Uint(flagDynQueueSizeMemory, 0, "(experimental) The max memory size in MiB to use for the dynamic queue.") - flags.String(flagCollectorTags, "", "One or more tags to be added to the Process tags of all spans passing through this collector. Ex: key1=value1,key2=${envVar:defaultValue}") - flags.Bool(flagSpanSizeMetricsEnabled, false, "Enables metrics based on processed span size, which are more expensive to calculate.") - - addHTTPFlags(flags, httpServerFlagsCfg, ports.PortToHostPort(ports.CollectorHTTP)) - addGRPCFlags(flags, grpcServerFlagsCfg, ports.PortToHostPort(ports.CollectorGRPC)) - - flags.Bool(flagCollectorOTLPEnabled, true, "Enables OpenTelemetry OTLP receiver on dedicated HTTP and gRPC ports") - addHTTPFlags(flags, otlpServerFlagsCfg.HTTP, ":4318") - corsOTLPFlags.AddFlags(flags) - addGRPCFlags(flags, otlpServerFlagsCfg.GRPC, ":4317") - - flags.String(flagZipkinHTTPHostPort, "", "The host:port (e.g. 127.0.0.1:9411 or :9411) of the collector's Zipkin server (disabled by default)") - flags.Bool(flagZipkinKeepAliveEnabled, true, "KeepAlive configures allow Keep-Alive for Zipkin HTTP server (enabled by default)") - tlsZipkinFlagsConfig.AddFlags(flags) - corsZipkinFlags.AddFlags(flags) - - tenancy.AddFlags(flags) +func AddFlags(flagSet *flag.FlagSet) { + flagSet.Int(flagNumWorkers, DefaultNumWorkers, "The number of workers pulling items from the queue") + flagSet.Int(flagQueueSize, DefaultQueueSize, "The queue size of the collector") + flagSet.Uint(flagDynQueueSizeMemory, 0, "(experimental) The max memory size in MiB to use for the dynamic queue.") + flagSet.String(flagCollectorTags, "", "One or more tags to be added to the Process tags of all spans passing through this collector. Ex: key1=value1,key2=${envVar:defaultValue}") + flagSet.Bool(flagSpanSizeMetricsEnabled, false, "Enables metrics based on processed span size, which are more expensive to calculate.") + + addHTTPFlags(flagSet, httpServerFlagsCfg, ports.PortToHostPort(ports.CollectorHTTP)) + addGRPCFlags(flagSet, grpcServerFlagsCfg, ports.PortToHostPort(ports.CollectorGRPC)) + + flagSet.Bool(flagCollectorOTLPEnabled, true, "Enables OpenTelemetry OTLP receiver on dedicated HTTP and gRPC ports") + addHTTPFlags(flagSet, otlpServerFlagsCfg.HTTP, ":4318") + corsOTLPFlags.AddFlags(flagSet) + addGRPCFlags(flagSet, otlpServerFlagsCfg.GRPC, ":4317") + + flagSet.String(flagZipkinHTTPHostPort, "", "The host:port (e.g. 127.0.0.1:9411 or :9411) of the collector's Zipkin server (disabled by default)") + flagSet.Bool(flagZipkinKeepAliveEnabled, true, "KeepAlive configures allow Keep-Alive for Zipkin HTTP server (enabled by default)") + tlsZipkinFlagsConfig.AddFlags(flagSet) + corsZipkinFlags.AddFlags(flagSet) + + tenancy.AddFlags(flagSet) } -func addHTTPFlags(flags *flag.FlagSet, cfg serverFlagsConfig, defaultHostPort string) { - flags.String(cfg.prefix+"."+flagSuffixHostPort, defaultHostPort, "The host:port (e.g. 127.0.0.1:12345 or :12345) of the collector's HTTP server") - flags.Duration(cfg.prefix+"."+flagSuffixHTTPIdleTimeout, 0, "See https://pkg.go.dev/net/http#Server") - flags.Duration(cfg.prefix+"."+flagSuffixHTTPReadTimeout, 0, "See https://pkg.go.dev/net/http#Server") - flags.Duration(cfg.prefix+"."+flagSuffixHTTPReadHeaderTimeout, 2*time.Second, "See https://pkg.go.dev/net/http#Server") - cfg.tls.AddFlags(flags) +func addHTTPFlags(flagSet *flag.FlagSet, cfg serverFlagsConfig, defaultHostPort string) { + flagSet.String(cfg.prefix+"."+flagSuffixHostPort, defaultHostPort, "The host:port (e.g. 127.0.0.1:12345 or :12345) of the collector's HTTP server") + flagSet.Duration(cfg.prefix+"."+flagSuffixHTTPIdleTimeout, 0, "See https://pkg.go.dev/net/http#Server") + flagSet.Duration(cfg.prefix+"."+flagSuffixHTTPReadTimeout, 0, "See https://pkg.go.dev/net/http#Server") + flagSet.Duration(cfg.prefix+"."+flagSuffixHTTPReadHeaderTimeout, 2*time.Second, "See https://pkg.go.dev/net/http#Server") + cfg.tls.AddFlags(flagSet) } -func addGRPCFlags(flags *flag.FlagSet, cfg serverFlagsConfig, defaultHostPort string) { - flags.String( +func addGRPCFlags(flagSet *flag.FlagSet, cfg serverFlagsConfig, defaultHostPort string) { + flagSet.String( cfg.prefix+"."+flagSuffixHostPort, defaultHostPort, "The host:port (e.g. 127.0.0.1:12345 or :12345) of the collector's gRPC server") - flags.Int( + flagSet.Int( cfg.prefix+"."+flagSuffixGRPCMaxReceiveMessageLength, DefaultGRPCMaxReceiveMessageLength, "The maximum receivable message size for the collector's gRPC server") - flags.Duration( + flagSet.Duration( cfg.prefix+"."+flagSuffixGRPCMaxConnectionAge, 0, "The maximum amount of time a connection may exist. Set this value to a few seconds or minutes on highly elastic environments, so that clients discover new collector nodes frequently. See https://pkg.go.dev/google.golang.org/grpc/keepalive#ServerParameters") - flags.Duration( + flagSet.Duration( cfg.prefix+"."+flagSuffixGRPCMaxConnectionAgeGrace, 0, "The additive period after MaxConnectionAge after which the connection will be forcibly closed. See https://pkg.go.dev/google.golang.org/grpc/keepalive#ServerParameters") - cfg.tls.AddFlags(flags) + cfg.tls.AddFlags(flagSet) } func (opts *HTTPOptions) initFromViper(v *viper.Viper, _ *zap.Logger, cfg serverFlagsConfig) error { diff --git a/cmd/collector/app/handler/grpc_handler_test.go b/cmd/collector/app/handler/grpc_handler_test.go index 08f7cbf98a4..6f9cb423304 100644 --- a/cmd/collector/app/handler/grpc_handler_test.go +++ b/cmd/collector/app/handler/grpc_handler_test.go @@ -103,9 +103,9 @@ func newClient(t *testing.T, addr net.Addr) (api_v2.CollectorServiceClient, *grp } func TestPostSpans(t *testing.T) { - processor := &mockSpanProcessor{} + proc := &mockSpanProcessor{} server, addr := initializeGRPCTestServer(t, func(s *grpc.Server) { - handler := NewGRPCHandler(zap.NewNop(), processor, &tenancy.Manager{}) + handler := NewGRPCHandler(zap.NewNop(), proc, &tenancy.Manager{}) api_v2.RegisterCollectorServiceServer(s, handler) }) defer server.Stop() @@ -130,17 +130,17 @@ func TestPostSpans(t *testing.T) { Batch: test.batch, }) require.NoError(t, err) - got := processor.getSpans() + got := proc.getSpans() require.Equal(t, len(test.batch.GetSpans()), len(got)) assert.Equal(t, test.expected, got) - processor.reset() + proc.reset() } } func TestGRPCCompressionEnabled(t *testing.T) { - processor := &mockSpanProcessor{} + proc := &mockSpanProcessor{} server, addr := initializeGRPCTestServer(t, func(s *grpc.Server) { - handler := NewGRPCHandler(zap.NewNop(), processor, &tenancy.Manager{}) + handler := NewGRPCHandler(zap.NewNop(), proc, &tenancy.Manager{}) api_v2.RegisterCollectorServiceServer(s, handler) }) defer server.Stop() @@ -214,9 +214,9 @@ func TestPostTenantedSpans(t *testing.T) { tenantHeader := "x-tenant" dummyTenant := "grpc-test-tenant" - processor := &mockSpanProcessor{} + proc := &mockSpanProcessor{} server, addr := initializeGRPCTestServer(t, func(s *grpc.Server) { - handler := NewGRPCHandler(zap.NewNop(), processor, + handler := NewGRPCHandler(zap.NewNop(), proc, tenancy.NewManager(&tenancy.Options{ Enabled: true, Header: tenantHeader, @@ -296,9 +296,9 @@ func TestPostTenantedSpans(t *testing.T) { } else { require.NoError(t, err) } - assert.Equal(t, test.expected, processor.getSpans()) - assert.Equal(t, test.expectedTenants, processor.getTenants()) - processor.reset() + assert.Equal(t, test.expected, proc.getSpans()) + assert.Equal(t, test.expectedTenants, proc.getTenants()) + proc.reset() }) } } @@ -351,8 +351,8 @@ func TestGetTenant(t *testing.T) { }, } - processor := &mockSpanProcessor{} - handler := NewGRPCHandler(zap.NewNop(), processor, + proc := &mockSpanProcessor{} + handler := NewGRPCHandler(zap.NewNop(), proc, tenancy.NewManager(&tenancy.Options{ Enabled: true, Header: tenantHeader, diff --git a/cmd/collector/app/options.go b/cmd/collector/app/options.go index 13077e0949f..03f4eb8c6f7 100644 --- a/cmd/collector/app/options.go +++ b/cmd/collector/app/options.go @@ -71,9 +71,9 @@ func (options) PreProcessSpans(preProcessSpans ProcessSpans) Option { } // Sanitizer creates an Option that initializes the sanitizer function -func (options) Sanitizer(sanitizer sanitizer.SanitizeSpan) Option { +func (options) Sanitizer(spanSanitizer sanitizer.SanitizeSpan) Option { return func(b *options) { - b.sanitizer = sanitizer + b.sanitizer = spanSanitizer } } diff --git a/cmd/collector/app/sanitizer/service_name_sanitizer.go b/cmd/collector/app/sanitizer/service_name_sanitizer.go index e327bfe4963..dcffe0c6215 100644 --- a/cmd/collector/app/sanitizer/service_name_sanitizer.go +++ b/cmd/collector/app/sanitizer/service_name_sanitizer.go @@ -10,8 +10,8 @@ import ( ) // NewServiceNameSanitizer creates a service name sanitizer. -func NewServiceNameSanitizer(cache cache.Cache) SanitizeSpan { - sanitizer := serviceNameSanitizer{cache: cache} +func NewServiceNameSanitizer(c cache.Cache) SanitizeSpan { + sanitizer := serviceNameSanitizer{cache: c} return sanitizer.Sanitize } diff --git a/cmd/ingester/app/builder/builder.go b/cmd/ingester/app/builder/builder.go index dc4abbec2fc..efa4ecefd6e 100644 --- a/cmd/ingester/app/builder/builder.go +++ b/cmd/ingester/app/builder/builder.go @@ -37,7 +37,7 @@ func CreateConsumer(logger *zap.Logger, metricsFactory metrics.Factory, spanWrit Writer: spanWriter, Unmarshaller: unmarshaller, } - spanProcessor := processor.NewSpanProcessor(spParams) + proc := processor.NewSpanProcessor(spParams) consumerConfig := kafkaConsumer.Configuration{ Brokers: options.Brokers, @@ -58,7 +58,7 @@ func CreateConsumer(logger *zap.Logger, metricsFactory metrics.Factory, spanWrit factoryParams := consumer.ProcessorFactoryParams{ Parallelism: options.Parallelism, SaramaConsumer: saramaConsumer, - BaseProcessor: spanProcessor, + BaseProcessor: proc, Logger: logger, Factory: metricsFactory, } diff --git a/cmd/ingester/app/consumer/committing_processor.go b/cmd/ingester/app/consumer/committing_processor.go index d4cc7f75106..31192fe7170 100644 --- a/cmd/ingester/app/consumer/committing_processor.go +++ b/cmd/ingester/app/consumer/committing_processor.go @@ -21,9 +21,9 @@ type offsetMarker interface { } // NewCommittingProcessor returns a processor that commits message offsets to Kafka -func NewCommittingProcessor(processor processor.SpanProcessor, marker offsetMarker) processor.SpanProcessor { +func NewCommittingProcessor(proc processor.SpanProcessor, marker offsetMarker) processor.SpanProcessor { return &comittingProcessor{ - processor: processor, + processor: proc, marker: marker, } } diff --git a/cmd/ingester/app/consumer/consumer_test.go b/cmd/ingester/app/consumer/consumer_test.go index 6647671af8e..05180ddd469 100644 --- a/cmd/ingester/app/consumer/consumer_test.go +++ b/cmd/ingester/app/consumer/consumer_test.go @@ -78,19 +78,19 @@ func newConsumer( t *testing.T, metricsFactory metrics.Factory, _ string, /* topic */ - processor processor.SpanProcessor, - consumer consumer.Consumer, + proc processor.SpanProcessor, + cons consumer.Consumer, ) *Consumer { logger, _ := zap.NewDevelopment() consumerParams := Params{ MetricsFactory: metricsFactory, Logger: logger, - InternalConsumer: consumer, + InternalConsumer: cons, ProcessorFactory: ProcessorFactory{ - consumer: consumer, + consumer: cons, metricsFactory: metricsFactory, logger: logger, - baseProcessor: processor, + baseProcessor: proc, parallelism: 1, }, } diff --git a/cmd/ingester/app/consumer/processor_factory.go b/cmd/ingester/app/consumer/processor_factory.go index 265c13dbaac..3159487b453 100644 --- a/cmd/ingester/app/consumer/processor_factory.go +++ b/cmd/ingester/app/consumer/processor_factory.go @@ -50,8 +50,8 @@ func NewProcessorFactory(params ProcessorFactoryParams) (*ProcessorFactory, erro func (c *ProcessorFactory) new(topic string, partition int32, minOffset int64) processor.SpanProcessor { c.logger.Info("Creating new processors", zap.Int32("partition", partition)) - markOffset := func(offset int64) { - c.consumer.MarkPartitionOffset(topic, partition, offset, "") + markOffset := func(offsetVal int64) { + c.consumer.MarkPartitionOffset(topic, partition, offsetVal, "") } om := offset.NewManager(minOffset, markOffset, topic, partition, c.metricsFactory) diff --git a/cmd/ingester/app/processor/decorator/retry.go b/cmd/ingester/app/processor/decorator/retry.go index a456b478ec0..c46a8e4488b 100644 --- a/cmd/ingester/app/processor/decorator/retry.go +++ b/cmd/ingester/app/processor/decorator/retry.go @@ -79,7 +79,7 @@ func PropagateError(b bool) RetryOption { // NewRetryingProcessor returns a processor that retries failures using an exponential backoff // with jitter. -func NewRetryingProcessor(f metrics.Factory, processor processor.SpanProcessor, opts ...RetryOption) processor.SpanProcessor { +func NewRetryingProcessor(f metrics.Factory, proc processor.SpanProcessor, opts ...RetryOption) processor.SpanProcessor { options := defaultOpts for _, opt := range opts { opt(&options) @@ -89,7 +89,7 @@ func NewRetryingProcessor(f metrics.Factory, processor processor.SpanProcessor, return &retryDecorator{ retryAttempts: m.Counter(metrics.Options{Name: "retry-attempts", Tags: nil}), exhausted: m.Counter(metrics.Options{Name: "retry-exhausted", Tags: nil}), - processor: processor, + processor: proc, options: options, } } diff --git a/cmd/jaeger/internal/exporters/storageexporter/exporter_test.go b/cmd/jaeger/internal/exporters/storageexporter/exporter_test.go index 1d03bf2c438..628eae6dfb3 100644 --- a/cmd/jaeger/internal/exporters/storageexporter/exporter_test.go +++ b/cmd/jaeger/internal/exporters/storageexporter/exporter_test.go @@ -69,12 +69,12 @@ func TestExporterStartBadNameError(t *testing.T) { host := storagetest.NewStorageHost() host.WithExtension(jaegerstorage.ID, &mockStorageExt{name: "foo"}) - exporter := &storageExporter{ + exp := &storageExporter{ config: &Config{ TraceStorage: "bar", }, } - err := exporter.start(context.Background(), host) + err := exp.start(context.Background(), host) require.Error(t, err) require.ErrorContains(t, err, "cannot find storage factory") } @@ -89,12 +89,12 @@ func TestExporterStartBadSpanstoreError(t *testing.T) { factory: factory, }) - exporter := &storageExporter{ + exp := &storageExporter{ config: &Config{ TraceStorage: "foo", }, } - err := exporter.start(context.Background(), host) + err := exp.start(context.Background(), host) require.Error(t, err) require.ErrorContains(t, err, "mocked error") } diff --git a/cmd/jaeger/internal/extension/jaegerquery/factory_test.go b/cmd/jaeger/internal/extension/jaegerquery/factory_test.go index 9a579ce6468..350b283a819 100644 --- a/cmd/jaeger/internal/extension/jaegerquery/factory_test.go +++ b/cmd/jaeger/internal/extension/jaegerquery/factory_test.go @@ -23,8 +23,8 @@ func Test_CreateExtension(t *testing.T) { ID: ID, } cfg := createDefaultConfig() - extension, err := createExtension(context.Background(), set, cfg) + ext, err := createExtension(context.Background(), set, cfg) require.NoError(t, err) - assert.NotNil(t, extension) + assert.NotNil(t, ext) } diff --git a/cmd/jaeger/internal/integration/span_writer.go b/cmd/jaeger/internal/integration/span_writer.go index 81b6de99874..da722b1681f 100644 --- a/cmd/jaeger/internal/integration/span_writer.go +++ b/cmd/jaeger/internal/integration/span_writer.go @@ -48,17 +48,17 @@ func createSpanWriter(logger *zap.Logger, port int) (*spanWriter, error) { set := exportertest.NewNopSettings() set.Logger = logger - exporter, err := factory.CreateTraces(context.Background(), set, cfg) + exp, err := factory.CreateTraces(context.Background(), set, cfg) if err != nil { return nil, err } - if err := exporter.Start(context.Background(), componenttest.NewNopHost()); err != nil { + if err := exp.Start(context.Background(), componenttest.NewNopHost()); err != nil { return nil, err } return &spanWriter{ logger: logger, - exporter: exporter, + exporter: exp, }, nil } diff --git a/cmd/query/app/apiv3/http_gateway.go b/cmd/query/app/apiv3/http_gateway.go index 86adf6537e4..01a81c02709 100644 --- a/cmd/query/app/apiv3/http_gateway.go +++ b/cmd/query/app/apiv3/http_gateway.go @@ -143,11 +143,11 @@ func (h *HTTPGateway) getTrace(w http.ResponseWriter, r *http.Request) { if h.tryParamError(w, err, paramTraceID) { return } - trace, err := h.QueryService.GetTrace(r.Context(), traceID) + trc, err := h.QueryService.GetTrace(r.Context(), traceID) if h.tryHandleError(w, err, http.StatusInternalServerError) { return } - h.returnSpans(trace.Spans, w) + h.returnSpans(trc.Spans, w) } func (h *HTTPGateway) findTraces(w http.ResponseWriter, r *http.Request) { @@ -162,8 +162,8 @@ func (h *HTTPGateway) findTraces(w http.ResponseWriter, r *http.Request) { return } var spans []*model.Span - for _, trace := range traces { - spans = append(spans, trace.Spans...) + for _, t := range traces { + spans = append(spans, t.Spans...) } h.returnSpans(spans, w) } diff --git a/cmd/query/app/http_handler.go b/cmd/query/app/http_handler.go index f868b75a904..a6123efd112 100644 --- a/cmd/query/app/http_handler.go +++ b/cmd/query/app/http_handler.go @@ -275,7 +275,7 @@ func (aH *APIHandler) tracesByIDs(ctx context.Context, traceIDs []model.TraceID) var traceErrors []structuredError retMe := make([]*model.Trace, 0, len(traceIDs)) for _, traceID := range traceIDs { - if trace, err := aH.queryService.GetTrace(ctx, traceID); err != nil { + if trc, err := aH.queryService.GetTrace(ctx, traceID); err != nil { if !errors.Is(err, spanstore.ErrTraceNotFound) { return nil, nil, err } @@ -284,7 +284,7 @@ func (aH *APIHandler) tracesByIDs(ctx context.Context, traceIDs []model.TraceID) TraceID: ui.TraceID(traceID.String()), }) } else { - retMe = append(retMe, trace) + retMe = append(retMe, trc) } } return retMe, traceErrors, nil @@ -363,16 +363,16 @@ func (aH *APIHandler) metrics(w http.ResponseWriter, r *http.Request, getMetrics aH.writeJSON(w, r, m) } -func (aH *APIHandler) convertModelToUI(trace *model.Trace, adjust bool) (*ui.Trace, *structuredError) { +func (aH *APIHandler) convertModelToUI(trc *model.Trace, adjust bool) (*ui.Trace, *structuredError) { var errs []error if adjust { var err error - trace, err = aH.queryService.Adjust(trace) + trc, err = aH.queryService.Adjust(trc) if err != nil { errs = append(errs, err) } } - uiTrace := uiconv.FromDomain(trace) + uiTrace := uiconv.FromDomain(trc) var uiError *structuredError if err := errors.Join(errs...); err != nil { uiError = &structuredError{ @@ -438,7 +438,7 @@ func (aH *APIHandler) getTrace(w http.ResponseWriter, r *http.Request) { if !ok { return } - trace, err := aH.queryService.GetTrace(r.Context(), traceID) + trc, err := aH.queryService.GetTrace(r.Context(), traceID) if errors.Is(err, spanstore.ErrTraceNotFound) { aH.handleError(w, err, http.StatusNotFound) return @@ -448,7 +448,7 @@ func (aH *APIHandler) getTrace(w http.ResponseWriter, r *http.Request) { } var uiErrors []structuredError - structuredRes := aH.tracesToResponse([]*model.Trace{trace}, shouldAdjust(r), uiErrors) + structuredRes := aH.tracesToResponse([]*model.Trace{trc}, shouldAdjust(r), uiErrors) aH.writeJSON(w, r, structuredRes) } diff --git a/cmd/query/app/http_handler_test.go b/cmd/query/app/http_handler_test.go index 7f3fb2f5c95..f47e61b980d 100644 --- a/cmd/query/app/http_handler_test.go +++ b/cmd/query/app/http_handler_test.go @@ -278,9 +278,9 @@ func TestGetTrace(t *testing.T) { extractTraces := func(t *testing.T, response *structuredResponse) []ui.Trace { var traces []ui.Trace - bytes, err := json.Marshal(response.Data) + resBytes, err := json.Marshal(response.Data) require.NoError(t, err) - err = json.Unmarshal(bytes, &traces) + err = json.Unmarshal(resBytes, &traces) require.NoError(t, err) return traces } diff --git a/crossdock/services/query.go b/crossdock/services/query.go index a50837c3879..235d88350a4 100644 --- a/crossdock/services/query.go +++ b/crossdock/services/query.go @@ -29,15 +29,15 @@ type queryService struct { } // NewQueryService returns an instance of QueryService. -func NewQueryService(url string, logger *zap.Logger) QueryService { +func NewQueryService(serviceURL string, logger *zap.Logger) QueryService { return &queryService{ - url: url, + url: serviceURL, logger: logger, } } -func getTraceURL(url string) string { - return url + "/api/traces?%s" +func getTraceURL(traceURL string) string { + return traceURL + "/api/traces?%s" } type response struct { @@ -54,8 +54,8 @@ func (s *queryService) GetTraces(serviceName, operation string, tags map[string] for k, v := range tags { values.Add("tag", k+":"+v) } - url := fmt.Sprintf(getTraceURL(s.url), values.Encode()) - resp, err := http.Get(url) + fmtURL := fmt.Sprintf(getTraceURL(s.url), values.Encode()) + resp, err := http.Get(fmtURL) if err != nil { return nil, err } @@ -64,7 +64,7 @@ func (s *queryService) GetTraces(serviceName, operation string, tags map[string] if err != nil { return nil, err } - s.logger.Info("GetTraces: received response from query", zap.String("body", string(body)), zap.String("url", url)) + s.logger.Info("GetTraces: received response from query", zap.String("body", string(body)), zap.String("url", fmtURL)) var queryResponse response if err = json.Unmarshal(body, &queryResponse); err != nil { diff --git a/examples/hotrod/services/frontend/best_eta.go b/examples/hotrod/services/frontend/best_eta.go index a9c04ba1aea..8a541c6d49f 100644 --- a/examples/hotrod/services/frontend/best_eta.go +++ b/examples/hotrod/services/frontend/best_eta.go @@ -60,13 +60,13 @@ func newBestETA(tracer trace.TracerProvider, logger log.Factory, options ConfigO } func (eta *bestETA) Get(ctx context.Context, customerID int) (*Response, error) { - customer, err := eta.customer.Get(ctx, customerID) + cust, err := eta.customer.Get(ctx, customerID) if err != nil { return nil, err } - eta.logger.For(ctx).Info("Found customer", zap.Any("customer", customer)) + eta.logger.For(ctx).Info("Found customer", zap.Any("customer", cust)) - m, err := baggage.NewMember("customer", customer.Name) + m, err := baggage.NewMember("customer", cust.Name) if err != nil { eta.logger.For(ctx).Error("cannot create baggage member", zap.Error(err)) } @@ -77,13 +77,13 @@ func (eta *bestETA) Get(ctx context.Context, customerID int) (*Response, error) } ctx = baggage.ContextWithBaggage(ctx, bag) - drivers, err := eta.driver.FindNearest(ctx, customer.Location) + drivers, err := eta.driver.FindNearest(ctx, cust.Location) if err != nil { return nil, err } eta.logger.For(ctx).Info("Found drivers", zap.Any("drivers", drivers)) - results := eta.getRoutes(ctx, customer, drivers) + results := eta.getRoutes(ctx, cust, drivers) eta.logger.For(ctx).Info("Found routes", zap.Any("routes", results)) resp := &Response{ETA: math.MaxInt64} @@ -111,19 +111,19 @@ type routeResult struct { } // getRoutes calls Route service for each (customer, driver) pair -func (eta *bestETA) getRoutes(ctx context.Context, customer *customer.Customer, drivers []driver.Driver) []routeResult { +func (eta *bestETA) getRoutes(ctx context.Context, cust *customer.Customer, drivers []driver.Driver) []routeResult { results := make([]routeResult, 0, len(drivers)) wg := sync.WaitGroup{} routesLock := sync.Mutex{} for _, dd := range drivers { wg.Add(1) - driver := dd // capture loop var + drv := dd // capture loop var // Use worker pool to (potentially) execute requests in parallel eta.pool.Execute(func() { - route, err := eta.route.FindRoute(ctx, driver.Location, customer.Location) + route, err := eta.route.FindRoute(ctx, drv.Location, cust.Location) routesLock.Lock() results = append(results, routeResult{ - driver: driver.DriverID, + driver: drv.DriverID, route: route, err: err, }) diff --git a/examples/hotrod/services/route/client.go b/examples/hotrod/services/route/client.go index 0b3c3c7396d..f4ff248f52b 100644 --- a/examples/hotrod/services/route/client.go +++ b/examples/hotrod/services/route/client.go @@ -38,9 +38,9 @@ func (c *Client) FindRoute(ctx context.Context, pickup, dropoff string) (*Route, v := url.Values{} v.Set("pickup", pickup) v.Set("dropoff", dropoff) - url := "http://" + c.hostPort + "/route?" + v.Encode() + routeURL := "http://" + c.hostPort + "/route?" + v.Encode() var route Route - if err := c.client.GetJSON(ctx, "/route", url, &route); err != nil { + if err := c.client.GetJSON(ctx, "/route", routeURL, &route); err != nil { c.logger.For(ctx).Error("Error getting route", zap.Error(err)) return nil, err } diff --git a/internal/metrics/otelmetrics/factory_test.go b/internal/metrics/otelmetrics/factory_test.go index a4feeb3fd9b..78c245144a5 100644 --- a/internal/metrics/otelmetrics/factory_test.go +++ b/internal/metrics/otelmetrics/factory_test.go @@ -96,12 +96,12 @@ func TestCounter(t *testing.T) { counter.Inc(1) testCounter := findMetric(t, registry, "test_counter_total") - metrics := testCounter.GetMetric() - assert.InDelta(t, float64(2), metrics[0].GetCounter().GetValue(), 0.01) + metricData := testCounter.GetMetric() + assert.InDelta(t, float64(2), metricData[0].GetCounter().GetValue(), 0.01) expectedLabels := map[string]string{ "tag1": "value1", } - assert.Equal(t, expectedLabels, promLabelsToMap(metrics[0].GetLabel())) + assert.Equal(t, expectedLabels, promLabelsToMap(metricData[0].GetLabel())) } func TestCounterNamingConvention(t *testing.T) { @@ -127,12 +127,12 @@ func TestGauge(t *testing.T) { testGauge := findMetric(t, registry, "test_gauge") - metrics := testGauge.GetMetric() - assert.InDelta(t, float64(2), metrics[0].GetGauge().GetValue(), 0.01) + metricData := testGauge.GetMetric() + assert.InDelta(t, float64(2), metricData[0].GetGauge().GetValue(), 0.01) expectedLabels := map[string]string{ "tag1": "value1", } - assert.Equal(t, expectedLabels, promLabelsToMap(metrics[0].GetLabel())) + assert.Equal(t, expectedLabels, promLabelsToMap(metricData[0].GetLabel())) } func TestHistogram(t *testing.T) { @@ -147,12 +147,12 @@ func TestHistogram(t *testing.T) { testHistogram := findMetric(t, registry, "test_histogram") - metrics := testHistogram.GetMetric() - assert.InDelta(t, float64(1), metrics[0].GetHistogram().GetSampleSum(), 0.01) + metricData := testHistogram.GetMetric() + assert.InDelta(t, float64(1), metricData[0].GetHistogram().GetSampleSum(), 0.01) expectedLabels := map[string]string{ "tag1": "value1", } - assert.Equal(t, expectedLabels, promLabelsToMap(metrics[0].GetLabel())) + assert.Equal(t, expectedLabels, promLabelsToMap(metricData[0].GetLabel())) } func TestTimer(t *testing.T) { @@ -167,12 +167,12 @@ func TestTimer(t *testing.T) { testTimer := findMetric(t, registry, "test_timer_seconds") - metrics := testTimer.GetMetric() - assert.InDelta(t, float64(0.1), metrics[0].GetHistogram().GetSampleSum(), 0.01) + metricData := testTimer.GetMetric() + assert.InDelta(t, float64(0.1), metricData[0].GetHistogram().GetSampleSum(), 0.01) expectedLabels := map[string]string{ "tag1": "value1", } - assert.Equal(t, expectedLabels, promLabelsToMap(metrics[0].GetLabel())) + assert.Equal(t, expectedLabels, promLabelsToMap(metricData[0].GetLabel())) } func TestNamespace(t *testing.T) { @@ -262,6 +262,6 @@ func TestNormalization(t *testing.T) { testGauge := findMetric(t, registry, "My_Namespace_My_Gauge") - metrics := testGauge.GetMetric() - assert.InDelta(t, float64(1), metrics[0].GetGauge().GetValue(), 0.01) + metricData := testGauge.GetMetric() + assert.InDelta(t, float64(1), metricData[0].GetGauge().GetValue(), 0.01) } diff --git a/model/adjuster/span_hash_deduper_test.go b/model/adjuster/span_hash_deduper_test.go index 56ca280eeb7..6fd898d264a 100644 --- a/model/adjuster/span_hash_deduper_test.go +++ b/model/adjuster/span_hash_deduper_test.go @@ -73,37 +73,37 @@ func getSpanIDs(spans []*model.Span) []int { } func TestDedupeBySpanHashTriggers(t *testing.T) { - trace := newDuplicatedSpansTrace() + trc := newDuplicatedSpansTrace() deduper := DedupeBySpanHash() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) - assert.Len(t, trace.Spans, 2, "should dedupe spans") + assert.Len(t, trc.Spans, 2, "should dedupe spans") - ids := getSpanIDs(trace.Spans) + ids := getSpanIDs(trc.Spans) assert.ElementsMatch(t, []int{int(clientSpanID), int(anotherSpanID)}, ids, "should keep unique span IDs") } func TestDedupeBySpanHashNotTriggered(t *testing.T) { - trace := newUniqueSpansTrace() + trc := newUniqueSpansTrace() deduper := DedupeBySpanHash() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) - assert.Len(t, trace.Spans, 2, "should not dedupe spans") + assert.Len(t, trc.Spans, 2, "should not dedupe spans") - ids := getSpanIDs(trace.Spans) + ids := getSpanIDs(trc.Spans) assert.ElementsMatch(t, []int{int(anotherSpanID), int(anotherSpanID)}, ids, "should keep unique span IDs") - assert.NotEqual(t, trace.Spans[0], trace.Spans[1], "should keep unique hashcodes") + assert.NotEqual(t, trc.Spans[0], trc.Spans[1], "should keep unique hashcodes") } func TestDedupeBySpanHashEmpty(t *testing.T) { - trace := &model.Trace{} + trc := &model.Trace{} deduper := DedupeBySpanHash() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) - assert.Empty(t, trace.Spans, "should be empty") + assert.Empty(t, trc.Spans, "should be empty") } func TestDedupeBySpanHashManyManySpans(t *testing.T) { @@ -116,13 +116,13 @@ func TestDedupeBySpanHashManyManySpans(t *testing.T) { SpanID: model.SpanID(i % distinctSpanIDs), }) } - trace := &model.Trace{Spans: spans} + trc := &model.Trace{Spans: spans} deduper := DedupeBySpanHash() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) - assert.Len(t, trace.Spans, distinctSpanIDs, "should dedupe spans") + assert.Len(t, trc.Spans, distinctSpanIDs, "should dedupe spans") - ids := getSpanIDs(trace.Spans) + ids := getSpanIDs(trc.Spans) assert.ElementsMatch(t, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, ids, "should keep unique span IDs") } diff --git a/model/adjuster/zipkin_span_id_uniquify_test.go b/model/adjuster/zipkin_span_id_uniquify_test.go index 1ad0895985f..13a2114ebc5 100644 --- a/model/adjuster/zipkin_span_id_uniquify_test.go +++ b/model/adjuster/zipkin_span_id_uniquify_test.go @@ -53,51 +53,51 @@ func newZipkinTrace() *model.Trace { } func TestZipkinSpanIDUniquifierTriggered(t *testing.T) { - trace := newZipkinTrace() + trc := newZipkinTrace() deduper := ZipkinSpanIDUniquifier() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) - clientSpan := trace.Spans[0] + clientSpan := trc.Spans[0] assert.Equal(t, clientSpanID, clientSpan.SpanID, "client span ID should not change") - serverSpan := trace.Spans[1] + serverSpan := trc.Spans[1] assert.Equal(t, clientSpanID+1, serverSpan.SpanID, "server span ID should be reassigned") assert.Equal(t, clientSpan.SpanID, serverSpan.ParentSpanID(), "client span should be server span's parent") - thirdSpan := trace.Spans[2] + thirdSpan := trc.Spans[2] assert.Equal(t, anotherSpanID, thirdSpan.SpanID, "3rd span ID should not change") assert.Equal(t, serverSpan.SpanID, thirdSpan.ParentSpanID(), "server span should be 3rd span's parent") } func TestZipkinSpanIDUniquifierNotTriggered(t *testing.T) { - trace := newZipkinTrace() - trace.Spans = trace.Spans[1:] // remove client span + trc := newZipkinTrace() + trc.Spans = trc.Spans[1:] // remove client span deduper := ZipkinSpanIDUniquifier() - trace, err := deduper.Adjust(trace) + trc, err := deduper.Adjust(trc) require.NoError(t, err) serverSpanID := clientSpanID // for better readability - serverSpan := trace.Spans[0] + serverSpan := trc.Spans[0] assert.Equal(t, serverSpanID, serverSpan.SpanID, "server span ID should be unchanged") - thirdSpan := trace.Spans[1] + thirdSpan := trc.Spans[1] assert.Equal(t, anotherSpanID, thirdSpan.SpanID, "3rd span ID should not change") assert.Equal(t, serverSpan.SpanID, thirdSpan.ParentSpanID(), "server span should be 3rd span's parent") } func TestZipkinSpanIDUniquifierError(t *testing.T) { - trace := newZipkinTrace() + trc := newZipkinTrace() maxID := int64(-1) assert.Equal(t, maxSpanID, model.NewSpanID(uint64(maxID)), "maxSpanID must be 2^64-1") - deduper := &spanIDDeduper{trace: trace} + deduper := &spanIDDeduper{trace: trc} deduper.groupSpansByID() deduper.maxUsedID = maxSpanID - 1 deduper.uniquifyServerSpanIDs() - if assert.Len(t, trace.Spans[1].Warnings, 1) { - assert.Equal(t, "cannot assign unique span ID, too many spans in the trace", trace.Spans[1].Warnings[0]) + if assert.Len(t, trc.Spans[1].Warnings, 1) { + assert.Equal(t, "cannot assign unique span ID, too many spans in the trace", trc.Spans[1].Warnings[0]) } } diff --git a/model/converter/json/sampling_test.go b/model/converter/json/sampling_test.go index 8bfa9a749cb..f1b147bb6f8 100644 --- a/model/converter/json/sampling_test.go +++ b/model/converter/json/sampling_test.go @@ -91,10 +91,10 @@ func TestSamplingStrategyResponseFromJSON(t *testing.T) { SamplingRate: 0.42, }, } - json, err := SamplingStrategyResponseToJSON(s1) + jsonData, err := SamplingStrategyResponseToJSON(s1) require.NoError(t, err) - s2, err := SamplingStrategyResponseFromJSON([]byte(json)) + s2, err := SamplingStrategyResponseFromJSON([]byte(jsonData)) require.NoError(t, err) assert.Equal(t, s1.GetStrategyType(), s2.GetStrategyType()) assert.EqualValues(t, s1.GetProbabilisticSampling(), s2.GetProbabilisticSampling()) diff --git a/model/converter/thrift/zipkin/to_domain.go b/model/converter/thrift/zipkin/to_domain.go index 720553e3b04..c287d958c1a 100644 --- a/model/converter/thrift/zipkin/to_domain.go +++ b/model/converter/thrift/zipkin/to_domain.go @@ -81,7 +81,7 @@ type toDomain struct{} func (td toDomain) ToDomain(zSpans []*zipkincore.Span) (*model.Trace, error) { var errs []error processes := newProcessHashtable() - trace := &model.Trace{} + trc := &model.Trace{} for _, zSpan := range zSpans { jSpans, err := td.ToDomainSpans(zSpan) if err != nil { @@ -90,10 +90,10 @@ func (td toDomain) ToDomain(zSpans []*zipkincore.Span) (*model.Trace, error) { for _, jSpan := range jSpans { // remove duplicate Process instances jSpan.Process = processes.add(jSpan.Process) - trace.Spans = append(trace.Spans, jSpan) + trc.Spans = append(trc.Spans, jSpan) } } - return trace, errors.Join(errs...) + return trc, errors.Join(errs...) } func (td toDomain) ToDomainSpans(zSpan *zipkincore.Span) ([]*model.Span, error) { diff --git a/model/converter/thrift/zipkin/to_domain_test.go b/model/converter/thrift/zipkin/to_domain_test.go index a71846a534e..d70f24e09c2 100644 --- a/model/converter/thrift/zipkin/to_domain_test.go +++ b/model/converter/thrift/zipkin/to_domain_test.go @@ -65,19 +65,19 @@ func TestToDomain(t *testing.T) { func TestToDomainNoServiceNameError(t *testing.T) { zSpans := getZipkinSpans(t, `[{ "trace_id": -1, "id": 31 }]`) - trace, err := ToDomain(zSpans) + trc, err := ToDomain(zSpans) require.EqualError(t, err, "cannot find service name in Zipkin span [traceID=ffffffffffffffff, spanID=1f]") - assert.Len(t, trace.Spans, 1) - assert.Equal(t, "unknown-service-name", trace.Spans[0].Process.ServiceName) + assert.Len(t, trc.Spans, 1) + assert.Equal(t, "unknown-service-name", trc.Spans[0].Process.ServiceName) } func TestToDomainServiceNameInBinAnnotation(t *testing.T) { zSpans := getZipkinSpans(t, `[{ "trace_id": -1, "id": 31, "binary_annotations": [{"key": "foo", "host": {"service_name": "bar", "ipv4": 23456}}] }]`) - trace, err := ToDomain(zSpans) + trc, err := ToDomain(zSpans) require.NoError(t, err) - assert.Len(t, trace.Spans, 1) - assert.Equal(t, "bar", trace.Spans[0].Process.ServiceName) + assert.Len(t, trc.Spans, 1) + assert.Equal(t, "bar", trc.Spans[0].Process.ServiceName) } func TestToDomainWithDurationFromServerAnnotations(t *testing.T) { @@ -85,10 +85,10 @@ func TestToDomainWithDurationFromServerAnnotations(t *testing.T) { {"value": "sr", "timestamp": 1, "host": {"service_name": "bar", "ipv4": 23456}}, {"value": "ss", "timestamp": 10, "host": {"service_name": "bar", "ipv4": 23456}} ]}]`) - trace, err := ToDomain(zSpans) + trc, err := ToDomain(zSpans) require.NoError(t, err) - assert.Equal(t, 1000, int(trace.Spans[0].StartTime.Nanosecond())) - assert.Equal(t, 9000, int(trace.Spans[0].Duration)) + assert.Equal(t, 1000, int(trc.Spans[0].StartTime.Nanosecond())) + assert.Equal(t, 9000, int(trc.Spans[0].Duration)) } func TestToDomainWithDurationFromClientAnnotations(t *testing.T) { @@ -96,10 +96,10 @@ func TestToDomainWithDurationFromClientAnnotations(t *testing.T) { {"value": "cs", "timestamp": 1, "host": {"service_name": "bar", "ipv4": 23456}}, {"value": "cr", "timestamp": 10, "host": {"service_name": "bar", "ipv4": 23456}} ]}]`) - trace, err := ToDomain(zSpans) + trc, err := ToDomain(zSpans) require.NoError(t, err) - assert.Equal(t, 1000, int(trace.Spans[0].StartTime.Nanosecond())) - assert.Equal(t, 9000, int(trace.Spans[0].Duration)) + assert.Equal(t, 1000, int(trc.Spans[0].StartTime.Nanosecond())) + assert.Equal(t, 9000, int(trc.Spans[0].Duration)) } func TestToDomainMultipleSpanKinds(t *testing.T) { @@ -135,18 +135,18 @@ func TestToDomainMultipleSpanKinds(t *testing.T) { } for _, test := range tests { - trace, err := ToDomain(getZipkinSpans(t, test.json)) + trc, err := ToDomain(getZipkinSpans(t, test.json)) require.NoError(t, err) - assert.Len(t, trace.Spans, 2) - assert.Len(t, trace.Spans[0].Tags, 1) - assert.Equal(t, test.tagFirstKey, trace.Spans[0].Tags[0].Key) - assert.Equal(t, test.tagFirstVal.String(), trace.Spans[0].Tags[0].VStr) + assert.Len(t, trc.Spans, 2) + assert.Len(t, trc.Spans[0].Tags, 1) + assert.Equal(t, test.tagFirstKey, trc.Spans[0].Tags[0].Key) + assert.Equal(t, test.tagFirstVal.String(), trc.Spans[0].Tags[0].VStr) - assert.Len(t, trace.Spans[1].Tags, 1) - assert.Equal(t, test.tagSecondKey, trace.Spans[1].Tags[0].Key) - assert.Equal(t, time.Duration(1000), trace.Spans[1].Duration) - assert.Equal(t, test.tagSecondVal.String(), trace.Spans[1].Tags[0].VStr) + assert.Len(t, trc.Spans[1].Tags, 1) + assert.Equal(t, test.tagSecondKey, trc.Spans[1].Tags[0].Key) + assert.Equal(t, time.Duration(1000), trc.Spans[1].Duration) + assert.Equal(t, test.tagSecondVal.String(), trc.Spans[1].Tags[0].VStr) } } @@ -181,9 +181,9 @@ func loadZipkinSpans(t *testing.T, file string) []*z.Span { } func loadJaegerTrace(t *testing.T, file string) *model.Trace { - var trace model.Trace - loadJSONPB(t, file, &trace) - return &trace + var trc model.Trace + loadJSONPB(t, file, &trc) + return &trc } func loadJSONPB(t *testing.T, fileName string, obj proto.Message) { diff --git a/pkg/clientcfg/clientcfghttp/handler.go b/pkg/clientcfg/clientcfghttp/handler.go index 53b1632be16..6b885fffbe2 100644 --- a/pkg/clientcfg/clientcfghttp/handler.go +++ b/pkg/clientcfg/clientcfghttp/handler.go @@ -119,9 +119,9 @@ func (h *HTTPHandler) serviceFromRequest(w http.ResponseWriter, r *http.Request) return services[0], nil } -func (h *HTTPHandler) writeJSON(w http.ResponseWriter, json []byte) error { +func (h *HTTPHandler) writeJSON(w http.ResponseWriter, jsonData []byte) error { w.Header().Add("Content-Type", mimeTypeApplicationJSON) - if _, err := w.Write(json); err != nil { + if _, err := w.Write(jsonData); err != nil { h.metrics.WriteFailures.Inc(1) return err } @@ -213,8 +213,8 @@ var samplingStrategyTypes = []api_v2.SamplingStrategyType{ // // Thrift 0.9.3 classes generate this JSON: // {"strategyType":"PROBABILISTIC","probabilisticSampling":{"samplingRate":0.5}} -func (*HTTPHandler) encodeThriftEnums092(json []byte) []byte { - str := string(json) +func (*HTTPHandler) encodeThriftEnums092(jsonData []byte) []byte { + str := string(jsonData) for _, strategyType := range samplingStrategyTypes { str = strings.Replace( str, diff --git a/pkg/clientcfg/clientcfghttp/handler_test.go b/pkg/clientcfg/clientcfghttp/handler_test.go index 742f4275254..91e4c7da164 100644 --- a/pkg/clientcfg/clientcfghttp/handler_test.go +++ b/pkg/clientcfg/clientcfghttp/handler_test.go @@ -59,9 +59,9 @@ func withServer( handler.RegisterRoutes(r) server = httptest.NewServer(r) } else { - mux := http.NewServeMux() - handler.RegisterRoutesWithHTTP(mux) - server = httptest.NewServer(mux) + httpMux := http.NewServeMux() + handler.RegisterRoutesWithHTTP(httpMux) + server = httptest.NewServer(httpMux) } defer server.Close() diff --git a/pkg/fswatcher/fswatcher.go b/pkg/fswatcher/fswatcher.go index 25bf861d1ff..56695425df9 100644 --- a/pkg/fswatcher/fswatcher.go +++ b/pkg/fswatcher/fswatcher.go @@ -132,10 +132,10 @@ func (w *FSWatcher) Close() error { } // isModified returns true if the file has been modified since the last check. -func (w *FSWatcher) isModified(filepath string, previousHash string) (bool, string) { - hash, err := hashFile(filepath) +func (w *FSWatcher) isModified(filePathName string, previousHash string) (bool, string) { + hash, err := hashFile(filePathName) if err != nil { - w.logger.Warn("Unable to read the file", zap.String("file", filepath), zap.Error(err)) + w.logger.Warn("Unable to read the file", zap.String("file", filePathName), zap.Error(err)) return true, "" } return previousHash != hash, hash diff --git a/pkg/gzipfs/gzip.go b/pkg/gzipfs/gzip.go index 9cea457a78d..1d9c394a058 100644 --- a/pkg/gzipfs/gzip.go +++ b/pkg/gzipfs/gzip.go @@ -73,8 +73,8 @@ func (fileInfo) Sys() any { return nil } // New wraps underlying fs that is expected to contain gzipped files // and presents an unzipped view of it. -func New(fs fs.FS) fs.FS { - return fileSystem{fs} +func New(fileSys fs.FS) fs.FS { + return fileSystem{fileSys} } func (cfs fileSystem) Open(path string) (fs.File, error) { diff --git a/pkg/version/handler.go b/pkg/version/handler.go index 689d0c04af6..bb094af94a9 100644 --- a/pkg/version/handler.go +++ b/pkg/version/handler.go @@ -13,12 +13,12 @@ import ( // RegisterHandler registers version handler to /version func RegisterHandler(mu *http.ServeMux, logger *zap.Logger) { info := Get() - json, err := json.Marshal(info) + jsonData, err := json.Marshal(info) if err != nil { logger.Fatal("Could not get Jaeger version", zap.Error(err)) } mu.HandleFunc("/version", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) - w.Write(json) + w.Write(jsonData) }) } diff --git a/plugin/metrics/prometheus/metricsstore/reader_test.go b/plugin/metrics/prometheus/metricsstore/reader_test.go index 6dd467797cb..6ead7bb10ef 100644 --- a/plugin/metrics/prometheus/metricsstore/reader_test.go +++ b/plugin/metrics/prometheus/metricsstore/reader_test.go @@ -918,16 +918,16 @@ func buildTestBaseQueryParametersFrom(tc metricsTestCase) metricsstore.BaseQuery } } -func prepareMetricsReaderAndServer(t *testing.T, config config.Configuration, wantPromQlQuery string, wantWarnings []string, tracer trace.TracerProvider) (metricsstore.Reader, *httptest.Server) { +func prepareMetricsReaderAndServer(t *testing.T, cfg config.Configuration, wantPromQlQuery string, wantWarnings []string, tracer trace.TracerProvider) (metricsstore.Reader, *httptest.Server) { mockPrometheus := startMockPrometheusServer(t, wantPromQlQuery, wantWarnings) logger := zap.NewNop() address := mockPrometheus.Listener.Addr().String() - config.ServerURL = "http://" + address - config.ConnectTimeout = defaultTimeout + cfg.ServerURL = "http://" + address + cfg.ConnectTimeout = defaultTimeout - reader, err := NewMetricsReader(config, logger, tracer) + reader, err := NewMetricsReader(cfg, logger, tracer) require.NoError(t, err) return reader, mockPrometheus diff --git a/plugin/sampling/strategyprovider/adaptive/aggregator.go b/plugin/sampling/strategyprovider/adaptive/aggregator.go index 42ca182fbe3..e08ce275017 100644 --- a/plugin/sampling/strategyprovider/adaptive/aggregator.go +++ b/plugin/sampling/strategyprovider/adaptive/aggregator.go @@ -44,13 +44,13 @@ type aggregator struct { // NewAggregator creates a throughput aggregator that simply emits metrics // about the number of operations seen over the aggregationInterval. func NewAggregator(options Options, logger *zap.Logger, metricsFactory metrics.Factory, participant leaderelection.ElectionParticipant, store samplingstore.Store) (samplingstrategy.Aggregator, error) { - hostname, err := hostname.AsIdentifier() + hostId, err := hostname.AsIdentifier() if err != nil { return nil, err } - logger.Info("Using unique participantName in adaptive sampling", zap.String("participantName", hostname)) + logger.Info("Using unique participantName in adaptive sampling", zap.String("participantName", hostId)) - postAggregator, err := newPostAggregator(options, hostname, store, participant, metricsFactory, logger) + postAggregator, err := newPostAggregator(options, hostId, store, participant, metricsFactory, logger) if err != nil { return nil, err } diff --git a/plugin/sampling/strategyprovider/static/provider.go b/plugin/sampling/strategyprovider/static/provider.go index f02a4031a16..56890ed63c0 100644 --- a/plugin/sampling/strategyprovider/static/provider.go +++ b/plugin/sampling/strategyprovider/static/provider.go @@ -84,13 +84,13 @@ func NewProvider(options Options, logger *zap.Logger) (ss.Provider, error) { // GetSamplingStrategy implements StrategyStore#GetSamplingStrategy. func (h *samplingProvider) GetSamplingStrategy(_ context.Context, serviceName string) (*api_v2.SamplingStrategyResponse, error) { - ss := h.storedStrategies.Load().(*storedStrategies) - serviceStrategies := ss.serviceStrategies + storedStrategies := h.storedStrategies.Load().(*storedStrategies) + serviceStrategies := storedStrategies.serviceStrategies if strategy, ok := serviceStrategies[serviceName]; ok { return strategy, nil } h.logger.Debug("sampling strategy not found, using default", zap.String("service", serviceName)) - return ss.defaultStrategy, nil + return storedStrategies.defaultStrategy, nil } // Close stops updating the strategies @@ -99,12 +99,12 @@ func (h *samplingProvider) Close() error { return nil } -func (h *samplingProvider) downloadSamplingStrategies(url string) ([]byte, error) { - h.logger.Info("Downloading sampling strategies", zap.String("url", url)) +func (h *samplingProvider) downloadSamplingStrategies(samplingURL string) ([]byte, error) { + h.logger.Info("Downloading sampling strategies", zap.String("url", samplingURL)) ctx, cx := context.WithTimeout(context.Background(), time.Second) defer cx() - req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + req, err := http.NewRequestWithContext(ctx, "GET", samplingURL, nil) if err != nil { return nil, fmt.Errorf("cannot construct HTTP request: %w", err) } @@ -185,13 +185,13 @@ func (h *samplingProvider) reloadSamplingStrategy(loadFn strategyLoader, lastVal return string(newValue) } -func (h *samplingProvider) updateSamplingStrategy(bytes []byte) error { +func (h *samplingProvider) updateSamplingStrategy(dataBytes []byte) error { var strategies strategies - if err := json.Unmarshal(bytes, &strategies); err != nil { + if err := json.Unmarshal(dataBytes, &strategies); err != nil { return fmt.Errorf("failed to unmarshal sampling strategies: %w", err) } h.parseStrategies(&strategies) - h.logger.Info("Updated sampling strategies:" + string(bytes)) + h.logger.Info("Updated sampling strategies:" + string(dataBytes)) return nil } diff --git a/plugin/sampling/strategyprovider/static/provider_test.go b/plugin/sampling/strategyprovider/static/provider_test.go index d0248c681b5..7924989acb2 100644 --- a/plugin/sampling/strategyprovider/static/provider_test.go +++ b/plugin/sampling/strategyprovider/static/provider_test.go @@ -178,18 +178,18 @@ func TestPerOperationSamplingStrategies(t *testing.T) { assert.Equal(t, *expected.ProbabilisticSampling, *s.ProbabilisticSampling) require.NotNil(t, s.OperationSampling) - os := s.OperationSampling - assert.InDelta(t, 0.8, os.DefaultSamplingProbability, 0.01) - require.Len(t, os.PerOperationStrategies, 4) - - assert.Equal(t, "op6", os.PerOperationStrategies[0].Operation) - assert.InDelta(t, 0.5, os.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op1", os.PerOperationStrategies[1].Operation) - assert.InDelta(t, 0.2, os.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op0", os.PerOperationStrategies[2].Operation) - assert.InDelta(t, 0.2, os.PerOperationStrategies[2].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op7", os.PerOperationStrategies[3].Operation) - assert.InDelta(t, 1.0, os.PerOperationStrategies[3].ProbabilisticSampling.SamplingRate, 0.01) + opSampling := s.OperationSampling + assert.InDelta(t, 0.8, opSampling.DefaultSamplingProbability, 0.01) + require.Len(t, opSampling.PerOperationStrategies, 4) + + assert.Equal(t, "op6", opSampling.PerOperationStrategies[0].Operation) + assert.InDelta(t, 0.5, opSampling.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op1", opSampling.PerOperationStrategies[1].Operation) + assert.InDelta(t, 0.2, opSampling.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op0", opSampling.PerOperationStrategies[2].Operation) + assert.InDelta(t, 0.2, opSampling.PerOperationStrategies[2].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op7", opSampling.PerOperationStrategies[3].Operation) + assert.InDelta(t, 1.0, opSampling.PerOperationStrategies[3].ProbabilisticSampling.SamplingRate, 0.01) expected = makeResponse(api_v2.SamplingStrategyType_RATE_LIMITING, 5) @@ -199,19 +199,19 @@ func TestPerOperationSamplingStrategies(t *testing.T) { assert.Equal(t, *expected.RateLimitingSampling, *s.RateLimitingSampling) require.NotNil(t, s.OperationSampling) - os = s.OperationSampling - assert.InDelta(t, 0.001, os.DefaultSamplingProbability, 1e-4) - require.Len(t, os.PerOperationStrategies, 5) - assert.Equal(t, "op3", os.PerOperationStrategies[0].Operation) - assert.InDelta(t, 0.3, os.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op5", os.PerOperationStrategies[1].Operation) - assert.InDelta(t, 0.4, os.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op0", os.PerOperationStrategies[2].Operation) - assert.InDelta(t, 0.2, os.PerOperationStrategies[2].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op6", os.PerOperationStrategies[3].Operation) - assert.InDelta(t, 0.0, os.PerOperationStrategies[3].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op7", os.PerOperationStrategies[4].Operation) - assert.InDelta(t, 1.0, os.PerOperationStrategies[4].ProbabilisticSampling.SamplingRate, 0.01) + opSampling = s.OperationSampling + assert.InDelta(t, 0.001, opSampling.DefaultSamplingProbability, 1e-4) + require.Len(t, opSampling.PerOperationStrategies, 5) + assert.Equal(t, "op3", opSampling.PerOperationStrategies[0].Operation) + assert.InDelta(t, 0.3, opSampling.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op5", opSampling.PerOperationStrategies[1].Operation) + assert.InDelta(t, 0.4, opSampling.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op0", opSampling.PerOperationStrategies[2].Operation) + assert.InDelta(t, 0.2, opSampling.PerOperationStrategies[2].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op6", opSampling.PerOperationStrategies[3].Operation) + assert.InDelta(t, 0.0, opSampling.PerOperationStrategies[3].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op7", opSampling.PerOperationStrategies[4].Operation) + assert.InDelta(t, 1.0, opSampling.PerOperationStrategies[4].ProbabilisticSampling.SamplingRate, 0.01) s, err = provider.GetSamplingStrategy(context.Background(), "default") require.NoError(t, err) @@ -257,11 +257,11 @@ func TestMissingServiceSamplingStrategyTypes(t *testing.T) { assert.Equal(t, *expected.ProbabilisticSampling, *s.ProbabilisticSampling) require.NotNil(t, s.OperationSampling) - os := s.OperationSampling - assert.InDelta(t, defaultSamplingProbability, os.DefaultSamplingProbability, 1e-4) - require.Len(t, os.PerOperationStrategies, 1) - assert.Equal(t, "op1", os.PerOperationStrategies[0].Operation) - assert.InDelta(t, 0.2, os.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.001) + opSampling := s.OperationSampling + assert.InDelta(t, defaultSamplingProbability, opSampling.DefaultSamplingProbability, 1e-4) + require.Len(t, opSampling.PerOperationStrategies, 1) + assert.Equal(t, "op1", opSampling.PerOperationStrategies[0].Operation) + assert.InDelta(t, 0.2, opSampling.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.001) expected = makeResponse(api_v2.SamplingStrategyType_PROBABILISTIC, defaultSamplingProbability) @@ -271,13 +271,13 @@ func TestMissingServiceSamplingStrategyTypes(t *testing.T) { assert.Equal(t, *expected.ProbabilisticSampling, *s.ProbabilisticSampling) require.NotNil(t, s.OperationSampling) - os = s.OperationSampling - assert.InDelta(t, 0.001, os.DefaultSamplingProbability, 1e-4) - require.Len(t, os.PerOperationStrategies, 2) - assert.Equal(t, "op3", os.PerOperationStrategies[0].Operation) - assert.InDelta(t, 0.3, os.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) - assert.Equal(t, "op5", os.PerOperationStrategies[1].Operation) - assert.InDelta(t, 0.4, os.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) + opSampling = s.OperationSampling + assert.InDelta(t, 0.001, opSampling.DefaultSamplingProbability, 1e-4) + require.Len(t, opSampling.PerOperationStrategies, 2) + assert.Equal(t, "op3", opSampling.PerOperationStrategies[0].Operation) + assert.InDelta(t, 0.3, opSampling.PerOperationStrategies[0].ProbabilisticSampling.SamplingRate, 0.01) + assert.Equal(t, "op5", opSampling.PerOperationStrategies[1].Operation) + assert.InDelta(t, 0.4, opSampling.PerOperationStrategies[1].ProbabilisticSampling.SamplingRate, 0.01) s, err = provider.GetSamplingStrategy(context.Background(), "default") require.NoError(t, err) diff --git a/plugin/storage/badger/factory_test.go b/plugin/storage/badger/factory_test.go index 6190f1510b6..e1ac27567e8 100644 --- a/plugin/storage/badger/factory_test.go +++ b/plugin/storage/badger/factory_test.go @@ -185,11 +185,11 @@ func TestBadgerMetrics(t *testing.T) { func TestConfigure(t *testing.T) { f := NewFactory() - config := &Config{ + cfg := &Config{ MaintenanceInterval: 42 * time.Second, } - f.configure(config) - assert.Equal(t, config, f.Config) + f.configure(cfg) + assert.Equal(t, cfg, f.Config) } func TestBadgerStorageFactoryWithConfig(t *testing.T) { diff --git a/plugin/storage/badger/spanstore/rw_internal_test.go b/plugin/storage/badger/spanstore/rw_internal_test.go index 6b9dd965ca7..60828a8b80a 100644 --- a/plugin/storage/badger/spanstore/rw_internal_test.go +++ b/plugin/storage/badger/spanstore/rw_internal_test.go @@ -157,7 +157,7 @@ func createDummySpan() model.Span { } func TestMergeJoin(t *testing.T) { - assert := assert.New(t) + chk := assert.New(t) // Test equals @@ -173,19 +173,19 @@ func TestMergeJoin(t *testing.T) { } merged := mergeJoinIds(left, right) - assert.Len(merged, 16) + chk.Len(merged, 16) // Check order - assert.Equal(uint32(15), binary.BigEndian.Uint32(merged[15])) + chk.Equal(uint32(15), binary.BigEndian.Uint32(merged[15])) // Test simple non-equality different size merged = mergeJoinIds(left[1:2], right[13:]) - assert.Empty(merged) + chk.Empty(merged) // Different size, some equalities merged = mergeJoinIds(left[0:3], right[1:7]) - assert.Len(merged, 2) - assert.Equal(uint32(2), binary.BigEndian.Uint32(merged[1])) + chk.Len(merged, 2) + chk.Equal(uint32(2), binary.BigEndian.Uint32(merged[1])) } diff --git a/plugin/storage/cassandra/factory.go b/plugin/storage/cassandra/factory.go index 1f91a837010..4654a2a2c82 100644 --- a/plugin/storage/cassandra/factory.go +++ b/plugin/storage/cassandra/factory.go @@ -197,13 +197,13 @@ func (f *Factory) CreateArchiveSpanWriter() (spanstore.Writer, error) { // CreateLock implements storage.SamplingStoreFactory func (f *Factory) CreateLock() (distributedlock.Lock, error) { - hostname, err := hostname.AsIdentifier() + hostId, err := hostname.AsIdentifier() if err != nil { return nil, err } - f.logger.Info("Using unique participantName in the distributed lock", zap.String("participantName", hostname)) + f.logger.Info("Using unique participantName in the distributed lock", zap.String("participantName", hostId)) - return cLock.NewLock(f.primarySession, hostname), nil + return cLock.NewLock(f.primarySession, hostId), nil } // CreateSamplingStore implements storage.SamplingStoreFactory diff --git a/plugin/storage/cassandra/spanstore/reader.go b/plugin/storage/cassandra/spanstore/reader.go index fec886a6c73..88ba7b8f335 100644 --- a/plugin/storage/cassandra/spanstore/reader.go +++ b/plugin/storage/cassandra/spanstore/reader.go @@ -151,9 +151,9 @@ func (s *SpanReader) readTrace(ctx context.Context, traceID dbmodel.TraceID) (*m defer span.End() span.SetAttributes(attribute.Key("trace_id").String(traceID.String())) - trace, err := s.readTraceInSpan(ctx, traceID) + trc, err := s.readTraceInSpan(ctx, traceID) logErrorToSpan(span, err) - return trace, err + return trc, err } func (s *SpanReader) readTraceInSpan(_ context.Context, traceID dbmodel.TraceID) (*model.Trace, error) { diff --git a/plugin/storage/es/options.go b/plugin/storage/es/options.go index 01cb2ce8d19..1c4157f58eb 100644 --- a/plugin/storage/es/options.go +++ b/plugin/storage/es/options.go @@ -118,9 +118,9 @@ func NewOptions(primaryNamespace string, otherNamespaces ...string) *Options { return options } -func (config *namespaceConfig) getTLSFlagsConfig() tlscfg.ClientFlagsConfig { +func (cfg *namespaceConfig) getTLSFlagsConfig() tlscfg.ClientFlagsConfig { return tlscfg.ClientFlagsConfig{ - Prefix: config.namespace, + Prefix: cfg.namespace, } } diff --git a/plugin/storage/es/spanstore/reader.go b/plugin/storage/es/spanstore/reader.go index c9f2e07c830..084f1131028 100644 --- a/plugin/storage/es/spanstore/reader.go +++ b/plugin/storage/es/spanstore/reader.go @@ -444,8 +444,8 @@ func (s *SpanReader) multiRead(ctx context.Context, traceIDs []model.TraceID, st } var traces []*model.Trace - for _, trace := range tracesMap { - traces = append(traces, trace) + for _, t := range tracesMap { + traces = append(traces, t) } return traces, nil } diff --git a/plugin/storage/es/spanstore/service_operation.go b/plugin/storage/es/spanstore/service_operation.go index 1b4afc08e1c..d5bb428f6ee 100644 --- a/plugin/storage/es/spanstore/service_operation.go +++ b/plugin/storage/es/spanstore/service_operation.go @@ -66,7 +66,7 @@ func (s *ServiceOperationStorage) Write(indexName string, jsonSpan *dbmodel.Span } } -func (s *ServiceOperationStorage) getServices(context context.Context, indices []string, maxDocCount int) ([]string, error) { +func (s *ServiceOperationStorage) getServices(ctx context.Context, indices []string, maxDocCount int) ([]string, error) { serviceAggregation := getServicesAggregation(maxDocCount) searchService := s.client().Search(indices...). @@ -74,7 +74,7 @@ func (s *ServiceOperationStorage) getServices(context context.Context, indices [ IgnoreUnavailable(true). Aggregation(servicesAggregation, serviceAggregation) - searchResult, err := searchService.Do(context) + searchResult, err := searchService.Do(ctx) if err != nil { return nil, fmt.Errorf("search services failed: %w", es.DetailedError(err)) } @@ -95,7 +95,7 @@ func getServicesAggregation(maxDocCount int) elastic.Query { Size(maxDocCount) // ES deprecated size omission for aggregating all. https://github.com/elastic/elasticsearch/issues/18838 } -func (s *ServiceOperationStorage) getOperations(context context.Context, indices []string, service string, maxDocCount int) ([]string, error) { +func (s *ServiceOperationStorage) getOperations(ctx context.Context, indices []string, service string, maxDocCount int) ([]string, error) { serviceQuery := elastic.NewTermQuery(serviceName, service) serviceFilter := getOperationsAggregation(maxDocCount) @@ -105,7 +105,7 @@ func (s *ServiceOperationStorage) getOperations(context context.Context, indices IgnoreUnavailable(true). Aggregation(operationsAggregation, serviceFilter) - searchResult, err := searchService.Do(context) + searchResult, err := searchService.Do(ctx) if err != nil { return nil, fmt.Errorf("search operations failed: %w", es.DetailedError(err)) } diff --git a/plugin/storage/integration/integration.go b/plugin/storage/integration/integration.go index e66ff1693f2..40c98beebf1 100644 --- a/plugin/storage/integration/integration.go +++ b/plugin/storage/integration/integration.go @@ -409,8 +409,8 @@ func loadAndParseJSON(t *testing.T, path string, object any) { } // required, because we want to only query on recent traces, so we replace all the dates with recent dates. -func correctTime(json []byte) []byte { - jsonString := string(json) +func correctTime(jsonData []byte) []byte { + jsonString := string(jsonData) now := time.Now().UTC() yesterday := now.AddDate(0, 0, -1).Format("2006-01-02") twoDaysAgo := now.AddDate(0, 0, -2).Format("2006-01-02")