-
Notifications
You must be signed in to change notification settings - Fork 342
/
admission.go
451 lines (380 loc) · 10.8 KB
/
admission.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package shedder
import (
"context"
"math"
"math/rand"
"net/http"
"sync"
"time"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
log "github.com/sirupsen/logrus"
"github.com/zalando/skipper/eskip"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/metrics"
"github.com/zalando/skipper/routing"
"go.uber.org/atomic"
)
func getIntArg(a interface{}) (int, error) {
if i, ok := a.(int); ok {
return i, nil
}
if f, ok := a.(float64); ok {
return int(f), nil
}
return 0, filters.ErrInvalidFilterParameters
}
func getDurationArg(a interface{}) (time.Duration, error) {
if s, ok := a.(string); ok {
return time.ParseDuration(s)
}
return 0, filters.ErrInvalidFilterParameters
}
func getFloat64Arg(a interface{}) (float64, error) {
if f, ok := a.(float64); ok {
return f, nil
}
return 0, filters.ErrInvalidFilterParameters
}
func getModeArg(a interface{}) (mode, error) {
s, ok := a.(string)
if !ok {
return 0, filters.ErrInvalidFilterParameters
}
switch s {
case "active":
return active, nil
case "inactive":
return inactive, nil
case "logInactive":
return logInactive, nil
}
return 0, filters.ErrInvalidFilterParameters
}
type mode int
const (
inactive mode = iota + 1
logInactive
active
)
func (m mode) String() string {
switch m {
case active:
return "active"
case inactive:
return "inactive"
case logInactive:
return "logInactive"
}
return "unknown"
}
const (
counterPrefix = "shedder.admission_control."
admissionControlSpanName = "admission_control"
admissionControlKey = "shedder:admission_control"
admissionControlValue = "reject"
minWindowSize = 1
maxWindowSize = 100
)
type Options struct {
Tracer opentracing.Tracer
}
type admissionControlPre struct{}
// Do removes duplicate filters, because we can only handle one in a
// chain. The last one will override the others.
func (spec *admissionControlPre) Do(routes []*eskip.Route) []*eskip.Route {
for _, r := range routes {
foundAt := -1
toDelete := make(map[int]struct{})
for i, f := range r.Filters {
if f.Name == filters.AdmissionControlName {
if foundAt != -1 {
toDelete[foundAt] = struct{}{}
}
foundAt = i
}
}
if len(toDelete) == 0 {
continue
}
rf := make([]*eskip.Filter, 0, len(r.Filters)-len(toDelete))
for i, f := range r.Filters {
if _, ok := toDelete[i]; !ok {
rf = append(rf, f)
}
}
r.Filters = rf
}
return routes
}
type admissionControlPost struct {
filters map[string]*admissionControl
}
// Do implements routing.PostProcessor and makes it possible to close goroutines.
func (spec *admissionControlPost) Do(routes []*routing.Route) []*routing.Route {
inUse := make(map[string]struct{})
for _, r := range routes {
for _, f := range r.Filters {
if ac, ok := f.Filter.(*admissionControl); ok {
oldAc, okOld := spec.filters[r.Id]
if okOld {
// replace: close the old one
oldAc.Close()
}
spec.filters[r.Id] = ac
inUse[r.Id] = struct{}{}
}
}
}
for id, f := range spec.filters {
if _, ok := inUse[id]; !ok {
// delete: close the old one
f.Close()
}
}
return routes
}
type AdmissionControlSpec struct {
tracer opentracing.Tracer
}
type admissionControl struct {
once sync.Once
mu sync.Mutex
quit chan struct{}
closed bool
metrics metrics.Metrics
metricSuffix string
tracer opentracing.Tracer
mode mode
windowSize int
minRps int
d time.Duration
successThreshold float64 // (0,1]
maxRejectProbability float64 // (0,1]
exponent float64 // >0
averageRpsFactor float64
totals []int64
success []int64
counter *atomic.Int64
successCounter *atomic.Int64
}
func NewAdmissionControl(o Options) filters.Spec {
tracer := o.Tracer
if tracer == nil {
tracer = &opentracing.NoopTracer{}
}
return &AdmissionControlSpec{
tracer: tracer,
}
}
func (*AdmissionControlSpec) PreProcessor() *admissionControlPre {
return &admissionControlPre{}
}
func (*AdmissionControlSpec) PostProcessor() *admissionControlPost {
return &admissionControlPost{
filters: make(map[string]*admissionControl),
}
}
func (*AdmissionControlSpec) Name() string { return filters.AdmissionControlName }
// CreateFilter creates a new admissionControl filter with passed configuration:
//
// admissionControl(metricSuffix, mode, d, windowSize, minRps, successThreshold, maxRejectProbability, exponent)
// admissionControl("$app", "active", "1s", 5, 10, 0.1, 0.95, 0.5)
//
// metricSuffix is the suffix key to expose reject counter, should be unique by filter instance
// mode is one of "active", "inactive", "logInactive"
//
// active will reject traffic
// inactive will never reject traffic
// logInactive will not reject traffic, but log to debug filter settings
//
// windowSize is within [minWindowSize, maxWindowSize]
// minRps threshold that needs to be reached such that the filter will apply
// successThreshold is within (0,1] and sets the lowest request success rate at which the filter will not reject requests.
// maxRejectProbability is within (0,1] and sets the upper bound of reject probability.
// exponent >0, 1: linear, 1/2: qudratic, 1/3: cubic, ..
//
// see also https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/admission_control_filter#admission-control
func (spec *AdmissionControlSpec) CreateFilter(args []interface{}) (filters.Filter, error) {
var err error
if len(args) != 8 {
return nil, filters.ErrInvalidFilterParameters
}
metricSuffix, ok := args[0].(string)
if !ok {
log.Warn("metricsuffix required as string")
return nil, filters.ErrInvalidFilterParameters
}
mode, err := getModeArg(args[1])
if err != nil {
log.Warnf("mode failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
d, err := getDurationArg(args[2])
if err != nil {
log.Warnf("d failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
windowSize, err := getIntArg(args[3])
if err != nil {
log.Warnf("windowsize failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
if minWindowSize > windowSize || windowSize > maxWindowSize {
log.Warnf("windowsize too small, should be within: [%d,%d], got: %d", minWindowSize, maxWindowSize, windowSize)
return nil, filters.ErrInvalidFilterParameters
}
minRps, err := getIntArg(args[4])
if err != nil {
log.Warnf("minRequests failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
threshold, err := getFloat64Arg(args[5])
if err != nil {
log.Warnf("threshold failed %v", err)
return nil, filters.ErrInvalidFilterParameters
}
maxRejectProbability, err := getFloat64Arg(args[6])
if err != nil {
log.Warnf("maxRejectProbability failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
exponent, err := getFloat64Arg(args[7])
if err != nil {
log.Warnf("exponent failed: %v", err)
return nil, filters.ErrInvalidFilterParameters
}
if exponent <= 0.0 {
log.Warn("exponent should be >0")
return nil, filters.ErrInvalidFilterParameters
}
averageRpsFactor := float64(time.Second) / (float64(d) * float64(windowSize))
ac := &admissionControl{
once: sync.Once{},
quit: make(chan struct{}),
metrics: metrics.Default,
metricSuffix: metricSuffix,
tracer: spec.tracer,
mode: mode,
d: d,
windowSize: windowSize,
minRps: minRps,
successThreshold: threshold,
maxRejectProbability: maxRejectProbability,
exponent: exponent,
averageRpsFactor: averageRpsFactor,
totals: make([]int64, windowSize),
success: make([]int64, windowSize),
counter: atomic.NewInt64(0),
successCounter: atomic.NewInt64(0),
}
go ac.tickWindows(d)
return ac, nil
}
// Close stops the background goroutine. The filter keeps working on stale data.
func (ac *admissionControl) Close() {
ac.once.Do(func() {
ac.closed = true
close(ac.quit)
})
}
func (ac *admissionControl) tickWindows(d time.Duration) {
t := time.NewTicker(d)
defer t.Stop()
i := 0
for range t.C {
select {
case <-ac.quit:
return
default:
}
val := ac.counter.Swap(0)
ok := ac.successCounter.Swap(0)
ac.mu.Lock()
ac.totals[i] = val
ac.success[i] = ok
ac.mu.Unlock()
i = (i + 1) % ac.windowSize
}
}
func (ac *admissionControl) count() (float64, float64) {
ac.mu.Lock()
defer ac.mu.Unlock()
return float64(sum(ac.totals)), float64(sum(ac.success))
}
func sum(a []int64) int64 {
var result int64
for _, v := range a {
result += v
}
return result
}
// calculates P_{reject} see https://opensource.zalando.com/skipper/reference/filters/#admissioncontrol
func (ac *admissionControl) pReject() float64 {
var rejectP float64
total, success := ac.count()
avgRps := total * ac.averageRpsFactor
if ac.mode == logInactive {
log.Infof("avgRps %0.2f does not reach minRps %d", avgRps, ac.minRps)
}
if avgRps < float64(ac.minRps) {
return -1
}
s := success / ac.successThreshold
if ac.mode == logInactive {
log.Infof("%s: total < s = %v, rejectP = (%0.2f - %0.2f) / (%0.2f + 1) --- success: %0.2f and threshold: %0.2f", filters.AdmissionControlName, total < s, total, s, total, success, ac.successThreshold)
}
if total < s {
return -1
}
rejectP = (total - s) / (total + 1)
rejectP = math.Pow(rejectP, ac.exponent)
rejectP = math.Min(rejectP, ac.maxRejectProbability)
return math.Max(rejectP, 0.0)
}
func (ac *admissionControl) shouldReject() bool {
p := ac.pReject() // [0, ac.maxRejectProbability] and -1 to disable
/* #nosec */
r := rand.Float64() // [0,1)
if ac.mode == logInactive {
log.Infof("%s: p: %0.2f, r: %0.2f", filters.AdmissionControlName, p, r)
}
return p > r
}
func (ac *admissionControl) Request(ctx filters.FilterContext) {
span := ac.startSpan(ctx.Request().Context())
defer span.Finish()
if ac.shouldReject() {
ac.metrics.IncCounter(counterPrefix + ac.metricSuffix)
ext.Error.Set(span, true)
ctx.StateBag()[admissionControlKey] = admissionControlValue
// shadow mode to measure data
if ac.mode != active {
return
}
ctx.Serve(&http.Response{
StatusCode: http.StatusServiceUnavailable,
})
}
}
func (ac *admissionControl) Response(ctx filters.FilterContext) {
// we don't want to count ourselves
if ctx.StateBag()[admissionControlKey] == admissionControlValue {
return
}
code := ctx.Response().StatusCode
if code < 499 {
ac.successCounter.Inc()
}
ac.counter.Inc()
}
func (ac *admissionControl) startSpan(ctx context.Context) (span opentracing.Span) {
parent := opentracing.SpanFromContext(ctx)
if parent != nil {
span = ac.tracer.StartSpan(admissionControlSpanName, opentracing.ChildOf(parent.Context()))
ext.Component.Set(span, "skipper")
ext.SpanKind.Set(span, "shedder")
span.SetTag("mode", ac.mode.String())
}
return
}