forked from bosun-monitor/bosun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collect.go
465 lines (431 loc) · 12.9 KB
/
collect.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Package collect provides functions for sending data to OpenTSDB.
//
// The "collect" namespace is used (i.e., <root>.collect) to collect
// program and queue metrics.
package collect // import "bosun.org/collect"
import (
"fmt"
"math"
"net/http"
"net/url"
"os"
"runtime"
"sort"
"strings"
"sync"
"time"
"bosun.org/metadata"
"bosun.org/opentsdb"
)
var (
// Freq is how often metrics are sent to OpenTSDB.
Freq = time.Second * 15
// MaxQueueLen is the maximum size of the queue, above which incoming data will
// be discarded. Defaults to about 150MB.
MaxQueueLen = 200000
// BatchSize is the maximum length of data points sent at once to OpenTSDB.
BatchSize = 500
// Debug enables debug logging.
Debug = false
// Print prints all datapoints to stdout instead of sending them.
Print = false
// DisableDefaultCollectors prevents the scollector self metrics from being
// generated.
DisableDefaultCollectors = false
// Tags is an opentsdb.TagSet used when sending self metrics.
Tags opentsdb.TagSet
// Dropped is the number of dropped data points due to a full queue.
dropped int64
// Sent is the number of sent data points.
sent int64
tchan chan *opentsdb.DataPoint
tsdbURL string
osHostname string
metricRoot string
queue []*opentsdb.DataPoint
qlock, mlock, slock sync.Mutex // Locks for queues, maps, stats.
counters = make(map[string]*addMetric)
sets = make(map[string]*setMetric)
puts = make(map[string]*putMetric)
aggs = make(map[string]*agMetric)
client = &http.Client{
Transport: &timeoutTransport{Transport: new(http.Transport)},
Timeout: time.Minute,
}
)
const (
descCollectAlloc = "Total number of bytes allocated and still in use by the runtime (via runtime.ReadMemStats)."
descCollectDropped = "Counter of dropped data points due to the queue being full."
descCollectGoRoutines = "Total number of goroutines that currently exist (via runtime.NumGoroutine)."
descCollectGcCpuFraction = "fraction of CPU time used by GC"
descCollectTotalGCPause = "Total GC Pause time in milliseconds"
descCollectPostBad = "Counter of HTTP POST requests where resp.StatusCode != http.StatusNoContent."
descCollectPostBatchSize = "Number of datapoints included in each batch."
descCollectPostCount = "Counter of batches sent to the server."
descCollectPostDuration = "How many milliseconds it took to send HTTP POST requests to the server."
descCollectPostError = "Counter of errors received when sending a batch to the server."
descCollectPostRestore = "Counter of data points restored from batches that could not be sent to the server."
descCollectPostTotalBytes = "Total number of gzipped bytes sent to the server."
descCollectPostTotalDuration = "Total number of milliseconds it took to send an HTTP POST request to the server."
descCollectQueued = "Total number of items currently queued and waiting to be sent to the server."
descCollectSent = "Counter of data points sent to the server."
)
type timeoutTransport struct {
*http.Transport
Timeout time.Time
}
func (t *timeoutTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if time.Now().After(t.Timeout) {
t.Transport.CloseIdleConnections()
t.Timeout = time.Now().Add(time.Minute * 5)
}
return t.Transport.RoundTrip(r)
}
// InitChan is similar to Init, but uses the given channel instead of creating a
// new one.
func InitChan(tsdbhost *url.URL, root string, ch chan *opentsdb.DataPoint) error {
if tchan != nil {
return fmt.Errorf("cannot init twice")
}
if err := checkClean(root, "metric root"); err != nil {
return err
}
u, err := tsdbhost.Parse("/api/put")
if err != nil {
return err
}
if strings.HasPrefix(u.Host, ":") {
u.Host = "localhost" + u.Host
}
tsdbURL = u.String()
metricRoot = root + "."
tchan = ch
go queuer()
go send()
go collect()
if DisableDefaultCollectors {
return nil
}
Set("collect.dropped", Tags, func() (i interface{}) {
slock.Lock()
i = dropped
slock.Unlock()
return
})
Set("collect.sent", Tags, func() (i interface{}) {
slock.Lock()
i = sent
slock.Unlock()
return
})
Set("collect.queued", Tags, func() (i interface{}) {
qlock.Lock()
i = len(queue)
qlock.Unlock()
return
})
Set("collect.alloc", Tags, func() interface{} {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
return ms.Alloc
})
Set("collect.gc.cpu_fraction", Tags, func() interface{} {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
return ms.GCCPUFraction
})
Set("collect.gc.total_pause", Tags, func() interface{} {
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
return ms.PauseTotalNs / uint64(time.Millisecond)
})
Set("collect.goroutines", Tags, func() interface{} {
return runtime.NumGoroutine()
})
AggregateMeta(metricRoot+"collect.post.batchsize", metadata.Count, descCollectPostBatchSize)
AggregateMeta(metricRoot+"collect.post.duration", metadata.MilliSecond, descCollectPostDuration)
metadata.AddMetricMeta(metricRoot+"collect.alloc", metadata.Gauge, metadata.Bytes, descCollectAlloc)
metadata.AddMetricMeta(metricRoot+"collect.goroutines", metadata.Gauge, metadata.Count, descCollectGoRoutines)
metadata.AddMetricMeta(metricRoot+"collect.gc.cpu_fraction", metadata.Gauge, metadata.Pct, descCollectGcCpuFraction)
metadata.AddMetricMeta(metricRoot+"collect.gc.total_pause", metadata.Counter, metadata.MilliSecond, descCollectTotalGCPause)
metadata.AddMetricMeta(metricRoot+"collect.post.bad_status", metadata.Counter, metadata.PerSecond, descCollectPostBad)
metadata.AddMetricMeta(metricRoot+"collect.post.count", metadata.Counter, metadata.PerSecond, descCollectPostCount)
metadata.AddMetricMeta(metricRoot+"collect.post.error", metadata.Counter, metadata.PerSecond, descCollectPostError)
metadata.AddMetricMeta(metricRoot+"collect.post.restore", metadata.Counter, metadata.PerSecond, descCollectPostRestore)
metadata.AddMetricMeta(metricRoot+"collect.post.total_bytes", metadata.Counter, metadata.Bytes, descCollectPostTotalBytes)
metadata.AddMetricMeta(metricRoot+"collect.post.total_duration", metadata.Counter, metadata.MilliSecond, descCollectPostTotalDuration)
metadata.AddMetricMeta(metricRoot+"collect.queued", metadata.Gauge, metadata.Item, descCollectQueued)
metadata.AddMetricMeta(metricRoot+"collect.sent", metadata.Counter, metadata.PerSecond, descCollectSent)
metadata.AddMetricMeta(metricRoot+"collect.dropped", metadata.Counter, metadata.PerSecond, descCollectDropped)
// Make sure these get zeroed out instead of going unknown on restart
Add("collect.post.error", Tags, 0)
Add("collect.post.bad_status", Tags, 0)
Add("collect.post.restore", Tags, 0)
return nil
}
// Init sets up the channels and the queue for sending data to OpenTSDB. It also
// sets up the basename for all metrics.
func Init(tsdbhost *url.URL, root string) error {
return InitChan(tsdbhost, root, make(chan *opentsdb.DataPoint))
}
func SetHostname(host string) error {
if err := checkClean(host, "host tag"); err != nil {
return err
}
osHostname = host
return nil
}
func setHostName() error {
h, err := os.Hostname()
if err != nil {
return err
}
osHostname = strings.ToLower(strings.SplitN(h, ".", 2)[0])
if err := checkClean(osHostname, "host tag"); err != nil {
return err
}
return nil
}
type agMetric struct {
metric string
ts opentsdb.TagSet
values []float64
}
func AggregateMeta(metric string, unit metadata.Unit, desc string) {
agStrings := []string{"avg", "count", "min", "median", "max", "95", "99"}
for _, ag := range agStrings {
if ag == "count" {
metadata.AddMetricMeta(metric+"_"+ag, metadata.Gauge, metadata.Count, "The number of samples per aggregation.")
continue
}
metadata.AddMetricMeta(metric+"_"+ag, metadata.Gauge, unit, desc)
}
}
func (am *agMetric) Process(now int64) {
var avg float64
for _, v := range am.values {
avg += v
}
avg /= float64(len(am.values))
extRoot := metricRoot + am.metric
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_avg",
Timestamp: now,
Value: avg,
Tags: am.ts,
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_count",
Timestamp: now,
Value: len(am.values),
Tags: am.ts,
}
sort.Float64s(am.values)
percentile := func(p float64) float64 {
if p <= 0 {
return am.values[0]
}
if p >= 1 {
return am.values[len(am.values)-1]
}
i := p * float64(len(am.values)-1)
i = math.Ceil(i)
return am.values[int(i)]
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_min",
Timestamp: now,
Value: percentile(0),
Tags: am.ts,
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_median",
Timestamp: now,
Value: percentile(.5),
Tags: am.ts,
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_max",
Timestamp: now,
Value: percentile(1),
Tags: am.ts,
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_95",
Timestamp: now,
Value: percentile(.95),
Tags: am.ts,
}
tchan <- &opentsdb.DataPoint{
Metric: extRoot + "_99",
Timestamp: now,
Value: percentile(.99),
Tags: am.ts,
}
}
func Sample(metric string, ts opentsdb.TagSet, v float64) error {
if err := check(metric, &ts); err != nil {
return err
}
tss := metric + ts.String()
mlock.Lock()
if aggs[tss] == nil {
aggs[tss] = &agMetric{
metric: metric,
ts: ts.Copy(),
}
}
aggs[tss].values = append(aggs[tss].values, v)
mlock.Unlock()
return nil
}
// StartTimer records the current time, and returns a function you can call to
// record the end of your action.
//
// Typical usage would be:
// done := collect.StartTimer("myMetric", opentsdb.TagSet{})
// doMyThing()
// done()
func StartTimer(metric string, ts opentsdb.TagSet) func() {
start := time.Now()
return func() {
d := time.Now().Sub(start) / time.Millisecond
Sample(metric, ts, float64(d))
}
}
type setMetric struct {
metric string
ts opentsdb.TagSet
f func() interface{}
}
// Set registers a callback for the given metric and tags, calling f immediately
// before queueing data for send.
func Set(metric string, ts opentsdb.TagSet, f func() interface{}) error {
if err := check(metric, &ts); err != nil {
return err
}
tss := metric + ts.String()
mlock.Lock()
sets[tss] = &setMetric{metric, ts.Copy(), f}
mlock.Unlock()
return nil
}
type addMetric struct {
metric string
ts opentsdb.TagSet
value int64
}
// Add takes a metric and increments a counter for that metric. The metric name
// is appended to the basename specified in the Init function.
func Add(metric string, ts opentsdb.TagSet, inc int64) error {
if err := check(metric, &ts); err != nil {
return err
}
tss := metric + ts.String()
mlock.Lock()
if counters[tss] == nil {
counters[tss] = &addMetric{
metric: metric,
ts: ts.Copy(),
}
}
counters[tss].value += inc
mlock.Unlock()
return nil
}
type putMetric struct {
metric string
ts opentsdb.TagSet
value interface{}
}
// Put is useful for capturing "events" that have a gauge value. Subsequent
// calls between the sending interval will overwrite previous calls.
func Put(metric string, ts opentsdb.TagSet, v interface{}) error {
if err := check(metric, &ts); err != nil {
return err
}
tss := metric + ts.String()
mlock.Lock()
puts[tss] = &putMetric{metric, ts.Copy(), v}
mlock.Unlock()
return nil
}
func check(metric string, ts *opentsdb.TagSet) error {
if err := checkClean(metric, "metric"); err != nil {
return err
}
for k, v := range *ts {
if err := checkClean(k, "tagk"); err != nil {
return err
}
if err := checkClean(v, "tagv"); err != nil {
return err
}
}
if osHostname == "" {
if err := setHostName(); err != nil {
return err
}
}
if *ts == nil {
*ts = make(opentsdb.TagSet)
}
if host, present := (*ts)["host"]; !present {
(*ts)["host"] = osHostname
} else if host == "" {
delete(*ts, "host")
}
return nil
}
func checkClean(s, t string) error {
if sc, err := opentsdb.Clean(s); s != sc || err != nil {
if err != nil {
return err
}
return fmt.Errorf("%s %s may only contain a to z, A to Z, 0 to 9, -, _, ., / or Unicode letters and may not be empty", t, s)
}
return nil
}
func collect() {
for {
time.Sleep(Freq)
flushData()
}
}
func flushData() {
mlock.Lock()
now := time.Now().Unix()
for _, c := range counters {
dp := &opentsdb.DataPoint{
Metric: metricRoot + c.metric,
Timestamp: now,
Value: c.value,
Tags: c.ts,
}
tchan <- dp
}
for _, s := range sets {
dp := &opentsdb.DataPoint{
Metric: metricRoot + s.metric,
Timestamp: now,
Value: s.f(),
Tags: s.ts,
}
tchan <- dp
}
for _, s := range puts {
dp := &opentsdb.DataPoint{
Metric: metricRoot + s.metric,
Timestamp: now,
Value: s.value,
Tags: s.ts,
}
tchan <- dp
}
for _, am := range aggs {
am.Process(now)
}
puts = make(map[string]*putMetric)
aggs = make(map[string]*agMetric)
mlock.Unlock()
}