/
log.go
405 lines (337 loc) · 9.5 KB
/
log.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
package main
import (
"bufio"
"fmt"
"log/syslog"
"net"
"strconv"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/pquerna/ffjson/ffjson"
"github.com/quipo/statsd"
"github.com/vmihailenco/msgpack"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
)
// codebeat:disable[TOO_MANY_IVARS]
type logOptions struct {
quiet bool
debug bool
Filename string
FluentdSocket string
MaxAge int
MaxBackups int
MaxSize int
KafkaBrokers string
KafkaTopic string
SyslogFacility string
SyslogPriority string
SensorName string
closed bool
control chan string
}
func NewLogOptions(config *pdnsConfig) *logOptions {
return &logOptions{
quiet: config.quiet,
debug: config.debug,
Filename: config.logFile,
FluentdSocket: config.fluentdSocket,
KafkaBrokers: config.kafkaBrokers,
KafkaTopic: config.kafkaTopic,
MaxAge: config.logMaxAge,
MaxSize: config.logMaxSize,
MaxBackups: config.logMaxBackups,
SyslogFacility: config.syslogFacility,
SyslogPriority: config.syslogPriority,
SensorName: config.sensorName,
}
}
func (lo *logOptions) IsDebug() bool {
return lo.debug
}
func (lo *logOptions) LogToStdout() bool {
return !lo.quiet
}
func (lo *logOptions) LogToFile() bool {
return !(lo.Filename == "")
}
func (lo *logOptions) LogToKafka() bool {
return !(lo.KafkaBrokers == "" && lo.KafkaTopic == "")
}
func (lo *logOptions) LogToSyslog() bool {
return (lo.SyslogFacility != "" && lo.SyslogPriority != "")
}
func (lo *logOptions) LogToFluentd() bool {
return (lo.FluentdSocket != "")
}
// codebeat:disable[TOO_MANY_IVARS]
type dnsLogEntry struct {
Query_ID uint16 `json:"query_id"`
Response_Code int `json:"rcode"`
Question string `json:"q"`
Question_Type string `json:"qtype"`
Answer string `json:"a"`
Answer_Type string `json:"atype"`
TTL uint32 `json:"ttl"`
Server net.IP `json:"dst"`
Client net.IP `json:"src"`
Timestamp string `json:"tstamp"`
Elapsed int64 `json:"elapsed"`
Client_Port string `json:"sport"`
Level string `json:"level"` // syslog level
Length int `json:"bytes"`
Proto string `json:"protocol"`
Truncated bool `json:"truncated"`
Authoritative_Answer bool `json:"aa"`
Recursion_Desired bool `json:"rd"`
Recursion_Available bool `json:"ra"`
encoded []byte //to hold the marshaled data structure
err error //encoding errors
}
// codebeat:enable[TOO_MANY_IVARS]
//private, idempotent function that ensures the json is encoded
func (dle *dnsLogEntry) ensureEncoded() {
if dle.encoded == nil && dle.err == nil {
dle.encoded, dle.err = ffjson.Marshal(dle)
}
}
//returns length of the encoded JSON
func (dle *dnsLogEntry) Size() int {
dle.ensureEncoded()
return len(dle.encoded)
}
//public method to encode the string
func (dle *dnsLogEntry) Encode() ([]byte, error) {
dle.ensureEncoded()
return dle.encoded, dle.err
}
func initLogging(opts *logOptions, config *pdnsConfig) chan dnsLogEntry {
if opts.IsDebug() {
log.SetLevel(log.DebugLevel)
}
//TODO: further logging setup?
/* spin up logging channel */
var logChan = make(chan dnsLogEntry, packetQueue*config.numprocs)
return logChan
}
func watchLogStats(stats *statsd.StatsdBuffer, logC chan dnsLogEntry, logs []chan dnsLogEntry) {
for {
stats.Gauge("incoming_log_depth", int64(len(logC)))
for i, logChan := range logs {
stats.Gauge(strconv.Itoa(i)+".log_depth", int64(len(logChan)))
}
time.Sleep(15 * time.Second)
}
}
//Spin up required logging threads and then round-robin log messages to log sinks
func logConn(logC chan dnsLogEntry, opts *logOptions, stats *statsd.StatsdBuffer) {
//holds the channels for the outgoing log channels
var logs []chan dnsLogEntry
if opts.LogToStdout() {
log.Debug("STDOUT logging enabled")
stdoutChan := make(chan dnsLogEntry)
logs = append(logs, stdoutChan)
go logConnStdout(stdoutChan)
}
if opts.LogToFile() {
log.Debug("file logging enabled to " + opts.Filename)
fileChan := make(chan dnsLogEntry)
logs = append(logs, fileChan)
go logConnFile(fileChan, opts)
}
if opts.LogToKafka() {
log.Debug("kafka logging enabled")
kafkaChan := make(chan dnsLogEntry)
logs = append(logs, kafkaChan)
go logConnKafka(kafkaChan, opts)
}
if opts.LogToSyslog() {
log.Debug("syslog logging enabled")
syslogChan := make(chan dnsLogEntry)
logs = append(logs, syslogChan)
go logConnSyslog(syslogChan, opts)
}
if opts.LogToFluentd() {
log.Debug("fluentd logging enabled")
fluentdlogChan := make(chan dnsLogEntry)
logs = append(logs, fluentdlogChan)
go logConnFluentd(fluentdlogChan, opts)
}
if stats != nil {
go watchLogStats(stats, logC, logs)
}
//setup is done, now we sit here and dispatch messages to the configured sinks
for message := range logC {
for _, logChan := range logs {
logChan <- message
}
}
//if the range exits, the channel was closed, so close the other channels
for _, logChan := range logs {
close(logChan)
}
return
}
//logs to stdout
func logConnStdout(logC chan dnsLogEntry) {
for message := range logC {
encoded, _ := message.Encode()
fmt.Println(string(encoded))
}
}
//logs to a file
func logConnFile(logC chan dnsLogEntry, opts *logOptions) {
logger := &lumberjack.Logger{
Filename: opts.Filename,
MaxSize: opts.MaxSize, // megabytes
MaxBackups: opts.MaxBackups,
MaxAge: opts.MaxAge, //days
}
enc := ffjson.NewEncoder(bufio.NewWriter(logger))
for message := range logC {
enc.Encode(message)
}
logger.Close()
}
//logs to kafka
func logConnKafka(logC chan dnsLogEntry, opts *logOptions) {
for message := range logC {
encoded, _ := message.Encode()
fmt.Println("Kafka: " + string(encoded))
}
}
//logs to syslog
func logConnSyslog(logC chan dnsLogEntry, opts *logOptions) {
level, err := levelToType(opts.SyslogPriority)
if err != nil {
log.Fatalf("string '%s' did not parse as a priority", opts.SyslogPriority)
}
facility, err := facilityToType(opts.SyslogFacility)
if err != nil {
log.Fatalf("string '%s' did not parse as a facility", opts.SyslogFacility)
}
logger, err := syslog.New(facility|level, "")
if err != nil {
log.Fatalf("failed to connect to the local syslog daemon: %s", err)
}
for message := range logC {
encoded, _ := message.Encode()
logger.Write([]byte(encoded))
}
}
//logs to fluentd via a unix socket
func logConnFluentd(logC chan dnsLogEntry, opts *logOptions) {
Tag := opts.SensorName + ".service"
tag, _ := msgpack.Marshal(Tag)
conn := fluentdSocket(opts.FluentdSocket)
defer conn.Close()
for message := range logC {
tm, _ := msgpack.Marshal(time.Now().Unix())
rec, err := msgpack.Marshal(&message)
if err != nil {
fmt.Println(err)
}
encoded := []byte{0x93}
encoded = append(encoded, tag...)
encoded = append(encoded, tm...)
encoded = append(encoded, rec...)
_, err = conn.Write(encoded)
if err != nil {
log.Fatalf("Unable to write to UNIX Socket %+v with err %+v\n", opts.FluentdSocket, err)
}
}
}
func facilityToType(facility string) (syslog.Priority, error) {
facility = strings.ToUpper(facility)
switch facility {
case "KERN":
return syslog.LOG_KERN, nil
case "USER":
return syslog.LOG_USER, nil
case "MAIL":
return syslog.LOG_MAIL, nil
case "DAEMON":
return syslog.LOG_DAEMON, nil
case "AUTH":
return syslog.LOG_AUTH, nil
case "SYSLOG":
return syslog.LOG_SYSLOG, nil
case "LPR":
return syslog.LOG_LPR, nil
case "NEWS":
return syslog.LOG_NEWS, nil
case "UUCP":
return syslog.LOG_UUCP, nil
case "CRON":
return syslog.LOG_CRON, nil
case "AUTHPRIV":
return syslog.LOG_AUTHPRIV, nil
case "FTP":
return syslog.LOG_FTP, nil
case "LOCAL0":
return syslog.LOG_LOCAL0, nil
case "LOCAL1":
return syslog.LOG_LOCAL1, nil
case "LOCAL2":
return syslog.LOG_LOCAL2, nil
case "LOCAL3":
return syslog.LOG_LOCAL3, nil
case "LOCAL4":
return syslog.LOG_LOCAL4, nil
case "LOCAL5":
return syslog.LOG_LOCAL5, nil
case "LOCAL6":
return syslog.LOG_LOCAL6, nil
case "LOCAL7":
return syslog.LOG_LOCAL7, nil
default:
return 0, fmt.Errorf("invalid syslog facility: %s", facility)
}
}
func levelToType(level string) (syslog.Priority, error) {
level = strings.ToUpper(level)
switch level {
case "EMERG":
return syslog.LOG_EMERG, nil
case "ALERT":
return syslog.LOG_ALERT, nil
case "CRIT":
return syslog.LOG_CRIT, nil
case "ERR":
return syslog.LOG_ERR, nil
case "WARNING":
return syslog.LOG_WARNING, nil
case "NOTICE":
return syslog.LOG_NOTICE, nil
case "INFO":
return syslog.LOG_INFO, nil
case "DEBUG":
return syslog.LOG_DEBUG, nil
default:
return 0, fmt.Errorf("Unknown priority: %s", level)
}
}
func fluentdSocket(path string) *net.UnixConn {
var retries int = 10
var timeout time.Duration = 5
// we want to have retries because fluentd can take some time to start.
for i := 1; i <= retries; i++ {
raddr, err := net.ResolveUnixAddr("unix", path)
if err != nil {
log.Printf("Failed to open remote socket. %s.\n", err)
}
conn, err := net.DialUnix("unix", nil, raddr)
if err != nil {
log.Printf("Failed to connect to fluentd socket. %s retrying in 5 seconds.", err)
time.Sleep(timeout * time.Second)
continue
}
err = conn.SetWriteBuffer(65536)
if err != nil {
log.Printf("Unable to set fluentd write buffer. %s", err)
}
return conn
}
log.Fatalf("Unable to open connection to fluentd socket after %d retries\n", retries)
return nil
}