-
Notifications
You must be signed in to change notification settings - Fork 3
/
transport_server.go
362 lines (320 loc) · 10.5 KB
/
transport_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
package bitflow
import (
"net"
"sync"
"github.com/antongulenko/golib"
log "github.com/sirupsen/logrus"
)
// TCPListenerSource implements the SampleSource interface as a TCP server.
// It listens for incoming TCP connections on a port and reads Headers and Samples
// from every accepted connection. See the doc for the different fields for options
// affecting the TCP connections and aspects of reading and parsing.
type TCPListenerSource struct {
AbstractUnmarshallingSampleSource
// TCPConnCounter has a configuration for limiting the total number of
// accepted connections. After that number of connections were accepted, no
// further connections are accepted. After they all are closed, the TCPListenerSource
// automatically stops.
TCPConnCounter
// SimultaneousConnections can limit the number of TCP connections accepted
// at the same time. Set to >0 to activate the limit. Connections going over
// the limit will be immediately closed, and a warning will be printed on the logger.
SimultaneousConnections uint
task *golib.TCPListenerTask
synchronizedSink SampleSink
connections map[*tcpListenerConnection]bool
}
// NewTcpListenerSource creates a new instance of TCPListenerSource listening on the given
// TCP endpoint. It must be a IP/hostname combined with a port that can be bound on the local
// machine.
func NewTcpListenerSource(endpoint string) *TCPListenerSource {
source := &TCPListenerSource{
connections: make(map[*tcpListenerConnection]bool),
}
source.task = &golib.TCPListenerTask{
ListenEndpoint: endpoint,
}
return source
}
// String implements the SampleSource interface.
func (source *TCPListenerSource) String() string {
return "TCP source on " + source.task.ListenEndpoint
}
// Start implements the SampleSource interface. It creates a socket listening
// for incoming connections on the configured endpoint. New connections are
// handled in separate goroutines.
func (source *TCPListenerSource) Start(wg *sync.WaitGroup) golib.StopChan {
source.connCounterDescription = source
source.task.Handler = source.handleConnection
source.task.StopHook = func() {
source.closeAllConnections()
source.CloseSinkParallel(wg)
}
if source.SimultaneousConnections == 1 {
source.synchronizedSink = source.GetSink()
} else {
source.synchronizedSink = &SynchronizingSampleSink{Out: source.GetSink()}
}
return source.task.ExtendedStart(func(addr net.Addr) {
log.WithField("format", source.Reader.Format()).Println("Listening for incoming data on", addr)
}, wg)
}
func (source *TCPListenerSource) handleConnection(wg *sync.WaitGroup, conn *net.TCPConn) {
if source.SimultaneousConnections > 0 && len(source.connections) >= int(source.SimultaneousConnections) {
log.WithField("remote", conn.RemoteAddr()).Warnln("Rejecting connection, already have", len(source.connections), "connections")
_ = conn.Close() // Drop error
return
}
if !source.countConnectionAccepted(conn.RemoteAddr().String()) {
_ = conn.Close() // Drop error
return
}
log.WithField("remote", conn.RemoteAddr()).Debugln("Accepted connection")
listenerConn := &tcpListenerConnection{
source: source,
stream: source.Reader.Open(conn, source.synchronizedSink),
finished: golib.NewStopChan(),
}
source.connections[listenerConn] = true
wg.Add(1)
go listenerConn.readSamples(wg, conn)
}
func (source *TCPListenerSource) closeAllConnections() {
for {
var conn *tcpListenerConnection
// Pick an arbitrary running connection, if there is any
// Use Execute() to synchronize this with tcpListenerConnection.readSamples()
source.task.Execute(func() {
for key := range source.connections {
conn = key
break
}
})
if conn == nil {
break
}
conn.finished.Execute(conn.closeStream)
conn.finished.Wait()
}
}
// Stop implements the SampleSource interface. It closes all active TCP connections
// and closes the listening socket.
func (source *TCPListenerSource) Close() {
source.task.Stop()
}
type tcpListenerConnection struct {
source *TCPListenerSource
stream *SampleInputStream
// This StopChan is only used as a condition that can be waited on
finished golib.StopChan
}
func (conn *tcpListenerConnection) isConnectionClosed() bool {
return conn.stream == nil
}
func (conn *tcpListenerConnection) readSamples(wg *sync.WaitGroup, connection *net.TCPConn) {
defer wg.Done()
conn.stream.ReadTcpSamples(connection, connection.RemoteAddr().String(), conn.isConnectionClosed)
if !conn.source.countConnectionClosed() {
conn.source.Close()
}
conn.finished.StopFunc(conn.closeStream)
// The Execute() method makes sure to synchronize the access to the conn.source.connections map
conn.source.task.Execute(func() {
delete(conn.source.connections, conn)
})
}
// This is always executed while the conn.finished StopChan is locked to avoid closing the stream twice
func (conn *tcpListenerConnection) closeStream() {
if stream := conn.stream; stream != nil {
conn.stream = nil // Make isConnectionClosed() return true
_ = stream.Close() // Drop error
}
}
// TCPListenerSink implements the SampleSink interface through a TCP server.
// It creates a socket listening on a local TCP endpoint and listens for incoming
// TCP connections. Once one or more connections are established, it forwards
// all incoming Headers and Samples to those connections. If a new header should
// be sent into a TCP connection, the old connection is instead closed and
// the TCPListenerSink waits for a new connection to be created.
type TCPListenerSink struct {
// AbstractTcpSink defines parameters for controlling TCP and marshalling
// aspects of the TCPListenerSink. See AbstractTcpSink for details.
AbstractTcpSink
// Endpoint defines the TCP host and port to listen on for incoming TCP connections.
// The host can be empty (e.g. ":1234"). If not, it must contain a hostname or IP of the
// local host.
Endpoint string
// If BufferedSamples is >0, the given number of samples will be kept in a ring buffer.
// New incoming connections will first receive all samples currently in the buffer, and will
// afterwards continue receiving live incoming samples.
BufferedSamples uint
buf outputSampleBuffer
task *golib.TCPListenerTask
}
// String implements the SampleSink interface.
func (sink *TCPListenerSink) String() string {
return "TCP sink on " + sink.Endpoint
}
// Start implements the SampleSink interface. It creates the TCP socket and
// starts listening on it in a separate goroutine. Any incoming connection is
// then handled in their own goroutine.
func (sink *TCPListenerSink) Start(wg *sync.WaitGroup) golib.StopChan {
sink.connCounterDescription = sink
sink.Protocol = "TCP"
capacity := sink.BufferedSamples
if capacity == 0 {
capacity = 1
}
sink.buf = outputSampleBuffer{
Capacity: capacity,
cond: sync.NewCond(new(sync.Mutex)),
}
sink.task = &golib.TCPListenerTask{
ListenEndpoint: sink.Endpoint,
StopHook: func() {
sink.buf.closeBuffer()
sink.CloseSink()
},
Handler: sink.handleConnection,
}
return sink.task.ExtendedStart(func(addr net.Addr) {
log.WithField("format", sink.Marshaller).Println("Listening for output connections on", addr)
}, wg)
}
// Close implements the SampleSink interface. It closes any existing connection
// and closes the TCP socket.
func (sink *TCPListenerSink) Close() {
sink.task.Stop()
}
func (sink *TCPListenerSink) handleConnection(wg *sync.WaitGroup, conn *net.TCPConn) {
if !sink.countConnectionAccepted(conn.RemoteAddr().String()) {
_ = conn.Close() // Drop error
return
}
writeConn := sink.OpenWriteConn(wg, conn.RemoteAddr().String(), conn)
wg.Add(1)
go sink.sendSamples(wg, writeConn)
}
// Sample implements the SampleSink interface. It stores the sample in a ring buffer
// and sends it to all established connections. New connections will first receive
// all samples stored in the buffer, before getting the live samples directly.
// If the buffer is disable or full, and there are no established connections,
// samples are dropped.
func (sink *TCPListenerSink) Sample(sample *Sample, header *Header) error {
sink.buf.add(sample, header)
return sink.AbstractSampleOutput.Sample(nil, sample, header)
}
func (sink *TCPListenerSink) sendSamples(wg *sync.WaitGroup, conn *TcpWriteConn) {
defer func() {
conn.Close()
if !sink.countConnectionClosed() {
sink.Close()
}
}()
defer wg.Done()
sink.buf.sendSamples(conn)
}
// ======================================= output sample buffer =======================================
type outputSampleBuffer struct {
Capacity uint
size uint
first *sampleListLink
last *sampleListLink
cond *sync.Cond
closed bool
}
type sampleListLink struct {
sample *Sample
header *Header
next *sampleListLink
}
func (b *outputSampleBuffer) add(sample *Sample, header *Header) {
b.cond.L.Lock()
defer b.cond.L.Unlock()
link := &sampleListLink{
sample: sample,
header: header,
}
if b.first == nil {
b.first = link
} else {
b.last.next = link
}
b.last = link
if b.size >= b.Capacity {
b.first = b.first.next
} else {
b.size++
}
b.cond.Broadcast()
}
func (b *outputSampleBuffer) getFirst() (*sampleListLink, uint) {
b.cond.L.Lock()
defer b.cond.L.Unlock()
for b.first == nil && !b.closed {
b.cond.Wait()
}
return b.first, b.size
}
func (b *outputSampleBuffer) next(l *sampleListLink) *sampleListLink {
if b.closed {
return nil
}
if l.next != nil {
return l.next
}
b.cond.L.Lock()
defer b.cond.L.Unlock()
for l.next == nil && !b.closed {
b.cond.Wait()
}
return l.next
}
func (b *outputSampleBuffer) closeBuffer() {
b.cond.L.Lock()
defer b.cond.L.Unlock()
b.closed = true
b.cond.Broadcast()
}
func (b *outputSampleBuffer) sendSamples(conn *TcpWriteConn) {
b.sendFilteredSamples(conn, nil, nil)
}
func (b *outputSampleBuffer) sendFilteredSamples(conn *TcpWriteConn, flushCallback func(), filter func(sample *Sample, header *Header) bool) {
first, num := b.getFirst()
if num > 1 {
conn.log.Debugln("Sending", num, "buffered samples")
}
for first != nil {
if !conn.IsRunning() {
return
}
if filter == nil || filter(first.sample, first.header) {
conn.Sample(first.sample, first.header)
if flushCallback != nil {
flushCallback()
}
}
if !conn.IsRunning() {
return
}
first = b.next(first)
}
}
func (b *outputSampleBuffer) sendOneSample(conn *TcpWriteConn, flushCallback func()) {
first, num := b.getFirst()
if num > 1 {
conn.log.Debugln("Sending", num, "buffered samples")
}
if first != nil {
if !conn.IsRunning() {
return
}
conn.Sample(first.sample, first.header)
if flushCallback != nil {
flushCallback()
}
if !conn.IsRunning() {
return
}
}
}