-
Notifications
You must be signed in to change notification settings - Fork 131
/
statsdaemon.go
616 lines (541 loc) · 13.9 KB
/
statsdaemon.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"net"
"os"
"os/signal"
"runtime"
"sort"
"strconv"
"strings"
"syscall"
"time"
)
const (
MAX_UNPROCESSED_PACKETS = 1000
TCP_READ_SIZE = 4096
)
var signalchan chan os.Signal
type Packet struct {
Bucket string
ValFlt float64
ValStr string
Modifier string
Sampling float32
}
type Float64Slice []float64
func (s Float64Slice) Len() int { return len(s) }
func (s Float64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s Float64Slice) Less(i, j int) bool { return s[i] < s[j] }
type Percentiles []*Percentile
type Percentile struct {
float float64
str string
}
func (a *Percentiles) Set(s string) error {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return err
}
*a = append(*a, &Percentile{f, strings.Replace(s, ".", "_", -1)})
return nil
}
func (p *Percentile) String() string {
return p.str
}
func (a *Percentiles) String() string {
return fmt.Sprintf("%v", *a)
}
func sanitizeBucket(bucket []byte) string {
var bl int
for i := 0; i < len(bucket); i++ {
c := bucket[i]
switch {
case c >= byte('a') && c <= byte('z'):
fallthrough
case c >= byte('A') && c <= byte('Z'):
fallthrough
case c >= byte('0') && c <= byte('9'):
fallthrough
case c == byte('-') || c == byte('.') || c == byte('_'):
bucket[bl] = c
bl++
case c == byte(' '):
bucket[bl] = byte('_')
bl++
case c == byte('/'):
bucket[bl] = byte('-')
bl++
}
}
return string(bucket[:bl])
}
var (
serviceAddress = flag.String("address", ":8125", "UDP service address")
tcpServiceAddress = flag.String("tcpaddr", "", "TCP service address, if set")
maxUdpPacketSize = flag.Int("max-udp-packet-size", 1472, "Maximum UDP packet size")
graphiteAddress = flag.String("graphite", "127.0.0.1:2003", "Graphite service address (or - to disable)")
flushInterval = flag.Int64("flush-interval", 10, "Flush interval (seconds)")
debug = flag.Bool("debug", false, "print statistics sent to graphite")
showVersion = flag.Bool("version", false, "print version string")
deleteGauges = flag.Bool("delete-gauges", true, "don't send values to graphite for inactive gauges, as opposed to sending the previous value")
persistCountKeys = flag.Int64("persist-count-keys", 60, "number of flush-intervals to persist count keys")
receiveCounter = flag.String("receive-counter", "", "Metric name for total metrics received per interval")
percentThreshold = Percentiles{}
prefix = flag.String("prefix", "", "Prefix for all stats")
postfix = flag.String("postfix", "", "Postfix for all stats")
heartbeatFilePath = flag.String("heartbeat-file", "", "heartbeat file to update after a successful write to graphite.")
)
func init() {
flag.Var(&percentThreshold, "percent-threshold",
"percentile calculation for timers (0-100, may be given multiple times)")
}
var (
In = make(chan *Packet, MAX_UNPROCESSED_PACKETS)
counters = make(map[string]float64)
gauges = make(map[string]float64)
timers = make(map[string]Float64Slice)
countInactivity = make(map[string]int64)
sets = make(map[string][]string)
)
func monitor() {
period := time.Duration(*flushInterval) * time.Second
ticker := time.NewTicker(period)
for {
select {
case sig := <-signalchan:
fmt.Printf("!! Caught signal %v... shutting down\n", sig)
if err := submit(time.Now().Add(period)); err != nil {
log.Printf("ERROR: %s", err)
}
return
case <-ticker.C:
if err := submit(time.Now().Add(period)); err != nil {
log.Printf("ERROR: %s", err)
}
case s := <-In:
packetHandler(s)
}
}
}
func packetHandler(s *Packet) {
if *receiveCounter != "" {
v, ok := counters[*receiveCounter]
if !ok || v < 0 {
counters[*receiveCounter] = 0
}
counters[*receiveCounter] += 1
}
switch s.Modifier {
case "ms":
_, ok := timers[s.Bucket]
if !ok {
var t Float64Slice
timers[s.Bucket] = t
}
timers[s.Bucket] = append(timers[s.Bucket], s.ValFlt)
case "g":
gaugeValue, _ := gauges[s.Bucket]
if s.ValStr == "" {
gaugeValue = s.ValFlt
} else if s.ValStr == "+" {
// watch out for overflows
if s.ValFlt > (math.MaxFloat64 - gaugeValue) {
gaugeValue = math.MaxFloat64
} else {
gaugeValue += s.ValFlt
}
} else if s.ValStr == "-" {
// subtract checking for negative numbers
if s.ValFlt > gaugeValue {
gaugeValue = 0
} else {
gaugeValue -= s.ValFlt
}
}
gauges[s.Bucket] = gaugeValue
case "c":
_, ok := counters[s.Bucket]
if !ok {
counters[s.Bucket] = 0
}
counters[s.Bucket] += s.ValFlt * float64(1/s.Sampling)
case "s":
_, ok := sets[s.Bucket]
if !ok {
sets[s.Bucket] = make([]string, 0)
}
sets[s.Bucket] = append(sets[s.Bucket], s.ValStr)
}
}
func submit(deadline time.Time) error {
var buffer bytes.Buffer
var num int64
now := time.Now().Unix()
if *graphiteAddress == "-" {
return nil
}
client, err := net.Dial("tcp", *graphiteAddress)
if err != nil {
if *debug {
log.Printf("WARNING: resetting counters when in debug mode")
processCounters(&buffer, now)
processGauges(&buffer, now)
processTimers(&buffer, now, percentThreshold)
processSets(&buffer, now)
}
errmsg := fmt.Sprintf("dialing %s failed - %s", *graphiteAddress, err)
return errors.New(errmsg)
}
defer client.Close()
err = client.SetDeadline(deadline)
if err != nil {
return err
}
num += processCounters(&buffer, now)
num += processGauges(&buffer, now)
num += processTimers(&buffer, now, percentThreshold)
num += processSets(&buffer, now)
if num == 0 {
return nil
}
if *debug {
for _, line := range bytes.Split(buffer.Bytes(), []byte("\n")) {
if len(line) == 0 {
continue
}
log.Printf("DEBUG: %s", line)
}
}
_, err = client.Write(buffer.Bytes())
if err != nil {
errmsg := fmt.Sprintf("failed to write stats - %s", err)
return errors.New(errmsg)
}
log.Printf("sent %d stats to %s", num, *graphiteAddress)
if *heartbeatFilePath != "" {
heartbeat()
}
return nil
}
func processCounters(buffer *bytes.Buffer, now int64) int64 {
var num int64
// continue sending zeros for counters for a short period of time even if we have no new data
for bucket, value := range counters {
fmt.Fprintf(buffer, "%s %s %d\n", bucket, strconv.FormatFloat(value, 'f', -1, 64), now)
delete(counters, bucket)
countInactivity[bucket] = 0
num++
}
for bucket, purgeCount := range countInactivity {
if purgeCount > 0 {
fmt.Fprintf(buffer, "%s 0 %d\n", bucket, now)
num++
}
countInactivity[bucket] += 1
if countInactivity[bucket] > *persistCountKeys {
delete(countInactivity, bucket)
}
}
return num
}
func processGauges(buffer *bytes.Buffer, now int64) int64 {
var num int64
for bucket, currentValue := range gauges {
fmt.Fprintf(buffer, "%s %s %d\n", bucket, strconv.FormatFloat(currentValue, 'f', -1, 64), now)
num++
if *deleteGauges {
delete(gauges, bucket)
}
}
return num
}
func processSets(buffer *bytes.Buffer, now int64) int64 {
num := int64(len(sets))
for bucket, set := range sets {
uniqueSet := map[string]bool{}
for _, str := range set {
uniqueSet[str] = true
}
fmt.Fprintf(buffer, "%s %d %d\n", bucket, len(uniqueSet), now)
delete(sets, bucket)
}
return num
}
func processTimers(buffer *bytes.Buffer, now int64, pctls Percentiles) int64 {
var num int64
for bucket, timer := range timers {
bucketWithoutPostfix := bucket[:len(bucket)-len(*postfix)]
num++
sort.Sort(timer)
min := timer[0]
max := timer[len(timer)-1]
maxAtThreshold := max
count := len(timer)
sum := float64(0)
for _, value := range timer {
sum += value
}
mean := sum / float64(len(timer))
for _, pct := range pctls {
if len(timer) > 1 {
var abs float64
if pct.float >= 0 {
abs = pct.float
} else {
abs = 100 + pct.float
}
// poor man's math.Round(x):
// math.Floor(x + 0.5)
indexOfPerc := int(math.Floor(((abs / 100.0) * float64(count)) + 0.5))
if pct.float >= 0 {
indexOfPerc -= 1 // index offset=0
}
maxAtThreshold = timer[indexOfPerc]
}
var tmpl string
var pctstr string
if pct.float >= 0 {
tmpl = "%s.upper_%s%s %s %d\n"
pctstr = pct.str
} else {
tmpl = "%s.lower_%s%s %s %d\n"
pctstr = pct.str[1:]
}
threshold_s := strconv.FormatFloat(maxAtThreshold, 'f', -1, 64)
fmt.Fprintf(buffer, tmpl, bucketWithoutPostfix, pctstr, *postfix, threshold_s, now)
}
mean_s := strconv.FormatFloat(mean, 'f', -1, 64)
max_s := strconv.FormatFloat(max, 'f', -1, 64)
min_s := strconv.FormatFloat(min, 'f', -1, 64)
fmt.Fprintf(buffer, "%s.mean%s %s %d\n", bucketWithoutPostfix, *postfix, mean_s, now)
fmt.Fprintf(buffer, "%s.upper%s %s %d\n", bucketWithoutPostfix, *postfix, max_s, now)
fmt.Fprintf(buffer, "%s.lower%s %s %d\n", bucketWithoutPostfix, *postfix, min_s, now)
fmt.Fprintf(buffer, "%s.count%s %d %d\n", bucketWithoutPostfix, *postfix, count, now)
delete(timers, bucket)
}
return num
}
type MsgParser struct {
reader io.Reader
newbuf []byte
buffer []byte
partialReads bool
done bool
}
func NewParser(reader io.Reader, partialReads bool) *MsgParser {
bufsz := *maxUdpPacketSize
if partialReads {
bufsz = TCP_READ_SIZE
}
newbuf := make([]byte, bufsz)
return &MsgParser{reader, newbuf, newbuf[:0], partialReads, false}
}
func (mp *MsgParser) Next() (*Packet, bool) {
buf := mp.buffer
for {
line, rest := mp.lineFrom(buf)
if line != nil {
mp.buffer = rest
return parseLine(line), true
}
if mp.done {
if len(rest) > 0 {
return parseLine(rest), false
}
return nil, false
}
// for udp, each message independent
// for tcp, copy to front and append
// unless no '\n' in entire TCP_READ_SIZE
idx := 0
if mp.partialReads && len(buf) < TCP_READ_SIZE {
idx = len(buf)
copy(mp.newbuf, buf)
}
buf = mp.newbuf
n, err := mp.reader.Read(buf[idx:])
buf = buf[:idx+n]
if err != nil {
if err != io.EOF {
log.Printf("ERROR: %s", err)
}
mp.done = true
}
}
}
func (mp *MsgParser) lineFrom(input []byte) ([]byte, []byte) {
split := bytes.SplitN(input, []byte("\n"), 2)
if len(split) == 2 {
return split[0], split[1]
}
if !mp.partialReads {
if len(input) == 0 {
input = nil
}
return input, []byte{}
}
// if input ended in '\n' then len(split) == 2 and returned above
return nil, input
}
func parseLine(line []byte) *Packet {
split := bytes.SplitN(line, []byte{'|'}, 3)
if len(split) < 2 {
logParseFail(line)
return nil
}
keyval := split[0]
typeCode := string(split[1])
sampling := float32(1)
if typeCode == "c" || typeCode == "ms" {
if len(split) == 3 && len(split[2]) > 0 && split[2][0] == '@' {
f64, err := strconv.ParseFloat(string(split[2][1:]), 32)
if err != nil {
log.Printf(
"ERROR: failed to ParseFloat %s - %s",
string(split[2][1:]),
err,
)
return nil
}
sampling = float32(f64)
}
}
split = bytes.SplitN(keyval, []byte{':'}, 2)
if len(split) < 2 {
logParseFail(line)
return nil
}
name := split[0]
val := split[1]
if len(val) == 0 {
logParseFail(line)
return nil
}
var (
err error
floatval float64
strval string
)
switch typeCode {
case "c":
floatval, err = strconv.ParseFloat(string(val), 64)
if err != nil {
log.Printf("ERROR: failed to ParseFloat %s - %s", string(val), err)
return nil
}
case "g":
var s string
if val[0] == '+' || val[0] == '-' {
strval = string(val[0])
s = string(val[1:])
} else {
s = string(val)
}
floatval, err = strconv.ParseFloat(s, 64)
if err != nil {
log.Printf("ERROR: failed to ParseFloat %s - %s", string(val), err)
return nil
}
case "s":
strval = string(val)
case "ms":
floatval, err = strconv.ParseFloat(string(val), 64)
if err != nil {
log.Printf("ERROR: failed to ParseFloat %s - %s", string(val), err)
return nil
}
default:
log.Printf("ERROR: unrecognized type code %q for metric %q", typeCode, name)
return nil
}
return &Packet{
Bucket: *prefix + sanitizeBucket(name) + *postfix,
ValFlt: floatval,
ValStr: strval,
Modifier: typeCode,
Sampling: sampling,
}
}
func logParseFail(line []byte) {
if *debug {
log.Printf("ERROR: failed to parse line: %q\n", string(line))
}
}
func parseTo(conn io.ReadCloser, partialReads bool, out chan<- *Packet) {
defer conn.Close()
parser := NewParser(conn, partialReads)
for {
p, more := parser.Next()
if p != nil {
out <- p
}
if !more {
break
}
}
}
func udpListener() {
address, _ := net.ResolveUDPAddr("udp", *serviceAddress)
log.Printf("listening on %s", address)
listener, err := net.ListenUDP("udp", address)
if err != nil {
log.Fatalf("ERROR: ListenUDP - %s", err)
}
parseTo(listener, false, In)
}
func tcpListener() {
address, _ := net.ResolveTCPAddr("tcp", *tcpServiceAddress)
log.Printf("listening on %s", address)
listener, err := net.ListenTCP("tcp", address)
if err != nil {
log.Fatalf("ERROR: ListenTCP - %s", err)
}
defer listener.Close()
for {
conn, err := listener.AcceptTCP()
if err != nil {
log.Fatalf("ERROR: AcceptTCP - %s", err)
}
go parseTo(conn, true, In)
}
}
func heartbeat() {
_, err := os.Stat(*heartbeatFilePath)
if err != nil && os.IsNotExist(err) {
file, err := os.Create(*heartbeatFilePath)
if err != nil {
log.Fatalf("ERROR: Creating heartbeat file - %s", err)
}
defer file.Close()
} else if err != nil {
log.Fatalf("ERROR: %s", err)
}
currentTime := time.Now()
err = os.Chtimes(*heartbeatFilePath, currentTime, currentTime)
if err != nil {
log.Fatalf("ERROR: Touching %s", err)
}
}
func main() {
flag.Parse()
if *showVersion {
fmt.Printf("statsdaemon v%s (built w/%s)\n", VERSION, runtime.Version())
return
}
*prefix = sanitizeBucket([]byte(*prefix))
*postfix = sanitizeBucket([]byte(*postfix))
signalchan = make(chan os.Signal, 1)
signal.Notify(signalchan, syscall.SIGTERM)
go udpListener()
if *tcpServiceAddress != "" {
go tcpListener()
}
monitor()
}