-
Notifications
You must be signed in to change notification settings - Fork 343
/
algorithm.go
370 lines (305 loc) · 9.38 KB
/
algorithm.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package loadbalancer
import (
"errors"
"hash/fnv"
"math"
"math/rand"
"net/url"
"sync"
"time"
log "github.com/sirupsen/logrus"
"github.com/zalando/skipper/eskip"
"github.com/zalando/skipper/net"
"github.com/zalando/skipper/routing"
)
// Algorithm indicates the used load balancing algorithm.
type Algorithm int
const (
// None is the default non-specified algorithm.
None Algorithm = iota
// RoundRobin indicates round-robin load balancing between the backend endpoints.
RoundRobin
// Random indicates random choice between the backend endpoints.
Random
// ConsistentHash indicates choice between the backends based on their hashed address.
ConsistentHash
// PowerOfRandomNChoices selects N random endpoints and picks the one with least outstanding requests from them.
PowerOfRandomNChoices
)
const powerOfRandomNChoicesDefaultN = 2
var (
algorithms = map[Algorithm]initializeAlgorithm{
RoundRobin: newRoundRobin,
Random: newRandom,
ConsistentHash: newConsistentHash,
PowerOfRandomNChoices: newPowerOfRandomNChoices,
}
defaultAlgorithm = newRoundRobin
)
func fadeInState(now time.Time, duration time.Duration, detected time.Time) (time.Duration, bool) {
rel := now.Sub(detected)
return rel, rel > 0 && rel < duration
}
func fadeIn(now time.Time, duration time.Duration, exponent float64, detected time.Time) float64 {
rel, fadingIn := fadeInState(now, duration, detected)
if !fadingIn {
return 1
}
return math.Pow(float64(rel)/float64(duration), exponent)
}
func shiftWeighted(rnd *rand.Rand, ctx *routing.LBContext, w []float64, now time.Time) routing.LBEndpoint {
var sum float64
weightSums := w
rt := ctx.Route
ep := ctx.Route.LBEndpoints
for _, epi := range ep {
wi := fadeIn(now, rt.LBFadeInDuration, rt.LBFadeInExponent, epi.Detected)
sum += wi
weightSums = append(weightSums, sum)
}
choice := ep[len(weightSums)-1]
r := rnd.Float64() * sum
for i := range weightSums {
if weightSums[i] > r {
choice = ep[i]
break
}
}
return choice
}
func shiftToRemaining(rnd *rand.Rand, ctx *routing.LBContext, wi []int, wf []float64, now time.Time) routing.LBEndpoint {
notFadingIndexes := wi
ep := ctx.Route.LBEndpoints
for i := 0; i < len(ep); i++ {
if _, fadingIn := fadeInState(now, ctx.Route.LBFadeInDuration, ep[i].Detected); !fadingIn {
notFadingIndexes = append(notFadingIndexes, i)
}
}
// if all endpoints are fading, the simplest approach is to use the oldest,
// this departs from the desired curve, but guarantees monotonic fade-in. From
// the perspective of the oldest endpoint, this is temporarily the same as if
// there was no fade-in.
if len(notFadingIndexes) == 0 {
return shiftWeighted(rnd, ctx, wf, now)
}
// otherwise equally distribute between the old endpoints
return ep[notFadingIndexes[rnd.Intn(len(notFadingIndexes))]]
}
func withFadeIn(rnd *rand.Rand, ctx *routing.LBContext, wi []int, wf []float64, choice int) routing.LBEndpoint {
now := time.Now()
f := fadeIn(
now,
ctx.Route.LBFadeInDuration,
ctx.Route.LBFadeInExponent,
ctx.Route.LBEndpoints[choice].Detected,
)
if rnd.Float64() < f {
return ctx.Route.LBEndpoints[choice]
}
return shiftToRemaining(rnd, ctx, wi, wf, now)
}
type roundRobin struct {
mx sync.Mutex
index int
rnd *rand.Rand
notFadingIndexes []int
fadingWeights []float64
}
func newRoundRobin(endpoints []string) routing.LBAlgorithm {
rnd := rand.New(rand.NewSource(time.Now().UnixNano())) // #nosec
return &roundRobin{
index: rnd.Intn(len(endpoints)),
rnd: rnd,
// preallocating frequently used slice
notFadingIndexes: make([]int, 0, len(endpoints)),
fadingWeights: make([]float64, 0, len(endpoints)),
}
}
// Apply implements routing.LBAlgorithm with a roundrobin algorithm.
func (r *roundRobin) Apply(ctx *routing.LBContext) routing.LBEndpoint {
if len(ctx.Route.LBEndpoints) == 1 {
return ctx.Route.LBEndpoints[0]
}
r.mx.Lock()
defer r.mx.Unlock()
r.index = (r.index + 1) % len(ctx.Route.LBEndpoints)
if ctx.Route.LBFadeInDuration <= 0 {
return ctx.Route.LBEndpoints[r.index]
}
return withFadeIn(r.rnd, ctx, r.notFadingIndexes, r.fadingWeights, r.index)
}
type random struct {
rand *rand.Rand
notFadingIndexes []int
fadingWeights []float64
}
func newRandom(endpoints []string) routing.LBAlgorithm {
t := time.Now().UnixNano()
// #nosec
return &random{
rand: rand.New(rand.NewSource(t)),
// preallocating frequently used slice
notFadingIndexes: make([]int, 0, len(endpoints)),
fadingWeights: make([]float64, 0, len(endpoints)),
}
}
// Apply implements routing.LBAlgorithm with a stateless random algorithm.
func (r *random) Apply(ctx *routing.LBContext) routing.LBEndpoint {
if len(ctx.Route.LBEndpoints) == 1 {
return ctx.Route.LBEndpoints[0]
}
i := r.rand.Intn(len(ctx.Route.LBEndpoints))
if ctx.Route.LBFadeInDuration <= 0 {
return ctx.Route.LBEndpoints[i]
}
return withFadeIn(r.rand, ctx, r.notFadingIndexes, r.fadingWeights, i)
}
type consistentHash struct{}
func newConsistentHash(endpoints []string) routing.LBAlgorithm {
return &consistentHash{}
}
// Apply implements routing.LBAlgorithm with a consistent hash algorithm.
func (ch *consistentHash) Apply(ctx *routing.LBContext) routing.LBEndpoint {
if len(ctx.Route.LBEndpoints) == 1 {
return ctx.Route.LBEndpoints[0]
}
var sum uint32
h := fnv.New32()
key := net.RemoteHost(ctx.Request).String()
if _, err := h.Write([]byte(key)); err != nil {
log.Errorf("Failed to write '%s' into hash: %v", key, err)
return ctx.Route.LBEndpoints[rand.Intn(len(ctx.Route.LBEndpoints))] // #nosec
}
sum = h.Sum32()
choice := int(sum) % len(ctx.Route.LBEndpoints)
if choice < 0 {
choice = len(ctx.Route.LBEndpoints) + choice
}
return ctx.Route.LBEndpoints[choice]
}
type powerOfRandomNChoices struct {
mx sync.Mutex
rand *rand.Rand
numberOfChoices int
}
// newPowerOfRandomNChoices selects N random backends and picks the one with less outstanding requests.
func newPowerOfRandomNChoices(endpoints []string) routing.LBAlgorithm {
rnd := rand.New(rand.NewSource(time.Now().UnixNano())) // #nosec
return &powerOfRandomNChoices{
rand: rnd,
numberOfChoices: powerOfRandomNChoicesDefaultN,
}
}
// Apply implements routing.LBAlgorithm with power of random N choices algorithm.
func (p *powerOfRandomNChoices) Apply(ctx *routing.LBContext) routing.LBEndpoint {
ne := len(ctx.Route.LBEndpoints)
p.mx.Lock()
defer p.mx.Unlock()
best := ctx.Route.LBEndpoints[p.rand.Intn(ne)]
for i := 1; i < p.numberOfChoices; i++ {
ce := ctx.Route.LBEndpoints[p.rand.Intn(ne)]
if p.getScore(ce) > p.getScore(best) {
best = ce
}
}
return best
}
// getScore returns negative value of inflightrequests count.
func (p *powerOfRandomNChoices) getScore(e routing.LBEndpoint) int {
// endpoints with higher inflight request should have lower score
return -e.Metrics.GetInflightRequests()
}
type (
algorithmProvider struct{}
initializeAlgorithm func(endpoints []string) routing.LBAlgorithm
)
// NewAlgorithmProvider creates a routing.PostProcessor used to initialize
// the algorithm of load balancing routes.
func NewAlgorithmProvider() routing.PostProcessor {
return &algorithmProvider{}
}
// AlgorithmFromString parses the string representation of the algorithm definition.
func AlgorithmFromString(a string) (Algorithm, error) {
switch a {
case "":
// This means that the user didn't explicitly specify which
// algorithm should be used, and we will use a default one.
return None, nil
case "roundRobin":
return RoundRobin, nil
case "random":
return Random, nil
case "consistentHash":
return ConsistentHash, nil
case "powerOfRandomNChoices":
return PowerOfRandomNChoices, nil
default:
return None, errors.New("unsupported algorithm")
}
}
// String returns the string representation of an algorithm definition.
func (a Algorithm) String() string {
switch a {
case RoundRobin:
return "roundRobin"
case Random:
return "random"
case ConsistentHash:
return "consistentHash"
case PowerOfRandomNChoices:
return "powerOfRandomNChoices"
default:
return ""
}
}
func parseEndpoints(r *routing.Route) error {
r.LBEndpoints = make([]routing.LBEndpoint, len(r.Route.LBEndpoints))
for i, e := range r.Route.LBEndpoints {
eu, err := url.ParseRequestURI(e)
if err != nil {
return err
}
r.LBEndpoints[i] = routing.LBEndpoint{
Scheme: eu.Scheme,
Host: eu.Host,
Metrics: &routing.LBMetrics{},
}
}
return nil
}
func setAlgorithm(r *routing.Route) error {
t, err := AlgorithmFromString(r.Route.LBAlgorithm)
if err != nil {
return err
}
initialize := defaultAlgorithm
if t != None {
initialize = algorithms[t]
}
r.LBAlgorithm = initialize(r.Route.LBEndpoints)
return nil
}
// Do implements routing.PostProcessor
func (p *algorithmProvider) Do(r []*routing.Route) []*routing.Route {
rr := make([]*routing.Route, 0, len(r))
for _, ri := range r {
if ri.Route.BackendType != eskip.LBBackend {
rr = append(rr, ri)
continue
}
if len(ri.Route.LBEndpoints) == 0 {
log.Errorf("failed to post-process LB route: %s, no endpoints defined", ri.Id)
continue
}
if err := parseEndpoints(ri); err != nil {
log.Errorf("failed to parse LB endpoints for route %s: %v", ri.Id, err)
continue
}
if err := setAlgorithm(ri); err != nil {
log.Errorf("failed to set LB algorithm implementation for route %s: %v", ri.Id, err)
continue
}
rr = append(rr, ri)
}
return rr
}