forked from jcoene/statsd-librato
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
348 lines (290 loc) · 7.55 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"github.com/jcoene/gologger"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
const VERSION = "0.1.4"
type Packet struct {
Bucket string
Value string
Modifier string
Sampling float32
}
var log *logger.Logger
var sanitizeRegexp = regexp.MustCompile("[^a-zA-Z0-9\\-_\\.,:\\|@]")
var packetRegexp = regexp.MustCompile("([a-zA-Z0-9_\\.,]+):(\\-?[0-9\\.]+)\\|(c|ms|g)(\\|@([0-9\\.]+))?")
var (
serviceAddress = flag.String("address", "0.0.0.0:8125", "udp listen address")
libratoUser = flag.String("user", "", "librato api username (LIBRATO_USER)")
libratoToken = flag.String("token", "", "librato api token (LIBRATO_TOKEN)")
libratoSource = flag.String("source", "", "librato api source (LIBRATO_SOURCE)")
flushInterval = flag.Int64("flush", 60, "interval at which data is sent to librato (in seconds)")
percentiles = flag.String("percentiles", "", "comma separated list of percentiles to calculate for timers (eg. \"95,99.5\")")
debug = flag.Bool("debug", false, "enable logging of inputs and submissions")
version = flag.Bool("version", false, "print version and exit")
)
var (
In = make(chan Packet, 10000)
counters = make(map[string]int64)
timers = make(map[string][]float64)
gauges = make(map[string]float64)
)
type Measurement struct {
Counters []Counter `json:"counters"`
Gauges []interface{} `json:"gauges"`
Source *string `json:"source,omitempty"`
}
func (m *Measurement) Count() int {
return (len(m.Counters) + len(m.Gauges))
}
type Counter struct {
Name string `json:"name"`
Source *string `json:"source,omitempty"`
Value int64 `json:"value"`
}
type SimpleGauge struct {
Name string `json:"name"`
Source *string `json:"source,omitempty"`
Value float64 `json:"value"`
}
type ComplexGauge struct {
Name string `json:"name"`
Source *string `json:"source,omitempty"`
Count int `json:"count"`
Sum float64 `json:"sum"`
Min float64 `json:"min"`
Max float64 `json:"max"`
SumSquares float64 `json:"sum_squares"`
Median float64 `json:"median"`
}
func monitor() {
t := time.NewTicker(time.Duration(*flushInterval) * time.Second)
for {
select {
case <-t.C:
if err := submit(); err != nil {
log.Error("submit: %s", err)
}
case s := <-In:
if s.Modifier == "ms" {
_, ok := timers[s.Bucket]
if !ok {
var t []float64
timers[s.Bucket] = t
}
floatValue, _ := strconv.ParseFloat(s.Value, 64)
timers[s.Bucket] = append(timers[s.Bucket], floatValue)
} else if s.Modifier == "g" {
_, ok := gauges[s.Bucket]
if !ok {
gauges[s.Bucket] = float64(0)
}
floatValue, _ := strconv.ParseFloat(s.Value, 64)
gauges[s.Bucket] = floatValue
} else {
_, ok := counters[s.Bucket]
if !ok {
counters[s.Bucket] = 0
}
floatValue, _ := strconv.ParseFloat(s.Value, 32)
counters[s.Bucket] += int64(float32(floatValue) * (1 / s.Sampling))
}
}
}
}
func parseBucket(bucket string) (string, *string) {
if strings.Contains(bucket, ",") {
ss := strings.SplitN(bucket, ",", 2)
return ss[1], &ss[0]
}
return bucket, nil
}
func submit() (err error) {
m := new(Measurement)
if *libratoSource != "" {
m.Source = libratoSource
}
m.Counters = make([]Counter, 0)
m.Gauges = make([]interface{}, 0)
for k, v := range counters {
c := new(Counter)
c.Name, c.Source = parseBucket(k)
c.Value = v
m.Counters = append(m.Counters, *c)
}
for k, v := range gauges {
g := new(SimpleGauge)
g.Name, g.Source = parseBucket(k)
g.Value = v
m.Gauges = append(m.Gauges, *g)
}
for k, t := range timers {
g := gaugePercentile(k, t, 100.0, "")
m.Gauges = append(m.Gauges, *g)
if *percentiles != "" {
pcts := strings.Split(*percentiles, ",")
for _, pct := range pcts {
pctf, err := strconv.ParseFloat(pct, 64)
if err != nil {
log.Warn("error parsing '%s' as float: %s", pct, err)
continue
}
if g = gaugePercentile(k, t, pctf, pct); g != nil {
m.Gauges = append(m.Gauges, *g)
}
}
}
}
if m.Count() == 0 {
log.Info("no new measurements in the last %d seconds", *flushInterval)
return
}
payload, err := json.MarshalIndent(m, "", " ")
if err != nil {
return
}
log.Debug("sending payload:\n%s", payload)
req, err := http.NewRequest("POST", "https://metrics-api.librato.com/v1/metrics", bytes.NewBuffer(payload))
req.Close = true
if err != nil {
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Set("User-Agent", "statsd/1.0")
req.SetBasicAuth(*libratoUser, *libratoToken)
resp, err := http.DefaultClient.Do(req)
if err == nil && resp.StatusCode != 200 {
if err == nil {
raw, _ := ioutil.ReadAll(resp.Body)
err = errors.New(fmt.Sprintf("%s: %s", resp.Status, string(raw)))
}
log.Warn("error sending %d measurements: %s", m.Count(), err)
return
}
log.Info("%d measurements sent", m.Count())
for k, _ := range timers {
delete(timers, k)
}
return
}
func gaugePercentile(k string, t []float64, pct float64, suffix string) *ComplexGauge {
thresholdIdx := ((100.0 - pct) / 100.0) * float64(len(t))
thresholdIdx = math.Floor(thresholdIdx + 0.5)
numInPct := len(t) - int(thresholdIdx)
if numInPct <= 0 {
return nil
}
g := new(ComplexGauge)
g.Name, g.Source = parseBucket(k)
if suffix != "" {
g.Name += "." + suffix
}
g.Count = numInPct
if g.Count > 0 {
sort.Float64s(t)
g.Min = t[0]
g.Max = t[numInPct-1]
for i := 0; i < numInPct; i++ {
v := t[i]
g.Sum += v
g.SumSquares += (v * v)
}
mid := g.Count / 2
g.Median = t[mid]
if g.Count > 2 && g.Count%2 == 0 {
g.Median += t[mid-1]
}
}
return g
}
func handle(conn *net.UDPConn, remaddr net.Addr, buf *bytes.Buffer) {
var packet Packet
var value string
s := sanitizeRegexp.ReplaceAllString(buf.String(), "")
for _, item := range packetRegexp.FindAllStringSubmatch(s, -1) {
value = item[2]
if item[3] == "ms" {
_, err := strconv.ParseFloat(item[2], 32)
if err != nil {
value = "0"
}
}
sampleRate, err := strconv.ParseFloat(item[5], 32)
if err != nil {
sampleRate = 1
}
packet.Bucket = item[1]
packet.Value = value
packet.Modifier = item[3]
packet.Sampling = float32(sampleRate)
In <- packet
}
}
func listen() {
address, _ := net.ResolveUDPAddr("udp", *serviceAddress)
listener, err := net.ListenUDP("udp", address)
defer listener.Close()
if err != nil {
log.Fatal("unable to listen: %s", err)
os.Exit(1)
}
log.Info("listening for events...")
for {
message := make([]byte, 512)
n, remaddr, error := listener.ReadFrom(message)
if error != nil {
continue
}
log.Debug("received metric: %s", message)
buf := bytes.NewBuffer(message[0:n])
go handle(listener, remaddr, buf)
}
}
func main() {
flag.Parse()
if *version {
fmt.Printf("statsd-librato v%s\n", VERSION)
return
}
if *debug {
log = logger.NewLogger(logger.LOG_LEVEL_DEBUG, "statsd")
} else {
log = logger.NewLogger(logger.LOG_LEVEL_INFO, "statsd")
}
if *libratoUser == "" {
if !getEnv(libratoUser, "LIBRATO_USER") {
log.Fatal("specify a librato user with -user or the LIBRATO_USER environment variable")
}
}
if *libratoToken == "" {
if !getEnv(libratoToken, "LIBRATO_TOKEN") {
log.Fatal("specify a librato token with -token or the LIBRATO_TOKEN environment variable")
}
}
if *libratoSource == "" {
getEnv(libratoSource, "LIBRATO_SOURCE")
}
go listen()
monitor()
}
func getEnv(p *string, key string) bool {
if s := os.Getenv(key); s != "" {
*p = s
return true
}
return false
}