forked from Shopify/toxiproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoxic_bandwidth.go
64 lines (58 loc) · 1.46 KB
/
toxic_bandwidth.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
package main
import "time"
// The BandwidthToxic passes data through at a limited rate
type BandwidthToxic struct {
Enabled bool `json:"enabled"`
// Rate in KB/s
Rate int64 `json:"rate"`
}
func (t *BandwidthToxic) Name() string {
return "bandwidth"
}
func (t *BandwidthToxic) IsEnabled() bool {
return t.Enabled
}
func (t *BandwidthToxic) SetEnabled(enabled bool) {
t.Enabled = enabled
}
func (t *BandwidthToxic) Pipe(stub *ToxicStub) {
var sleep time.Duration = 0
for {
select {
case <-stub.interrupt:
return
case p := <-stub.input:
if p == nil {
stub.Close()
return
}
if t.Rate <= 0 {
sleep = 0
} else {
sleep += time.Duration(len(p.data)) * time.Millisecond / time.Duration(t.Rate)
}
// If the rate is low enough, split the packet up and send in 100 millisecond intervals
for int64(len(p.data)) > t.Rate*100 {
select {
case <-time.After(100 * time.Millisecond):
stub.output <- &StreamChunk{p.data[:t.Rate*100], p.timestamp}
p.data = p.data[t.Rate*100:]
sleep -= 100 * time.Millisecond
case <-stub.interrupt:
stub.output <- p // Don't drop any data on the floor
return
}
}
start := time.Now()
select {
case <-time.After(sleep):
// time.After only seems to have ~1ms prevision, so offset the next sleep by the error
sleep -= time.Now().Sub(start)
stub.output <- p
case <-stub.interrupt:
stub.output <- p // Don't drop any data on the floor
return
}
}
}
}