forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
async_worker.go
195 lines (165 loc) · 4.26 KB
/
async_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
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
package lb
import (
"time"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/op"
"github.com/elastic/beats/libbeat/logp"
"github.com/elastic/beats/libbeat/outputs"
"github.com/elastic/beats/libbeat/outputs/mode"
)
type asyncWorkerFactory struct {
clients []mode.AsyncProtocolClient
waitRetry, maxWaitRetry time.Duration
}
// asyncWorker instances handle one load-balanced output per instance. Workers receive
// messages from context and return failed send attempts back to the context.
// Client connection state is fully handled by the worker.
type asyncWorker struct {
id int
client mode.AsyncProtocolClient
backoff *common.Backoff
ctx context
}
func AsyncClients(
clients []mode.AsyncProtocolClient,
waitRetry, maxWaitRetry time.Duration,
) WorkerFactory {
return &asyncWorkerFactory{
clients: clients,
waitRetry: waitRetry,
maxWaitRetry: maxWaitRetry,
}
}
func (s *asyncWorkerFactory) count() int { return len(s.clients) }
func (s *asyncWorkerFactory) mk(ctx context) ([]worker, error) {
workers := make([]worker, len(s.clients))
for i, client := range s.clients {
workers[i] = newAsyncWorker(i, client, ctx, s.waitRetry, s.maxWaitRetry)
}
return workers, nil
}
func newAsyncWorker(
id int,
client mode.AsyncProtocolClient,
ctx context,
waitRetry, maxWaitRetry time.Duration,
) *asyncWorker {
return &asyncWorker{
id: id,
client: client,
backoff: common.NewBackoff(ctx.done, waitRetry, maxWaitRetry),
ctx: ctx,
}
}
func (w *asyncWorker) run() {
client := w.client
debugf("load balancer: start client loop")
defer debugf("load balancer: stop client loop")
done := false
for !done {
if done = w.connect(); !done {
done = w.sendLoop()
debugf("close client (done=%v)", done)
client.Close()
}
}
}
func (w *asyncWorker) connect() bool {
for {
err := w.client.Connect(w.ctx.timeout)
if err == nil {
w.backoff.Reset()
return false
}
logp.Err("Connect failed with: %v", err)
cont := w.backoff.Wait()
if !cont {
return true
}
}
}
func (w *asyncWorker) sendLoop() (done bool) {
for {
msg, ok := w.ctx.receive()
if !ok {
return true
}
msg.worker = w.id
err := w.onMessage(msg)
done = !w.backoff.WaitOnError(err)
if done || err != nil {
return done
}
}
}
func (w *asyncWorker) onMessage(msg eventsMessage) error {
if msg.datum.Event != nil {
return w.client.AsyncPublishEvent(w.handleResult(msg), msg.datum)
}
return w.client.AsyncPublishEvents(w.handleResults(msg), msg.data)
}
func (w *asyncWorker) handleResult(msg eventsMessage) func(error) {
return func(err error) {
if err != nil {
if msg.attemptsLeft > 0 {
msg.attemptsLeft--
}
w.onFail(msg, err)
return
}
op.SigCompleted(msg.signaler)
}
}
func (w *asyncWorker) handleResults(msg eventsMessage) func([]outputs.Data, error) {
total := len(msg.data)
return func(data []outputs.Data, err error) {
debugf("handleResults")
if err != nil {
debugf("handle publish error: %v", err)
if msg.attemptsLeft > 0 {
msg.attemptsLeft--
}
// reset attempt count if subset of messages has been processed
if len(data) < total && msg.attemptsLeft >= 0 {
msg.attemptsLeft = w.ctx.maxAttempts
}
if err != mode.ErrTempBulkFailure {
// retry non-published subset of events in batch
msg.data = data
w.onFail(msg, err)
return
}
if w.ctx.maxAttempts > 0 && msg.attemptsLeft == 0 {
// no more attempts left => drop
dropping(msg)
return
}
// retry non-published subset of events in batch
msg.data = data
w.onFail(msg, err)
return
}
// re-insert non-published events into pipeline
if len(data) != 0 {
go func() {
debugf("add non-published events back into pipeline: %v", len(data))
msg.data = data
w.ctx.pushFailed(msg)
}()
return
}
// all events published -> signal success
debugf("async bulk publish success (signaler=%v)", msg.signaler)
op.SigCompleted(msg.signaler)
}
}
func (w *asyncWorker) onFail(msg eventsMessage, err error) {
if !w.ctx.tryPushFailed(msg) {
// break possible deadlock by spawning go-routine returning failed messages
// into retries queue
go func() {
logp.Info("Error publishing events (retrying): %s", err)
w.ctx.pushFailed(msg)
}()
}
}