dogstatsd: Drop metrics according to sample rate (#884)
Sample rate is for allowing to lower traffic generated by
the statsd packets so the observations need to be dropped.
statsd server will multiple the metrics with the inverse
of sample rate to compenstate.
Fixes #778
Martin Sucha authored 4 years ago
Peter Bourgon committed 4 years ago
13 | 13 | "context" |
14 | 14 | "fmt" |
15 | 15 | "io" |
16 | "math/rand" | |
16 | 17 | "strings" |
17 | 18 | "sync" |
18 | 19 | "sync/atomic" |
72 | 73 | d.rates.Set(name, sampleRate) |
73 | 74 | return &Counter{ |
74 | 75 | name: name, |
75 | obs: d.counters.Observe, | |
76 | obs: sampleObservations(d.counters.Observe, sampleRate), | |
76 | 77 | } |
77 | 78 | } |
78 | 79 | |
94 | 95 | d.rates.Set(name, sampleRate) |
95 | 96 | return &Timing{ |
96 | 97 | name: name, |
97 | obs: d.timings.Observe, | |
98 | obs: sampleObservations(d.timings.Observe, sampleRate), | |
98 | 99 | } |
99 | 100 | } |
100 | 101 | |
104 | 105 | d.rates.Set(name, sampleRate) |
105 | 106 | return &Histogram{ |
106 | 107 | name: name, |
107 | obs: d.histograms.Observe, | |
108 | obs: sampleObservations(d.histograms.Observe, sampleRate), | |
108 | 109 | } |
109 | 110 | } |
110 | 111 | |
238 | 239 | |
239 | 240 | type observeFunc func(name string, lvs lv.LabelValues, value float64) |
240 | 241 | |
242 | // sampleObservations returns a modified observeFunc that samples observations. | |
243 | func sampleObservations(obs observeFunc, sampleRate float64) observeFunc { | |
244 | if sampleRate >= 1 { | |
245 | return obs | |
246 | } | |
247 | return func(name string, lvs lv.LabelValues, value float64) { | |
248 | if rand.Float64() > sampleRate { | |
249 | return | |
250 | } | |
251 | obs(name, lvs, value) | |
252 | } | |
253 | } | |
254 | ||
241 | 255 | // Counter is a DogStatsD counter. Observations are forwarded to a Dogstatsd |
242 | 256 | // object, and aggregated (summed) per timeseries. |
243 | 257 | type Counter struct { |