-
Notifications
You must be signed in to change notification settings - Fork 0
/
sample.go
67 lines (57 loc) · 1.42 KB
/
sample.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
package trace
import (
"math/rand"
"sync/atomic"
"time"
)
const (
slotLength = 2048
)
var ignoreds = []string{"/metrics", "/ping"} // NOTE: add YOUR URL PATH that want ignore
func init() {
rand.Seed(time.Now().UnixNano())
}
func oneAtTimeHash(s string) (hash uint32) {
b := []byte(s)
for i := range b {
hash += uint32(b[i])
hash += hash << 10
hash ^= hash >> 6
}
hash += hash << 3
hash ^= hash >> 11
hash += hash << 15
return
}
// sampler decides whether a new trace should be sampled or not.
type sampler interface {
IsSampled(traceID uint64, operationName string) (bool, float32)
Close() error
}
type probabilitySampling struct {
probability float32
slot [slotLength]int64
}
func (p *probabilitySampling) IsSampled(traceID uint64, operationName string) (bool, float32) {
for _, ignored := range ignoreds {
if operationName == ignored {
return false, 0
}
}
now := time.Now().Unix()
idx := oneAtTimeHash(operationName) % slotLength
old := atomic.LoadInt64(&p.slot[idx])
if old != now {
atomic.SwapInt64(&p.slot[idx], now)
return true, 1
}
return rand.Float32() < float32(p.probability), float32(p.probability)
}
func (p *probabilitySampling) Close() error { return nil }
// newSampler new probability sampler
func newSampler(probability float32) sampler {
if probability <= 0 || probability > 1 {
panic("probability P ∈ (0, 1]")
}
return &probabilitySampling{probability: probability}
}