This repository has been archived by the owner on May 23, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 287
/
sampler.go
337 lines (292 loc) Β· 9.72 KB
/
sampler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package jaeger
import (
"fmt"
"net/url"
"sync"
"time"
"github.com/uber/jaeger-client-go/thrift-gen/sampling"
"github.com/uber/jaeger-client-go/utils"
)
const defaultSamplingServerHostPort = "localhost:5778"
// Sampler decides whether a new trace should be sampled or not.
type Sampler interface {
// IsSampled decides whether a trace with given `id` should be sampled.
IsSampled(id uint64) bool
// Close does a clean shutdown of the sampler, stopping any background
// go-routines it may have started.
Close()
// Equal checks if the `other` sampler is functionally equivalent
// to this sampler.
Equal(other Sampler) bool
// getTags return a set of tags that can be used to identify the type of
// sampling that was applied to the root span. Most simple samplers
// would return two tags, sampler.type and sampler.param, similar to
// those use in the Configuration
getTags() []tag
}
// -----------------------
// ConstSampler is a sampler that always makes the same decision.
type ConstSampler struct {
Decision bool
tags []tag
}
// NewConstSampler creates a ConstSampler.
func NewConstSampler(sample bool) Sampler {
tags := []tag{
{key: SamplerTypeTagKey, value: SamplerTypeConst},
{key: SamplerParamTagKey, value: sample},
}
return &ConstSampler{Decision: sample, tags: tags}
}
// IsSampled implements IsSampled() of Sampler.
func (s *ConstSampler) IsSampled(id uint64) bool {
return s.Decision
}
// Close implements Close() of Sampler.
func (s *ConstSampler) Close() {
// nothing to do
}
// Equal implements Equal() of Sampler.
func (s *ConstSampler) Equal(other Sampler) bool {
if o, ok := other.(*ConstSampler); ok {
return s.Decision == o.Decision
}
return false
}
// Tags implements Tags of Sampler
func (s *ConstSampler) getTags() []tag {
return s.tags
}
// -----------------------
// ProbabilisticSampler is a sampler that randomly samples a certain percentage
// of traces.
type ProbabilisticSampler struct {
SamplingBoundary uint64
tags []tag
}
const maxRandomNumber = ^(uint64(1) << 63) // i.e. 0x7fffffffffffffff
// NewProbabilisticSampler creates a sampler that randomly samples a certain percentage of traces specified by the
// samplingRate, in the range between 0.0 and 1.0.
//
// It relies on the fact that new trace IDs are 63bit random numbers themselves, thus making the sampling decision
// without generating a new random number, but simply calculating if traceID < (samplingRate * 2^63).
func NewProbabilisticSampler(samplingRate float64) (Sampler, error) {
if samplingRate < 0.0 || samplingRate > 1.0 {
return nil, fmt.Errorf("Sampling Rate must be between 0.0 and 1.0, received %f", samplingRate)
}
tags := []tag{
{key: SamplerTypeTagKey, value: SamplerTypeProbabilistic},
{key: SamplerParamTagKey, value: samplingRate},
}
return &ProbabilisticSampler{
SamplingBoundary: uint64(float64(maxRandomNumber) * samplingRate),
tags: tags}, nil
}
// IsSampled implements IsSampled() of Sampler.
func (s *ProbabilisticSampler) IsSampled(id uint64) bool {
return s.SamplingBoundary >= id
}
// Close implements Close() of Sampler.
func (s *ProbabilisticSampler) Close() {
// nothing to do
}
// Equal implements Equal() of Sampler.
func (s *ProbabilisticSampler) Equal(other Sampler) bool {
if o, ok := other.(*ProbabilisticSampler); ok {
return s.SamplingBoundary == o.SamplingBoundary
}
return false
}
// Tags implements Tags of Sampler
func (s *ProbabilisticSampler) getTags() []tag {
return s.tags
}
// -----------------------
type rateLimitingSampler struct {
maxTracesPerSecond float64
rateLimiter utils.RateLimiter
tags []tag
}
// NewRateLimitingSampler creates a sampler that samples at most maxTracesPerSecond. The distribution of sampled
// traces follows burstiness of the service, i.e. a service with uniformly distributed requests will have those
// requests sampled uniformly as well, but if requests are bursty, especially sub-second, then a number of
// sequential requests can be sampled each second.
func NewRateLimitingSampler(maxTracesPerSecond float64) (Sampler, error) {
tags := []tag{
{key: SamplerTypeTagKey, value: SamplerTypeRateLimiting},
{key: SamplerParamTagKey, value: maxTracesPerSecond},
}
return &rateLimitingSampler{
maxTracesPerSecond: maxTracesPerSecond,
rateLimiter: utils.NewRateLimiter(maxTracesPerSecond),
tags: tags,
}, nil
}
// IsSampled implements IsSampled() of Sampler.
func (s *rateLimitingSampler) IsSampled(id uint64) bool {
return s.rateLimiter.CheckCredit(1.0)
}
func (s *rateLimitingSampler) Close() {
// nothing to do
}
func (s *rateLimitingSampler) Equal(other Sampler) bool {
if o, ok := other.(*rateLimitingSampler); ok {
return s.maxTracesPerSecond == o.maxTracesPerSecond
}
return false
}
// Tags implements Tags of Sampler
func (s *rateLimitingSampler) getTags() []tag {
return s.tags
}
// -----------------------
// RemotelyControlledSampler is a delegating sampler that polls a remote server
// for the appropriate sampling strategy, constructs a corresponding sampler and
// delegates to it for sampling decisions.
type RemotelyControlledSampler struct {
sync.RWMutex
serviceName string
manager sampling.SamplingManager
logger Logger
timer *time.Ticker
sampler Sampler
pollStopped sync.WaitGroup
metrics Metrics
}
type httpSamplingManager struct {
serverURL string
}
func (s *httpSamplingManager) GetSamplingStrategy(serviceName string) (*sampling.SamplingStrategyResponse, error) {
var out sampling.SamplingStrategyResponse
v := url.Values{}
v.Set("service", serviceName)
if err := utils.GetJSON(s.serverURL+"/?"+v.Encode(), &out); err != nil {
return nil, err
}
return &out, nil
}
// NewRemotelyControlledSampler creates a sampler that periodically pulls
// the sampling strategy from an HTTP sampling server (e.g. jaeger-agent).
func NewRemotelyControlledSampler(
serviceName string,
initial Sampler,
hostPort string,
metrics *Metrics,
logger Logger,
) *RemotelyControlledSampler {
if hostPort == "" {
hostPort = defaultSamplingServerHostPort
}
manager := &httpSamplingManager{serverURL: "http://" + hostPort}
if logger == nil {
logger = NullLogger
}
sampler := &RemotelyControlledSampler{
serviceName: serviceName,
manager: manager,
logger: logger,
metrics: *metrics,
timer: time.NewTicker(1 * time.Minute),
}
if initial != nil {
sampler.sampler = initial
} else {
sampler.sampler, _ = NewProbabilisticSampler(0.001)
}
go sampler.pollController()
return sampler
}
// IsSampled implements IsSampled() of Sampler.
func (s *RemotelyControlledSampler) IsSampled(id uint64) bool {
s.RLock()
defer s.RUnlock()
return s.sampler.IsSampled(id)
}
// Close implements Close() of Sampler.
func (s *RemotelyControlledSampler) Close() {
s.RLock()
s.timer.Stop()
s.RUnlock()
s.pollStopped.Wait()
}
// Tags implements Tags of Sampler
func (s *RemotelyControlledSampler) getTags() []tag {
s.RLock()
defer s.RUnlock()
return s.sampler.getTags()
}
// Equal implements Equal() of Sampler.
func (s *RemotelyControlledSampler) Equal(other Sampler) bool {
if o, ok := other.(*RemotelyControlledSampler); ok {
s.RLock()
o.RLock()
defer s.RUnlock()
defer o.RUnlock()
return s.sampler.Equal(o.sampler)
}
return false
}
func (s *RemotelyControlledSampler) pollController() {
// in unit tests we re-assign the timer Ticker, so need to lock to avoid data races
s.Lock()
timer := s.timer
s.Unlock()
for range timer.C {
s.updateSampler()
}
s.pollStopped.Add(1)
}
func (s *RemotelyControlledSampler) updateSampler() {
if res, err := s.manager.GetSamplingStrategy(s.serviceName); err == nil {
if sampler, err := s.extractSampler(res); err == nil {
s.metrics.SamplerRetrieved.Inc(1)
if !s.sampler.Equal(sampler) {
s.Lock()
s.sampler = sampler
s.Unlock()
s.metrics.SamplerUpdated.Inc(1)
}
} else {
s.metrics.SamplerParsingFailure.Inc(1)
s.logger.Infof("Unable to handle sampling strategy response %+v. Got error: %v", res, err)
}
} else {
s.metrics.SamplerQueryFailure.Inc(1)
}
}
func (s *RemotelyControlledSampler) extractSampler(res *sampling.SamplingStrategyResponse) (Sampler, error) {
if probabilistic := res.GetProbabilisticSampling(); probabilistic != nil {
sampler, err := NewProbabilisticSampler(probabilistic.SamplingRate)
if err != nil {
return nil, err
}
return sampler, nil
}
if rateLimiting := res.GetRateLimitingSampling(); rateLimiting != nil {
sampler, err := NewRateLimitingSampler(float64(rateLimiting.MaxTracesPerSecond))
if err != nil {
return nil, err
}
return sampler, nil
}
return nil, fmt.Errorf("Unsupported sampling strategy type %v", res.GetStrategyType())
}