-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
balance.go
230 lines (205 loc) · 6.12 KB
/
balance.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
package mode
import (
"sync"
"time"
"github.com/elastic/libbeat/common"
"github.com/elastic/libbeat/logp"
"github.com/elastic/libbeat/outputs"
)
// LoadBalancerMode balances the sending of events between multiple connections.
//
// The balancing algorithm is mostly pull-based, with multiple workers trying to pull
// some amount of work from a shared queue. Workers will try to get a new work item
// only if they have a working/active connection. Workers without active connection
// do not participate until a connection has been re-established.
// Due to the pull based nature the algorithm will load-balance events by random
// with workers having less latencies/turn-around times potentially getting more
// work items then other workers with higher latencies. Thusly the algorithm
// dynamically adapts to resource availability of server events are forwarded to.
//
// Workers not participating in the load-balancing will continuously try to reconnect
// to their configured endpoints. Once a new connection has been established,
// these workers will participate in in load-balancing again.
//
// If a connection becomes unavailable, the events are rescheduled for another
// connection to pick up. Rescheduling events is limited to a maximum number of
// send attempts. If events have not been send after maximum number of allowed
// attemps has been passed, they will be dropped.
//
// Distributing events to workers is subject to timeout. If no worker is available to
// pickup a message for sending, the message will be dropped internally.
type LoadBalancerMode struct {
timeout time.Duration // send/retry timeout. Every timeout is a failed send attempt
waitRetry time.Duration // duration to wait during re-connection attempts
// maximum number of configured send attempts. If set to 0, publisher will
// block until event has been successfully published.
maxAttempts int
// waitGroup + signaling channel for handling shutdown
wg sync.WaitGroup
done chan struct{}
// channels for forwarding work items to workers.
// The work channel is used by publisher to insert new events
// into the load balancer. The work channel is synchronous blocking until timeout
// for one worker available.
// The retries channel is used to forward failed send attempts to other workers.
// The retries channel is buffered to mitigate possible deadlocks when all
// workers become unresponsive.
work chan eventsMessage
retries chan eventsMessage
}
type eventsMessage struct {
attemptsLeft int
signaler outputs.Signaler
events []common.MapStr
event common.MapStr
}
// NewLoadBalancerMode create a new load balancer connection mode.
func NewLoadBalancerMode(
clients []ProtocolClient,
maxAttempts int,
waitRetry, timeout time.Duration,
) (*LoadBalancerMode, error) {
m := &LoadBalancerMode{
timeout: timeout,
waitRetry: waitRetry,
maxAttempts: maxAttempts,
work: make(chan eventsMessage),
retries: make(chan eventsMessage, len(clients)*2),
done: make(chan struct{}),
}
m.start(clients)
return m, nil
}
// Close stops all workers and closes all open connections. In flight events
// are signaled as failed.
func (m *LoadBalancerMode) Close() error {
close(m.done)
m.wg.Wait()
return nil
}
// PublishEvents forwards events to some load balancing worker.
func (m *LoadBalancerMode) PublishEvents(
signaler outputs.Signaler,
events []common.MapStr,
) error {
return m.publishEventsMessage(eventsMessage{
attemptsLeft: m.maxAttempts,
signaler: signaler,
events: events,
})
}
// PublishEvent forwards the event to some load balancing worker.
func (m *LoadBalancerMode) PublishEvent(
signaler outputs.Signaler,
event common.MapStr,
) error {
return m.publishEventsMessage(eventsMessage{
attemptsLeft: m.maxAttempts,
signaler: signaler,
event: event,
})
}
func (m *LoadBalancerMode) publishEventsMessage(msg eventsMessage) error {
if ok := m.forwardEvent(m.work, msg); !ok {
outputs.SignalFailed(msg.signaler, nil)
}
return nil
}
func (m *LoadBalancerMode) start(clients []ProtocolClient) {
var waitStart sync.WaitGroup
worker := func(client ProtocolClient) {
defer func() {
if client.IsConnected() {
_ = client.Close()
}
m.wg.Done()
}()
waitStart.Done()
for {
// reconnect loop
for !client.IsConnected() {
if err := client.Connect(m.timeout); err == nil {
break
}
select {
case <-m.done:
return
case <-time.After(m.waitRetry):
}
}
// receive and process messages
var msg eventsMessage
select {
case <-m.done:
return
case msg = <-m.retries: // receive message from other failed worker
case msg = <-m.work: // receive message from publisher
}
m.onMessage(client, msg)
}
}
for _, client := range clients {
m.wg.Add(1)
waitStart.Add(1)
go worker(client)
}
waitStart.Wait()
}
func (m *LoadBalancerMode) onMessage(client ProtocolClient, msg eventsMessage) {
if msg.event != nil {
if err := client.PublishEvent(msg.event); err != nil {
m.onFail(msg, err)
return
}
} else {
published := 0
events := msg.events
send := 0
for published < len(events) {
n, err := client.PublishEvents(events[published:])
if err != nil {
// retry only non-confirmed subset of events in batch
msg.events = msg.events[published:]
// reset attempt count if subset of message has been send
if send > 0 {
msg.attemptsLeft = m.maxAttempts + 1
}
m.onFail(msg, err)
return
}
published += n
send++
}
}
outputs.SignalCompleted(msg.signaler)
}
func (m *LoadBalancerMode) onFail(msg eventsMessage, err error) {
logp.Info("Error publishing events (retrying): %s", err)
if ok := m.forwardEvent(m.retries, msg); !ok {
outputs.SignalFailed(msg.signaler, err)
}
}
func (m *LoadBalancerMode) forwardEvent(
ch chan eventsMessage,
msg eventsMessage,
) bool {
if m.maxAttempts == 0 {
select {
case ch <- msg:
return true
case <-m.done: // shutdown
return false
}
} else {
for ; msg.attemptsLeft > 0; msg.attemptsLeft-- {
select {
case ch <- msg:
return true
case <-m.done: // shutdown
return false
case <-time.After(m.timeout):
}
}
}
return false
}