-
Notifications
You must be signed in to change notification settings - Fork 17
/
tcp.go
210 lines (175 loc) · 4.98 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
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
package input
import (
"bufio"
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"sync/atomic"
"time"
"github.com/AdRoll/baker"
log "github.com/sirupsen/logrus"
)
var TCPDesc = baker.InputDesc{
Name: "TCP",
New: NewTCP,
Config: &TCPConfig{},
Help: "This input relies on a TCP connection to receive records in the usual format\n" +
"Configure it with a host and port that you want to accept connection from.\n" +
"By default it listens on port 6000 for any connection\n" +
"It never exits.\n",
}
const (
// gzipInput reads records in chunks, for maximizing speed. This is the
// size of each chunk.
tcpChunkBuffer = 128 * 1024
// This is the expected maximum length of a single record. We still handle
// longer lines, but with a slower code-path.
tcpMaxLineLength = 4 * 1024
)
type TCPConfig struct {
Listener string `help:"Host:Port to bind to"`
}
func (cfg *TCPConfig) fillDefaults() {
if cfg.Listener == "" {
cfg.Listener = ":6000"
}
}
type TCP struct {
Cfg *TCPConfig
data chan<- *baker.Data
pool sync.Pool
numLines int64
stop int64
}
func NewTCP(cfg baker.InputParams) (baker.Input, error) {
dcfg := cfg.DecodedConfig.(*TCPConfig)
dcfg.fillDefaults()
return &TCP{
Cfg: dcfg,
pool: sync.Pool{
New: func() interface{} {
return &baker.Data{Bytes: make([]byte, tcpChunkBuffer)}
},
},
}, nil
}
func (s *TCP) Run(inch chan<- *baker.Data) error {
s.setOutputChannel(inch)
ctxLog := log.WithFields(log.Fields{"f": "Run"})
addr, err := net.ResolveTCPAddr("tcp", s.Cfg.Listener)
if err != nil {
ctxLog.WithFields(log.Fields{"listener": s.Cfg.Listener}).Error("Can't resolve")
return err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return err
}
defer l.Close()
wg := sync.WaitGroup{}
for atomic.LoadInt64(&s.stop) == 0 {
l.SetDeadline(time.Now().Add(1 * time.Second))
conn, err := l.AcceptTCP()
if err != nil {
if errors.Is(err, os.ErrDeadlineExceeded) {
continue
}
ctxLog.WithFields(log.Fields{"error": err}).Error("Error while accepting")
}
ctxLog.WithFields(log.Fields{"addr": conn.RemoteAddr()}).Info("Connected")
wg.Add(1)
go func(conn *net.TCPConn) {
defer func() {
conn.Close()
wg.Done()
}()
if err := s.handleStream(conn); err != nil {
ctxLog.WithError(err).WithFields(log.Fields{"error": err}).Error("Error when handling stream")
}
}(conn)
}
wg.Wait()
return nil
}
func (s *TCP) setOutputChannel(data chan<- *baker.Data) {
s.data = data
}
func (s *TCP) send(data *baker.Data) {
nlines := int64(bytes.Count(data.Bytes, []byte{'\n'}))
atomic.AddInt64(&s.numLines, nlines)
s.data <- data
}
func (s *TCP) FreeMem(data *baker.Data) {
data.Bytes = data.Bytes[:tcpChunkBuffer]
s.pool.Put(data)
}
func (s *TCP) Stats() baker.InputStats {
return baker.InputStats{
NumProcessedLines: atomic.LoadInt64(&s.numLines),
}
}
func (s *TCP) Stop() {
atomic.StoreInt64(&s.stop, 1)
}
func (s *TCP) handleStream(conn *net.TCPConn) error {
r, err := gzip.NewReader(conn)
if err != nil {
return fmt.Errorf("error initializing gzip: %v", err)
}
defer r.Close()
rbuf := bufio.NewReaderSize(r, tcpChunkBuffer)
for atomic.LoadInt64(&s.stop) == 0 {
bakerData := s.pool.Get().(*baker.Data)
// Read a big chunk of data (but keeping tcpMaxLineLength
// bytes available for completing the last line).
n, err := rbuf.Read(bakerData.Bytes[:tcpChunkBuffer-tcpMaxLineLength])
if err == io.EOF {
bakerData.Bytes = bakerData.Bytes[:n]
s.send(bakerData)
break
}
if err != nil {
return fmt.Errorf("error reading stream: %v", err)
}
// We need to send a batch of complete lines to the filter
// (sending truncated lines would generate parsing errors),
// so we want to finish reading the last line we read until its
// terminator.
// NOTE: it might also happen that the chunk we just read
// finished the file; so we check if the chunk ends with a
// terminator, to avoid receiving a io.EOF from ReadBytes; EOFs
// will be handled back when we begin the loop again.
if bakerData.Bytes[n-1] != '\n' {
endl, err := rbuf.ReadBytes('\n')
if err != nil {
return fmt.Errorf("error searching for new line char: %v", err)
}
// If there is no space in the buffer to complete the
// current line, we need to handle it differently.
if n+len(endl) > tcpChunkBuffer {
// Drop the initial part of the truncated line from the buffer
lastn := n
n = bytes.LastIndexByte(bakerData.Bytes[:n], '\n') + 1
// Process the huge line by itself. Allocate a new buffer
// from the pool, copy the initial part, and then concatenate
// up to the endline
bakerData2 := s.pool.Get().(*baker.Data)
bakerData2.Meta = bakerData.Meta
bakerData2.Bytes = append(bakerData2.Bytes[:0], bakerData.Bytes[n:lastn]...)
bakerData2.Bytes = append(bakerData2.Bytes, endl...)
s.send(bakerData2)
} else {
copy(bakerData.Bytes[n:], endl)
n += len(endl)
}
}
bakerData.Bytes = bakerData.Bytes[:n]
s.send(bakerData)
}
return nil
}