-
-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathtcpclient.go
326 lines (269 loc) · 8.46 KB
/
tcpclient.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
package workers
import (
"bufio"
"crypto/tls"
"encoding/json"
"errors"
"io"
"net"
"strconv"
"strings"
"time"
"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 TCPClient struct {
*GenericWorker
stopRead, doneRead chan bool
textFormat []string
transport string
transportWriter *bufio.Writer
transportConn net.Conn
transportReady, transportReconnect chan bool
writerReady bool
}
func NewTCPClient(config *pkgconfig.Config, logger *logger.Logger, name string) *TCPClient {
bufSize := config.Global.Worker.ChannelBufferSize
if config.Loggers.TCPClient.ChannelBufferSize > 0 {
bufSize = config.Loggers.TCPClient.ChannelBufferSize
}
w := &TCPClient{GenericWorker: NewGenericWorker(config, logger, name, "tcpclient", bufSize, pkgconfig.DefaultMonitor)}
w.transportReady = make(chan bool)
w.transportReconnect = make(chan bool)
w.stopRead = make(chan bool)
w.doneRead = make(chan bool)
w.ReadConfig()
return w
}
func (w *TCPClient) ReadConfig() {
w.transport = w.GetConfig().Loggers.TCPClient.Transport
// begin backward compatibility
if w.GetConfig().Loggers.TCPClient.TLSSupport {
w.transport = netutils.SocketTLS
}
if len(w.GetConfig().Loggers.TCPClient.SockPath) > 0 {
w.transport = netutils.SocketUnix
}
// end
if len(w.GetConfig().Loggers.TCPClient.TextFormat) > 0 {
w.textFormat = strings.Fields(w.GetConfig().Loggers.TCPClient.TextFormat)
} else {
w.textFormat = strings.Fields(w.GetConfig().Global.TextFormat)
}
}
func (w *TCPClient) Disconnect() {
if w.transportConn != nil {
w.LogInfo("closing tcp connection")
w.transportConn.Close()
}
}
func (w *TCPClient) ReadFromConnection() {
buffer := make([]byte, 4096)
go func() {
for {
_, err := w.transportConn.Read(buffer)
if err != nil {
if errors.Is(err, io.EOF) || errors.Is(err, net.ErrClosed) {
w.LogInfo("read from connection terminated")
break
}
w.LogError("Error on reading: %s", err.Error())
}
// We just discard the data
}
}()
// block goroutine until receive true event in stopRead channel
<-w.stopRead
w.doneRead <- true
w.LogInfo("read goroutine terminated")
}
func (w *TCPClient) ConnectToRemote() {
for {
if w.transportConn != nil {
w.transportConn.Close()
w.transportConn = nil
}
address := w.GetConfig().Loggers.TCPClient.RemoteAddress + ":" + strconv.Itoa(w.GetConfig().Loggers.TCPClient.RemotePort)
connTimeout := time.Duration(w.GetConfig().Loggers.TCPClient.ConnectTimeout) * time.Second
// make the connection
var conn net.Conn
var err error
switch w.transport {
case netutils.SocketUnix:
address = w.GetConfig().Loggers.TCPClient.RemoteAddress
if len(w.GetConfig().Loggers.TCPClient.SockPath) > 0 {
address = w.GetConfig().Loggers.TCPClient.SockPath
}
w.LogInfo("connecting to %s://%s", w.transport, address)
conn, err = net.DialTimeout(w.transport, address, connTimeout)
case netutils.SocketTCP:
w.LogInfo("connecting to %s://%s", w.transport, address)
conn, err = net.DialTimeout(w.transport, address, connTimeout)
case netutils.SocketTLS:
w.LogInfo("connecting to %s://%s", w.transport, address)
var tlsConfig *tls.Config
tlsOptions := netutils.TLSOptions{
InsecureSkipVerify: w.GetConfig().Loggers.TCPClient.TLSInsecure,
MinVersion: w.GetConfig().Loggers.TCPClient.TLSMinVersion,
CAFile: w.GetConfig().Loggers.TCPClient.CAFile,
CertFile: w.GetConfig().Loggers.TCPClient.CertFile,
KeyFile: w.GetConfig().Loggers.TCPClient.KeyFile,
}
tlsConfig, err = netutils.TLSClientConfig(tlsOptions)
if err == nil {
dialer := &net.Dialer{Timeout: connTimeout}
conn, err = tls.DialWithDialer(dialer, netutils.SocketTCP, address, tlsConfig)
}
default:
w.LogFatal("invalid transport:", w.transport)
}
// something is wrong during connection ?
if err != nil {
w.LogError("%s", err)
w.LogInfo("retry to connect in %d seconds", w.GetConfig().Loggers.TCPClient.RetryInterval)
time.Sleep(time.Duration(w.GetConfig().Loggers.TCPClient.RetryInterval) * time.Second)
continue
}
w.transportConn = conn
// block until framestream is ready
w.transportReady <- true
// block until an error occurred, need to reconnect
w.transportReconnect <- true
}
}
func (w *TCPClient) FlushBuffer(buf *[]dnsutils.DNSMessage) {
for _, dm := range *buf {
if w.GetConfig().Loggers.TCPClient.Mode == pkgconfig.ModeText {
w.transportWriter.Write(dm.Bytes(w.textFormat,
w.GetConfig().Global.TextFormatDelimiter,
w.GetConfig().Global.TextFormatBoundary))
w.transportWriter.WriteString(w.GetConfig().Loggers.TCPClient.PayloadDelimiter)
}
if w.GetConfig().Loggers.TCPClient.Mode == pkgconfig.ModeJSON {
json.NewEncoder(w.transportWriter).Encode(dm)
w.transportWriter.WriteString(w.GetConfig().Loggers.TCPClient.PayloadDelimiter)
}
if w.GetConfig().Loggers.TCPClient.Mode == pkgconfig.ModeFlatJSON {
flat, err := dm.Flatten()
if err != nil {
w.LogError("flattening DNS message failed: %e", err)
continue
}
json.NewEncoder(w.transportWriter).Encode(flat)
w.transportWriter.WriteString(w.GetConfig().Loggers.TCPClient.PayloadDelimiter)
}
// flush the transport buffer
err := w.transportWriter.Flush()
if err != nil {
w.LogError("send frame error", err.Error())
w.writerReady = false
<-w.transportReconnect
break
}
}
// reset buffer
*buf = nil
}
func (w *TCPClient) 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()
// loop to process incoming messages
for {
select {
case <-w.OnStop():
w.StopLogger()
subprocessors.Reset()
w.stopRead <- true
<-w.doneRead
return
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 *TCPClient) 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.TCPClient.FlushInterval) * time.Second
flushTimer := time.NewTimer(flushInterval)
// init remote conn
go w.ConnectToRemote()
w.LogInfo("ready to process")
for {
select {
case <-w.OnLoggerStopped():
// closing remote connection if exist
w.Disconnect()
return
case <-w.transportReady:
w.LogInfo("transport connected with success")
w.transportWriter = bufio.NewWriter(w.transportConn)
w.writerReady = true
// read from the connection until we stop
go w.ReadFromConnection()
// incoming dns message to process
case dm, opened := <-w.GetOutputChannel():
if !opened {
w.LogInfo("output channel closed!")
return
}
// drop dns message if the connection is not ready to avoid memory leak or
// to block the channel
if !w.writerReady {
continue
}
// append dns message to buffer
bufferDm = append(bufferDm, dm)
// buffer is full ?
if len(bufferDm) >= w.GetConfig().Loggers.TCPClient.BufferSize {
w.FlushBuffer(&bufferDm)
}
// flush the buffer
case <-flushTimer.C:
if !w.writerReady {
bufferDm = nil
}
if len(bufferDm) > 0 {
w.FlushBuffer(&bufferDm)
}
// restart timer
flushTimer.Reset(flushInterval)
}
}
}