forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
135 lines (111 loc) · 2.32 KB
/
worker.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
package publisher
import (
"expvar"
"sync"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/op"
)
// Metrics that can retrieved through the expvar web interface.
var (
messagesInWorkerQueues = expvar.NewInt("libbeatMessagesInWorkerQueues")
)
type worker interface {
send(m message)
}
type messageWorker struct {
queue chan message
bulkQueue chan message
ws *workerSignal
handler messageHandler
}
type workerSignal struct {
done chan struct{}
wg sync.WaitGroup
}
type message struct {
client *client
context Context
event common.MapStr
events []common.MapStr
}
type messageHandler interface {
onMessage(m message)
onStop()
}
func newMessageWorker(ws *workerSignal, hwm, bulkHWM int, h messageHandler) *messageWorker {
p := &messageWorker{}
p.init(ws, hwm, bulkHWM, h)
return p
}
func (p *messageWorker) init(ws *workerSignal, hwm, bulkHWM int, h messageHandler) {
p.queue = make(chan message, hwm)
p.bulkQueue = make(chan message, bulkHWM)
p.ws = ws
p.handler = h
ws.wg.Add(1)
go p.run()
}
func (p *messageWorker) run() {
defer p.shutdown()
for {
select {
case <-p.ws.done:
return
case m := <-p.queue:
p.onEvent(m)
case m := <-p.bulkQueue:
p.onEvent(m)
}
}
}
func (p *messageWorker) shutdown() {
p.handler.onStop()
stopQueue(p.queue)
stopQueue(p.bulkQueue)
p.ws.wg.Done()
}
func (p *messageWorker) onEvent(m message) {
messagesInWorkerQueues.Add(-1)
p.handler.onMessage(m)
}
func (p *messageWorker) send(m message) {
send(p.queue, p.bulkQueue, m)
}
func (ws *workerSignal) stop() {
close(ws.done)
ws.wg.Wait()
}
func newWorkerSignal() *workerSignal {
w := &workerSignal{}
w.Init()
return w
}
func (ws *workerSignal) Init() {
ws.done = make(chan struct{})
}
func stopQueue(qu chan message) {
close(qu)
for msg := range qu { // clear queue and send fail signal
op.SigFailed(msg.context.Signal, nil)
}
}
func send(qu, bulkQu chan message, m message) {
var ch chan message
if m.event != nil {
ch = qu
} else {
ch = bulkQu
}
var done <-chan struct{}
if m.client != nil {
done = m.client.canceler.Done()
}
select {
case <-done: // blocks if nil
// client closed -> signal drop
// XXX: send Cancel or Fail signal?
op.SigFailed(m.context.Signal, ErrClientClosed)
case ch <- m:
messagesInWorkerQueues.Add(1)
}
}