Skip to content
This repository has been archived by the owner on Jul 31, 2023. It is now read-only.

Defer IDGenerator initialization until first use #1228

Merged
merged 1 commit into from Oct 6, 2020
Merged
Changes from all 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
35 changes: 23 additions & 12 deletions trace/trace.go
Expand Up @@ -206,6 +206,10 @@ func startSpanInternal(name string, hasParent bool, parent SpanContext, remotePa
span.spanContext = parent

cfg := config.Load().(*Config)
if gen, ok := cfg.IDGenerator.(*defaultIDGenerator); ok {
// lazy initialization
gen.init()
}

if !hasParent {
span.spanContext.TraceID = cfg.IDGenerator.NewTraceID()
Expand Down Expand Up @@ -534,20 +538,9 @@ func (s *Span) String() string {
var config atomic.Value // access atomically

func init() {
gen := &defaultIDGenerator{}
// initialize traceID and spanID generators.
var rngSeed int64
for _, p := range []interface{}{
&rngSeed, &gen.traceIDAdd, &gen.nextSpanID, &gen.spanIDInc,
} {
binary.Read(crand.Reader, binary.LittleEndian, p)
}
gen.traceIDRand = rand.New(rand.NewSource(rngSeed))
gen.spanIDInc |= 1

config.Store(&Config{
DefaultSampler: ProbabilitySampler(defaultSamplingProbability),
IDGenerator: gen,
IDGenerator: &defaultIDGenerator{},
MaxAttributesPerSpan: DefaultMaxAttributesPerSpan,
MaxAnnotationEventsPerSpan: DefaultMaxAnnotationEventsPerSpan,
MaxMessageEventsPerSpan: DefaultMaxMessageEventsPerSpan,
Expand All @@ -571,6 +564,24 @@ type defaultIDGenerator struct {

traceIDAdd [2]uint64
traceIDRand *rand.Rand

initOnce sync.Once
}

// init initializes the generator on the first call to avoid consuming entropy
// unnecessarily.
func (gen *defaultIDGenerator) init() {
gen.initOnce.Do(func() {
// initialize traceID and spanID generators.
var rngSeed int64
for _, p := range []interface{}{
&rngSeed, &gen.traceIDAdd, &gen.nextSpanID, &gen.spanIDInc,
} {
binary.Read(crand.Reader, binary.LittleEndian, p)
}
gen.traceIDRand = rand.New(rand.NewSource(rngSeed))
gen.spanIDInc |= 1
})
}

// NewSpanID returns a non-zero span ID from a randomly-chosen sequence.
Expand Down