/
rules.go
391 lines (358 loc) · 9.59 KB
/
rules.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package sample
import (
"encoding/json"
"math/rand"
"strings"
"github.com/honeycombio/refinery/config"
"github.com/honeycombio/refinery/logger"
"github.com/honeycombio/refinery/metrics"
"github.com/honeycombio/refinery/types"
"github.com/tidwall/gjson"
)
type RulesBasedSampler struct {
Config *config.RulesBasedSamplerConfig
Logger logger.Logger
Metrics metrics.Metrics
samplers map[string]Sampler
}
func (s *RulesBasedSampler) Start() error {
s.Logger.Debug().Logf("Starting RulesBasedSampler")
defer func() { s.Logger.Debug().Logf("Finished starting RulesBasedSampler") }()
s.Metrics.Register("rulessampler_num_dropped", "counter")
s.Metrics.Register("rulessampler_num_kept", "counter")
s.Metrics.Register("rulessampler_sample_rate", "histogram")
s.samplers = make(map[string]Sampler)
// Check if any rule has a downstream sampler and create it
for _, rule := range s.Config.Rule {
for _, cond := range rule.Condition {
if err := cond.Init(); err != nil {
s.Logger.Debug().WithFields(map[string]interface{}{
"rule_name": rule.Name,
"condition": cond.String(),
}).Logf("error creating rule evaluation function: %s", err)
continue
}
}
if rule.Sampler != nil {
var sampler Sampler
if rule.Sampler.DynamicSampler != nil {
sampler = &DynamicSampler{Config: rule.Sampler.DynamicSampler, Logger: s.Logger, Metrics: s.Metrics}
} else if rule.Sampler.EMADynamicSampler != nil {
sampler = &EMADynamicSampler{Config: rule.Sampler.EMADynamicSampler, Logger: s.Logger, Metrics: s.Metrics}
} else if rule.Sampler.TotalThroughputSampler != nil {
sampler = &TotalThroughputSampler{Config: rule.Sampler.TotalThroughputSampler, Logger: s.Logger, Metrics: s.Metrics}
} else {
s.Logger.Debug().WithFields(map[string]interface{}{
"rule_name": rule.Name,
}).Logf("invalid or missing downstream sampler")
continue
}
err := sampler.Start()
if err != nil {
s.Logger.Debug().WithFields(map[string]interface{}{
"rule_name": rule.Name,
}).Logf("error creating downstream sampler: %s", err)
continue
}
s.samplers[rule.String()] = sampler
}
}
return nil
}
func (s *RulesBasedSampler) GetSampleRate(trace *types.Trace) (rate uint, keep bool, reason string) {
logger := s.Logger.Debug().WithFields(map[string]interface{}{
"trace_id": trace.TraceID,
})
for _, rule := range s.Config.Rule {
var matched bool
var reason string
switch rule.Scope {
case "span":
matched = ruleMatchesSpanInTrace(trace, rule, s.Config.CheckNestedFields)
reason = "rules/span/"
case "trace", "":
matched = ruleMatchesTrace(trace, rule, s.Config.CheckNestedFields)
reason = "rules/trace/"
default:
logger.WithFields(map[string]interface{}{
"rule_name": rule.Name,
"scope": rule.Scope,
}).Logf("invalid scope %s given for rule: %s", rule.Scope, rule.Name)
matched = true
reason = "rules/invalid scope/"
}
if matched {
var rate uint
var keep bool
var samplerReason string
if rule.Sampler != nil {
var sampler Sampler
var found bool
if sampler, found = s.samplers[rule.String()]; !found {
logger.WithFields(map[string]interface{}{
"rule_name": rule.Name,
}).Logf("could not find downstream sampler for rule: %s", rule.Name)
return 1, true, reason + "bad_rule:" + rule.Name
}
rate, keep, samplerReason = sampler.GetSampleRate(trace)
reason += rule.Name + ":" + samplerReason
} else {
rate = uint(rule.SampleRate)
keep = !rule.Drop && rule.SampleRate > 0 && rand.Intn(rule.SampleRate) == 0
reason += rule.Name
}
s.Metrics.Histogram("rulessampler_sample_rate", float64(rule.SampleRate))
if keep {
s.Metrics.Increment("rulessampler_num_kept")
} else {
s.Metrics.Increment("rulessampler_num_dropped")
}
logger.WithFields(map[string]interface{}{
"rate": rate,
"keep": keep,
"drop_rule": rule.Drop,
}).Logf("got sample rate and decision")
return rate, keep, reason
}
}
return 1, true, "no rule matched"
}
func ruleMatchesTrace(t *types.Trace, rule *config.RulesBasedSamplerRule, checkNestedFields bool) bool {
// We treat a rule with no conditions as a match.
if rule.Condition == nil {
return true
}
var matched int
for _, condition := range rule.Condition {
span:
for _, span := range t.GetSpans() {
value, exists := extractValueFromSpan(span, condition, checkNestedFields)
if condition.Matches == nil {
if conditionMatchesValue(condition, value, exists) {
matched++
break span
}
continue
} else if condition.Matches(value, exists) {
matched++
break span
}
}
}
return matched == len(rule.Condition)
}
func ruleMatchesSpanInTrace(trace *types.Trace, rule *config.RulesBasedSamplerRule, checkNestedFields bool) bool {
// We treat a rule with no conditions as a match.
if rule.Condition == nil {
return true
}
for _, span := range trace.GetSpans() {
ruleMatched := true
for _, condition := range rule.Condition {
// whether this condition is matched by this span.
value, exists := extractValueFromSpan(span, condition, checkNestedFields)
if condition.Matches == nil {
if !conditionMatchesValue(condition, value, exists) {
ruleMatched = false
break // if any condition fails, we can't possibly succeed, so exit inner loop early
}
}
if condition.Matches != nil {
if !condition.Matches(value, exists) {
ruleMatched = false
break // if any condition fails, we can't possibly succeed, so exit inner loop early
}
}
}
// If this span was matched by every condition, then the rule as a whole
// matches (and we can return)
if ruleMatched {
return true
}
}
// if the rule didn't match above, then it doesn't match the trace.
return false
}
func extractValueFromSpan(span *types.Span, condition *config.RulesBasedSamplerCondition, checkNestedFields bool) (interface{}, bool) {
// whether this condition is matched by this span.
value, exists := span.Data[condition.Field]
if !exists && checkNestedFields {
jsonStr, err := json.Marshal(span.Data)
if err == nil {
result := gjson.Get(string(jsonStr), condition.Field)
if result.Exists() {
value = result.String()
exists = true
}
}
}
return value, exists
}
func conditionMatchesValue(condition *config.RulesBasedSamplerCondition, value interface{}, exists bool) bool {
var match bool
switch exists {
case true:
switch condition.Operator {
case "exists":
match = exists
case "!=":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison != equal
}
case "=":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison == equal
}
case ">":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison == more
}
case ">=":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison == more || comparison == equal
}
case "<":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison == less
}
case "<=":
if comparison, ok := compare(value, condition.Value); ok {
match = comparison == less || comparison == equal
}
case "starts-with":
switch a := value.(type) {
case string:
switch b := condition.Value.(type) {
case string:
match = strings.HasPrefix(a, b)
}
}
case "contains":
switch a := value.(type) {
case string:
switch b := condition.Value.(type) {
case string:
match = strings.Contains(a, b)
}
}
case "does-not-contain":
switch a := value.(type) {
case string:
switch b := condition.Value.(type) {
case string:
match = !strings.Contains(a, b)
}
}
}
case false:
switch condition.Operator {
case "not-exists":
match = !exists
}
}
return match
}
const (
less = -1
equal = 0
more = 1
)
func compare(a, b interface{}) (int, bool) {
// a is the tracing data field value. This can be: float64, int64, bool, or string
// b is the Rule condition value. This can be: float64, int64, int, bool, or string
// Note: in YAML config parsing, the Value may be returned as int
// When comparing numeric values, we need to check across the 3 types: float64, int64, and int
if a == nil {
if b == nil {
return equal, true
}
return less, true
}
if b == nil {
return more, true
}
switch at := a.(type) {
case int64:
switch bt := b.(type) {
case int:
i := int(at)
switch {
case i < bt:
return less, true
case i > bt:
return more, true
default:
return equal, true
}
case int64:
switch {
case at < bt:
return less, true
case at > bt:
return more, true
default:
return equal, true
}
case float64:
f := float64(at)
switch {
case f < bt:
return less, true
case f > bt:
return more, true
default:
return equal, true
}
}
case float64:
switch bt := b.(type) {
case int:
f := float64(bt)
switch {
case at < f:
return less, true
case at > f:
return more, true
default:
return equal, true
}
case int64:
f := float64(bt)
switch {
case at < f:
return less, true
case at > f:
return more, true
default:
return equal, true
}
case float64:
switch {
case at < bt:
return less, true
case at > bt:
return more, true
default:
return equal, true
}
}
case bool:
switch bt := b.(type) {
case bool:
switch {
case !at && bt:
return less, true
case at && !bt:
return more, true
default:
return equal, true
}
}
case string:
switch bt := b.(type) {
case string:
return strings.Compare(at, bt), true
}
}
return equal, false
}