forked from influxdata/influxdb-relay
/
graphite.go
360 lines (298 loc) · 7.97 KB
/
graphite.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
package relay
import (
"compress/gzip"
"crypto/tls"
"fmt"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
log "github.com/golang/glog"
"github.com/influxdata/influxdb/models"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/plugins/outputs/graphite"
"github.com/robfig/cron"
)
// Metering Read-Write mutex
var mu = &sync.RWMutex{}
var metering = make(map[string]map[string]int)
var amqpURL string
// GraphiteRelay is a relay for graphite backends
type GraphiteRelay struct {
addr string
name string
schema string
cert string
closing int64
l net.Listener
enableMetering bool
ampqURL string
dropUnauthorized bool
cronJob *cron.Cron
cronSchedule string
backends []*graphiteBackend
}
func (g *GraphiteRelay) Name() string {
if g.name == "" {
return fmt.Sprintf("%s://%s", g.schema, g.addr)
}
return g.name
}
func (g *GraphiteRelay) Run() error {
l, err := net.Listen("tcp", g.addr)
if g.cronSchedule != "" {
g.cronJob.AddFunc(g.cronSchedule, pushToAmqp)
g.cronJob.Start()
}
if err != nil {
return err
}
// support HTTPS
if g.cert != "" {
cert, err := tls.LoadX509KeyPair(g.cert, g.cert)
if err != nil {
return err
}
l = tls.NewListener(l, &tls.Config{
Certificates: []tls.Certificate{cert},
})
}
g.l = l
log.Infof("Starting Graphite relay %q on %v", g.Name(), g.addr)
err = http.Serve(l, g)
if atomic.LoadInt64(&g.closing) != 0 {
return nil
}
return err
}
func (g *GraphiteRelay) Stop() error {
atomic.StoreInt64(&g.closing, 1)
if g.cronSchedule != "" {
g.cronJob.Stop()
}
return g.l.Close()
}
func NewGraphiteRelay(cfg GraphiteConfig) (Relay, error) {
g := new(GraphiteRelay)
g.addr = cfg.Addr
g.name = cfg.Name
g.cert = cfg.SSLCombinedPem
g.schema = "http"
if g.cert != "" {
g.schema = "https"
}
for i := range cfg.Outputs {
backend, err := NewGraphiteBackend(&cfg.Outputs[i])
if err != nil {
return nil, err
}
g.backends = append(g.backends, backend)
}
g.enableMetering = cfg.EnableMetering
g.ampqURL = cfg.AMQPUrl
amqpURL = cfg.AMQPUrl
if g.enableMetering && g.ampqURL == "" {
g.enableMetering = false
log.Warning("You have to set AMQPUrl in config for metering to work")
log.Warning("Disabling metering for now")
}
g.dropUnauthorized = cfg.DropUnauthorized
g.cronSchedule = cfg.CronSchedule
if g.cronSchedule != "" {
g.cronJob = cron.New()
}
return g, nil
}
// NewGraphiteBackend Initializes a new Graphite Backend
func NewGraphiteBackend(cfg *GraphiteOutputConfig) (*graphiteBackend, error) {
if cfg.Name == "" {
cfg.Name = cfg.Location
}
return &graphiteBackend{
name: cfg.Name,
location: cfg.Location,
}, nil
}
type graphiteBackend struct {
// poster
name string
location string
}
func (g *GraphiteRelay) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
graphiteServers := make([]string, len(g.backends))
for i := range g.backends {
graphiteServers = append(graphiteServers, g.backends[i].location)
}
graphiteClient := &graphite.Graphite{
Servers: graphiteServers,
Prefix: "bucky",
}
conErr := graphiteClient.Connect()
if conErr != nil {
jsonError(w, http.StatusInternalServerError, "unable to connect to graphite")
log.Fatalf("Could not connect to graphite: %s", conErr)
}
queryParams := r.URL.Query()
// if r.URL.Path == "/metrics" {
// resp := ""
// t := time.Now().UnixNano()
// mu.RLock()
// for orgID, machineMap := range metering {
// for machineID, samples := range machineMap {
// resp += fmt.Sprintf("gocky_samples_total{relay=graphite,orgID=%s,machineID=%s} %d %d\n", orgID, machineID, samples, t)
// }
// }
// mu.RUnlock()
// io.WriteString(w, resp)
// return
// }
if r.URL.Path != "/write" {
jsonError(w, 204, "Dummy response for db creation")
return
}
var body = r.Body
if r.Header.Get("Content-Encoding") == "gzip" {
b, err := gzip.NewReader(r.Body)
if err != nil {
jsonError(w, http.StatusBadRequest, "unable to decode gzip body")
}
defer b.Close()
body = b
}
bodyBuf := getBuf()
_, err := bodyBuf.ReadFrom(body)
if err != nil {
putBuf(bodyBuf)
jsonError(w, http.StatusInternalServerError, "problem reading request body")
return
}
precision := queryParams.Get("precision")
points, err := models.ParsePointsWithPrecision(bodyBuf.Bytes(), start, precision)
if err != nil {
putBuf(bodyBuf)
jsonError(w, http.StatusBadRequest, "unable to parse points")
return
}
machineID := ""
if r.Header["X-Gocky-Tag-Machine-Id"] != nil {
machineID = r.Header["X-Gocky-Tag-Machine-Id"][0]
} else {
if g.dropUnauthorized {
log.Error("Gocky Headers are missing. Dropping packages...")
jsonError(w, http.StatusForbidden, "cannot find Gocky headers")
return
}
}
sourceType := "unix"
if r.Header["X-Gocky-Tag-Source-Type"][0] == "windows" {
sourceType = "windows"
}
go pushToGraphite(points, graphiteClient, machineID, sourceType)
if g.enableMetering {
orgID := "Unauthorized"
if r.Header["X-Gocky-Tag-Org-Id"] != nil {
orgID = r.Header["X-Gocky-Tag-Org-Id"][0]
}
machineID := ""
if r.Header["X-Gocky-Tag-Machine-Id"] != nil {
machineID = r.Header["X-Gocky-Tag-Machine-Id"][0]
}
mu.Lock()
_, orgExists := metering[orgID]
if !orgExists {
metering[orgID] = make(map[string]int)
}
_, machExists := metering[orgID][machineID]
if !machExists {
metering[orgID][machineID] = len(points)
} else {
metering[orgID][machineID] += len(points)
}
mu.Unlock()
}
// telegraf expects a 204 response on write
w.WriteHeader(204)
}
func pushToGraphite(points []models.Point, g *graphite.Graphite, machineID, sourceType string) (*responseData, error) {
for _, p := range points {
tags := make(map[string]string)
for _, v := range p.Tags() {
tags[string(v.Key)] = string(v.Value)
}
if machineID == "" {
machineID = "Unknown." + tags["machine_id"]
}
tags["machine_id"] = machineID
graphiteMetrics := make([]telegraf.Metric, 0, len(points))
fi := p.FieldIterator()
for fi.Next() {
switch fi.Type() {
case models.Float:
v, _ := fi.FloatValue()
if utf8.ValidString(string(fi.FieldKey())) {
switch sourceType {
case "windows":
grphPoint := GraphiteWindowsMetric(string(p.Name()), tags, p.UnixNano(), v, string(fi.FieldKey()))
if grphPoint != nil {
graphiteMetrics = append(graphiteMetrics, grphPoint)
}
default:
grphPoint := GraphiteMetric(string(p.Name()), tags, p.UnixNano(), v, string(fi.FieldKey()))
if grphPoint != nil {
graphiteMetrics = append(graphiteMetrics, grphPoint)
}
}
}
case models.Integer:
v, _ := fi.IntegerValue()
if utf8.ValidString(string(fi.FieldKey())) {
switch sourceType {
case "windows":
grphPoint := GraphiteWindowsMetric(string(p.Name()), tags, p.UnixNano(), v, string(fi.FieldKey()))
if grphPoint != nil {
graphiteMetrics = append(graphiteMetrics, grphPoint)
}
default:
grphPoint := GraphiteMetric(string(p.Name()), tags, p.UnixNano(), v, string(fi.FieldKey()))
if grphPoint != nil {
graphiteMetrics = append(graphiteMetrics, grphPoint)
}
}
}
// case models.String:
// log.Println("String values not supported")
// case models.Boolean:
// log.Println("Boolean values not supported")
// case models.Empty:
// log.Println("Empry values not supported")
// default:
// log.Println("Unknown value type")
}
}
err := g.Write(graphiteMetrics)
if log.V(5) {
log.Infof("Sending datapoints to graphite backend: %s, from machine: %s", g.Servers[0], machineID)
}
for i := 0; i < 3; i++ {
if err == nil {
break
}
log.Error(err)
log.Errorf("Retrying to send datapoints to graphite backend: %s, from machine: %s", g.Servers[0], machineID)
time.Sleep(1000 * time.Millisecond)
err = g.Write(graphiteMetrics)
}
if err != nil {
return nil, err
}
}
return &responseData{
ContentType: "",
ContentEncoding: "",
StatusCode: 200,
Body: nil,
}, nil
}