-
Notifications
You must be signed in to change notification settings - Fork 0
/
metrics.go
229 lines (194 loc) · 6.1 KB
/
metrics.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package storage
import (
"fmt"
"strconv"
"time"
"github.com/gomodule/redigo/redis"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
// AggregationInterval defines the aggregation type.
type AggregationInterval string
// Metrics aggregation intervals.
const (
AggregationMinute AggregationInterval = "MINUTE"
AggregationHour AggregationInterval = "HOUR"
AggregationDay AggregationInterval = "DAY"
AggregationMonth AggregationInterval = "MONTH"
)
const (
metricsKeyTempl = "lora:ns:metrics:%s:%s:%d" // metrics key (identifier | aggregation | timestamp)
)
var (
timeLocation = time.Local
aggregationIntervals []AggregationInterval
metricsMinuteTTL time.Duration
metricsHourTTL time.Duration
metricsDayTTL time.Duration
metricsMonthTTL time.Duration
)
// MetricsRecord holds a single metrics record.
type MetricsRecord struct {
Time time.Time
Metrics map[string]float64
}
// SetTimeLocation sets the time location.
func SetTimeLocation(name string) error {
var err error
timeLocation, err = time.LoadLocation(name)
if err != nil {
return errors.Wrap(err, "load location error")
}
return nil
}
// SetAggregationIntervals sets the metrics aggregation to the given intervals.
func SetAggregationIntervals(intervals []AggregationInterval) error {
aggregationIntervals = intervals
return nil
}
// SetMetricsTTL sets the storage TTL.
func SetMetricsTTL(minute, hour, day, month time.Duration) {
metricsMinuteTTL = minute
metricsHourTTL = hour
metricsDayTTL = day
metricsMonthTTL = month
}
// SaveMetrics stores the given metrics into Redis.
func SaveMetrics(p *redis.Pool, name string, metrics MetricsRecord) error {
for _, agg := range aggregationIntervals {
if err := SaveMetricsForInterval(p, agg, name, metrics); err != nil {
return errors.Wrap(err, "save metrics for interval error")
}
}
log.WithFields(log.Fields{
"name": name,
"aggregation": aggregationIntervals,
}).Info("metrics saved")
return nil
}
// SaveMetricsForInterval aggregates and stores the given metrics.
func SaveMetricsForInterval(p *redis.Pool, agg AggregationInterval, name string, metrics MetricsRecord) error {
if len(metrics.Metrics) == 0 {
return nil
}
c := p.Get()
defer c.Close()
var exp int64
// handle aggregation
ts := metrics.Time.In(timeLocation)
switch agg {
case AggregationMinute:
// truncate timestamp to minute precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), ts.Minute(), 0, 0, timeLocation)
exp = int64(metricsMinuteTTL) / int64(time.Millisecond)
case AggregationHour:
// truncate timestamp to hour precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), ts.Hour(), 0, 0, 0, timeLocation)
exp = int64(metricsHourTTL) / int64(time.Millisecond)
case AggregationDay:
// truncate timestamp to day precision
ts = time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, timeLocation)
exp = int64(metricsDayTTL) / int64(time.Millisecond)
case AggregationMonth:
// truncate timestamp to month precision
ts = time.Date(ts.Year(), ts.Month(), 1, 0, 0, 0, 0, timeLocation)
exp = int64(metricsMonthTTL) / int64(time.Millisecond)
default:
return fmt.Errorf("unexepcted aggregation interval: %s", agg)
}
key := fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix())
c.Send("MULTI")
for k, v := range metrics.Metrics {
c.Send("HINCRBYFLOAT", key, k, v)
}
c.Send("PEXPIRE", key, exp)
if _, err := c.Do("EXEC"); err != nil {
return errors.Wrap(err, "exec error")
}
log.WithFields(log.Fields{
"name": name,
"aggregation": agg,
}).Debug("metrics saved")
return nil
}
// GetMetrics returns the metrics for the requested aggregation interval.
func GetMetrics(p *redis.Pool, agg AggregationInterval, name string, start, end time.Time) ([]MetricsRecord, error) {
c := p.Get()
defer c.Close()
var keys []string
var timestamps []time.Time
start = start.In(timeLocation)
end = end.In(timeLocation)
// handle aggregation keys
switch agg {
case AggregationMinute:
end = time.Date(end.Year(), end.Month(), end.Day(), end.Hour(), end.Minute(), 0, 0, timeLocation)
for i := 0; ; i++ {
ts := time.Date(start.Year(), start.Month(), start.Day(), start.Hour(), start.Minute()+i, 0, 0, timeLocation)
if ts.After(end) {
break
}
timestamps = append(timestamps, ts)
keys = append(keys, fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix()))
}
case AggregationHour:
end = time.Date(end.Year(), end.Month(), end.Day(), end.Hour(), 0, 0, 0, timeLocation)
for i := 0; ; i++ {
ts := time.Date(start.Year(), start.Month(), start.Day(), start.Hour()+i, 0, 0, 0, timeLocation)
if ts.After(end) {
break
}
timestamps = append(timestamps, ts)
keys = append(keys, fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix()))
}
case AggregationDay:
end = time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, timeLocation)
for i := 0; ; i++ {
ts := time.Date(start.Year(), start.Month(), start.Day()+i, 0, 0, 0, 0, timeLocation)
if ts.After(end) {
break
}
timestamps = append(timestamps, ts)
keys = append(keys, fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix()))
}
case AggregationMonth:
end = time.Date(end.Year(), end.Month(), 1, 0, 0, 0, 0, timeLocation)
for i := 0; ; i++ {
ts := time.Date(start.Year(), start.Month()+time.Month(i), 1, 0, 0, 0, 0, timeLocation)
if ts.After(end) {
break
}
timestamps = append(timestamps, ts)
keys = append(keys, fmt.Sprintf(metricsKeyTempl, name, agg, ts.Unix()))
}
default:
return nil, fmt.Errorf("unexepcted aggregation interval: %s", agg)
}
if len(keys) == 0 {
return nil, nil
}
for _, k := range keys {
c.Send("HGETALL", k)
}
c.Flush()
var out []MetricsRecord
for _, ts := range timestamps {
metrics := MetricsRecord{
Time: ts,
Metrics: make(map[string]float64),
}
vals, err := redis.StringMap(c.Receive())
if err != nil {
return nil, errors.Wrap(err, "receive stringmap error")
}
for k, v := range vals {
f, err := strconv.ParseFloat(v, 64)
if err != nil {
return nil, errors.Wrap(err, "parse float error")
}
metrics.Metrics[k] = f
}
out = append(out, metrics)
}
return out, nil
}