Skip to content

Commit

Permalink
Solve panic due to concurrent access to ExportSpans
Browse files Browse the repository at this point in the history
Signed-off-by: Gahl Saraf <[email protected]>
  • Loading branch information
gsaraf committed Dec 29, 2022
1 parent e6f4ea0 commit afb01a7
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
22 changes: 16 additions & 6 deletions util/tracing/detect/detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,21 +73,31 @@ func detectExporter() (sdktrace.SpanExporter, error) {
return nil, nil
}

func detect() error {
tp = trace.NewNoopTracerProvider()

func getExporter() (sdktrace.SpanExporter, error) {
exp, err := detectExporter()
if err != nil {
return err
return nil, err
}

if exp != nil {
exp = &threadSafeExporterWrapper{
exporter: exp,
}
}

if Recorder != nil {
Recorder.SpanExporter = exp
exp = Recorder
}
return exp, nil
}

func detect() error {
tp = trace.NewNoopTracerProvider()

if exp == nil {
return nil
exp, err := getExporter()
if err != nil || exp == nil {
return err
}

// enable log with traceID when valid exporter
Expand Down
26 changes: 26 additions & 0 deletions util/tracing/detect/threadsafe.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package detect

import (
"context"
"sync"

sdktrace "go.opentelemetry.io/otel/sdk/trace"
)

// threadSafeExporterWrapper wraps an OpenTelemetry SpanExporter and makes it thread-safe.
type threadSafeExporterWrapper struct {
mu sync.Mutex
exporter sdktrace.SpanExporter
}

func (tse *threadSafeExporterWrapper) ExportSpans(ctx context.Context, spans []sdktrace.ReadOnlySpan) error {
tse.mu.Lock()
defer tse.mu.Unlock()
return tse.exporter.ExportSpans(ctx, spans)
}

func (tse *threadSafeExporterWrapper) Shutdown(ctx context.Context) error {
tse.mu.Lock()
defer tse.mu.Unlock()
return tse.exporter.Shutdown(ctx)
}

0 comments on commit afb01a7

Please sign in to comment.