/
grafananet.go
278 lines (245 loc) · 8.14 KB
/
grafananet.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
package route
import (
"bytes"
"crypto/tls"
"hash/fnv"
"net"
"net/http"
"sync"
"sync/atomic"
"time"
"github.com/Dieterbe/go-metrics"
"github.com/golang/snappy"
dest "github.com/graphite-ng/carbon-relay-ng/destination"
"github.com/graphite-ng/carbon-relay-ng/matcher"
"github.com/graphite-ng/carbon-relay-ng/stats"
"github.com/graphite-ng/carbon-relay-ng/util"
"github.com/jpillora/backoff"
"github.com/lomik/go-carbon/persister"
"gopkg.in/raintank/schema.v1"
"gopkg.in/raintank/schema.v1/msg"
)
type GrafanaNet struct {
baseRoute
addr string
apiKey string
buf chan []byte
schemas persister.WhisperSchemas
bufSize int // amount of messages we can buffer up. each message is about 100B. so 1e7 is about 1GB.
flushMaxNum int
flushMaxWait time.Duration
timeout time.Duration
sslVerify bool
blocking bool
dispatch func(chan []byte, []byte, metrics.Gauge, metrics.Counter)
concurrency int
orgId int
writeQueues []chan []byte
shutdown chan struct{}
wg *sync.WaitGroup
client *http.Client
numErrFlush metrics.Counter
numOut metrics.Counter // metrics successfully written to our buffered conn (no flushing yet)
numDropBuffFull metrics.Counter // metric drops due to queue full
durationTickFlush metrics.Timer // only updated after successful flush
durationManuFlush metrics.Timer // only updated after successful flush. not implemented yet
tickFlushSize metrics.Histogram // only updated after successful flush
manuFlushSize metrics.Histogram // only updated after successful flush. not implemented yet
numBuffered metrics.Gauge
bufferSize metrics.Gauge
}
// NewGrafanaNet creates a special route that writes to a grafana.net datastore
// We will automatically run the route and the destination
// ignores spool for now
func NewGrafanaNet(key, prefix, sub, regex, addr, apiKey, schemasFile string, spool, sslVerify, blocking bool, bufSize, flushMaxNum, flushMaxWait, timeout, concurrency, orgId int) (Route, error) {
m, err := matcher.New(prefix, sub, regex)
if err != nil {
return nil, err
}
schemas, err := getSchemas(schemasFile)
if err != nil {
return nil, err
}
cleanAddr := util.AddrToPath(addr)
r := &GrafanaNet{
baseRoute: baseRoute{sync.Mutex{}, atomic.Value{}, key},
addr: addr,
apiKey: apiKey,
buf: make(chan []byte, bufSize), // takes about 228MB on 64bit
schemas: schemas,
bufSize: bufSize,
flushMaxNum: flushMaxNum,
flushMaxWait: time.Duration(flushMaxWait) * time.Millisecond,
timeout: time.Duration(timeout) * time.Millisecond,
sslVerify: sslVerify,
blocking: blocking,
concurrency: concurrency,
orgId: orgId,
writeQueues: make([]chan []byte, concurrency),
shutdown: make(chan struct{}),
wg: new(sync.WaitGroup),
numErrFlush: stats.Counter("dest=" + cleanAddr + ".unit=Err.type=flush"),
numOut: stats.Counter("dest=" + cleanAddr + ".unit=Metric.direction=out"),
durationTickFlush: stats.Timer("dest=" + cleanAddr + ".what=durationFlush.type=ticker"),
durationManuFlush: stats.Timer("dest=" + cleanAddr + ".what=durationFlush.type=manual"),
tickFlushSize: stats.Histogram("dest=" + cleanAddr + ".unit=B.what=FlushSize.type=ticker"),
manuFlushSize: stats.Histogram("dest=" + cleanAddr + ".unit=B.what=FlushSize.type=manual"),
numBuffered: stats.Gauge("dest=" + cleanAddr + ".unit=Metric.what=numBuffered"),
bufferSize: stats.Gauge("dest=" + cleanAddr + ".unit=Metric.what=bufferSize"),
numDropBuffFull: stats.Counter("dest=" + cleanAddr + ".unit=Metric.action=drop.reason=queue_full"),
}
r.bufferSize.Update(int64(bufSize))
if blocking {
r.dispatch = dispatchBlocking
} else {
r.dispatch = dispatchNonBlocking
}
for i := 0; i < r.concurrency; i++ {
r.writeQueues[i] = make(chan []byte)
}
r.config.Store(baseConfig{*m, make([]*dest.Destination, 0)})
r.client = &http.Client{
Timeout: r.timeout,
}
if !r.sslVerify {
// this transport should be the equivalent of Go's DefaultTransport
r.client.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).Dial,
TLSHandshakeTimeout: 10 * time.Second,
// except we removed ExpectContinueTimeout cause it doesn't seem very useful, requires go 1.6, and prevents using http2.
// and except for this
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
}
go r.run()
return r, nil
}
func (route *GrafanaNet) run() {
metrics := make([][]*schema.MetricData, route.concurrency)
route.wg.Add(route.concurrency)
for i := 0; i < route.concurrency; i++ {
metrics[i] = make([]*schema.MetricData, 0, route.flushMaxNum)
// start up our goroutines for writing data to tsdb-gw
go route.flush(i)
}
flush := func(shard int) {
if len(metrics[shard]) == 0 {
return
}
mda := schema.MetricDataArray(metrics[shard])
data, err := msg.CreateMsg(mda, 0, msg.FormatMetricDataArrayMsgp)
if err != nil {
panic(err)
}
route.writeQueues[shard] <- data
route.numOut.Inc(int64(len(metrics[shard])))
metrics[shard] = metrics[shard][:0]
}
hasher := fnv.New32a()
ticker := time.NewTicker(route.flushMaxWait)
for {
select {
case buf := <-route.buf:
route.numBuffered.Dec(1)
md, err := parseMetric(buf, route.schemas, route.orgId)
if err != nil {
log.Error("RouteGrafanaNet: %s", err)
continue
}
md.SetId()
//re-use our []byte slice to save an allocation.
buf = md.KeyBySeries(buf[:0])
hasher.Reset()
hasher.Write(buf)
shard := int(hasher.Sum32() % uint32(route.concurrency))
metrics[shard] = append(metrics[shard], md)
if len(metrics[shard]) == route.flushMaxNum {
flush(shard)
}
case <-ticker.C:
for shard := 0; shard < route.concurrency; shard++ {
flush(shard)
}
case <-route.shutdown:
for shard := 0; shard < route.concurrency; shard++ {
flush(shard)
close(route.writeQueues[shard])
}
return
}
}
}
func (route *GrafanaNet) flush(shard int) {
b := &backoff.Backoff{
Min: 100 * time.Millisecond,
Max: time.Minute,
Factor: 1.5,
Jitter: true,
}
body := new(bytes.Buffer)
for data := range route.writeQueues[shard] {
for {
pre := time.Now()
body.Reset()
snappyBody := snappy.NewWriter(body)
snappyBody.Write(data)
snappyBody.Close()
req, err := http.NewRequest("POST", route.addr, body)
if err != nil {
panic(err)
}
req.Header.Add("Authorization", "Bearer "+route.apiKey)
req.Header.Add("Content-Type", "rt-metric-binary-snappy")
resp, err := route.client.Do(req)
diff := time.Since(pre)
if err == nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
b.Reset()
log.Info("GrafanaNet sent metrics in %s -msg size %d", diff, len(data))
route.tickFlushSize.Update(int64(len(data)))
route.durationTickFlush.Update(diff)
resp.Body.Close()
break
}
route.numErrFlush.Inc(1)
dur := b.Duration()
if err != nil {
log.Warning("GrafanaNet failed to submit data: %s will try again in %s (this attempt took %s)", err, dur, diff)
} else {
buf := make([]byte, 300)
n, _ := resp.Body.Read(buf)
log.Warning("GrafanaNet failed to submit data: http %d - %s will try again in %s (this attempt took %s)", resp.StatusCode, buf[:n], dur, diff)
resp.Body.Close()
}
time.Sleep(dur)
}
}
route.wg.Done()
}
func (route *GrafanaNet) Dispatch(buf []byte) {
//conf := route.config.Load().(Config)
// should return as quickly as possible
log.Info("route %s sending to dest %s: %s", route.key, route.addr, buf)
route.dispatch(route.buf, buf, route.numBuffered, route.numDropBuffFull)
}
func (route *GrafanaNet) Flush() error {
//conf := route.config.Load().(Config)
// no-op. Flush() is currently not called by anything.
return nil
}
func (route *GrafanaNet) Shutdown() error {
//conf := route.config.Load().(Config)
// trigger all of our queues to be flushed to the tsdb-gw
route.shutdown <- struct{}{}
// wait for all tsdb-gw writes to complete.
route.wg.Wait()
return nil
}
func (route *GrafanaNet) Snapshot() Snapshot {
return makeSnapshot(&route.baseRoute, "GrafanaNet")
}