-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathsyslog.go
343 lines (288 loc) · 9.38 KB
/
syslog.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
package workers
import (
"bytes"
"crypto/tls"
"encoding/json"
"time"
"strings"
syslog "github.com/dmachard/go-clientsyslog"
"github.com/dmachard/go-dnscollector/dnsutils"
"github.com/dmachard/go-dnscollector/pkgconfig"
"github.com/dmachard/go-dnscollector/transformers"
"github.com/dmachard/go-logger"
"github.com/dmachard/go-netutils"
)
type Syslog struct {
*GenericWorker
severity, facility syslog.Priority
syslogWriter *syslog.Writer
syslogReady bool
transportReady, transportReconnect chan bool
textFormat []string
}
func NewSyslog(config *pkgconfig.Config, console *logger.Logger, name string) *Syslog {
bufSize := config.Global.Worker.ChannelBufferSize
if config.Loggers.Syslog.ChannelBufferSize > 0 {
bufSize = config.Loggers.Syslog.ChannelBufferSize
}
w := &Syslog{GenericWorker: NewGenericWorker(config, console, name, "syslog", bufSize, pkgconfig.DefaultMonitor)}
w.transportReady = make(chan bool)
w.transportReconnect = make(chan bool)
w.ReadConfig()
return w
}
func (w *Syslog) ReadConfig() {
if !netutils.IsValidTLS(w.GetConfig().Loggers.Syslog.TLSMinVersion) {
w.LogFatal(pkgconfig.PrefixLogWorker + "invalid tls min version")
}
if !pkgconfig.IsValidMode(w.GetConfig().Loggers.Syslog.Mode) {
w.LogFatal(pkgconfig.PrefixLogWorker + "invalid mode text or json expected")
}
severity, err := syslog.GetPriority(w.GetConfig().Loggers.Syslog.Severity)
if err != nil {
w.LogFatal(pkgconfig.PrefixLogWorker + "invalid severity")
}
w.severity = severity
facility, err := syslog.GetPriority(w.GetConfig().Loggers.Syslog.Facility)
if err != nil {
w.LogFatal(pkgconfig.PrefixLogWorker + "invalid facility")
}
w.facility = facility
if len(w.GetConfig().Loggers.Syslog.TextFormat) > 0 {
w.textFormat = strings.Fields(w.GetConfig().Loggers.Syslog.TextFormat)
} else {
w.textFormat = strings.Fields(w.GetConfig().Global.TextFormat)
}
}
func (w *Syslog) ConnectToRemote() {
for {
if w.syslogWriter != nil {
w.syslogWriter.Close()
w.syslogWriter = nil
}
var logWriter *syslog.Writer
var tlsConfig *tls.Config
var err error
switch w.GetConfig().Loggers.Syslog.Transport {
case "local":
w.LogInfo("connecting to local syslog...")
logWriter, err = syslog.New(w.facility|w.severity, "")
case netutils.SocketUnix:
w.LogInfo("connecting to %s://%s ...",
w.GetConfig().Loggers.Syslog.Transport,
w.GetConfig().Loggers.Syslog.RemoteAddress)
logWriter, err = syslog.Dial("",
w.GetConfig().Loggers.Syslog.RemoteAddress, w.facility|w.severity,
w.GetConfig().Loggers.Syslog.Tag)
case netutils.SocketUDP, netutils.SocketTCP:
w.LogInfo("connecting to %s://%s ...",
w.GetConfig().Loggers.Syslog.Transport,
w.GetConfig().Loggers.Syslog.RemoteAddress)
logWriter, err = syslog.Dial(w.GetConfig().Loggers.Syslog.Transport,
w.GetConfig().Loggers.Syslog.RemoteAddress, w.facility|w.severity,
w.GetConfig().Loggers.Syslog.Tag)
case netutils.SocketTLS:
w.LogInfo("connecting to %s://%s ...",
w.GetConfig().Loggers.Syslog.Transport,
w.GetConfig().Loggers.Syslog.RemoteAddress)
tlsOptions := netutils.TLSOptions{
InsecureSkipVerify: w.GetConfig().Loggers.Syslog.TLSInsecure,
MinVersion: w.GetConfig().Loggers.Syslog.TLSMinVersion,
CAFile: w.GetConfig().Loggers.Syslog.CAFile,
CertFile: w.GetConfig().Loggers.Syslog.CertFile,
KeyFile: w.GetConfig().Loggers.Syslog.KeyFile,
}
tlsConfig, err = netutils.TLSClientConfig(tlsOptions)
if err == nil {
logWriter, err = syslog.DialWithTLSConfig(w.GetConfig().Loggers.Syslog.Transport,
w.GetConfig().Loggers.Syslog.RemoteAddress, w.facility|w.severity,
w.GetConfig().Loggers.Syslog.Tag,
tlsConfig)
}
default:
w.LogFatal("invalid syslog transport: ", w.GetConfig().Loggers.Syslog.Transport)
}
// something is wrong during connection ?
if err != nil {
w.LogError("%s", err)
w.LogInfo("retry to connect in %d seconds", w.GetConfig().Loggers.Syslog.RetryInterval)
time.Sleep(time.Duration(w.GetConfig().Loggers.Syslog.RetryInterval) * time.Second)
continue
}
w.syslogWriter = logWriter
// set syslog format
switch strings.ToLower(w.GetConfig().Loggers.Syslog.Formatter) {
case "unix":
w.syslogWriter.SetFormatter(syslog.UnixFormatter)
case "rfc3164":
w.syslogWriter.SetFormatter(syslog.RFC3164Formatter)
case "rfc5424", "":
w.syslogWriter.SetFormatter(syslog.RFC5424Formatter)
}
// set syslog framer
switch strings.ToLower(w.GetConfig().Loggers.Syslog.Framer) {
case "none", "":
w.syslogWriter.SetFramer(syslog.DefaultFramer)
case "rfc5425":
w.syslogWriter.SetFramer(syslog.RFC5425MessageLengthFramer)
}
// custom hostname
if len(w.GetConfig().Loggers.Syslog.Hostname) > 0 {
w.syslogWriter.SetHostname(w.GetConfig().Loggers.Syslog.Hostname)
}
// custom program name
if len(w.GetConfig().Loggers.Syslog.AppName) > 0 {
w.syslogWriter.SetProgram(w.GetConfig().Loggers.Syslog.AppName)
}
// notify process that the transport is ready
// block the loop until a reconnect is needed
w.transportReady <- true
w.transportReconnect <- true
}
}
func (w *Syslog) StartCollect() {
w.LogInfo("starting data collection")
defer w.CollectDone()
// prepare next channels
defaultRoutes, defaultNames := GetRoutes(w.GetDefaultRoutes())
droppedRoutes, droppedNames := GetRoutes(w.GetDroppedRoutes())
// prepare transforms
subprocessors := transformers.NewTransforms(&w.GetConfig().OutgoingTransformers, w.GetLogger(), w.GetName(), w.GetOutputChannelAsList(), 0)
// goroutine to process transformed dns messages
go w.StartLogging()
// init remote conn
go w.ConnectToRemote()
// loop to process incoming messages
for {
select {
case <-w.OnStop():
w.StopLogger()
subprocessors.Reset()
return
// new config provided?
case cfg := <-w.NewConfig():
w.SetConfig(cfg)
w.ReadConfig()
subprocessors.ReloadConfig(&cfg.OutgoingTransformers)
case dm, opened := <-w.GetInputChannel():
if !opened {
w.LogInfo("input channel closed!")
return
}
// count global messages
w.CountIngressTraffic()
// apply tranforms, init dns message with additionnals parts if necessary
transformResult, err := subprocessors.ProcessMessage(&dm)
if err != nil {
w.LogError(err.Error())
}
if transformResult == transformers.ReturnDrop {
w.SendDroppedTo(droppedRoutes, droppedNames, dm)
continue
}
// send to output channel
w.CountEgressTraffic()
w.GetOutputChannel() <- dm
// send to next ?
w.SendForwardedTo(defaultRoutes, defaultNames, dm)
}
}
}
func (w *Syslog) FlushBuffer(buf *[]dnsutils.DNSMessage) {
buffer := new(bytes.Buffer)
var err error
for _, dm := range *buf {
switch w.GetConfig().Loggers.Syslog.Mode {
case pkgconfig.ModeText:
// write the text line to the buffer
buffer.Write(dm.Bytes(w.textFormat, w.GetConfig().Global.TextFormatDelimiter, w.GetConfig().Global.TextFormatBoundary))
// replace NULL char from text line directly in the buffer
// because the NULL is a end of log in syslog
for i := 0; i < buffer.Len(); i++ {
if buffer.Bytes()[i] == 0 {
buffer.Bytes()[i] = w.GetConfig().Loggers.Syslog.ReplaceNullChar[0]
}
}
// ensure it ends in a \n
buffer.WriteString("\n")
// write the modified content of the buffer to s.syslogWriter
// and reset the buffer
_, err = buffer.WriteTo(w.syslogWriter)
case pkgconfig.ModeJSON:
// encode to json the dns message
json.NewEncoder(buffer).Encode(dm)
// write the content of the buffer to s.syslogWriter
// and reset the buffer
_, err = buffer.WriteTo(w.syslogWriter)
case pkgconfig.ModeFlatJSON:
// get flatten object
flat, errflat := dm.Flatten()
if errflat != nil {
w.LogError("flattening DNS message failed: %e", err)
continue
}
// encode to json
json.NewEncoder(buffer).Encode(flat)
// write the content of the buffer to s.syslogWriter
// and reset the buffer
_, err = buffer.WriteTo(w.syslogWriter)
}
if err != nil {
w.LogError("write error %s", err)
w.syslogReady = false
<-w.transportReconnect
break
}
}
// reset buffer
*buf = nil
}
func (w *Syslog) StartLogging() {
w.LogInfo("logging has started")
defer w.LoggingDone()
// init buffer
bufferDm := []dnsutils.DNSMessage{}
// init flust timer for buffer
flushInterval := time.Duration(w.GetConfig().Loggers.Syslog.FlushInterval) * time.Second
flushTimer := time.NewTimer(flushInterval)
w.LogInfo("processing dns messages...")
for {
select {
case <-w.OnLoggerStopped():
// close connection
if w.syslogWriter != nil {
w.syslogWriter.Close()
}
return
case <-w.transportReady:
w.LogInfo("syslog transport is ready")
w.syslogReady = true
// incoming dns message to process
case dm, opened := <-w.GetOutputChannel():
if !opened {
w.LogInfo("output channel closed!")
return
}
// discar dns message if the connection is not ready
if !w.syslogReady {
continue
}
// append dns message to buffer
bufferDm = append(bufferDm, dm)
// buffer is full ?
if len(bufferDm) >= w.GetConfig().Loggers.Syslog.BufferSize {
w.FlushBuffer(&bufferDm)
}
// flush the buffer
case <-flushTimer.C:
if !w.syslogReady {
bufferDm = nil
}
if len(bufferDm) > 0 {
w.FlushBuffer(&bufferDm)
}
// restart timer
flushTimer.Reset(flushInterval)
}
}
}