forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
86 lines (73 loc) · 1.53 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
package publisher
import (
"expvar"
"github.com/elastic/beats/libbeat/common"
)
// 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 *common.WorkerSignal
handler messageHandler
}
type message struct {
context Context
event common.MapStr
events []common.MapStr
}
type messageHandler interface {
onMessage(m message)
onStop()
}
func newMessageWorker(ws *common.WorkerSignal, hwm, bulkHWM int, h messageHandler) *messageWorker {
p := &messageWorker{}
p.init(ws, hwm, bulkHWM, h)
return p
}
func (p *messageWorker) init(ws *common.WorkerSignal, hwm, bulkHWM int, h messageHandler) {
p.queue = make(chan message, hwm)
p.bulkQueue = make(chan message, bulkHWM)
p.ws = ws
p.handler = h
defer p.ws.WorkerStart()
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()
close(p.queue)
close(p.bulkQueue)
p.ws.WorkerFinished()
}
func (p *messageWorker) onEvent(m message) {
messagesInWorkerQueues.Add(-1)
p.handler.onMessage(m)
p.ws.DoneEvent()
}
func (p *messageWorker) send(m message) {
p.ws.AddEvent(1)
if m.event != nil {
p.queue <- m
} else {
p.bulkQueue <- m
}
messagesInWorkerQueues.Add(1)
}