forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcp.go
109 lines (91 loc) · 2.1 KB
/
tcp.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
package tcp
import (
"fmt"
"net"
"github.com/pkg/errors"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/metricbeat/helper/server"
"github.com/elastic/beats/metricbeat/mb"
)
type TcpServer struct {
tcpAddr *net.TCPAddr
listener *net.TCPListener
receiveBufferSize int
done chan struct{}
eventQueue chan server.Event
}
type TcpEvent struct {
event common.MapStr
}
func (m *TcpEvent) GetEvent() common.MapStr {
return m.event
}
func (m *TcpEvent) GetMeta() server.Meta {
return server.Meta{}
}
func NewTcpServer(base mb.BaseMetricSet) (server.Server, error) {
config := defaultTcpConfig()
err := base.Module().UnpackConfig(&config)
if err != nil {
return nil, err
}
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", config.Host, config.Port))
if err != nil {
return nil, err
}
return &TcpServer{
tcpAddr: addr,
receiveBufferSize: config.ReceiveBufferSize,
done: make(chan struct{}),
eventQueue: make(chan server.Event),
}, nil
}
func (g *TcpServer) Start() error {
listener, err := net.ListenTCP("tcp", g.tcpAddr)
if err != nil {
return errors.Wrap(err, "failed to start TCP server")
}
g.listener = listener
logp.Info("Started listening for TCP on: %s", g.tcpAddr.String())
go g.watchMetrics()
return nil
}
func (g *TcpServer) watchMetrics() {
buffer := make([]byte, g.receiveBufferSize)
for {
select {
case <-g.done:
return
default:
}
conn, err := g.listener.Accept()
if err != nil {
logp.Err("Unable to accept connection due to error: %v", err)
continue
}
defer func() {
if conn != nil {
conn.Close()
}
}()
length, err := conn.Read(buffer)
if err != nil {
logp.Err("Error reading from buffer: %v", err.Error())
continue
}
g.eventQueue <- &TcpEvent{
event: common.MapStr{
server.EventDataKey: buffer[:length],
},
}
}
}
func (g *TcpServer) GetEvents() chan server.Event {
return g.eventQueue
}
func (g *TcpServer) Stop() {
close(g.done)
g.listener.Close()
close(g.eventQueue)
}