-
Notifications
You must be signed in to change notification settings - Fork 23
/
load-multiplier-token-bucket.go
192 lines (165 loc) · 6.22 KB
/
load-multiplier-token-bucket.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
package scheduler
import (
"context"
"sync"
"time"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus"
policysyncv1 "github.com/fluxninja/aperture/api/v2/gen/proto/go/aperture/policy/sync/v1"
"github.com/fluxninja/aperture/v2/pkg/log"
)
// Check if TokenBucketLoadMultiplier implements TokenManager interface.
var _ TokenManager = &LoadMultiplierTokenBucket{}
// LoadMultiplierTokenBucket is a token bucket with load multiplier.
type LoadMultiplierTokenBucket struct {
lmGauge prometheus.Gauge // metrics
tbb *tokenBucketBase
counter *WindowedCounter
lm float64 // load multiplier >=0
lock sync.Mutex
continuousTracking bool
validUntil time.Time
}
// NewLoadMultiplierTokenBucket creates a new TokenBucketLoadMultiplier.
func NewLoadMultiplierTokenBucket(
clk clockwork.Clock,
slotCount uint8,
slotDuration time.Duration,
lmGauge prometheus.Gauge,
tbMetrics *TokenBucketMetrics,
) *LoadMultiplierTokenBucket {
tbb := newTokenBucket(clk, tbMetrics)
tbls := &LoadMultiplierTokenBucket{
tbb: tbb,
counter: NewWindowedCounter(clk, slotCount, slotDuration),
lm: 0,
continuousTracking: false,
validUntil: time.Time{},
}
tbls.tbb.setPassThrough(true)
tbls.lmGauge = lmGauge
tbls.setLMGauge(float64(tbls.lm))
return tbls
}
// SetContinuousTracking sets whether to continuously track the token rate and adjust the fill rate based on load multiplier.
func (tbls *LoadMultiplierTokenBucket) SetContinuousTracking(continuousTracking bool) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
tbls.continuousTracking = continuousTracking
}
// SetLoadDecisionValues sets the load multiplier number --> 0 = no load accepted, 1 = accept up to 100% of current load, 2 = accept up to 200% of current load.
func (tbls *LoadMultiplierTokenBucket) SetLoadDecisionValues(loadDecision *policysyncv1.LoadDecision) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
lm := loadDecision.GetLoadMultiplier()
if lm >= 0 {
// set valid till timestamp if it is set else set it to 0
loadDecisionValidUntil := loadDecision.GetValidUntil()
if loadDecisionValidUntil != nil {
tbls.validUntil = loadDecisionValidUntil.AsTime()
} else {
tbls.validUntil = time.Time{}
}
tbls.lm = lm
tbls.setLMGauge(float64(tbls.lm))
if !tbls.counter.IsBootstrapping() {
// set fillRate based on latest sched.tokenRate
tbls.setFillRate()
log.Trace().
Float64("loadMultiplier", tbls.lm).
Float64("calculated fillRate", tbls.tbb.getFillRate()).
Float64("calculated token rate", tbls.counter.CalculateTokenRate()).
Msg("Controller update - Setting fill rate")
}
} else {
log.Panic().Msgf("Load multiplier must be greater than 0, got %f", lm)
}
}
// setFillRate - unsage, must be called with lock held.
func (tbls *LoadMultiplierTokenBucket) setFillRate() {
fillRate := tbls.counter.CalculateTokenRate() * tbls.lm
tbls.tbb.setFillRate(fillRate)
}
// LoadMultiplier returns the current load multiplier.
func (tbls *LoadMultiplierTokenBucket) LoadMultiplier() float64 {
tbls.lock.Lock()
defer tbls.lock.Unlock()
return tbls.lm
}
// PreprocessRequest preprocesses a request and makes decision whether to pro-actively accept a request.
func (tbls *LoadMultiplierTokenBucket) PreprocessRequest(_ context.Context, request *Request) bool {
tbls.lock.Lock()
defer tbls.lock.Unlock()
wasBootstrapping := tbls.counter.IsBootstrapping()
// Shift counter slot if needed
ready := tbls.counter.AddTokens(request)
// recalculate token rate
if ready {
if wasBootstrapping || tbls.continuousTracking {
// adjust fillRate based on the new tokenRate
tbls.setFillRate()
log.Trace().
Float64("loadMultiplier", tbls.lm).
Float64("calculated fillRate", tbls.tbb.getFillRate()).
Float64("calculated token rate", tbls.counter.CalculateTokenRate()).
Msg("Sliding window update - Setting fill rate")
if wasBootstrapping {
// This is the first time we are learning the tokenRate, initialize the token bucket
tbls.tbb.addTokens(tbls.tbb.getFillRate())
}
}
}
// Accept this request if we are still learning the tokenRate
if tbls.counter.IsBootstrapping() {
tbls.tbb.adjustTokens()
return true
}
return tbls.getPassThrough()
}
// TakeIfAvailable takes tokens from the token bucket if available, otherwise return false.
func (tbls *LoadMultiplierTokenBucket) TakeIfAvailable(_ context.Context, tokens float64) (bool, time.Duration, float64, float64, string) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
ok, waitTime, remaining, current := tbls.tbb.takeIfAvailable(tokens)
return ok, waitTime, remaining, current, ""
}
// Take takes tokens from the token bucket even if available tokens are less than asked.
// If tokens are not available at the moment, it will return amount of wait time and checks
// whether the operation was successful or not.
func (tbls *LoadMultiplierTokenBucket) Take(ctx context.Context, tokens float64) (bool, time.Duration, float64, float64, string) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
ok, waitTime, remaining, current := tbls.tbb.take(ctx, tokens)
return ok, waitTime, remaining, current, ""
}
// Return returns tokens to the token bucket.
func (tbls *LoadMultiplierTokenBucket) Return(_ context.Context, tokens float64, _ string) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
tbls.tbb.returnTokens(tokens)
}
func (tbls *LoadMultiplierTokenBucket) setLMGauge(v float64) {
if tbls.lmGauge != nil {
tbls.lmGauge.Set(v)
}
}
// GetPassThrough gets value of passThrough flag.
func (tbls *LoadMultiplierTokenBucket) GetPassThrough() bool {
tbls.lock.Lock()
defer tbls.lock.Unlock()
return tbls.getPassThrough()
}
// getPassThrough gets value of passThrough flag. Unsafe, must be called with lock held.
func (tbls *LoadMultiplierTokenBucket) getPassThrough() bool {
if !tbls.validUntil.IsZero() && tbls.validUntil.Before(time.Now()) {
return true
}
return tbls.tbb.getPassThrough()
}
// SetPassThrough sets PassThrough flag which decides whether to pass through requests.
func (tbls *LoadMultiplierTokenBucket) SetPassThrough(passThrough bool) {
tbls.lock.Lock()
defer tbls.lock.Unlock()
log.Trace().Msgf("Setting passThrough to %v", passThrough)
tbls.tbb.setPassThrough(passThrough)
}