forked from go-chassis/go-chassis
/
main.go
executable file
·116 lines (98 loc) · 2.53 KB
/
main.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
// Package main implements an http server which executes a hystrix command each request and
// sends metrics to a statsd instance to aid performance testing.
package main
import (
"flag"
"log"
"math/rand"
"net/http"
_ "net/http/pprof"
"runtime"
"time"
"github.com/ServiceComb/go-chassis/third_party/forked/afex/hystrix-go/hystrix"
"github.com/ServiceComb/go-chassis/third_party/forked/afex/hystrix-go/hystrix/metric_collector"
"github.com/ServiceComb/go-chassis/third_party/forked/afex/hystrix-go/plugins"
"github.com/cactus/go-statsd-client/statsd"
)
const (
deltaWindow = 10
minDelay = 35
maxDelay = 55
)
var (
delay int
)
const (
up = iota
down
)
func init() {
delay = minDelay
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
statsdHost := flag.String("statsd", "", "Statsd host to record load test metrics")
flag.Parse()
stats, err := statsd.NewClient(*statsdHost, "hystrix.loadtest.service")
if err != nil {
log.Fatalf("could not initialize statsd client: %v", err)
}
c, err := plugins.InitializeStatsdCollector(&plugins.StatsdCollectorConfig{
StatsdAddr: *statsdHost,
Prefix: "hystrix.loadtest.circuits",
})
if err != nil {
log.Fatalf("could not initialize statsd client: %v", err)
}
metricCollector.Registry.Register(c.NewStatsdCollector)
hystrix.ConfigureCommand("test", hystrix.CommandConfig{
Timeout: 50,
})
go rotateDelay()
http.HandleFunc("/", timedHandler(handle, stats))
log.Print("starting server")
log.Fatal(http.ListenAndServe(":8888", nil))
}
func timedHandler(fn func(w http.ResponseWriter, r *http.Request), stats statsd.Statter) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
fn(w, r)
stats.TimingDuration("request", time.Since(start), 1)
}
}
func handle(w http.ResponseWriter, r *http.Request) {
done := make(chan struct{}, 1)
errChan := hystrix.Go("test", func() error {
delta := rand.Intn(deltaWindow)
time.Sleep(time.Duration(delay+delta) * time.Millisecond)
done <- struct{}{}
return nil
}, func(err error) error {
done <- struct{}{}
return nil
})
select {
case err := <-errChan:
http.Error(w, err.Error(), 500)
case <-done:
w.Write([]byte("OK"))
}
}
func rotateDelay() {
direction := up
for {
if direction == up && delay == maxDelay {
direction = down
}
if direction == down && delay == minDelay {
direction = up
}
if direction == up {
delay += 1
} else {
delay -= 1
}
time.Sleep(5 * time.Second)
log.Printf("setting delay to %v", delay)
}
}