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

fix(tracing): Protect from concurrent reads/writes to Span Tags, Contexts, Data #609

Merged
merged 5 commits into from Apr 4, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions tracing.go
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"regexp"
"strings"
"sync"
"time"
)

Expand Down Expand Up @@ -37,6 +38,8 @@ type Span struct { //nolint: maligned // prefer readability over optimal memory
Sampled Sampled `json:"-"`
Source TransactionSource `json:"-"`

// mu protects concurrent writes to map fields
mu sync.RWMutex
// sample rate the span was sampled with.
sampleRate float64
// ctx is the context where the span was started. Always non-nil.
Expand Down Expand Up @@ -221,6 +224,9 @@ func (s *Span) StartChild(operation string, options ...SpanOption) *Span {
// accessing the tags map directly as SetTag takes care of initializing the map
// when necessary.
func (s *Span) SetTag(name, value string) {
s.mu.Lock()
defer s.mu.Unlock()

if s.Tags == nil {
s.Tags = make(map[string]string)
}
Expand All @@ -231,6 +237,9 @@ func (s *Span) SetTag(name, value string) {
// accessing the data map directly as SetData takes care of initializing the map
// when necessary.
func (s *Span) SetData(name, value string) {
s.mu.Lock()
defer s.mu.Unlock()

if s.Data == nil {
s.Data = make(map[string]interface{})
}
Expand All @@ -241,6 +250,9 @@ func (s *Span) SetData(name, value string) {
// accessing the contexts map directly as SetContext takes care of initializing the map
// when necessary.
func (s *Span) SetContext(key string, value Context) {
s.mu.Lock()
defer s.mu.Unlock()

if s.contexts == nil {
s.contexts = make(map[string]Context)
}
Expand Down Expand Up @@ -478,6 +490,9 @@ func (s *Span) sample() Sampled {
}

func (s *Span) toEvent() *Event {
s.mu.Lock()
defer s.mu.Unlock()

if !s.isTransaction {
return nil // only transactions can be transformed into events
}
Expand Down