forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket_server.go
406 lines (347 loc) · 9.62 KB
/
socket_server.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 input
import (
"context"
"fmt"
"io"
"net"
"strings"
"sync"
"time"
"github.com/dafanshu/benthos/v3/internal/codec"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/message"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/types"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeSocketServer] = TypeSpec{
constructor: fromSimpleConstructor(NewSocketServer),
Summary: `Creates a server that receives a stream of messages over a tcp, udp or unix socket.`,
Description: `
The field ` + "`max_buffer`" + ` specifies the maximum amount of memory to allocate _per connection_ for buffering lines of data. If a line of data from a connection exceeds this value then the connection will be closed.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("network", "A network type to accept (unix|tcp|udp).").HasOptions(
"unix", "tcp", "udp",
),
docs.FieldCommon("address", "The address to listen from.", "/tmp/benthos.sock", "0.0.0.0:6000"),
codec.ReaderDocs.AtVersion("3.42.0"),
docs.FieldAdvanced("max_buffer", "The maximum message buffer size. Must exceed the largest message to be consumed."),
docs.FieldDeprecated("multipart"),
docs.FieldDeprecated("delimiter"),
},
Categories: []Category{
CategoryNetwork,
},
}
}
//------------------------------------------------------------------------------
// SocketServerConfig contains configuration for the SocketServer input type.
type SocketServerConfig struct {
Network string `json:"network" yaml:"network"`
Address string `json:"address" yaml:"address"`
Codec string `json:"codec" yaml:"codec"`
MaxBuffer int `json:"max_buffer" yaml:"max_buffer"`
Multipart bool `json:"multipart" yaml:"multipart"`
Delim string `json:"delimiter" yaml:"delimiter"`
}
// NewSocketServerConfig creates a new SocketServerConfig with default values.
func NewSocketServerConfig() SocketServerConfig {
return SocketServerConfig{
Network: "unix",
Address: "/tmp/benthos.sock",
Codec: "lines",
MaxBuffer: 1000000,
// TODO: V4 Remove these fields
Multipart: false,
Delim: "",
}
}
//------------------------------------------------------------------------------
type wrapPacketConn struct {
net.PacketConn
}
func (w *wrapPacketConn) Read(p []byte) (n int, err error) {
n, _, err = w.ReadFrom(p)
return
}
// SocketServer is an input type that binds to an address and consumes streams of
// messages over Socket.
type SocketServer struct {
conf SocketServerConfig
stats metrics.Type
log log.Modular
codecCtor codec.ReaderConstructor
listener net.Listener
conn net.PacketConn
retriesMut sync.RWMutex
transactions chan types.Transaction
ctx context.Context
closeFn func()
closedChan chan struct{}
mLatency metrics.StatTimer
}
// NewSocketServer creates a new SocketServer input type.
func NewSocketServer(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
var ln net.Listener
var cn net.PacketConn
var err error
sconf := conf.SocketServer
if len(sconf.Delim) > 0 {
sconf.Codec = "delim:" + sconf.Delim
}
if sconf.Multipart && !strings.HasSuffix(sconf.Codec, "/multipart") {
sconf.Codec += "/multipart"
}
codecConf := codec.NewReaderConfig()
codecConf.MaxScanTokenSize = sconf.MaxBuffer
ctor, err := codec.GetReader(sconf.Codec, codecConf)
if err != nil {
return nil, err
}
switch sconf.Network {
case "tcp", "unix":
ln, err = net.Listen(sconf.Network, sconf.Address)
case "udp":
cn, err = net.ListenPacket(sconf.Network, sconf.Address)
default:
return nil, fmt.Errorf("socket network '%v' is not supported by this input", sconf.Network)
}
if err != nil {
return nil, err
}
t := SocketServer{
conf: conf.SocketServer,
stats: stats,
log: log,
codecCtor: ctor,
listener: ln,
conn: cn,
transactions: make(chan types.Transaction),
closedChan: make(chan struct{}),
mLatency: stats.GetTimer("latency"),
}
t.ctx, t.closeFn = context.WithCancel(context.Background())
if ln == nil {
go t.udpLoop()
} else {
go t.loop()
}
return &t, nil
}
//------------------------------------------------------------------------------
// Addr returns the underlying Socket listeners address.
func (t *SocketServer) Addr() net.Addr {
if t.listener != nil {
return t.listener.Addr()
}
return t.conn.LocalAddr()
}
func (t *SocketServer) sendMsg(msg types.Message) bool {
tStarted := time.Now()
// Block whilst retries are happening
t.retriesMut.Lock()
// nolint:staticcheck, gocritic // Ignore SA2001 empty critical section, Ignore badLock
t.retriesMut.Unlock()
resChan := make(chan types.Response)
select {
case t.transactions <- types.NewTransaction(msg, resChan):
case <-t.ctx.Done():
return false
}
go func() {
hasLocked := false
defer func() {
if hasLocked {
t.retriesMut.RUnlock()
}
}()
for {
select {
case res, open := <-resChan:
if !open {
return
}
var sendErr error
if res != nil {
sendErr = res.Error()
}
if sendErr == nil || sendErr == types.ErrTypeClosed {
if sendErr == nil {
t.mLatency.Timing(time.Since(tStarted).Nanoseconds())
}
return
}
if !hasLocked {
hasLocked = true
t.retriesMut.RLock()
}
t.log.Errorf("failed to send message: %v\n", sendErr)
// Wait before attempting again
select {
case <-time.After(time.Second):
case <-t.ctx.Done():
return
}
// And then resend the transaction
select {
case t.transactions <- types.NewTransaction(msg, resChan):
case <-t.ctx.Done():
return
}
case <-t.ctx.Done():
return
}
}
}()
return true
}
func (t *SocketServer) loop() {
var (
mCount = t.stats.GetCounter("count")
mRcvd = t.stats.GetCounter("batch.received")
mPartsRcvd = t.stats.GetCounter("received")
)
var wg sync.WaitGroup
defer func() {
wg.Wait()
t.retriesMut.Lock()
// nolint:staticcheck, gocritic // Ignore SA2001 empty critical section, Ignore badLock
t.retriesMut.Unlock()
t.listener.Close()
close(t.transactions)
close(t.closedChan)
}()
t.log.Infof("Receiving %v socket messages from address: %v\n", t.conf.Network, t.listener.Addr())
go func() {
<-t.ctx.Done()
t.listener.Close()
}()
acceptLoop:
for {
conn, err := t.listener.Accept()
if err != nil {
if !strings.Contains(err.Error(), "use of closed network connection") {
t.log.Errorf("Failed to accept Socket connection: %v\n", err)
}
select {
case <-time.After(time.Second):
continue acceptLoop
case <-t.ctx.Done():
return
}
}
connCtx, connDone := context.WithCancel(t.ctx)
go func() {
<-connCtx.Done()
conn.Close()
}()
wg.Add(1)
go func(c net.Conn) {
defer func() {
connDone()
wg.Done()
c.Close()
}()
codec, err := t.codecCtor("", c, func(ctx context.Context, err error) error {
return nil
})
if err != nil {
t.log.Errorf("Failed to create codec for new connection: %v\n", err)
return
}
for {
parts, ackFn, err := codec.Next(t.ctx)
if err != nil {
if err != io.EOF && err != types.ErrTimeout {
t.log.Errorf("Connection dropped due to: %v\n", err)
}
return
}
mCount.Incr(1)
mRcvd.Incr(1)
mPartsRcvd.Incr(int64(len(parts)))
// We simply bounce rejected messages in a loop downstream so
// there's no benefit to aggregating acks.
_ = ackFn(t.ctx, nil)
msg := message.New(nil)
msg.Append(parts...)
if !t.sendMsg(msg) {
return
}
}
}(conn)
}
}
func (t *SocketServer) udpLoop() {
var (
mCount = t.stats.GetCounter("count")
mRcvd = t.stats.GetCounter("batch.received")
mPartsRcvd = t.stats.GetCounter("received")
)
defer func() {
t.retriesMut.Lock()
// nolint:staticcheck, gocritic // Ignore SA2001 empty critical section, Ignore badLock
t.retriesMut.Unlock()
close(t.transactions)
close(t.closedChan)
}()
codec, err := t.codecCtor("", &wrapPacketConn{PacketConn: t.conn}, func(ctx context.Context, err error) error {
return nil
})
if err != nil {
t.log.Errorf("Connection error due to: %v\n", err)
return
}
go func() {
<-t.ctx.Done()
codec.Close(context.Background())
t.conn.Close()
}()
t.log.Infof("Receiving udp socket messages from address: %v\n", t.conn.LocalAddr())
for {
parts, ackFn, err := codec.Next(t.ctx)
if err != nil {
if err != io.EOF && err != types.ErrTimeout {
t.log.Errorf("Connection dropped due to: %v\n", err)
}
return
}
mCount.Incr(1)
mRcvd.Incr(1)
mPartsRcvd.Incr(int64(len(parts)))
// We simply bounce rejected messages in a loop downstream so
// there's no benefit to aggregating acks.
_ = ackFn(t.ctx, nil)
msg := message.New(nil)
msg.Append(parts...)
if !t.sendMsg(msg) {
return
}
}
}
// TransactionChan returns a transactions channel for consuming messages from
// this input.
func (t *SocketServer) TransactionChan() <-chan types.Transaction {
return t.transactions
}
// Connected returns a boolean indicating whether this input is currently
// connected to its target.
func (t *SocketServer) Connected() bool {
return true
}
// CloseAsync shuts down the SocketServer input and stops processing requests.
func (t *SocketServer) CloseAsync() {
t.closeFn()
}
// WaitForClose blocks until the SocketServer input has closed down.
func (t *SocketServer) WaitForClose(timeout time.Duration) error {
select {
case <-t.closedChan:
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------