forked from grafana/k6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.go
655 lines (587 loc) · 16.5 KB
/
run.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*
*
* k6 - a next-generation load testing tool
* Copyright (C) 2016 Load Impact
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package main
import (
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"os/signal"
"regexp"
"sort"
"strings"
"sync"
"syscall"
"time"
log "github.com/Sirupsen/logrus"
"github.com/fatih/color"
"github.com/ghodss/yaml"
"github.com/loadimpact/k6/api"
"github.com/loadimpact/k6/js"
"github.com/loadimpact/k6/lib"
"github.com/loadimpact/k6/loader"
"github.com/loadimpact/k6/simple"
"github.com/loadimpact/k6/stats"
"github.com/loadimpact/k6/stats/influxdb"
"github.com/loadimpact/k6/stats/json"
"github.com/loadimpact/k6/ui"
"github.com/spf13/afero"
"gopkg.in/guregu/null.v3"
"gopkg.in/urfave/cli.v1"
)
const (
TypeAuto = "auto"
TypeURL = "url"
TypeJS = "js"
)
var urlRegex = regexp.MustCompile(`(?i)^https?://`)
var commandRun = cli.Command{
Name: "run",
Usage: "Starts running a load test",
ArgsUsage: "url|filename",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "quiet, q",
Usage: "hide the progress bar",
},
cli.Int64Flag{
Name: "vus, u",
Usage: "virtual users to simulate",
Value: 1,
},
cli.Int64Flag{
Name: "max, m",
Usage: "max number of virtual users, if more than --vus",
},
cli.DurationFlag{
Name: "duration, d",
Usage: "test duration, 0 to run until cancelled",
},
cli.Int64Flag{
Name: "iterations, i",
Usage: "run a set number of iterations, multiplied by VU count",
},
cli.StringSliceFlag{
Name: "stage, s",
Usage: "define a test stage, in the format time[:vus] (10s:100)",
},
cli.BoolFlag{
Name: "paused, p",
Usage: "start test in a paused state",
},
cli.StringFlag{
Name: "type, t",
Usage: "input type, one of: auto, url, js",
Value: "auto",
},
cli.BoolFlag{
Name: "linger, l",
Usage: "linger after test completion",
},
cli.Int64Flag{
Name: "max-redirects",
Usage: "follow at most n redirects",
Value: 10,
},
cli.BoolFlag{
Name: "insecure-skip-tls-verify",
Usage: "INSECURE: skip verification of TLS certificates",
},
cli.StringFlag{
Name: "out, o",
Usage: "output metrics to an external data store (format: type=uri)",
EnvVar: "K6_OUT",
},
cli.StringSliceFlag{
Name: "config, c",
Usage: "read additional config files",
},
cli.BoolFlag{
Name: "no-usage-report",
Usage: "don't send heartbeat to k6 project on test execution",
EnvVar: "K6_NO_USAGE_REPORT",
},
},
Action: actionRun,
Description: `Run starts a load test.
This is the main entry point to k6, and will do two things:
- Construct an Engine and provide it with a Runner, depending on the first
argument and the --type flag, which is used to execute the test.
- Start an a web server on the address specified by the global --address
flag, which serves a web interface and a REST API for remote control.
For ease of use, you may also pass initial status parameters (vus, max,
duration) to 'run', which will be applied through a normal API call.`,
}
var commandInspect = cli.Command{
Name: "inspect",
Aliases: []string{"i"},
Usage: "Merges and prints test configuration",
ArgsUsage: "url|filename",
Flags: []cli.Flag{
cli.StringFlag{
Name: "type, t",
Usage: "input type, one of: auto, url, js",
Value: "auto",
},
cli.StringSliceFlag{
Name: "config, c",
Usage: "read additional config files",
},
},
Action: actionInspect,
}
func guessType(data []byte) string {
if urlRegex.Match(data) {
return TypeURL
}
return TypeJS
}
func getSrcData(filename string, fs afero.Fs) (*lib.SourceData, error) {
if filename == "-" {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
return nil, err
}
return &lib.SourceData{Filename: "-", Data: data}, nil
}
if ok, _ := afero.Exists(fs, filename); ok {
data, err := afero.ReadFile(fs, filename)
if err != nil {
return nil, err
}
return &lib.SourceData{Filename: filename, Data: data}, nil
}
pwd, err := os.Getwd()
if err != nil {
pwd = "/"
}
return loader.Load(fs, pwd, filename)
}
func makeRunner(runnerType string, src *lib.SourceData, fs afero.Fs) (lib.Runner, error) {
switch runnerType {
case TypeAuto:
return makeRunner(guessType(src.Data), src, fs)
case TypeURL:
u, err := url.Parse(strings.TrimSpace(string(src.Data)))
if err != nil || u.Scheme == "" {
return nil, errors.New("Failed to parse URL")
}
r, err := simple.New(u)
if err != nil {
return nil, err
}
return r, err
case TypeJS:
return js.New(src, fs)
default:
return nil, errors.New("Invalid type specified, see --help")
}
}
func parseCollectorString(s string) (t, p string, err error) {
parts := strings.SplitN(s, "=", 2)
if len(parts) != 2 {
return "", "", errors.New("Malformed output; must be in the form 'type=url'")
}
return parts[0], parts[1], nil
}
func makeCollector(s string, src *lib.SourceData, opts lib.Options) (lib.Collector, error) {
t, p, err := parseCollectorString(s)
if err != nil {
return nil, err
}
switch t {
case "influxdb":
return influxdb.New(p, opts)
case "json":
return json.New(p, afero.NewOsFs(), opts)
default:
return nil, errors.New("Unknown output type: " + t)
}
}
func actionRun(cc *cli.Context) error {
wg := sync.WaitGroup{}
args := cc.Args()
if len(args) != 1 {
return cli.NewExitError("Wrong number of arguments!", 1)
}
// Collect CLI arguments, most (not all) relating to options.
addr := cc.GlobalString("address")
out := cc.String("out")
quiet := cc.Bool("quiet")
cliOpts := lib.Options{
Paused: cliBool(cc, "paused"),
VUs: cliInt64(cc, "vus"),
VUsMax: cliInt64(cc, "max"),
Duration: cliDuration(cc, "duration"),
Iterations: cliInt64(cc, "iterations"),
Linger: cliBool(cc, "linger"),
MaxRedirects: cliInt64(cc, "max-redirects"),
InsecureSkipTLSVerify: cliBool(cc, "insecure-skip-tls-verify"),
NoUsageReport: cliBool(cc, "no-usage-report"),
}
for _, s := range cc.StringSlice("stage") {
stage, err := ParseStage(s)
if err != nil {
log.WithError(err).Error("Invalid stage specified")
return err
}
cliOpts.Stages = append(cliOpts.Stages, stage)
}
opts := cliOpts
// Make the Runner, extract script-defined options.
arg := args[0]
fs := afero.NewOsFs()
src, err := getSrcData(arg, fs)
if err != nil {
log.WithError(err).Error("Failed to parse input data")
return err
}
runnerType := cc.String("type")
if runnerType == TypeAuto {
runnerType = guessType(src.Data)
}
runner, err := makeRunner(runnerType, src, fs)
if err != nil {
if errstr, ok := err.(fmt.Stringer); ok {
log.Error(errstr.String())
} else {
log.WithError(err).Error("Couldn't create a runner")
}
return err
}
opts = opts.Apply(runner.GetOptions())
// Read config files.
for _, filename := range cc.StringSlice("config") {
data, err := afero.ReadFile(fs, filename)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
var configOpts lib.Options
if err := yaml.Unmarshal(data, &configOpts); err != nil {
return cli.NewExitError(err.Error(), 1)
}
opts = opts.Apply(configOpts)
}
// CLI options override everything.
opts = opts.Apply(cliOpts)
// Default to 1 iteration if duration and stages are unspecified.
if !opts.Duration.Valid && !opts.Iterations.Valid && len(opts.Stages) == 0 {
opts.Iterations = null.IntFrom(1)
}
// Apply defaults.
opts = opts.SetAllValid(true)
// Make sure VUsMax defaults to VUs if not specified.
if opts.VUsMax.Int64 == 0 {
opts.VUsMax.Int64 = opts.VUs.Int64
if len(opts.Stages) > 0 {
for _, stage := range opts.Stages {
if stage.Target.Valid && stage.Target.Int64 > opts.VUsMax.Int64 {
opts.VUsMax = stage.Target
}
}
}
}
// Update the runner's options.
runner.ApplyOptions(opts)
// Make the metric collector, if requested.
var collector lib.Collector
if out != "" {
c, err := makeCollector(out, src, opts)
if err != nil {
log.WithError(err).Error("Couldn't create output")
return err
}
collector = c
}
fmt.Fprintln(color.Output, "")
color.Cyan(` /\ |‾‾| /‾‾/ /‾/ `)
color.Cyan(` /\ / \ | |_/ / / / `)
color.Cyan(` / \/ \ | | / ‾‾\ `)
color.Cyan(` / \ | |‾\ \ | (_) | `)
color.Cyan(` / __________ \ |__| \__\ \___/ Welcome to k6 v%s!`, cc.App.Version)
collectorString := "-"
if collector != nil {
collector.Init()
collectorString = fmt.Sprint(collector)
}
fmt.Fprintln(color.Output, "")
fmt.Fprintf(color.Output, " execution: %s\n", color.CyanString("local"))
fmt.Fprintf(color.Output, " output: %s\n", color.CyanString(collectorString))
fmt.Fprintf(color.Output, " script: %s (%s)\n", color.CyanString(src.Filename), color.CyanString(runnerType))
fmt.Fprintf(color.Output, "\n")
fmt.Fprintf(color.Output, " duration: %s, iterations: %s\n", color.CyanString(opts.Duration.String), color.CyanString("%d", opts.Iterations.Int64))
fmt.Fprintf(color.Output, " vus: %s, max: %s\n", color.CyanString("%d", opts.VUs.Int64), color.CyanString("%d", opts.VUsMax.Int64))
fmt.Fprintf(color.Output, "\n")
fmt.Fprintf(color.Output, " web ui: %s\n", color.CyanString("http://%s/", addr))
fmt.Fprintf(color.Output, "\n")
// Make the Engine
engine, err := lib.NewEngine(runner, opts)
if err != nil {
log.WithError(err).Error("Couldn't create the engine")
return err
}
ctx, cancel := context.WithCancel(context.Background())
engine.Collector = collector
// Send usage report, if we're allowed to
if opts.NoUsageReport.Valid && !opts.NoUsageReport.Bool {
go func() {
conn, err := net.Dial("udp", "k6reports.loadimpact.com:6565")
if err == nil {
// This is a best-effort attempt to send a usage report. We don't want
// to inconvenience users if this doesn't work, for whatever reason
_, _ = conn.Write([]byte("nyoom"))
_ = conn.Close()
}
}()
}
// Run the engine.
wg.Add(1)
go func() {
defer func() {
log.Debug("Engine terminated")
wg.Done()
}()
log.Debug("Starting engine...")
if err := engine.Run(ctx); err != nil {
log.WithError(err).Error("Engine Error")
}
cancel()
}()
// Start the API server in the background.
go func() {
if err := api.ListenAndServe(addr, engine); err != nil {
log.WithError(err).Error("Couldn't start API server!")
}
}()
// Progress bar for TTYs.
progressBar := ui.ProgressBar{Width: 60}
if isTTY && !quiet {
fmt.Fprintf(color.Output, " starting %s -- / --\r", progressBar.String())
}
// Wait for a signal or timeout before shutting down
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
// Print status at a set interval; less frequently on non-TTYs.
tickInterval := 10 * time.Millisecond
if !isTTY || quiet {
tickInterval = 1 * time.Second
}
ticker := time.NewTicker(tickInterval)
loop:
for {
select {
case <-ticker.C:
if !engine.IsRunning() {
break loop
}
statusString := "running"
if engine.IsPaused() {
statusString = "paused"
}
atTime := engine.AtTime()
totalTime := engine.TotalTime()
progress := 0.0
if totalTime > 0 {
progress = float64(atTime) / float64(totalTime)
}
if isTTY && !quiet {
progressBar.Progress = progress
fmt.Fprintf(color.Output, "%10s %s %10s / %s\r",
statusString,
progressBar.String(),
roundDuration(atTime, 100*time.Millisecond),
roundDuration(totalTime, 100*time.Millisecond),
)
} else {
fmt.Fprintf(color.Output, "[%-10s] %s / %s\n",
statusString,
roundDuration(atTime, 100*time.Millisecond),
roundDuration(totalTime, 100*time.Millisecond),
)
}
case <-ctx.Done():
log.Debug("Engine terminated; shutting down...")
break loop
case sig := <-signals:
log.WithField("signal", sig).Debug("Signal received; shutting down...")
break loop
}
}
// Shut down the API server and engine.
cancel()
wg.Wait()
// Test done, leave that status as the final progress bar!
atTime := engine.AtTime()
if isTTY && !quiet {
progressBar.Progress = 1.0
fmt.Fprintf(color.Output, " done %s %10s / %s\n",
progressBar.String(),
roundDuration(atTime, 100*time.Millisecond),
roundDuration(atTime, 100*time.Millisecond),
)
} else {
fmt.Fprintf(color.Output, "[%-10s] %s / %s\n",
"done",
roundDuration(atTime, 100*time.Millisecond),
roundDuration(atTime, 100*time.Millisecond),
)
}
fmt.Fprintf(color.Output, "\n")
// Print groups.
var printGroup func(g *lib.Group, level int)
printGroup = func(g *lib.Group, level int) {
indent := strings.Repeat(" ", level)
if g.Name != "" && g.Parent != nil {
fmt.Fprintf(color.Output, "%s█ %s\n", indent, g.Name)
}
if len(g.Checks) > 0 {
if g.Name != "" && g.Parent != nil {
fmt.Fprintf(color.Output, "\n")
}
for _, check := range g.Checks {
icon := "✓"
statusColor := color.GreenString
if check.Fails > 0 {
icon = "✗"
statusColor = color.RedString
}
fmt.Fprint(color.Output, statusColor("%s %s %2.2f%% - %s\n",
indent,
icon,
100*(float64(check.Passes)/float64(check.Passes+check.Fails)),
check.Name,
))
}
fmt.Fprintf(color.Output, "\n")
}
if len(g.Groups) > 0 {
if g.Name != "" && g.Parent != nil && len(g.Checks) > 0 {
fmt.Fprintf(color.Output, "\n")
}
for _, g := range g.Groups {
printGroup(g, level+1)
}
}
}
printGroup(engine.Runner.GetDefaultGroup(), 1)
// Sort and print metrics.
metricNames := make([]string, 0, len(engine.Metrics))
metricNameWidth := 0
for _, m := range engine.Metrics {
metricNames = append(metricNames, m.Name)
if l := len(m.Name); l > metricNameWidth {
metricNameWidth = l
}
}
sort.Strings(metricNames)
for _, name := range metricNames {
m := engine.Metrics[name]
sample := m.Sink.Format()
keys := make([]string, 0, len(sample))
for k := range sample {
keys = append(keys, k)
}
sort.Strings(keys)
var val string
switch len(keys) {
case 0:
continue
case 1:
for _, k := range keys {
val = color.CyanString(m.HumanizeValue(sample[k]))
if atTime > 1*time.Second && m.Type == stats.Counter && m.Contains != stats.Time {
perS := m.HumanizeValue(sample[k] / float64(atTime/time.Second))
val += " " + color.New(color.Faint, color.FgCyan).Sprintf("(%s/s)", perS)
}
}
default:
var parts []string
for _, k := range keys {
parts = append(parts, fmt.Sprintf("%s=%s", k, color.CyanString(m.HumanizeValue(sample[k]))))
}
val = strings.Join(parts, " ")
}
if val == "0" {
continue
}
icon := " "
if m.Tainted.Valid {
if !m.Tainted.Bool {
icon = color.GreenString("✓")
} else {
icon = color.RedString("✗")
}
}
namePadding := strings.Repeat(".", metricNameWidth-len(name)+3)
fmt.Fprintf(color.Output, " %s %s%s %s\n",
icon,
name,
color.New(color.Faint).Sprint(namePadding+":"),
val,
)
}
if opts.Linger.Bool {
<-signals
}
if engine.IsTainted() {
return cli.NewExitError("", 99)
}
return nil
}
func actionInspect(cc *cli.Context) error {
args := cc.Args()
if len(args) != 1 {
return cli.NewExitError("Wrong number of arguments!", 1)
}
arg := args[0]
fs := afero.NewOsFs()
src, err := getSrcData(arg, fs)
if err != nil {
return err
}
runnerType := cc.String("type")
if runnerType == TypeAuto {
runnerType = guessType(src.Data)
}
var opts lib.Options
switch runnerType {
case TypeJS:
r, err := js.NewBundle(src, fs)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
opts = opts.Apply(r.Options)
}
for _, filename := range cc.StringSlice("config") {
data, err := afero.ReadFile(fs, filename)
if err != nil {
return cli.NewExitError(err.Error(), 1)
}
var configOpts lib.Options
if err := yaml.Unmarshal(data, &configOpts); err != nil {
return cli.NewExitError(err.Error(), 1)
}
opts = opts.Apply(configOpts)
}
return dumpYAML(opts)
}