This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.go
101 lines (85 loc) · 1.85 KB
/
worker.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
package stats
import (
"context"
"time"
"golang.org/x/sync/errgroup"
)
// Worker of stats collector
type Worker struct {
client *Client
statType StatDuration
writer Writer
ctx context.Context
canceler context.CancelFunc
lastIntervalEnd time.Time
}
// NewWorker returns the new stats collector
func NewWorker(client *Client, statType StatDuration, writer Writer) *Worker {
return &Worker{
client: client,
statType: statType,
writer: writer,
lastIntervalEnd: time.Now().Add(-2 * statType.Duration()),
}
}
// Start the stats collector
func (w *Worker) Start(ctx context.Context) {
w.ctx, w.canceler = context.WithCancel(ctx)
// in the first time, do it as soon as possible.
w.ticker(w.ctx)
timer := time.NewTicker(w.statType.Duration())
defer timer.Stop()
for {
select {
case <-ctx.Done():
return
case <-w.ctx.Done():
return
case <-timer.C:
w.ticker(w.ctx)
}
}
}
// Stop the stats collector
func (w *Worker) Stop() {
w.canceler()
}
func (w *Worker) ticker(ctx context.Context) {
eg, ctx := errgroup.WithContext(ctx)
getters := []statGetter{
w.client.getQueryStats,
w.client.getTransactionStats,
w.client.getLockStats,
}
for _, getter := range getters {
getter := getter
eg.Go(func() error {
stats := w.getStat(ctx, getter)
if len(stats) == 0 {
return nil
}
w.writer.Write(stats)
return nil
})
}
_ = eg.Wait()
}
func (w *Worker) getStat(
ctx context.Context,
getter statGetter,
) []stat {
stats := getter(ctx, w.statType, w.lastIntervalEnd)
if len(stats) == 0 {
return nil
}
// filter last 1 intervalEnd
e := stats[0].getIntervalEnd()
for i, s := range stats {
if e != s.getIntervalEnd() || w.lastIntervalEnd.After(s.getIntervalEnd()) {
stats = stats[:i]
w.lastIntervalEnd = e
break
}
}
return stats
}