forked from ruflin/filebeat
/
client.go
273 lines (237 loc) · 6.52 KB
/
client.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
package logstash
import (
"bytes"
"compress/zlib"
"encoding/binary"
"encoding/json"
"errors"
"io"
"net"
"time"
"github.com/elastic/libbeat/common"
"github.com/elastic/libbeat/logp"
)
// lumberjackClient implements the ProtocolClient interface to be used
// with different mode. The client implements slow start with low window sizes +
// window size backoff in case of long running transactions.
//
// it is suggested to use lumberjack in conjunction with roundRobinConnectionMode
// if logstash becomes unresponsive
type lumberjackClient struct {
TransportClient
windowSize int
maxOkWindowSize int // max window size sending was successful for
timeout time.Duration
countTimeoutErr int
}
// TODO: make max window size configurable
const (
minWindowSize int = 1
maxWindowSize int = 1024
defaultStartMaxWindowSize int = 10
maxAllowedTimeoutErr int = 3
)
// errors
var (
// ErrProtocolError is returned if an protocol error was detected in the
// conversation with lumberjack server.
ErrProtocolError = errors.New("lumberjack protocol error")
)
var (
codeVersion byte = '2'
codeWindowSize = []byte{codeVersion, 'W'}
codeJSONDataFrame = []byte{codeVersion, 'J'}
codeCompressed = []byte{codeVersion, 'C'}
)
func newLumberjackClient(conn TransportClient, timeout time.Duration) *lumberjackClient {
return &lumberjackClient{
TransportClient: conn,
windowSize: defaultStartMaxWindowSize,
timeout: timeout,
}
}
func (l *lumberjackClient) PublishEvent(event common.MapStr) error {
_, err := l.PublishEvents([]common.MapStr{event})
return err
}
func (l *lumberjackClient) PublishEvents(
events []common.MapStr,
) ([]common.MapStr, error) {
if len(events) == 0 {
return nil, nil
}
// prepare message payload
if len(events) > l.windowSize {
events = events[:l.windowSize]
}
count, payload, err := l.compressEvents(events)
if err != nil {
return events, err
}
if count == 0 {
// encoding of all events failed. Let's stop here and report all events
// as exported so no one tries to send/encode the same events once again
// The compress/encode function already prints critical per failed encoding
// failure.
return nil, nil
}
// send window size:
if err = l.sendWindowSize(count); err != nil {
return l.onFail(events, err)
}
// send payload
if err = l.sendCompressed(payload); err != nil {
return l.onFail(events, err)
}
// wait for ACK (accept partial ACK to reset timeout)
// reset timeout timer for every ACK received.
var ackSeq uint32
for ackSeq < count {
// read until all acks
ackSeq, err = l.readACK()
if err != nil {
return l.onFail(events[ackSeq:], err)
}
}
// success: increase window size by factor 1.5 until max window size
// (window size grows exponentially)
// TODO: use duration until ACK to estimate an ok max window size value
if l.maxOkWindowSize < l.windowSize {
l.maxOkWindowSize = l.windowSize
if l.windowSize < maxWindowSize {
l.windowSize = l.windowSize + l.windowSize/2
if l.windowSize > maxWindowSize {
l.windowSize = maxWindowSize
}
}
} else if l.windowSize < l.maxOkWindowSize {
l.windowSize = l.windowSize + l.windowSize/2
if l.windowSize > l.maxOkWindowSize {
l.windowSize = l.maxOkWindowSize
}
}
return nil, nil
}
func (l *lumberjackClient) onFail(
events []common.MapStr,
err error,
) ([]common.MapStr, error) {
// if timeout error, back off and ignore error
nerr, ok := err.(net.Error)
if !ok || !nerr.Timeout() {
// no timeout error, close connection and return error
_ = l.Close()
return events, err
}
// if we've seen 3 consecutive timeout errors, close connection
l.countTimeoutErr++
if l.countTimeoutErr == maxAllowedTimeoutErr {
_ = l.Close()
return events, err
}
// timeout error. reduce window size and return 0 published events. Send
// mode might try to publish again with reduce window size or ask another
// client to send events (round robin load balancer)
l.windowSize = l.windowSize / 2
if l.windowSize < minWindowSize {
l.windowSize = minWindowSize
}
return events, nil
}
func (l *lumberjackClient) compressEvents(
events []common.MapStr,
) (uint32, []byte, error) {
buf := bytes.NewBuffer(nil)
// compress events
compressor, _ := zlib.NewWriterLevel(buf, 3) // todo make compression level configurable?
var sequence uint32
for _, event := range events {
sequence++
err := l.writeDataFrame(event, sequence, compressor)
if err != nil {
logp.Critical("failed to encode event: %v", err)
sequence-- //forget this last broken event and continue
}
}
if err := compressor.Close(); err != nil {
debug("Finalizing zlib compression failed with: %s", err)
return 0, nil, err
}
payload := buf.Bytes()
return sequence, payload, nil
}
func (l *lumberjackClient) readACK() (uint32, error) {
if err := l.SetDeadline(time.Now().Add(l.timeout)); err != nil {
return 0, err
}
response := make([]byte, 6)
ackbytes := 0
for ackbytes < 6 {
n, err := l.Read(response[ackbytes:])
if err != nil {
return 0, err
}
ackbytes += n
}
isACK := response[0] == codeVersion && response[1] == 'A'
if !isACK {
return 0, ErrProtocolError
}
seq := binary.BigEndian.Uint32(response[2:])
return seq, nil
}
func (l *lumberjackClient) sendWindowSize(window uint32) error {
if err := l.SetDeadline(time.Now().Add(l.timeout)); err != nil {
return err
}
if _, err := l.Write(codeWindowSize); err != nil {
return err
}
return writeUint32(l, window)
}
func (l *lumberjackClient) sendCompressed(payload []byte) error {
if err := l.SetDeadline(time.Now().Add(l.timeout)); err != nil {
return err
}
if _, err := l.Write(codeCompressed); err != nil {
return err
}
if err := writeUint32(l, uint32(len(payload))); err != nil {
return err
}
_, err := l.Write(payload)
return err
}
func (l *lumberjackClient) writeDataFrame(
event common.MapStr,
seq uint32,
out io.Writer,
) error {
// Write JSON Data Frame:
// version: uint8 = '2'
// code: uint8 = 'J'
// seq: uint32
// payloadLen (bytes): uint32
// payload: JSON document
jsonEvent, err := json.Marshal(event)
if err != nil {
debug("Fail to convert the event to JSON: %s", err)
return err
}
if _, err := out.Write(codeJSONDataFrame); err != nil { // version + code
return err
}
if err := writeUint32(out, seq); err != nil {
return err
}
if err := writeUint32(out, uint32(len(jsonEvent))); err != nil {
return err
}
if _, err := out.Write(jsonEvent); err != nil {
return err
}
return nil
}
func writeUint32(out io.Writer, v uint32) error {
return binary.Write(out, binary.BigEndian, v)
}