-
Notifications
You must be signed in to change notification settings - Fork 0
/
appoptics.go
264 lines (251 loc) · 9.44 KB
/
appoptics.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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package appoptics
import (
"fmt"
"log"
"regexp"
"strings"
"time"
"github.com/rcrowley/go-metrics"
)
// a regexp for extracting the unit from time.Duration.String
var unitRegexp = regexp.MustCompile("[^\\d]+$")
// a helper that turns a time.Duration into AppOptics display attributes for timer metrics
func translateTimerAttributes(d time.Duration) (attrs map[string]interface{}) {
attrs = make(map[string]interface{})
attrs[DisplayTransform] = fmt.Sprintf("x/%d", int64(d))
attrs[DisplayUnitsShort] = string(unitRegexp.Find([]byte(d.String())))
return
}
type Reporter struct {
Token string
Tags map[string]string
Interval time.Duration
Registry metrics.Registry
Percentiles []float64 // percentiles to report on histogram metrics
Prefix string // prefix metric names for upload (eg "servicename.")
WhitelistedRuntimeMetrics map[string]bool // runtime.* metrics to upload (nil = allow all)
TimerAttributes map[string]interface{} // units in which timers will be displayed
intervalSec int64
measurementsURI string
}
func NewReporter(registry metrics.Registry, interval time.Duration, token string, tags map[string]string,
percentiles []float64, timeUnits time.Duration, prefix string, whitelistedRuntimeMetrics []string, measurementsURI string) *Reporter {
// set up lookups for our whitelist. Translate from []string to map[string]bool for easy lookups
// nil = allow all; empty slice = block all
var whitelist map[string]bool
if whitelistedRuntimeMetrics != nil {
whitelist = map[string]bool{}
for _, name := range whitelistedRuntimeMetrics {
whitelist[name] = true
}
}
return &Reporter{token, tags, interval, registry, percentiles, prefix,
whitelist, translateTimerAttributes(timeUnits),
int64(interval / time.Second), measurementsURI}
}
// Call in a goroutine to start metric uploading.
// Using whitelistedRuntimeMetrics: a non-nil value sets this reporter to upload only a subset
// of the runtime.* metrics that are gathered by go-metrics runtime memory stats
// (CaptureRuntimeMemStats). The full list of possible values is at
// https://github.com/rcrowley/go-metrics/blob/master/runtime.go#L181-L211
// Passing an empty slice disables uploads for all runtime.* metrics.
func AppOptics(registry metrics.Registry, interval time.Duration, token string, tags map[string]string,
percentiles []float64, timeUnits time.Duration, prefix string, whitelistedRuntimeMetrics []string, measurementsURI string) {
NewReporter(registry, interval, token, tags, percentiles, timeUnits, prefix, whitelistedRuntimeMetrics, measurementsURI).Run()
}
func (self *Reporter) Run() {
ticker := time.Tick(self.Interval)
metricsApi := NewAppOpticsClient(self.Token, self.measurementsURI)
for now := range ticker {
var metrics Batch
var err error
if metrics, err = self.BuildRequest(now, self.Registry); err != nil {
log.Printf("ERROR constructing AppOptics request body %s", err)
continue
}
if err := metricsApi.PostMetrics(metrics); err != nil {
log.Printf("ERROR sending metrics to AppOptics %s", err)
continue
}
}
}
func (self *Reporter) BuildRequest(now time.Time, r metrics.Registry) (batch Batch, err error) {
batch = Batch{
// coerce timestamps to a stepping fn so that they line up in AppOptics graphs
Time: (now.Unix() / self.intervalSec) * self.intervalSec,
}
batch.Measurements = make([]Measurement, 0)
histogramMeasurementCount := 1 + len(self.Percentiles)
r.Each(func(name string, metric interface{}) {
// if whitelis is set (non-nil), only upload runtime.* metrics from the list
if strings.HasPrefix(name, "runtime.") && self.WhitelistedRuntimeMetrics != nil &&
!self.WhitelistedRuntimeMetrics[name] {
return
}
name, tags := decodeMetricName(name)
name = self.Prefix + name
measurement := Measurement{}
measurement[Period] = self.Interval.Seconds()
mergedTags := map[string]string{}
// Copy to prevent mutating Reporter's global tags
for tagName, tagValue := range self.Tags {
mergedTags[tagName] = tagValue
}
// Per-measurement tags override global tags
for tagName, tagValue := range tags {
mergedTags[tagName] = tagValue
}
measurement[Tags] = mergedTags
switch m := metric.(type) {
case metrics.Counter:
if m.Count() > 0 {
measurement[Name] = fmt.Sprintf("%s.%s", name, "count")
measurement[Value] = float64(m.Count())
measurement[Attributes] = map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
}
batch.Measurements = append(batch.Measurements, measurement)
}
case metrics.Gauge:
measurement[Name] = name
measurement[Value] = float64(m.Value())
batch.Measurements = append(batch.Measurements, measurement)
case metrics.GaugeFloat64:
measurement[Name] = name
measurement[Value] = float64(m.Value())
batch.Measurements = append(batch.Measurements, measurement)
case metrics.Histogram:
s := m.Snapshot().Sample()
if s.Count() > 0 {
measurements := make([]Measurement, histogramMeasurementCount, histogramMeasurementCount)
measurement[Name] = fmt.Sprintf("%s.%s", name, "hist")
// For AppOptics, count must be the number of measurements in this sample. It will show sum/count as the mean.
// Sample.Size() gives us this. Sample.Count() gives the total number of measurements ever recorded for the
// life of the histogram, which means the AppOptics graph will trend toward 0 as more measurements are recored.
measurement[Count] = uint64(s.Size())
measurement[Max] = float64(s.Max())
measurement[Min] = float64(s.Min())
measurement[Sum] = float64(s.Sum())
measurement[StdDev] = float64(s.StdDev())
measurements[0] = measurement
for i, p := range self.Percentiles {
measurements[i+1] = Measurement{
Name: fmt.Sprintf("%s.%.2f", measurement[Name], p),
Tags: mergedTags,
Value: s.Percentile(p),
Period: measurement[Period],
}
}
batch.Measurements = append(batch.Measurements, measurements...)
}
case metrics.Meter:
s := m.Snapshot()
measurement[Name] = name
measurement[Value] = float64(s.Count())
batch.Measurements = append(batch.Measurements, measurement)
batch.Measurements = append(batch.Measurements,
Measurement{
Name: fmt.Sprintf("%s.%s", name, "1min"),
Tags: mergedTags,
Value: s.Rate1(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
Measurement{
Name: fmt.Sprintf("%s.%s", name, "5min"),
Tags: mergedTags,
Value: s.Rate5(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
Measurement{
Name: fmt.Sprintf("%s.%s", name, "15min"),
Tags: mergedTags,
Value: s.Rate15(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
)
case metrics.Timer:
s := m.Snapshot()
measurement[Name] = name
measurement[Value] = float64(s.Count())
batch.Measurements = append(batch.Measurements, measurement)
if m.Count() > 0 {
appOpticsName := fmt.Sprintf("%s.%s", name, "timer.mean")
measurements := make([]Measurement, histogramMeasurementCount, histogramMeasurementCount)
measurements[0] = Measurement{
Name: appOpticsName,
Tags: mergedTags,
Count: uint64(s.Count()),
Sum: s.Mean() * float64(s.Count()),
Max: float64(s.Max()),
Min: float64(s.Min()),
StdDev: float64(s.StdDev()),
Period: int64(self.Interval.Seconds()),
Attributes: self.TimerAttributes,
}
for i, p := range self.Percentiles {
measurements[i+1] = Measurement{
Name: fmt.Sprintf("%s.timer.%2.0f", name, p*100),
Tags: mergedTags,
Value: m.Percentile(p),
Period: int64(self.Interval.Seconds()),
Attributes: self.TimerAttributes,
}
}
batch.Measurements = append(batch.Measurements, measurements...)
batch.Measurements = append(batch.Measurements,
Measurement{
Name: fmt.Sprintf("%s.%s", name, "rate.1min"),
Tags: mergedTags,
Value: s.Rate1(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
Measurement{
Name: fmt.Sprintf("%s.%s", name, "rate.5min"),
Tags: mergedTags,
Value: s.Rate5(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
Measurement{
Name: fmt.Sprintf("%s.%s", name, "rate.15min"),
Tags: mergedTags,
Value: s.Rate15(),
Period: int64(self.Interval.Seconds()),
Attributes: map[string]interface{}{
DisplayUnitsLong: Operations,
DisplayUnitsShort: OperationsShort,
DisplayMin: "0",
},
},
)
}
}
})
return
}