/
fluent.go
354 lines (313 loc) · 6.79 KB
/
fluent.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
package fluent
import (
"container/list"
"math"
"net"
"sync"
"time"
"github.com/ugorji/go/codec"
)
type ErrorHandler interface {
HandleError(error)
}
type ErrorHandlerFunc func(error)
func (f ErrorHandlerFunc) HandleError(err error) {
f(err)
}
type pending struct {
list *list.List
limit int
m sync.Mutex
flushing bool
}
func newPending(limit int) *pending {
return &pending{
list: list.New(),
limit: limit,
}
}
func (p *pending) Add(b []byte) {
p.m.Lock()
defer p.m.Unlock()
// If not flushing now, trim the pending if limit exceeded.
// Otherwise, to avoid conflict, trimming is temporary disabled.
if !p.flushing {
for i := p.list.Len() - p.limit; i >= 0; i-- {
p.list.Remove(p.list.Front())
}
}
p.list.PushBack(b)
}
func (p *pending) Flush(conn net.Conn, timeout time.Duration) error {
p.m.Lock()
n := p.list.Len()
p.flushing = true
p.m.Unlock()
defer func() {
p.flushing = false
}()
for i, e := 0, p.list.Front(); i < n; i, e = i+1, p.list.Front() {
conn.SetDeadline(time.Now().Add(timeout))
if _, err := conn.Write(e.Value.([]byte)); err != nil {
return err
}
p.m.Lock()
p.list.Remove(e)
p.m.Unlock()
}
conn.SetDeadline(time.Time{})
return nil
}
type Options struct {
Addr string
TagPrefix string
SendBufSize int
ErrorBufSize int
ErrorHandler ErrorHandler
LogHandler func(string, ...interface{})
DialTimeout time.Duration
CloseTimeout time.Duration
Timeout time.Duration
RetryWait time.Duration
MaxBackoff int
MaxPendingSize int
IsFluxion bool
// If NonBlocking is true and send buffer is full, further events will be dropped.
NonBlocking bool
}
func (o *Options) Default() {
if o.SendBufSize == 0 {
o.SendBufSize = 50000
}
if o.ErrorBufSize == 0 {
o.ErrorBufSize = 100
}
if o.DialTimeout == 0 {
o.DialTimeout = 5 * time.Second
}
if o.CloseTimeout == 0 {
o.CloseTimeout = 5 * time.Second
}
if o.Timeout == 0 {
o.Timeout = 5 * time.Second
}
if o.RetryWait == 0 {
o.RetryWait = 100 * time.Millisecond
}
if o.MaxBackoff == 0 {
o.MaxBackoff = 8
}
if o.MaxPendingSize == 0 {
o.MaxPendingSize = 1000 * 1000
}
}
type Client struct {
conn net.Conn
inputCh chan interface{}
errorCh chan error
closeCh chan bool
opts *Options
pending *pending
mh *codec.MsgpackHandle
}
func NewClient(opts Options) *Client {
opts.Default()
c := &Client{
opts: &opts,
inputCh: make(chan interface{}, opts.SendBufSize),
closeCh: make(chan bool),
pending: newPending(opts.MaxPendingSize),
}
c.log("Fluent options: %+v", opts)
if !opts.IsFluxion {
c.mh = &codec.MsgpackHandle{}
} else {
c.mh = &codec.MsgpackHandle{WriteExt: true}
c.mh.RawToString = true
}
if c.opts.ErrorHandler != nil {
c.errorCh = make(chan error, c.opts.ErrorBufSize)
go c.errorWorker()
}
go c.sender()
return c
}
// Send sends record v with given tag. v can be any type which can be encoded
// to msgpack. Specially, if type of v is []byte, it will be sent without any
// modification.
func (c *Client) Send(tag string, v interface{}) {
c.SendWithTime(tag, time.Now(), v)
}
// SendWithTime sends record v with given tag and time. See Send.
func (c *Client) SendWithTime(tag string, t time.Time, v interface{}) {
if c.opts.TagPrefix != "" {
if tag != "" {
tag = c.opts.TagPrefix + "." + tag
} else {
tag = c.opts.TagPrefix
}
}
var tt interface{}
if !c.opts.IsFluxion {
tt = t.Unix()
} else {
tt = t
}
val := []interface{}{tag, tt, v}
if c.opts.NonBlocking {
select {
case c.inputCh <- val:
default:
}
} else {
c.inputCh <- val
}
}
func (c *Client) Close() {
close(c.inputCh)
select {
case <-c.closeCh:
case <-time.After(c.opts.CloseTimeout):
}
}
func (c *Client) sender() {
defer func() {
if c.errorCh != nil {
close(c.errorCh)
} else {
close(c.closeCh)
}
}()
conn, err := net.DialTimeout("tcp", c.opts.Addr, c.opts.DialTimeout)
if err != nil {
c.pushError(err)
c.reconnect()
} else {
c.conn = conn
}
for v := range c.inputCh {
b, err := c.encode(v)
if err != nil {
c.pushError(err)
continue
}
c.conn.SetDeadline(time.Now().Add(c.opts.Timeout))
if _, err = c.conn.Write(b); err != nil {
c.pending.Add(b)
c.pushError(err)
c.conn.Close()
c.reconnect()
}
// Cancel deadline setting
c.conn.SetDeadline(time.Time{})
}
}
func (c *Client) encode(v interface{}) ([]byte, error) {
if b, ok := v.([]byte); ok {
return b, nil
}
var b []byte
err := codec.NewEncoderBytes(&b, c.mh).Encode(v)
return b, err
}
func (c *Client) reconnect() {
c.log("Connection failed, enter reconnection loop")
stop := c.poll()
for {
for attempts := 0; ; attempts++ {
time.Sleep(backoff(c.opts.RetryWait, attempts, c.opts.MaxBackoff))
c.log("Reconnect attempt %d", attempts+1)
if conn, err := net.DialTimeout("tcp", c.opts.Addr, c.opts.DialTimeout); err == nil {
c.log("Reconnected! try to flush pendings")
err, f := c.flush(conn, stop)
if err == nil {
c.conn = conn
c.log("Reconnection process completed! enter normal loop")
return
}
conn.Close()
if f != nil {
stop = f
}
}
}
}
}
func (c *Client) flush(conn net.Conn, stop func()) (error, func()) {
for attempts := 1; ; attempts++ {
t := time.Now()
if err := c.pending.Flush(conn, c.opts.Timeout); err != nil {
c.log("Failed to flush pendings, retrying...")
return err, nil
}
if took := time.Since(t); took < c.opts.Timeout {
c.log("Flushing almost completed in an acceptable time (%v)", took)
stop()
break
} else {
c.log("Flush attempts %d in %v", attempts, took)
}
}
if err := c.pending.Flush(conn, c.opts.Timeout); err != nil {
c.log("Failed to flush last piece of pendings")
f := c.poll()
return err, f
}
c.log("All flushing process succeeded!")
return nil, nil
}
func (c *Client) poll() (stop func()) {
closeC, doneC := make(chan bool, 1), make(chan bool)
go func() {
c.log("Start pending loop")
defer c.log("Stop pending loop")
for {
select {
case <-closeC:
doneC <- true
return
case v, ok := <-c.inputCh:
if !ok {
doneC <- true
return
}
b, err := c.encode(v)
if err != nil {
c.pushError(err)
} else {
c.pending.Add(b)
}
}
}
}()
return func() {
closeC <- true
<-doneC
}
}
func (c *Client) log(s string, args ...interface{}) {
if c.opts.LogHandler != nil {
c.opts.LogHandler(s, args...)
}
}
func (c *Client) errorWorker() {
defer close(c.closeCh)
for err := range c.errorCh {
c.opts.ErrorHandler.HandleError(err)
}
}
func (c *Client) pushError(err error) {
if c.errorCh == nil {
return
}
select {
case c.errorCh <- err:
default:
}
}
func backoff(interval time.Duration, count, limit int) time.Duration {
if count > limit {
count = limit
}
return interval * time.Duration(math.Exp2(float64(count)))
}