-
Notifications
You must be signed in to change notification settings - Fork 346
/
diag.go
541 lines (453 loc) · 13 KB
/
diag.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/*
Package diag provides a set of network throttling filters for diagnostic purpose.
The filters enable adding artificial latency, limiting bandwidth or chunking responses with custom chunk size
and delay. This throttling can be applied to the proxy responses or to the outgoing backend requests. An
additional filter, randomContent, can be used to generate response with random text of specified length.
*/
package diag
import (
"fmt"
"io"
"math/rand"
"net/http"
"strconv"
"sync"
"time"
"github.com/zalando/skipper/filters"
)
const defaultChunkSize = 512
const (
// Deprecated, use filters.RandomContentName instead
RandomName = filters.RandomContentName
// Deprecated, use filters.RepeatContentName instead
RepeatName = filters.RepeatContentName
// Deprecated, use filters.LatencyName instead
LatencyName = filters.LatencyName
// Deprecated, use filters.ChunksName instead
ChunksName = filters.ChunksName
// Deprecated, use filters.BandwidthName instead
BandwidthName = filters.BandwidthName
// Deprecated, use filters.BackendLatencyName instead
BackendLatencyName = filters.BackendLatencyName
// Deprecated, use filters.BackendBandwidthName instead
BackendBandwidthName = filters.BackendBandwidthName
// Deprecated, use filters.BackendChunksName instead
BackendChunksName = filters.BackendChunksName
)
type throttleType int
const (
latency throttleType = iota
bandwidth
chunks
backendLatency
backendBandwidth
backendChunks
)
type random struct {
mx sync.Mutex
rand *rand.Rand
len int64
}
type repeat struct {
bytes []byte
len int64
}
type repeatReader struct {
bytes []byte
offset int
}
type throttle struct {
typ throttleType
chunkSize int
delay time.Duration
}
type distribution int
const (
uniformRequestDistribution distribution = iota
normalRequestDistribution
uniformResponseDistribution
normalResponseDistribution
)
type jitter struct {
mean time.Duration
delta time.Duration
typ distribution
}
var randomChars = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
func kbps2bpms(kbps float64) float64 {
return kbps * 1024 / 1000
}
// NewRandom creates a filter specification whose filter instances can be used
// to respond to requests with random text of specified length. It expects the
// the byte length of the random response to be generated as an argument.
// Eskip example:
//
// * -> randomContent(2048) -> <shunt>;
//
func NewRandom() filters.Spec { return &random{} }
// NewRepeat creates a filter specification whose filter instances can be used
// to respond to requests with a repeated text. It expects the text and
// the byte length of the response body to be generated as arguments.
// Eskip example:
//
// * -> repeatContent("x", 100) -> <shunt>;
//
func NewRepeat() filters.Spec { return &repeat{} }
// NewLatency creates a filter specification whose filter instances can be used
// to add additional latency to responses. It expects the latency in milliseconds
// as an argument. It always adds this value in addition to the natural latency,
// and does not do any adjustments. Eskip example:
//
// * -> latency(120) -> "https://www.example.org";
//
func NewLatency() filters.Spec { return &throttle{typ: latency} }
// NewBandwidth creates a filter specification whose filter instances can be used
// to maximize the bandwidth of the responses. It expects the bandwidth in
// kbyte/sec as an argument.
//
// * -> bandwidth(30) -> "https://www.example.org";
//
func NewBandwidth() filters.Spec { return &throttle{typ: bandwidth} }
// NewChunks creates a filter specification whose filter instances can be used
// set artificial delays in between response chunks. It expects the byte length
// of the chunks and the delay milliseconds.
//
// * -> chunks(1024, "120ms") -> "https://www.example.org";
//
func NewChunks() filters.Spec { return &throttle{typ: chunks} }
// NewBackendLatency is the equivalent of NewLatency but for outgoing backend
// requests. Eskip example:
//
// * -> backendLatency(120) -> "https://www.example.org";
//
func NewBackendLatency() filters.Spec { return &throttle{typ: backendLatency} }
// NewBackendBandwidth is the equivalent of NewBandwidth but for outgoing backend
// requests. Eskip example:
//
// * -> backendBandwidth(30) -> "https://www.example.org";
//
func NewBackendBandwidth() filters.Spec { return &throttle{typ: backendBandwidth} }
// NewBackendChunks is the equivalent of NewChunks but for outgoing backend
// requests. Eskip example:
//
// * -> backendChunks(1024, 120) -> "https://www.example.org";
//
func NewBackendChunks() filters.Spec { return &throttle{typ: backendChunks} }
// NewUniformRequestLatency creates a latency for requests with uniform
// distribution. Example delay around 1s with +/-120ms.
//
// * -> uniformRequestLatency("1s", "120ms") -> "https://www.example.org";
//
func NewUniformRequestLatency() filters.Spec { return &jitter{typ: uniformRequestDistribution} }
// NewNormalRequestLatency creates a latency for requests with normal
// distribution. Example delay around 1s with +/-120ms.
//
// * -> normalRequestLatency("1s", "120ms") -> "https://www.example.org";
//
func NewNormalRequestLatency() filters.Spec { return &jitter{typ: normalRequestDistribution} }
// NewUniformResponseLatency creates a latency for responses with uniform
// distribution. Example delay around 1s with +/-120ms.
//
// * -> uniformRequestLatency("1s", "120ms") -> "https://www.example.org";
//
func NewUniformResponseLatency() filters.Spec { return &jitter{typ: uniformResponseDistribution} }
// NewNormalResponseLatency creates a latency for responses with normal
// distribution. Example delay around 1s with +/-120ms.
//
// * -> normalRequestLatency("1s", "120ms") -> "https://www.example.org";
//
func NewNormalResponseLatency() filters.Spec { return &jitter{typ: normalResponseDistribution} }
func (r *random) Name() string { return filters.RandomContentName }
func (r *random) CreateFilter(args []interface{}) (filters.Filter, error) {
if len(args) != 1 {
return nil, filters.ErrInvalidFilterParameters
}
if l, ok := args[0].(float64); ok {
return &random{rand: rand.New(rand.NewSource(time.Now().UnixNano())), len: int64(l)}, nil // #nosec
} else {
return nil, filters.ErrInvalidFilterParameters
}
}
func (r *random) Read(p []byte) (int, error) {
r.mx.Lock()
defer r.mx.Unlock()
for i := 0; i < len(p); i++ {
p[i] = randomChars[r.rand.Intn(len(randomChars))]
}
return len(p), nil
}
func (r *random) Request(ctx filters.FilterContext) {
ctx.Serve(&http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(io.LimitReader(r, r.len)),
})
}
func (r *random) Response(ctx filters.FilterContext) {}
func (r *repeat) Name() string { return filters.RepeatContentName }
func (r *repeat) CreateFilter(args []interface{}) (filters.Filter, error) {
if len(args) != 2 {
return nil, filters.ErrInvalidFilterParameters
}
text, ok := args[0].(string)
if !ok || text == "" {
return nil, filters.ErrInvalidFilterParameters
}
var len int64
switch v := args[1].(type) {
case float64:
len = int64(v)
case int:
len = int64(v)
case int64:
len = v
default:
return nil, filters.ErrInvalidFilterParameters
}
if len < 0 {
return nil, filters.ErrInvalidFilterParameters
}
return &repeat{[]byte(text), len}, nil
}
func (r *repeat) Request(ctx filters.FilterContext) {
ctx.Serve(&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Length": []string{strconv.FormatInt(r.len, 10)}},
Body: io.NopCloser(io.LimitReader(&repeatReader{r.bytes, 0}, r.len)),
})
}
func (r *repeatReader) Read(p []byte) (int, error) {
n := copy(p, r.bytes[r.offset:])
if n < len(p) {
n += copy(p[n:], r.bytes[:r.offset])
for n < len(p) {
copy(p[n:], p[:n])
n *= 2
}
}
r.offset = (r.offset + len(p)) % len(r.bytes)
return len(p), nil
}
func (r *repeat) Response(ctx filters.FilterContext) {}
func (t *throttle) Name() string {
switch t.typ {
case latency:
return filters.LatencyName
case bandwidth:
return filters.BandwidthName
case chunks:
return filters.ChunksName
case backendLatency:
return filters.BackendLatencyName
case backendBandwidth:
return filters.BackendBandwidthName
case backendChunks:
return filters.BackendChunksName
default:
panic("invalid throttle type")
}
}
func parseDuration(v interface{}) (time.Duration, error) {
var d time.Duration
switch vt := v.(type) {
case float64:
d = time.Duration(vt) * time.Millisecond
case string:
var err error
d, err = time.ParseDuration(vt)
if err != nil {
return 0, filters.ErrInvalidFilterParameters
}
}
if d < 0 {
return 0, filters.ErrInvalidFilterParameters
}
return d, nil
}
func parseLatencyArgs(args []interface{}) (int, time.Duration, error) {
if len(args) != 1 {
return 0, 0, filters.ErrInvalidFilterParameters
}
d, err := parseDuration(args[0])
return 0, d, err
}
func parseBandwidthArgs(args []interface{}) (int, time.Duration, error) {
if len(args) != 1 {
return 0, 0, filters.ErrInvalidFilterParameters
}
kbps, ok := args[0].(float64)
if !ok || kbps <= 0 {
return 0, 0, filters.ErrInvalidFilterParameters
}
bpms := kbps2bpms(kbps)
return defaultChunkSize, time.Duration(float64(defaultChunkSize)/bpms) * time.Millisecond, nil
}
func parseChunksArgs(args []interface{}) (int, time.Duration, error) {
if len(args) != 2 {
return 0, 0, filters.ErrInvalidFilterParameters
}
size, ok := args[0].(float64)
if !ok || size <= 0 {
return 0, 0, filters.ErrInvalidFilterParameters
}
d, err := parseDuration(args[1])
return int(size), d, err
}
func (t *throttle) CreateFilter(args []interface{}) (filters.Filter, error) {
var (
chunkSize int
delay time.Duration
err error
)
switch t.typ {
case latency, backendLatency:
chunkSize, delay, err = parseLatencyArgs(args)
case bandwidth, backendBandwidth:
chunkSize, delay, err = parseBandwidthArgs(args)
case chunks, backendChunks:
chunkSize, delay, err = parseChunksArgs(args)
default:
panic("invalid throttle type")
}
if err != nil {
return nil, err
}
return &throttle{t.typ, chunkSize, delay}, nil
}
func (t *throttle) goThrottle(in io.ReadCloser, close bool) io.ReadCloser {
if t.chunkSize <= 0 {
time.Sleep(t.delay)
return in
}
r, w := io.Pipe()
time.Sleep(t.delay)
go func() {
var err error
defer func() {
w.CloseWithError(err)
if close {
in.Close()
}
}()
b := make([]byte, defaultChunkSize)
for err == nil {
n := 0
var start time.Time
switch t.typ {
case bandwidth, backendBandwidth:
start = time.Now()
}
for n < t.chunkSize {
ni := 0
eof := false
bi := b
if t.chunkSize-n < len(bi) {
bi = bi[:t.chunkSize-n]
}
ni, err = in.Read(bi)
if err == io.EOF {
eof = true
err = nil
}
if err != nil {
break
}
ni, err = w.Write(bi[:ni])
if err != nil {
break
}
n += ni
if eof {
err = io.EOF
break
}
}
if err == nil {
delay := t.delay
switch t.typ {
case bandwidth, backendBandwidth:
delay -= time.Since(start)
}
time.Sleep(delay)
}
}
}()
return r
}
func (t *throttle) Request(ctx filters.FilterContext) {
switch t.typ {
case latency, bandwidth, chunks:
return
}
req := ctx.Request()
req.Body = t.goThrottle(req.Body, false)
}
func (t *throttle) Response(ctx filters.FilterContext) {
switch t.typ {
case backendLatency, backendBandwidth, backendChunks:
return
}
rsp := ctx.Response()
rsp.Body = t.goThrottle(rsp.Body, true)
}
func (j *jitter) Name() string {
switch j.typ {
case normalRequestDistribution:
return filters.NormalRequestLatencyName
case uniformRequestDistribution:
return filters.UniformRequestLatencyName
case normalResponseDistribution:
return filters.NormalResponseLatencyName
case uniformResponseDistribution:
return filters.UniformResponseLatencyName
}
return "unknown"
}
func (j *jitter) CreateFilter(args []interface{}) (filters.Filter, error) {
var (
mean time.Duration
delta time.Duration
err error
)
if len(args) != 2 {
return nil, filters.ErrInvalidFilterParameters
}
if mean, err = parseDuration(args[0]); err != nil {
return nil, fmt.Errorf("failed to parse duration mean %v: %w", args[0], err)
}
if delta, err = parseDuration(args[1]); err != nil {
return nil, fmt.Errorf("failed to parse duration delta %v: %w", args[1], err)
}
return &jitter{
typ: j.typ,
mean: mean,
delta: delta,
}, nil
}
func (j *jitter) Request(filters.FilterContext) {
var r float64
switch j.typ {
case uniformRequestDistribution:
/* #nosec */
r = 2*rand.Float64() - 1 // +/- sizing
case normalRequestDistribution:
r = rand.NormFloat64()
default:
return
}
f := r * float64(j.delta)
time.Sleep(j.mean + time.Duration(int64(f)))
}
func (j *jitter) Response(filters.FilterContext) {
var r float64
switch j.typ {
case uniformResponseDistribution:
/* #nosec */
r = 2*rand.Float64() - 1 // +/- sizing
case normalResponseDistribution:
r = rand.NormFloat64()
default:
return
}
f := r * float64(j.delta)
time.Sleep(j.mean + time.Duration(int64(f)))
}