-
Notifications
You must be signed in to change notification settings - Fork 0
/
balance.go
285 lines (249 loc) · 5.63 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
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
package balance
import (
"container/heap"
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/cenkalti/backoff"
"github.com/gopacket/gopacket"
)
type Settings struct {
NumWorkers int
WorkerQueueSize int
ShutdownTimeout time.Duration
Backoff backoff.BackOff
}
var Default = Settings{
NumWorkers: 8,
WorkerQueueSize: 10000,
ShutdownTimeout: 30 * time.Second,
Backoff: backoff.WithMaxRetries(
newExponentialBackOff(),
10,
),
}
type Stats struct {
processed atomic.Uint64
failedBusy atomic.Uint64
failedType atomic.Uint64
failedHash atomic.Uint64
processedPerWorker map[string]uint64
}
func (b *Stats) Processed() uint64 {
return b.processed.Load()
}
func (b *Stats) Failed() uint64 {
return b.FailedBusy() + b.FailedHash() + b.FailedType()
}
func (b *Stats) FailedBusy() uint64 {
return b.failedBusy.Load()
}
func (b *Stats) FailedType() uint64 {
return b.failedType.Load()
}
func (b *Stats) FailedHash() uint64 {
return b.failedHash.Load()
}
func (b *Stats) ProcessedPerWorker() map[string]uint64 {
return b.processedPerWorker
}
type pool struct {
lock sync.RWMutex
heap Heap
wg sync.WaitGroup
}
func newPool(numWorkers int) *pool {
p := &pool{
heap: make(Heap, 0, numWorkers),
}
p.wg.Add(numWorkers)
return p
}
func newExponentialBackOff() backoff.BackOff {
expBackoff := backoff.NewExponentialBackOff()
expBackoff.InitialInterval = 1 * time.Microsecond
expBackoff.RandomizationFactor = 0.1
expBackoff.Multiplier = 1.5
return expBackoff
}
type Balancer struct {
Stats Stats
ctx context.Context
cancelBalancer context.CancelFunc
wg sync.WaitGroup
cancelWorkers context.CancelFunc
completed chan *worker
blocker *blocker
flowTable *flowLookup
p *pool
}
func New(processFn Handler, settings Settings) *Balancer {
ctx, cancelBalancer := context.WithCancel(context.Background())
completed := make(chan *worker, settings.WorkerQueueSize*2)
workerCtx, cancelWorkers := context.WithCancel(context.Background())
p := newPool(settings.NumWorkers)
for i := 0; i < settings.NumWorkers; i++ {
w, err := newWorker(
workerCtx,
workerSettings{
initialIndex: i,
handler: processFn,
completed: completed,
queueSize: settings.WorkerQueueSize,
postStop: p.wg.Done,
shutdownTimeout: settings.ShutdownTimeout,
},
)
if err != nil {
cancelBalancer()
cancelWorkers()
return nil
}
heap.Push(&p.heap, w)
w.start()
}
heap.Init(&p.heap)
return &Balancer{
Stats: Stats{
processedPerWorker: make(map[string]uint64),
},
ctx: ctx,
cancelBalancer: cancelBalancer,
cancelWorkers: cancelWorkers,
p: p,
completed: completed,
blocker: NewBlocker(
backoff.WithMaxRetries(
newExponentialBackOff(),
10,
),
),
flowTable: newFlowLookup(),
}
}
func (b *Balancer) Start(in <-chan gopacket.Packet) {
b.wg.Add(2)
go b.handleCompleted()
go b.handleDispatch(in)
}
func (b *Balancer) Stop() {
defer close(b.completed)
// It is important that the dispatch and completed goroutines exit before
// the worker goroutines. This ensures that no data is lost due to race
// conditions between the final packets being dispatched and the worker
// goroutines draining their request channels.
b.cancelBalancer()
b.wg.Wait()
b.cancelWorkers()
b.p.wg.Wait()
withTimeout(func() {
numCompleted := len(b.completed)
if numCompleted > 0 {
for i := 0; i < numCompleted; i++ {
worker, ok := <-b.completed
if !ok {
return
}
b.Stats.processed.Add(1)
b.Stats.processedPerWorker[worker.uuid]++
}
}
}, 5*time.Second)
}
func (b *Balancer) Delete(hash string) {
b.flowTable.delete(hash)
}
func (b *Balancer) handleCompleted() {
defer b.wg.Done()
for {
select {
case <-b.ctx.Done():
return
case worker, ok := <-b.completed:
if !ok {
return
}
b.updateHeap(worker)
b.Stats.processed.Add(1)
// this is a race condition
b.Stats.processedPerWorker[worker.uuid]++
// b.print()
}
}
}
func (b *Balancer) handleDispatch(in <-chan gopacket.Packet) {
defer b.wg.Done()
for {
select {
case <-b.ctx.Done():
return
case pkt, ok := <-in:
if !ok {
return
}
b.dispatch(pkt)
}
}
}
func (b *Balancer) dispatch(pkt gopacket.Packet) {
hash, err := hash(pkt)
if err != nil {
b.Stats.failedHash.Add(1)
return
}
b.p.lock.RLock()
selectedWorker := b.p.heap[0]
b.p.lock.RUnlock()
existingWorker, found := b.flowTable.load(hash)
if found {
selectedWorker = existingWorker
}
err = b.blocker.Wait(b.queueIsNotFull(selectedWorker))
if err != nil {
b.Stats.failedBusy.Add(1)
return
}
b.p.lock.Lock()
defer b.p.lock.Unlock()
if found {
selectedWorker.requests <- pkt
selectedWorker.pending++
heap.Fix(&b.p.heap, selectedWorker.idx)
} else {
w := heap.Pop(&b.p.heap).(*worker)
w.requests <- pkt
heap.Push(&b.p.heap, w)
w.pending++
b.flowTable.store(hash, w)
}
}
func (b *Balancer) updateHeap(w *worker) {
b.p.lock.Lock()
defer b.p.lock.Unlock()
w.pending--
mruWorker := heap.Remove(&b.p.heap, w.idx)
heap.Push(&b.p.heap, mruWorker)
}
func (b *Balancer) queueIsNotFull(w *worker) func() error {
return func() error {
if cap(w.requests) == len(w.requests) {
return errors.New("queue is full")
}
return nil
}
}
func (b *Balancer) print() {
sum := 0
sumsq := 0
for _, w := range b.p.heap {
fmt.Printf("%d ", w.pending)
sum += w.pending
sumsq += w.pending * w.pending
}
avg := float64(sum) / float64(len(b.p.heap))
variance := float64(sumsq)/float64(len(b.p.heap)) - avg*avg
fmt.Printf(" %.2f %.2f\n", avg, variance)
}