-
Notifications
You must be signed in to change notification settings - Fork 10
/
runner.go
280 lines (255 loc) · 6.84 KB
/
runner.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
package hazana
import (
"context"
"flag"
"fmt"
"os"
"os/signal"
"runtime"
"syscall"
"time"
"go.uber.org/ratelimit"
)
// BeforeRunner can be implemented by an Attacker
// and its method is called before a test or run.
type BeforeRunner interface {
BeforeRun(c Config) error
}
// AfterRunner can be implemented by an Attacker
// and its method is called after a test or run.
// The report is passed to compute the Failed field and/or store values in Output.
type AfterRunner interface {
AfterRun(r *RunReport) error
}
type runner struct {
config Config
attackers []Attack
next, quit, abort chan bool
aborted bool
results chan result
prototype Attack
metrics map[string]*Metrics
resultsPipeline func(r result) result
}
// Run starts attacking a service using an Attack implementation and a configuration.
// Return a report with statistics per sample and the configuration used.
func Run(a Attack, c Config) *RunReport {
if c.Verbose {
Printf("*** Hazana load runner ready to attack ***\n")
Printf("%v", c)
Printf("[%d] available logical CPUs\n", runtime.NumCPU())
}
r := new(runner)
r.config = c
r.prototype = a
// validate the configuration
if msg := c.Validate(); len(msg) > 0 {
for _, each := range msg {
fmt.Println("[hazana] - a configuration error was found", each)
}
fmt.Println()
flag.Usage()
os.Exit(0)
}
r.init()
// is the attacker interested in the run lifecycle?
if lifecycler, ok := a.(BeforeRunner); ok {
if err := lifecycler.BeforeRun(c); err != nil {
Printf("BeforeRun failed:%v\n", err)
}
}
// do a test if the flag says so
if *oSample > 0 {
report := r.test(*oSample)
if lifecycler, ok := a.(AfterRunner); ok {
if err := lifecycler.AfterRun(report); err != nil {
Printf("AfterRun failed:%v\n", err)
}
}
return report
}
report := r.run()
if lifecycler, ok := a.(AfterRunner); ok {
if err := lifecycler.AfterRun(report); err != nil {
Printf("AfterRun failed:%v\n", err)
}
}
return report
}
func (r *runner) listenForAbort() {
r.abort = make(chan bool)
// abort will stop test,rampup or full attack
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, os.Kill, syscall.SIGTERM)
go func() {
sig := <-ch
Printf("caught signal %v. aborting run...\n", sig)
r.aborted = true
r.abort <- true
Printf("aborted. clean up...\n")
}()
}
func (r *runner) init() {
r.next = make(chan bool)
r.quit = make(chan bool)
r.results = make(chan result)
r.attackers = []Attack{}
r.metrics = map[string]*Metrics{}
r.resultsPipeline = r.addResult
r.listenForAbort()
}
func (r *runner) spawnAttacker() {
if r.config.Verbose {
Printf("setup and spawn new attacker [%d]\n", len(r.attackers)+1)
}
attacker := r.prototype.Clone()
if err := attacker.Setup(r.config); err != nil {
Printf("attacker [%d] setup failed with [%v]\n", len(r.attackers)+1, err)
return
}
r.attackers = append(r.attackers, attacker)
go attack(attacker, r.next, r.quit, r.results, r.config.timeout())
}
// used if debug=true
func (r *runner) addDebugResult(s result) result {
Printf("%s\n", s.doResult)
return r.addResult(s)
}
// addResult is called from a dedicated goroutine.
func (r *runner) addResult(s result) result {
m, ok := r.metrics[s.doResult.RequestLabel]
if !ok {
m = new(Metrics)
r.metrics[s.doResult.RequestLabel] = m
}
m.add(s)
return s
}
// test uses the Attack to perform {count} calls and report its result
// it is intended for development of an Attack implementation.
func (r *runner) test(count int) *RunReport {
probe := r.prototype.Clone()
if err := probe.Setup(r.config); err != nil {
Printf("test attack setup failed [%v]", err)
return &RunReport{Configuration: r.config, Output: map[string]interface{}{}}
}
defer probe.Teardown()
for s := count; s > 0; s-- {
now := time.Now()
doResult := probe.Do(context.Background())
end := time.Now()
r.addResult(result{
doResult: doResult,
begin: now,
end: end,
elapsed: end.Sub(now),
})
errorString := "no error"
if doResult.Error != nil {
errorString = fmt.Sprintf("error [%v:%T]", doResult.Error, doResult.Error)
}
Printf("test attack call [%s] took [%v] with status [%v] and %s\n", doResult.RequestLabel, end.Sub(now), doResult.StatusCode, errorString)
select {
case <-r.abort:
goto end
default:
}
}
end:
return r.reportMetrics()
}
// run offers the complete flow of a load test.
func (r *runner) run() *RunReport {
go r.collectResults()
r.rampUp()
r.fullAttack()
r.quitAttackers()
r.tearDownAttackers()
return r.reportMetrics()
}
func (r *runner) fullAttack() {
if r.aborted {
return
}
// attack can only proceed when at least one attacker is waiting for rps tokens
if len(r.attackers) == 0 {
// rampup probably has failed too
return
}
if r.config.Verbose {
Printf("BEGIN full attack of [%d] remaining seconds\n", r.config.AttackTimeSec-r.config.RampupTimeSec)
}
// restore pipeline function in case it was changed by the rampup strategy
if *oDebug {
r.resultsPipeline = r.addDebugResult
} else {
r.resultsPipeline = r.addResult
}
fullAttackStartedAt = time.Now()
limiter := ratelimit.New(r.config.RPS) // per second
doneDeadline := time.Now().Add(time.Duration(r.config.AttackTimeSec-r.config.RampupTimeSec) * time.Second)
for time.Now().Before(doneDeadline) {
limiter.Take()
select {
case <-r.abort:
goto end
default:
r.next <- true
}
}
end:
if r.config.Verbose {
Printf("END full attack\n")
}
}
func (r *runner) rampUp() {
strategy := strategyParameters{line: r.config.rampupStrategy()}
if r.config.Verbose {
Printf("||| BEGIN rampup of [%d] seconds to RPS [%d] within attack of [%d] seconds\n", r.config.RampupTimeSec, r.config.RPS, r.config.AttackTimeSec)
}
if strategy.is("linear") {
linearIncreasingGoroutinesAndRequestsPerSecondStrategy{}.execute(r)
}
if strategy.is("exp2") {
spawnAsWeNeedStrategy{parameters: strategy}.execute(r)
}
if r.config.Verbose {
Printf("||| rampup ENDing up with [%d] attackers\n", len(r.attackers))
}
}
func (r *runner) quitAttackers() {
if r.config.Verbose {
Printf("stopping attackers [%d]\n", len(r.attackers))
}
for range r.attackers {
r.quit <- true
}
}
func (r *runner) tearDownAttackers() {
if r.config.Verbose {
Printf("tearing down attackers [%d]\n", len(r.attackers))
}
for i, each := range r.attackers {
if err := each.Teardown(); err != nil {
Printf("failed to teardown attacker [%d]:%v\n", i, err)
}
}
}
func (r *runner) reportMetrics() *RunReport {
for _, each := range r.metrics {
each.updateLatencies()
}
return &RunReport{
StartedAt: fullAttackStartedAt,
FinishedAt: time.Now(),
Configuration: r.config,
Metrics: r.metrics,
Failed: false, // must be overwritten by program
Output: map[string]interface{}{},
}
}
func (r *runner) collectResults() {
for {
r.resultsPipeline(<-r.results)
}
}