Debian Codegraph @

samplers/probability/consistent/sampler.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package consistent provides a consistent probability based sampler.
5 package consistent // import "go.opentelemetry.io/contrib/samplers/probability/consistent"
6
7 import (
8 "fmt"
9 "math/bits"
10 "math/rand"
11 "sync"
12
13 "go.opentelemetry.io/otel"
14 sdktrace "go.opentelemetry.io/otel/sdk/trace"
15 "go.opentelemetry.io/otel/trace"
16 )
17
18 type (
19 // ProbabilityBasedOption is an option to the
20 // ConssitentProbabilityBased sampler.
21 ProbabilityBasedOption interface {
22 apply(*consistentProbabilityBasedConfig)
23 }
24
25 consistentProbabilityBasedConfig struct {
26 source rand.Source
27 }
28
29 consistentProbabilityBasedRandomSource struct {
30 rand.Source
31 }
32
33 consistentProbabilityBased struct {
34 // "LAC" is an abbreviation for the logarithm of
35 // adjusted count. Greater values have greater
36 // representivity, therefore lesser sampling
37 // probability.
38
39 // lowLAC is the lower-probability log-adjusted count
40 lowLAC uint8
41 // highLAC is the higher-probability log-adjusted
42 // count. except for the zero probability special
43 // case, highLAC == lowLAC - 1.
44 highLAC uint8
45 // lowProb is the probability that lowLAC should be used,
46 // in the interval (0, 1]. For exact powers of two and the
47 // special case of 0 probability, lowProb == 1.
48 lowProb float64
49
50 // lock protects rnd
51 lock sync.Mutex
52 rnd *rand.Rand
53 }
54 )
55
56 // WithRandomSource sets the source of the randomness used by the Sampler.
57 func WithRandomSource(source rand.Source) ProbabilityBasedOption {
58 return consistentProbabilityBasedRandomSource{source}
59 }
60
61 func (s consistentProbabilityBasedRandomSource) apply(cfg *consistentProbabilityBasedConfig) {
62 cfg.source = s.Source
63 }
64
65 // ProbabilityBased samples a given fraction of traces. Based on the
66 // OpenTelemetry specification, this Sampler supports only power-of-two
67 // fractions. When the input fraction is not a power of two, it will
68 // be rounded down.
69 // - Fractions >= 1 will always sample.
70 // - Fractions < 2^-62 are treated as zero.
71 //
72 // This Sampler sets the OpenTelemetry tracestate p-value and/or r-value.
73 //
74 // To respect the parent trace's `SampledFlag`, this sampler should be
75 // used as the root delegate of a `Parent` sampler.
76 func ProbabilityBased(fraction float64, opts ...ProbabilityBasedOption) sdktrace.Sampler {
77 cfg := consistentProbabilityBasedConfig{
78 source: rand.NewSource(rand.Int63()), //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) is ignored as this is not security-sensitive.
79 }
80 for _, opt := range opts {
81 opt.apply(&cfg)
82 }
83
84 if fraction < 0 {
85 fraction = 0
86 } else if fraction > 1 {
87 fraction = 1
88 }
89
90 lowLAC, highLAC, lowProb := splitProb(fraction)
91
92 return &consistentProbabilityBased{
93 lowLAC: lowLAC,
94 highLAC: highLAC,
95 lowProb: lowProb,
96 rnd: rand.New(cfg.source), //nolint:gosec // G404: Use of weak random number generator (math/rand instead of crypto/rand) is ignored as this is not security-sensitive.
97 }
98 }
99
100 func (cs *consistentProbabilityBased) newR() uint8 {
101 cs.lock.Lock()
102 defer cs.lock.Unlock()
103 return uint8(bits.LeadingZeros64(uint64(cs.rnd.Int63())) - 1) //nolint:gosec // Int63 returns an always positive number.
104 }
105
106 func (cs *consistentProbabilityBased) lowChoice() bool {
107 cs.lock.Lock()
108 defer cs.lock.Unlock()
109 return cs.rnd.Float64() < cs.lowProb
110 }
111
112 // ShouldSample implements "go.opentelemetry.io/otel/sdk/trace".Sampler.
113 func (cs *consistentProbabilityBased) ShouldSample(p sdktrace.SamplingParameters) sdktrace.SamplingResult {
114 psc := trace.SpanContextFromContext(p.ParentContext)
115
116 // Note: this ignores whether psc.IsValid() because this
117 // allows other otel trace state keys to pass through even
118 // for root decisions.
119 state := psc.TraceState()
120
121 otts, err := parseOTelTraceState(state.Get(traceStateKey), psc.IsSampled())
122 if err != nil {
123 // Note: a state.Insert(traceStateKey)
124 // follows, nothing else needs to be done here.
125 otel.Handle(err)
126 }
127
128 if !otts.hasRValue() {
129 otts.rvalue = cs.newR()
130 }
131
132 var decision sdktrace.SamplingDecision
133 var lac uint8
134
135 if cs.lowProb == 1 || cs.lowChoice() {
136 lac = cs.lowLAC
137 } else {
138 lac = cs.highLAC
139 }
140
141 if lac <= otts.rvalue {
142 decision = sdktrace.RecordAndSample
143 otts.pvalue = lac
144 } else {
145 decision = sdktrace.Drop
146 otts.pvalue = invalidValue
147 }
148
149 // Note: see the note in
150 // "go.opentelemetry.io/otel/trace".TraceState.Insert(). The
151 // error below is not a condition we're supposed to handle.
152 state, _ = state.Insert(traceStateKey, otts.serialize())
153
154 return sdktrace.SamplingResult{
155 Decision: decision,
156 Tracestate: state,
157 }
158 }
159
160 // Description returns "ProbabilityBased{%g}" with the configured probability.
161 func (cs *consistentProbabilityBased) Description() string {
162 var prob float64
163 if cs.lowLAC != pZeroValue {
164 prob = cs.lowProb * expToFloat64(-int(cs.lowLAC))
165 prob += (1 - cs.lowProb) * expToFloat64(-int(cs.highLAC))
166 }
167 return fmt.Sprintf("ProbabilityBased{%g}", prob)
168 }