-
Notifications
You must be signed in to change notification settings - Fork 4
/
buffered.go
272 lines (242 loc) · 6.59 KB
/
buffered.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
package fluent
import (
"context"
"time"
pdebug "github.com/lestrrat-go/pdebug"
"github.com/pkg/errors"
)
// NewBuffered creates a new Buffered client.
// Options may be one of the following:
//
// - fluent.WithAddress
// - fluent.WithBufferLimit
// - fluent.WithDialTimeout
// - fluent.WithJSONMarshaler
// - fluent.WithMaxConnAttempts
// - fluent.WithMsgpackMarshaler
// - fluent.WithMarshaller
// - fluent.WithNetwork
// - fluent.WithTagPrefix
// - fluent.WithWriteThreshold
// - fluent.WithWriteQueueSize
//
// Please see their respective documentation for details.
func NewBuffered(options ...Option) (client *Buffered, err error) {
if pdebug.Enabled {
g := pdebug.Marker("fluent.NewBuffered").BindError(&err)
defer g.End()
}
m, err := newMinion(options...)
if err != nil {
return nil, err
}
var c Buffered
ctx, cancel := context.WithCancel(context.Background())
var subsecond bool
//nolint:forcetypeassert
for _, opt := range options {
switch opt.Ident() {
case identSubSecond{}:
subsecond = opt.Value().(bool)
}
}
c.minionDone = m.done
c.minionQueue = m.incoming
c.minionCancel = cancel
c.pingQueue = m.pingCh
c.subsecond = subsecond
go m.runReader(ctx)
go m.runWriter(ctx)
return &c, nil
}
// Post posts the given structure after encoding it along with the given tag.
//
// An error is returned if the client has already been closed.
//
// If you would like to specify options to `Post()`, you may pass them at the end of
// the method. Currently you can use the following:
//
// fluent.WithContext: specify context.Context to use
// fluent.WithTimestamp: allows you to set arbitrary timestamp values
// fluent.WithSyncAppend: allows you to verify if the append was successful
//
// If fluent.WithSyncAppend is provide and is true, the following errors
// may be returned:
//
// 1. If the current underlying pending buffer is not large enough to
// hold this new data, an error will be returned
// 2. If the marshaling into msgpack/json failed, it is returned
func (c *Buffered) Post(tag string, v interface{}, options ...Option) (err error) {
if pdebug.Enabled {
g := pdebug.Marker("fluent.Buffered.Post").BindError(&err)
defer g.End()
}
// Do not allow processing at all if we have closed
c.muClosed.RLock()
defer c.muClosed.RUnlock()
if c.closed {
return errors.New(`client has already been closed`)
}
var syncAppend bool
var subsecond = c.subsecond
var t time.Time
var ctx = context.Background()
//nolint:forcetypeassert
for _, opt := range options {
switch opt.Ident() {
case identTimestamp{}:
t = opt.Value().(time.Time)
case identSyncAppend{}:
syncAppend = opt.Value().(bool)
case identSubSecond{}:
subsecond = opt.Value().(bool)
case identContext{}:
if pdebug.Enabled {
pdebug.Printf("client: using user-supplied context")
}
//nolint:fatcontext
ctx = opt.Value().(context.Context)
}
}
if t.IsZero() {
t = time.Now()
}
msg := makeMessage(tag, v, t, subsecond, syncAppend)
// This has to be separate from msg.replyCh, b/c msg would be
// put back to the pool
var replyCh = msg.replyCh
if syncAppend {
if pdebug.Enabled {
pdebug.Printf("client: synchronous append requested. creating channel")
}
}
// Because case statements in a select is evaluated in random
// order, writing to c.minionQueue in the subsequent select
// may succeed or fail depending on the run.
//
// This extra check ensures that if the context is canceled
// well in advance, we never get into the ambiguous situation
select {
case <-ctx.Done():
return ctx.Err()
default:
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.minionDone:
return errors.New("writer has been closed. Shutdown called?")
case c.minionQueue <- msg:
if pdebug.Enabled {
pdebug.Printf("client: wrote message to queue")
}
}
if syncAppend {
if pdebug.Enabled {
pdebug.Printf("client: Post is waiting for return status")
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.minionDone:
return errors.New("writer has been closed. Shutdown called?")
case e := <-replyCh:
if pdebug.Enabled {
pdebug.Printf("client: synchronous result received")
}
return e
}
}
return nil
}
// Close closes the connection, but does not wait for the pending buffers
// to be flushed. If you want to make sure that background minion has properly
// exited, you should probably use the Shutdown() method
func (c *Buffered) Close() error {
c.muClosed.Lock()
c.closed = true
if c.minionQueue != nil {
close(c.minionQueue)
c.minionQueue = nil
}
if c.pingQueue != nil {
close(c.pingQueue)
c.pingQueue = nil
}
c.muClosed.Unlock()
c.minionCancel()
return nil
}
// Shutdown closes the connection, and notifies the background worker to
// flush all existing buffers. This method will block until the
// background minion exits, or the provided context object is canceled.
func (c *Buffered) Shutdown(ctx context.Context) error {
if pdebug.Enabled {
pdebug.Printf("client: shutdown requested")
defer pdebug.Printf("client: shutdown completed")
}
if ctx == nil {
ctx = context.Background() // no cancel...
}
if err := c.Close(); err != nil {
return errors.Wrap(err, `failed to close`)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-c.minionDone:
return nil
}
}
// Ping synchronously sends a ping message. This ping bypasses the underlying
// buffer of pending messages, and establishes a connection to the
// server entirely for this ping message.
func (c *Buffered) Ping(tag string, record interface{}, options ...Option) (err error) {
if pdebug.Enabled {
g := pdebug.Marker("Buffered.Ping").BindError(&err)
defer g.End()
}
var ctx = context.Background()
var subsecond bool
var t time.Time
//nolint:forcetypeassert
for _, opt := range options {
switch opt.Ident() {
case identSubSecond{}:
subsecond = opt.Value().(bool)
case identTimestamp{}:
t = opt.Value().(time.Time)
case identContext{}:
if pdebug.Enabled {
pdebug.Printf("client: using user-supplied context")
}
//nolint:fatcontext
ctx = opt.Value().(context.Context)
}
}
if t.IsZero() {
t = time.Now()
}
msg := makeMessage(tag, record, t, subsecond, true)
// Do not allow processing at all if we have closed
c.muClosed.RLock()
if c.closed {
c.muClosed.RUnlock()
return errors.New(`client has already been closed`)
}
if pdebug.Enabled {
pdebug.Printf("Sending to ping queue")
}
replyCh := msg.replyCh
c.pingQueue <- msg
c.muClosed.RUnlock()
if pdebug.Enabled {
pdebug.Printf("Waiting for synchronous ping response...")
}
select {
case <-ctx.Done():
return ctx.Err()
case e := <-replyCh:
return e
}
}