/
probe.go
119 lines (96 loc) · 2.07 KB
/
probe.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
package probe
import (
"fmt"
"runtime/debug"
"sync"
"time"
)
var GProbe Probe = newProbe()
type Probe interface {
Init(config *ProbeConfig) error
GetContext() (*ProbeContext, error)
}
type probe struct {
mutex sync.Mutex
kChan chan int
ctx *ProbeContext
}
func newProbe() *probe {
p := new(probe)
p.kChan = make(chan int)
return p
}
func (p *probe) contextFit(newCtx *ProbeContext) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.ctx.Fit(newCtx)
}
func (p *probe) keeper() {
defer func() {
if rcvErr := recover(); rcvErr != nil {
logger.Errorf("recovered from panic error:[%v]", rcvErr)
debug.PrintStack()
}
}()
logger.Info("started")
for sig := range p.kChan {
switch sig {
case 1:
go p.samplingTimer()
}
}
}
func (p *probe) samplingTimer() {
interval := time.Duration(GConfig.SamplingInterval) * time.Second
now := time.Now()
timer := time.NewTimer(now.Truncate(interval).Add(interval).Sub(time.Now()))
defer func() {
if rcvErr := recover(); rcvErr != nil {
logger.Errorf("recovered from panic error:[%v]", rcvErr)
debug.PrintStack()
}
timer.Stop()
p.kChan <- 1
}()
logger.Info("started")
var err error
for {
timer.Reset(now.Truncate(interval).Add(interval).Sub(time.Now()))
select {
case now = <-timer.C:
now = now.Truncate(time.Second)
newCtx := NewProbeContext()
if err = newCtx.Sample(); err != nil {
logger.Errorf("sample error:[%v]", err)
continue
}
p.contextFit(newCtx)
logger.WithField("time_cost", time.Since(now).Seconds()).Infof("finished")
}
}
}
func (p *probe) Init(config *ProbeConfig) error {
p.mutex.Lock()
defer p.mutex.Unlock()
GConfig = config
err := GConfig.Check()
if err != nil {
return err
}
p.ctx = NewProbeContext()
go p.keeper()
go p.samplingTimer()
logger.WithField("config", GConfig).Info("finished")
return nil
}
func (p *probe) GetContext() (*ProbeContext, error) {
p.mutex.Lock()
defer p.mutex.Unlock()
ctx := p.ctx
p.ctx = NewProbeContext()
if ctx.SamplingCounter < 1 {
return nil, fmt.Errorf("too few sample")
}
ctx.Average()
return ctx, nil
}