forked from StephanU/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
broker.go
363 lines (296 loc) · 6.64 KB
/
broker.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
355
356
357
358
359
360
361
362
363
package memqueue
import (
"fmt"
"math"
"sync"
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/publisher"
"github.com/elastic/beats/libbeat/publisher/queue"
)
type Broker struct {
done chan struct{}
logger logger
buf brokerBuffer
minEvents int
idleTimeout time.Duration
// api channels
events chan pushRequest
requests chan getRequest
pubCancel chan producerCancelRequest
// internal channels
acks chan int
scheduledACKs chan chanList
eventer queue.Eventer
// wait group for worker shutdown
wg sync.WaitGroup
waitOnClose bool
}
type Settings struct {
Eventer queue.Eventer
Events int
FlushMinEvents int
FlushTimeout time.Duration
WaitOnClose bool
}
type ackChan struct {
next *ackChan
ch chan batchAckRequest
seq uint
start, count int // number of events waiting for ACK
}
type chanList struct {
head *ackChan
tail *ackChan
}
func init() {
queue.RegisterType("mem", create)
}
func create(eventer queue.Eventer, cfg *common.Config) (queue.Queue, error) {
config := defaultConfig
if err := cfg.Unpack(&config); err != nil {
return nil, err
}
return NewBroker(Settings{
Eventer: eventer,
Events: config.Events,
FlushMinEvents: config.FlushMinEvents,
FlushTimeout: config.FlushTimeout,
}), nil
}
// NewBroker creates a new broker based in-memory queue holding up to sz number of events.
// If waitOnClose is set to true, the broker will block on Close, until all internal
// workers handling incoming messages and ACKs have been shut down.
func NewBroker(
settings Settings,
) *Broker {
// define internal channel size for procuder/client requests
// to the broker
chanSize := 20
var (
sz = settings.Events
minEvents = settings.FlushMinEvents
flushTimeout = settings.FlushTimeout
)
if minEvents < 1 {
minEvents = 1
}
if minEvents > 1 && flushTimeout <= 0 {
minEvents = 1
flushTimeout = 0
}
if minEvents > sz {
minEvents = sz
}
logger := defaultLogger
b := &Broker{
done: make(chan struct{}),
logger: logger,
// broker API channels
events: make(chan pushRequest, chanSize),
requests: make(chan getRequest),
pubCancel: make(chan producerCancelRequest, 5),
// internal broker and ACK handler channels
acks: make(chan int),
scheduledACKs: make(chan chanList),
waitOnClose: settings.WaitOnClose,
eventer: settings.Eventer,
}
b.buf.init(logger, sz)
b.minEvents = minEvents
b.idleTimeout = flushTimeout
eventLoop := newEventLoop(b)
ack := &ackLoop{broker: b}
b.wg.Add(2)
go func() {
defer b.wg.Done()
eventLoop.run()
}()
go func() {
defer b.wg.Done()
ack.run()
}()
return b
}
func (b *Broker) Close() error {
close(b.done)
if b.waitOnClose {
b.wg.Wait()
}
return nil
}
func (b *Broker) BufferConfig() queue.BufferConfig {
return queue.BufferConfig{
Events: b.buf.Size(),
}
}
func (b *Broker) Producer(cfg queue.ProducerConfig) queue.Producer {
return newProducer(b, cfg.ACK, cfg.OnDrop, cfg.DropOnCancel)
}
func (b *Broker) Consumer() queue.Consumer {
return newConsumer(b)
}
func (b *Broker) insert(req *pushRequest) (int, bool) {
var avail int
if req.state == nil {
_, avail = b.buf.insert(req.event, clientState{})
} else {
st := req.state
if st.cancelled {
b.logger.Debugf("cancelled producer - ignore event: %v\t%v\t%p", req.event, req.seq, req.state)
// do not add waiting events if producer did send cancel signal
if cb := st.dropCB; cb != nil {
cb(req.event.Content)
}
return -1, false
}
_, avail = b.buf.insert(req.event, clientState{
seq: req.seq,
state: st,
})
}
return avail, true
}
func (b *Broker) get(max int) (startIndex int, events []publisher.Event) {
return b.buf.reserve(max)
}
func (b *Broker) cancel(st *produceState) int {
return b.buf.cancel(st)
}
func (b *Broker) full() bool {
return b.buf.Full()
}
func (b *Broker) avail() int {
return b.buf.Avail()
}
func (b *Broker) totalAvail() int {
return b.buf.TotalAvail()
}
func (b *Broker) cleanACKs(count int) {
b.buf.ack(count)
}
func (b *Broker) reportACK(states []clientState, start, N int) {
{
start := time.Now()
b.logger.Debug("handle ACKs: ", N)
defer func() {
b.logger.Debug("handle ACK took: ", time.Since(start))
}()
}
if e := b.eventer; e != nil {
e.OnACK(N)
}
// TODO: global boolean to check if clients will need an ACK
// no need to report ACKs if no client is interested in ACKs
idx := start + N - 1
if idx >= len(states) {
idx -= len(states)
}
total := 0
for i := N - 1; i >= 0; i-- {
if idx < 0 {
idx = len(states) - 1
}
st := &states[idx]
b.logger.Debugf("try ack index: (idx=%v, i=%v, seq=%v)\n", idx, i, st.seq)
idx--
if st.state == nil {
b.logger.Debug("no state set")
continue
}
count := (st.seq - st.state.lastACK)
if count == 0 || count > math.MaxUint32/2 {
// seq number comparison did underflow. This happens only if st.seq has
// allready been acknowledged
// b.logger.Debug("seq number already acked: ", st.seq)
st.state = nil
continue
}
b.logger.Debugf("broker ACK events: count=%v, start-seq=%v, end-seq=%v\n",
count,
st.state.lastACK+1,
st.seq,
)
total += int(count)
if total > N {
panic(fmt.Sprintf("Too many events acked (expected=%v, total=%v)",
count, total,
))
}
st.state.cb(int(count))
st.state.lastACK = st.seq
st.state = nil
}
}
var ackChanPool = sync.Pool{
New: func() interface{} {
return &ackChan{
ch: make(chan batchAckRequest, 1),
}
},
}
func newACKChan(seq uint, start, count int) *ackChan {
ch := ackChanPool.Get().(*ackChan)
ch.next = nil
ch.seq = seq
ch.start = start
ch.count = count
return ch
}
func releaseACKChan(c *ackChan) {
c.next = nil
ackChanPool.Put(c)
}
func (l *chanList) prepend(ch *ackChan) {
ch.next = l.head
l.head = ch
if l.tail == nil {
l.tail = ch
}
}
func (l *chanList) concat(other *chanList) {
if l.head == nil {
*l = *other
return
}
l.tail.next = other.head
l.tail = other.tail
}
func (l *chanList) append(ch *ackChan) {
if l.head == nil {
l.head = ch
} else {
l.tail.next = ch
}
l.tail = ch
}
func (l *chanList) count() (elems, count int) {
for ch := l.head; ch != nil; ch = ch.next {
elems++
count += ch.count
}
return
}
func (l *chanList) empty() bool {
return l.head == nil
}
func (l *chanList) front() *ackChan {
return l.head
}
func (l *chanList) channel() chan batchAckRequest {
if l.head == nil {
return nil
}
return l.head.ch
}
func (l *chanList) pop() *ackChan {
ch := l.head
if ch != nil {
l.head = ch.next
if l.head == nil {
l.tail = nil
}
}
ch.next = nil
return ch
}