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

Update tracer to guard for a nil ctx #3110

15 changes: 15 additions & 0 deletions sdk/trace/trace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,21 @@ func TestStartSpanWithParent(t *testing.T) {
}
}

// Test we get a successful span as a new root if a nil context is sent in, as opposed to a panic.
// See https://github.com/open-telemetry/opentelemetry-go/issues/3109
func TestStartSpanWithNilContext(t *testing.T) {
alwaysSampleTp := NewTracerProvider()
sampledTr := alwaysSampleTp.Tracer("AlwaysSampled")

defer func() {
if r := recover(); r != nil {
t.Error("unexpected panic creating span with nil context")
}
}()
//nolint // no nil context, but that's the point of the test
wildefires marked this conversation as resolved.
Show resolved Hide resolved
sampledTr.Start(nil, "should-not-panic")
}

func TestStartSpanNewRootNotSampled(t *testing.T) {
alwaysSampleTp := NewTracerProvider()
sampledTr := alwaysSampleTp.Tracer("AlwaysSampled")
Expand Down
5 changes: 5 additions & 0 deletions sdk/trace/tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ var _ trace.Tracer = &tracer{}
func (tr *tracer) Start(ctx context.Context, name string, options ...trace.SpanStartOption) (context.Context, trace.Span) {
config := trace.NewSpanStartConfig(options...)

// If ctx is nil, set to context.Background() as context.WithValue will panic on a nil value.
if ctx == nil {
ctx = context.Background()
wildefires marked this conversation as resolved.
Show resolved Hide resolved
}

// For local spans created by this SDK, track child span count.
if p := trace.SpanFromContext(ctx); p != nil {
if sdkSpan, ok := p.(*recordingSpan); ok {
Expand Down