-
Notifications
You must be signed in to change notification settings - Fork 493
/
stats.go
121 lines (111 loc) · 2.43 KB
/
stats.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
package kapacitor
import (
"errors"
"fmt"
"sync"
"time"
"github.com/influxdata/kapacitor/edge"
"github.com/influxdata/kapacitor/pipeline"
)
type StatsNode struct {
node
s *pipeline.StatsNode
en Node
closing chan struct{}
closed bool
mu sync.Mutex
}
// Create a new FromNode which filters data from a source.
func newStatsNode(et *ExecutingTask, n *pipeline.StatsNode, d NodeDiagnostic) (*StatsNode, error) {
// Lookup the executing node for stats.
en := et.lookup[n.SourceNode.ID()]
if en == nil {
return nil, fmt.Errorf("no node found for %s", n.SourceNode.Name())
}
if n.Interval <= 0 {
return nil, errors.New("stats node must have positive interval")
}
sn := &StatsNode{
node: node{Node: n, et: et, diag: d},
s: n,
en: en,
closing: make(chan struct{}),
}
sn.node.runF = sn.runStats
sn.node.stopF = sn.stopStats
return sn, nil
}
func (n *StatsNode) runStats([]byte) error {
if n.s.AlignFlag {
// Wait till we are roughly aligned with the interval.
now := time.Now()
next := now.Truncate(n.s.Interval).Add(n.s.Interval)
dur := next.Sub(now)
if dur <= 0 { // this can happen during a time-changeover like a leap second, or if something is messing about with the system
return errors.New("alignment interval should be positive but was not")
}
after := time.NewTicker(dur)
select {
case <-after.C:
after.Stop()
case <-n.closing:
after.Stop()
return nil
}
if err := n.emit(now); err != nil {
return err
}
}
if n.s.Interval <= 0 {
return errors.New("stats interval should be positive but was not")
}
ticker := time.NewTicker(n.s.Interval)
defer ticker.Stop()
for {
select {
case <-n.closing:
return nil
case now := <-ticker.C:
if err := n.emit(now); err != nil {
return err
}
}
}
}
// Emit a set of stats data points.
func (n *StatsNode) emit(now time.Time) error {
n.timer.Start()
defer n.timer.Stop()
name := "stats"
t := now.UTC()
if n.s.AlignFlag {
t = t.Round(n.s.Interval)
}
stats := n.en.nodeStatsByGroup()
for _, stat := range stats {
point := edge.NewPointMessage(
name, "", "",
stat.Dimensions,
stat.Fields,
stat.Tags,
t,
)
n.timer.Pause()
for _, out := range n.outs {
err := out.Collect(point)
if err != nil {
return err
}
}
n.timer.Resume()
}
return nil
}
func (n *StatsNode) stopStats() {
n.mu.Lock()
defer n.mu.Unlock()
if !n.closed {
n.closed = true
close(n.closing)
}
}