forked from Shopify/toxiproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoxic_latency.go
58 lines (51 loc) · 1.09 KB
/
toxic_latency.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
package main
import (
"math/rand"
"time"
)
// The LatencyToxic passes data through with the a delay of latency +/- jitter added.
type LatencyToxic struct {
Enabled bool `json:"enabled"`
// Times in milliseconds
Latency int64 `json:"latency"`
Jitter int64 `json:"jitter"`
}
func (t *LatencyToxic) Name() string {
return "latency"
}
func (t *LatencyToxic) IsEnabled() bool {
return t.Enabled
}
func (t *LatencyToxic) SetEnabled(enabled bool) {
t.Enabled = enabled
}
func (t *LatencyToxic) delay() time.Duration {
// Delay = t.Latency +/- t.Jitter
delay := t.Latency
jitter := int64(t.Jitter)
if jitter > 0 {
delay += rand.Int63n(jitter*2) - jitter
}
return time.Duration(delay) * time.Millisecond
}
func (t *LatencyToxic) Pipe(stub *ToxicStub) {
for {
select {
case <-stub.interrupt:
return
case c := <-stub.input:
if c == nil {
stub.Close()
return
}
sleep := t.delay() - time.Now().Sub(c.timestamp)
select {
case <-time.After(sleep):
stub.output <- c
case <-stub.interrupt:
stub.output <- c // Don't drop any data on the floor
return
}
}
}
}