File: latency.go

package info (click to toggle)
toxiproxy 2.0.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 388 kB
  • ctags: 321
  • sloc: sh: 91; makefile: 59
file content (55 lines) | stat: -rw-r--r-- 1,092 bytes parent folder | download | duplicates (2)
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
package toxics

import (
	"math/rand"
	"time"
)

// The LatencyToxic passes data through with the a delay of latency +/- jitter added.
type LatencyToxic struct {
	// Times in milliseconds
	Latency int64 `json:"latency"`
	Jitter  int64 `json:"jitter"`
}

func (t *LatencyToxic) GetBufferSize() int {
	return 1024
}

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.Since(c.Timestamp)
			select {
			case <-time.After(sleep):
				c.Timestamp = c.Timestamp.Add(sleep)
				stub.Output <- c
			case <-stub.Interrupt:
				// Exit fast without applying latency.
				stub.Output <- c // Don't drop any data on the floor
				return
			}
		}
	}
}

func init() {
	Register("latency", new(LatencyToxic))
}