-
Notifications
You must be signed in to change notification settings - Fork 5.6k
/
Copy pathgraylog.go
406 lines (331 loc) · 7.61 KB
/
graylog.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
package graylog
import (
"bytes"
"compress/zlib"
"crypto/rand"
"crypto/tls"
"encoding/binary"
ejson "encoding/json"
"fmt"
"io"
"math"
"net"
"os"
"strings"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
tlsint "github.com/influxdata/telegraf/plugins/common/tls"
"github.com/influxdata/telegraf/plugins/outputs"
)
const (
defaultEndpoint = "127.0.0.1:12201"
defaultConnection = "wan"
defaultMaxChunkSizeWan = 1420
defaultMaxChunkSizeLan = 8154
defaultScheme = "udp"
defaultTimeout = 5 * time.Second
)
type gelfConfig struct {
Endpoint string
Connection string
MaxChunkSizeWan int
MaxChunkSizeLan int
}
type gelf interface {
io.WriteCloser
Connect() error
}
type gelfCommon struct {
gelfConfig
dialer *net.Dialer
conn net.Conn
}
type gelfUDP struct {
gelfCommon
}
type gelfTCP struct {
gelfCommon
tlsConfig *tls.Config
}
func newGelfWriter(cfg gelfConfig, dialer *net.Dialer, tlsConfig *tls.Config) gelf {
if cfg.Endpoint == "" {
cfg.Endpoint = defaultEndpoint
}
if cfg.Connection == "" {
cfg.Connection = defaultConnection
}
if cfg.MaxChunkSizeWan == 0 {
cfg.MaxChunkSizeWan = defaultMaxChunkSizeWan
}
if cfg.MaxChunkSizeLan == 0 {
cfg.MaxChunkSizeLan = defaultMaxChunkSizeLan
}
scheme := defaultScheme
parts := strings.SplitN(cfg.Endpoint, "://", 2)
if len(parts) == 2 {
scheme = strings.ToLower(parts[0])
cfg.Endpoint = parts[1]
}
common := gelfCommon{
gelfConfig: cfg,
dialer: dialer,
}
var g gelf
switch scheme {
case "tcp":
g = &gelfTCP{gelfCommon: common, tlsConfig: tlsConfig}
default:
g = &gelfUDP{gelfCommon: common}
}
return g
}
func (g *gelfUDP) Write(message []byte) (n int, err error) {
compressed := g.compress(message)
chunksize := g.gelfConfig.MaxChunkSizeWan
length := compressed.Len()
if length > chunksize {
chunkCountInt := int(math.Ceil(float64(length) / float64(chunksize)))
id := make([]byte, 8)
rand.Read(id)
for i, index := 0, 0; i < length; i, index = i+chunksize, index+1 {
packet := g.createChunkedMessage(index, chunkCountInt, id, &compressed)
err = g.send(packet.Bytes())
if err != nil {
return 0, err
}
}
} else {
err = g.send(compressed.Bytes())
if err != nil {
return 0, err
}
}
n = len(message)
return n, nil
}
func (g *gelfUDP) Close() (err error) {
if g.conn != nil {
err = g.conn.Close()
g.conn = nil
}
return err
}
func (g *gelfUDP) createChunkedMessage(index int, chunkCountInt int, id []byte, compressed *bytes.Buffer) bytes.Buffer {
var packet bytes.Buffer
chunksize := g.getChunksize()
packet.Write(g.intToBytes(30))
packet.Write(g.intToBytes(15))
packet.Write(id)
packet.Write(g.intToBytes(index))
packet.Write(g.intToBytes(chunkCountInt))
packet.Write(compressed.Next(chunksize))
return packet
}
func (g *gelfUDP) getChunksize() int {
if g.gelfConfig.Connection == "wan" {
return g.gelfConfig.MaxChunkSizeWan
}
if g.gelfConfig.Connection == "lan" {
return g.gelfConfig.MaxChunkSizeLan
}
return g.gelfConfig.MaxChunkSizeWan
}
func (g *gelfUDP) intToBytes(i int) []byte {
buf := new(bytes.Buffer)
binary.Write(buf, binary.LittleEndian, int8(i))
return buf.Bytes()
}
func (g *gelfUDP) compress(b []byte) bytes.Buffer {
var buf bytes.Buffer
comp := zlib.NewWriter(&buf)
comp.Write(b)
comp.Close()
return buf
}
func (g *gelfUDP) Connect() error {
conn, err := g.dialer.Dial("udp", g.gelfConfig.Endpoint)
if err != nil {
return err
}
g.conn = conn
return nil
}
func (g *gelfUDP) send(b []byte) error {
if g.conn == nil {
err := g.Connect()
if err != nil {
return err
}
}
_, err := g.conn.Write(b)
if err != nil {
_ = g.conn.Close()
g.conn = nil
}
return err
}
func (g *gelfTCP) Write(message []byte) (n int, err error) {
err = g.send(message)
if err != nil {
return 0, err
}
n = len(message)
return n, nil
}
func (g *gelfTCP) Close() (err error) {
if g.conn != nil {
err = g.conn.Close()
g.conn = nil
}
return err
}
func (g *gelfTCP) Connect() error {
var err error
var conn net.Conn
if g.tlsConfig == nil {
conn, err = g.dialer.Dial("tcp", g.gelfConfig.Endpoint)
} else {
conn, err = tls.DialWithDialer(g.dialer, "tcp", g.gelfConfig.Endpoint, g.tlsConfig)
}
if err != nil {
return err
}
g.conn = conn
return nil
}
func (g *gelfTCP) send(b []byte) error {
if g.conn == nil {
err := g.Connect()
if err != nil {
return err
}
}
_, err := g.conn.Write(b)
if err != nil {
_ = g.conn.Close()
g.conn = nil
} else {
_, err = g.conn.Write([]byte{0}) // message delimiter
if err != nil {
_ = g.conn.Close()
g.conn = nil
}
}
return err
}
type Graylog struct {
Servers []string `toml:"servers"`
ShortMessageField string `toml:"short_message_field"`
Timeout config.Duration `toml:"timeout"`
tlsint.ClientConfig
writer io.Writer
closers []io.WriteCloser
}
var sampleConfig = `
## Endpoints for your graylog instances.
servers = ["udp://127.0.0.1:12201"]
## Connection timeout.
# timeout = "5s"
## The field to use as the GELF short_message, if unset the static string
## "telegraf" will be used.
## example: short_message_field = "message"
# short_message_field = ""
## Optional TLS Config
# tls_ca = "/etc/telegraf/ca.pem"
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
## Use TLS but skip chain & host verification
# insecure_skip_verify = false
`
func (g *Graylog) Connect() error {
var writers []io.Writer
dialer := &net.Dialer{Timeout: time.Duration(g.Timeout)}
if len(g.Servers) == 0 {
g.Servers = append(g.Servers, "localhost:12201")
}
tlsCfg, err := g.ClientConfig.TLSConfig()
if err != nil {
return err
}
for _, server := range g.Servers {
w := newGelfWriter(gelfConfig{Endpoint: server}, dialer, tlsCfg)
err := w.Connect()
if err != nil {
return fmt.Errorf("failed to connect to server [%s]: %v", server, err)
}
writers = append(writers, w)
g.closers = append(g.closers, w)
}
g.writer = io.MultiWriter(writers...)
return nil
}
func (g *Graylog) Close() error {
for _, closer := range g.closers {
_ = closer.Close()
}
return nil
}
func (g *Graylog) SampleConfig() string {
return sampleConfig
}
func (g *Graylog) Description() string {
return "Send telegraf metrics to graylog"
}
func (g *Graylog) Write(metrics []telegraf.Metric) error {
for _, metric := range metrics {
values, err := g.serialize(metric)
if err != nil {
return err
}
for _, value := range values {
_, err := g.writer.Write([]byte(value))
if err != nil {
return fmt.Errorf("error writing message: %q, %v", value, err)
}
}
}
return nil
}
func (g *Graylog) serialize(metric telegraf.Metric) ([]string, error) {
out := []string{}
m := make(map[string]interface{})
m["version"] = "1.1"
m["timestamp"] = float64(metric.Time().UnixNano()) / 1_000_000_000
m["short_message"] = "telegraf"
m["_name"] = metric.Name()
if host, ok := metric.GetTag("host"); ok {
m["host"] = host
} else {
host, err := os.Hostname()
if err != nil {
return []string{}, err
}
m["host"] = host
}
for _, tag := range metric.TagList() {
if tag.Key != "host" {
m["_"+tag.Key] = tag.Value
}
}
for _, field := range metric.FieldList() {
if field.Key == g.ShortMessageField {
m["short_message"] = field.Value
} else {
m["_"+field.Key] = field.Value
}
}
serialized, err := ejson.Marshal(m)
if err != nil {
return []string{}, err
}
out = append(out, string(serialized))
return out, nil
}
func init() {
outputs.Add("graylog", func() telegraf.Output {
return &Graylog{
Timeout: config.Duration(defaultTimeout),
}
})
}