Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable lint revive Rule: unchecked-type-assertion #5516

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,7 @@ linters-settings:
- name: var-naming
disabled: true
# could be useful to catch issues, but needs a clean-up and some ignores
- name: unchecked-type-assertion
disabled: true

# wtf: "you have exceeded the maximum number of public struct declarations"
- name: max-public-structs
disabled: true
Expand Down
13 changes: 11 additions & 2 deletions cmd/agent/app/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ func NewAgent(

// GetHTTPRouter returns Gorilla HTTP router used by the agent's HTTP server.
func (a *Agent) GetHTTPRouter() *mux.Router {
return a.httpServer.Handler.(*mux.Router)
router, ok := a.httpServer.Handler.(*mux.Router)
if !ok {
// Handle the case where the type assertion fails gracefully
return nil // Or return a default router, or log an error and return
}
return router
}

// Run runs all of agent UDP and HTTP servers in separate go-routines.
Expand Down Expand Up @@ -84,7 +89,11 @@ func (a *Agent) Run() error {

// HTTPAddr returns the address that HTTP server is listening on
func (a *Agent) HTTPAddr() string {
return a.httpAddr.Load().(string)
addr, ok := a.httpAddr.Load().(string)
if !ok {
return ""
}
return addr
}

// Stop forces all agent go routines to exit.
Expand Down
5 changes: 4 additions & 1 deletion cmd/agent/app/processors/thrift_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ func (s *ThriftProcessor) Stop() {
// the processor to process
func (s *ThriftProcessor) processBuffer() {
for readBuf := range s.server.DataChan() {
protocol := s.protocolPool.Get().(thrift.TProtocol)
protocol, ok := s.protocolPool.Get().(thrift.TProtocol)
if !ok {
return
}
payload := readBuf.GetBytes()
protocol.Transport().Write(payload)
s.logger.Debug("Span(s) received by the agent", zap.Int("bytes-received", len(payload)))
Expand Down
10 changes: 8 additions & 2 deletions cmd/agent/app/reporter/client_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,10 @@ func (r *ClientMetricsReporter) expireClientMetricsLoop() {
func (r *ClientMetricsReporter) expireClientMetrics(t time.Time) {
var size int64
r.lastReceivedClientStats.Range(func(k, v any) bool {
stats := v.(*lastReceivedClientStats)
stats, ok := v.(*lastReceivedClientStats)
if !ok {
return false
}
stats.lock.Lock()
defer stats.lock.Unlock()

Expand Down Expand Up @@ -179,7 +182,10 @@ func (r *ClientMetricsReporter) updateClientMetrics(batch *jaeger.Batch) {
}
entry = ent
}
clientStats := entry.(*lastReceivedClientStats)
clientStats, ok := entry.(*lastReceivedClientStats)
if !ok {
return
}
clientStats.update(*batch.SeqNo, batch.Stats, r.clientMetrics)
}

Expand Down
6 changes: 5 additions & 1 deletion cmd/agent/app/reporter/connect_metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@ func NewConnectMetrics(mf metrics.Factory) *ConnectMetrics {
if r := expvar.Get("gRPCTarget"); r == nil {
cm.target = expvar.NewString("gRPCTarget")
} else {
cm.target = r.(*expvar.String)
str, ok := r.(*expvar.String)
if !ok {
return nil
}
cm.target = str
}

return cm
Expand Down
5 changes: 4 additions & 1 deletion cmd/agent/app/servers/tbuffered_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,10 @@ func (s *TBufferedServer) Serve() {
}

for s.IsServing() {
readBuf := s.readBufPool.Get().(*ReadBuf)
readBuf, ok := s.readBufPool.Get().(*ReadBuf)
if !ok {
return
}
n, err := s.transport.Read(readBuf.bytes)
if err == nil {
readBuf.n = n
Expand Down
6 changes: 5 additions & 1 deletion cmd/collector/app/handler/otlp_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package handler

import (
"context"
"errors"
"fmt"

otlp2jaeger "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/translator/jaeger"
Expand Down Expand Up @@ -69,7 +70,10 @@ func startOTLPReceiver(
createTracesReceiver func(ctx context.Context, set receiver.CreateSettings,
cfg component.Config, nextConsumer consumer.Traces) (receiver.Traces, error),
) (receiver.Traces, error) {
otlpReceiverConfig := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)
otlpReceiverConfig, ok := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)
if !ok {
return nil, errors.New("type assertion to *otlpreceiver.Config failed")
}
applyGRPCSettings(otlpReceiverConfig.GRPC, &options.OTLP.GRPC)
applyHTTPSettings(otlpReceiverConfig.HTTP.ServerConfig, &options.OTLP.HTTP)
statusReporter := func(ev *component.StatusEvent) {
Expand Down
12 changes: 8 additions & 4 deletions cmd/collector/app/handler/otlp_receiver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,10 @@ func TestOtelHost(t *testing.T) {

func TestApplyOTLPGRPCServerSettings(t *testing.T) {
otlpFactory := otlpreceiver.NewFactory()
otlpReceiverConfig := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)

otlpReceiverConfig, ok := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)
if !ok {
t.Fatal("Type assertion to *otlpreceiver.Config failed")
}
grpcOpts := &flags.GRPCOptions{
HostPort: ":54321",
MaxReceiveMessageLength: 42 * 1024 * 1024,
Expand Down Expand Up @@ -194,8 +196,10 @@ func TestApplyOTLPGRPCServerSettings(t *testing.T) {

func TestApplyOTLPHTTPServerSettings(t *testing.T) {
otlpFactory := otlpreceiver.NewFactory()
otlpReceiverConfig := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)

otlpReceiverConfig, ok := otlpFactory.CreateDefaultConfig().(*otlpreceiver.Config)
if !ok {
t.Fatal("Type assertion to *otlpreceiver.Config failed")
}
httpOpts := &flags.HTTPOptions{
HostPort: ":12345",
TLS: tlscfg.Options{
Expand Down
7 changes: 6 additions & 1 deletion cmd/collector/app/handler/zipkin_receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package handler

import (
"context"
"errors"
"fmt"

"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/zipkinreceiver"
Expand Down Expand Up @@ -53,7 +54,11 @@ func startZipkinReceiver(
createTracesReceiver func(ctx context.Context, set receiver.CreateSettings,
cfg component.Config, nextConsumer consumer.Traces) (receiver.Traces, error),
) (receiver.Traces, error) {
receiverConfig := zipkinFactory.CreateDefaultConfig().(*zipkinreceiver.Config)
receiverConfig, ok := zipkinFactory.CreateDefaultConfig().(*zipkinreceiver.Config)
if !ok {
return nil, errors.New("type assertion to *zipkinreceiver.Config failed")
}

applyHTTPSettings(&receiverConfig.ServerConfig, &flags.HTTPOptions{
HostPort: options.Zipkin.HTTPHostPort,
TLS: options.Zipkin.TLS,
Expand Down
5 changes: 4 additions & 1 deletion cmd/collector/app/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,10 @@ func (m *spanCountsBySvc) countByServiceName(serviceName string, isDebug bool) {
}

func (m *traceCountsBySvc) buildKey(serviceName, samplerType string) string {
keyBuilder := m.stringBuilderPool.Get().(*strings.Builder)
keyBuilder, ok := m.stringBuilderPool.Get().(*strings.Builder)
if !ok {
return ""
}
keyBuilder.Reset()
keyBuilder.WriteString(serviceName)
keyBuilder.WriteString(concatenation)
Expand Down
5 changes: 4 additions & 1 deletion cmd/collector/app/span_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ func NewSpanProcessor(
sp := newSpanProcessor(spanWriter, additional, opts...)

sp.queue.StartConsumers(sp.numWorkers, func(item any) {
value := item.(*queueItem)
value, ok := item.(*queueItem)
if !ok {
return
}
sp.processItemFromQueue(value)
})

Expand Down
24 changes: 14 additions & 10 deletions cmd/collector/app/span_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,8 +245,8 @@ func makeJaegerSpan(service string, rootSpan bool, debugEnabled bool) (*jaeger.S

func TestSpanProcessor(t *testing.T) {
w := &fakeSpanWriter{}
p := NewSpanProcessor(w, nil, Options.QueueSize(1)).(*spanProcessor)

p, ok := NewSpanProcessor(w, nil, Options.QueueSize(1)).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessor failed")
res, err := p.ProcessSpans(
[]*model.Span{{}}, // empty span should be enriched by sanitizers
processor.SpansOptions{SpanFormat: processor.JaegerSpanFormat})
Expand All @@ -266,13 +266,13 @@ func TestSpanProcessorErrors(t *testing.T) {
mb := metricstest.NewFactory(time.Hour)
defer mb.Backend.Stop()
serviceMetrics := mb.Namespace(metrics.NSOptions{Name: "service", Tags: nil})
p := NewSpanProcessor(w,
p, ok := NewSpanProcessor(w,
nil,
Options.Logger(logger),
Options.ServiceMetrics(serviceMetrics),
Options.QueueSize(1),
).(*spanProcessor)

require.True(t, ok, "Type assertion to *spanProcessor failed")
res, err := p.ProcessSpans([]*model.Span{
{
Process: &model.Process{
Expand Down Expand Up @@ -312,12 +312,13 @@ func (w *blockingWriter) WriteSpan(ctx context.Context, span *model.Span) error

func TestSpanProcessorBusy(t *testing.T) {
w := &blockingWriter{}
p := NewSpanProcessor(w,
p, ok := NewSpanProcessor(w,
nil,
Options.NumWorkers(1),
Options.QueueSize(1),
Options.ReportBusy(true),
).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessor failed")
defer require.NoError(t, p.Close())

// block the writer so that the first span is read from the queue and blocks the processor,
Expand Down Expand Up @@ -353,7 +354,8 @@ func TestSpanProcessorWithNilProcess(t *testing.T) {
serviceMetrics := mb.Namespace(metrics.NSOptions{Name: "service", Tags: nil})

w := &fakeSpanWriter{}
p := NewSpanProcessor(w, nil, Options.ServiceMetrics(serviceMetrics)).(*spanProcessor)
p, ok := NewSpanProcessor(w, nil, Options.ServiceMetrics(serviceMetrics)).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessor failed")
defer require.NoError(t, p.Close())

p.saveSpan(&model.Span{}, "")
Expand All @@ -372,8 +374,8 @@ func TestSpanProcessorWithCollectorTags(t *testing.T) {
}

w := &fakeSpanWriter{}
p := NewSpanProcessor(w, nil, Options.CollectorTags(testCollectorTags)).(*spanProcessor)

p, ok := NewSpanProcessor(w, nil, Options.CollectorTags(testCollectorTags)).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessor failed")
defer require.NoError(t, p.Close())
span := &model.Span{
Process: model.NewProcess("unit-test-service", []model.KeyValue{
Expand Down Expand Up @@ -461,7 +463,8 @@ func TestSpanProcessorCountSpan(t *testing.T) {
} else {
opts = append(opts, Options.DynQueueSizeMemory(0))
}
p := NewSpanProcessor(w, nil, opts...).(*spanProcessor)
p, ok := NewSpanProcessor(w, nil, opts...).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessorfailed")
defer func() {
require.NoError(t, p.Close())
}()
Expand Down Expand Up @@ -685,13 +688,14 @@ func TestSpanProcessorWithOnDroppedSpanOption(t *testing.T) {
}

w := &blockingWriter{}
p := NewSpanProcessor(w,
p, ok := NewSpanProcessor(w,
nil,
Options.NumWorkers(1),
Options.QueueSize(1),
Options.OnDroppedSpan(customOnDroppedSpan),
Options.ReportBusy(true),
).(*spanProcessor)
require.True(t, ok, "Type assertion to *spanProcessor failed")
defer p.Close()

// Acquire the lock externally to force the writer to block.
Expand Down
5 changes: 4 additions & 1 deletion cmd/es-rollover/app/init/action.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ func createIndexIfNotExist(c client.IndexAPI, index string) error {
// return unmarshal error
return err
}
errorMap := jsonError["error"].(map[string]any)
errorMap, ok := jsonError["error"].(map[string]any)
if !ok {
return errors.New("type assertion to map[string]any failed")
}
// check for reason, ignore already exist error
if strings.Contains(errorMap["type"].(string), "resource_already_exists_exception") {
return nil
Expand Down
3 changes: 2 additions & 1 deletion cmd/ingester/app/processor/span_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ func TestSpanProcessor_Process(t *testing.T) {
mockWriter.On("WriteSpan", context.TODO(), span).
Return(nil).
Run(func(args mock.Arguments) {
span := args[1].(*model.Span)
span, ok := args[1].(*model.Span)
require.True(t, ok, "type assertion to *model.Span failed")
assert.NotNil(t, span.Process, "sanitizer must fix Process=nil data issue")
})

Expand Down
3 changes: 2 additions & 1 deletion cmd/internal/flags/admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ func TestAdminServerHandlesPortZero(t *testing.T) {
assert.Equal(t, 1, message.Len(), "Expected Admin server started log message.")

onlyEntry := message.All()[0]
hostPort := onlyEntry.ContextMap()["http.host-port"].(string)
hostPort, ok := onlyEntry.ContextMap()["http.host-port"].(string)
require.True(t, ok, "Type assertion to string failed")
port, _ := strconv.Atoi(strings.Split(hostPort, ":")[3])
assert.Greater(t, port, 0)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ func (storageHost) GetExporters() map[component.DataType]map[component.ID]compon
}

func TestExporterConfigError(t *testing.T) {
config := createDefaultConfig().(*Config)
config, ok := createDefaultConfig().(*Config)
require.True(t, ok, "Type assertion to *Config failed")
err := config.Validate()
require.EqualError(t, err, "TraceStorage: non zero value required")
}
Expand Down
6 changes: 5 additions & 1 deletion cmd/jaeger/internal/exporters/storageexporter/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package storageexporter

import (
"context"
"errors"

"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/config/configretry"
Expand Down Expand Up @@ -33,7 +34,10 @@ func createDefaultConfig() component.Config {
}

func createTracesExporter(ctx context.Context, set exporter.CreateSettings, config component.Config) (exporter.Traces, error) {
cfg := config.(*Config)
cfg, ok := config.(*Config)
if !ok {
return nil, errors.New("type assertion to *Config failed")
}
ex := newExporter(cfg, set.TelemetrySettings)
return exporterhelper.NewTracesExporter(ctx, set, cfg,
ex.pushTraces,
Expand Down
5 changes: 4 additions & 1 deletion cmd/jaeger/internal/extension/jaegerstorage/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@
}

func (cfg *Config) Validate() error {
emptyCfg := createDefaultConfig().(*Config)
emptyCfg, ok := createDefaultConfig().(*Config)
if !ok {
return fmt.Errorf("type assertion to *Config failed")

Check warning on line 38 in cmd/jaeger/internal/extension/jaegerstorage/config.go

View check run for this annotation

Codecov / codecov/patch

cmd/jaeger/internal/extension/jaegerstorage/config.go#L36-L38

Added lines #L36 - L38 were not covered by tests
}
if reflect.DeepEqual(*cfg, *emptyCfg) {
return fmt.Errorf("%s: no storage type present in config", ID)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ func (e errorFactory) Close() error {
}

func TestStorageExtensionConfigError(t *testing.T) {
config := createDefaultConfig().(*Config)
config, ok := createDefaultConfig().(*Config)
require.True(t, ok, "Type assertion to *Config failed")
err := config.Validate()
require.ErrorContains(t, err, "no storage type present in config")
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/jaeger/internal/integration/e2e_integration.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ func createStorageCleanerConfig(t *testing.T, configFile string, storage string)
require.True(t, ok)
query, ok := extensions["jaeger_query"].(map[string]any)
require.True(t, ok)
trace_storage := query["trace_storage"].(string)
trace_storage, ok := query["trace_storage"].(string)
require.True(t, ok)
extensions["storage_cleaner"] = map[string]string{"trace_storage": trace_storage}

jaegerStorage, ok := extensions["jaeger_storage"].(map[string]any)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package storagereceiver

import (
"context"
"errors"

"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
Expand All @@ -30,7 +31,9 @@ func createDefaultConfig() component.Config {
}

func createTracesReceiver(ctx context.Context, set receiver.CreateSettings, config component.Config, nextConsumer consumer.Traces) (receiver.Traces, error) {
cfg := config.(*Config)

cfg, ok := config.(*Config)
if !ok {
return nil, errors.New("Type assertion to *Config failed")
}
return newTracesReceiver(cfg, set, nextConsumer)
}
Loading
Loading