-
Notifications
You must be signed in to change notification settings - Fork 5
/
state.go
72 lines (55 loc) · 1.22 KB
/
state.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
package metrics
import (
"time"
)
type MetricState interface {
Type() MetricType
Update(interface{}) MetricState
Value() float32
}
type DerivativeState struct {
lastUpdated time.Time
// This is a uint64 because we want calculate
// derivatives accurately.
//
// When's the last time you saw a system
// counter that was a float?
prev uint64
value float32
}
type GaugeState struct {
lastUpdated time.Time
value float32
}
func (g GaugeState) Update(value interface{}) MetricState {
g.value = getFloat32Value(value)
g.lastUpdated = time.Now()
return g
}
func (g GaugeState) Type() MetricType {
return TypeGauge
}
func (g GaugeState) Value() float32 {
return g.value
}
func (d DerivativeState) Update(value interface{}) MetricState {
now := time.Now()
timeDelta := now.Sub(d.lastUpdated)
currentValue := getUint64Value(value)
if d.prev >= currentValue {
// Rollover? Keep the value we have.
d.lastUpdated = now
d.prev = currentValue
return d
}
d.value = float32(float64(currentValue-d.prev) / timeDelta.Seconds())
d.lastUpdated = now
d.prev = currentValue
return d
}
func (d DerivativeState) Type() MetricType {
return TypeDerivative
}
func (d DerivativeState) Value() float32 {
return d.value
}