-
Notifications
You must be signed in to change notification settings - Fork 65
/
lib.rs
3331 lines (3082 loc) · 136 KB
/
lib.rs
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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Goose
//!
//! Have you ever been attacked by a goose?
//!
//! Goose is a load testing tool inspired by [Locust](https://locust.io/).
//! User behavior is defined with standard Rust code.
//!
//! Goose load tests, called Goose Attacks, are built by creating an application
//! with Cargo, and declaring a dependency on the Goose library.
//!
//! Goose uses [`reqwest`](https://docs.rs/reqwest/) to provide a convenient HTTP
//! client.
//!
//! ## Creating and running a Goose load test
//!
//! ### Creating a simple Goose load test
//!
//! First create a new empty cargo application, for example:
//!
//! ```bash
//! $ cargo new loadtest
//! Created binary (application) `loadtest` package
//! $ cd loadtest/
//! ```
//!
//! Add Goose as a dependency in `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! goose = "0.10"
//! ```
//!
//! Add the following boilerplate `use` declaration at the top of your `src/main.rs`:
//!
//! ```rust
//! use goose::prelude::*;
//! ```
//!
//! Using the above prelude will automatically add the following `use` statements
//! necessary for your load test, so you don't need to manually add them:
//!
//! ```rust
//! use goose::goose::{
//! GooseTask, GooseTaskError, GooseTaskFunction, GooseTaskResult, GooseTaskSet, GooseUser,
//! };
//! use goose::metrics::GooseMetrics;
//! use goose::{task, taskset, GooseAttack, GooseDefault, GooseDefaultType, GooseError};
//! ```
//!
//! Below your `main` function (which currently is the default `Hello, world!`), add
//! one or more load test functions. The names of these functions are arbitrary, but it is
//! recommended you use self-documenting names. Load test functions must be async. Each load
//! test function must accept a reference to a `GooseUser` object and return a
//! `GooseTaskResult`. For example:
//!
//! ```rust
//! use goose::prelude::*;
//!
//! async fn loadtest_foo(user: &GooseUser) -> GooseTaskResult {
//! let _goose = user.get("/path/to/foo").await?;
//!
//! Ok(())
//! }
//! ```
//!
//! In the above example, we're using the GooseUser helper method `get` to load a path
//! on the website we are load testing. This helper creates a Reqwest request builder, and
//! uses it to build and execute a request for the above path. If you want access to the
//! request builder object, you can instead use the `goose_get` helper, for example to
//! set a timeout on this specific request:
//!
//! ```rust
//! use std::time;
//!
//! use goose::prelude::*;
//!
//! async fn loadtest_bar(user: &GooseUser) -> GooseTaskResult {
//! let request_builder = user.goose_get("/path/to/bar").await?;
//! let _goose = user.goose_send(request_builder.timeout(time::Duration::from_secs(3)), None).await?;
//!
//! Ok(())
//! }
//! ```
//!
//! We pass the `request_builder` object to `goose_send` which builds and executes it, also
//! collecting useful metrics. The `.await` at the end is necessary as `goose_send` is an
//! async function.
//!
//! Once all our tasks are created, we edit the main function to initialize goose and register
//! the tasks. In this very simple example we only have two tasks to register, while in a real
//! load test you can have any number of task sets with any number of individual tasks.
//!
//! ```rust,no_run
//! use goose::prelude::*;
//!
//! fn main() -> Result<(), GooseError> {
//! let _goose_metrics = GooseAttack::initialize()?
//! .register_taskset(taskset!("LoadtestTasks")
//! // Register the foo task, assigning it a weight of 10.
//! .register_task(task!(loadtest_foo).set_weight(10)?)
//! // Register the bar task, assigning it a weight of 2 (so it
//! // runs 1/5 as often as bar). Apply a task name which shows up
//! // in metrics.
//! .register_task(task!(loadtest_bar).set_name("bar").set_weight(2)?)
//! )
//! // You could also set a default host here, for example:
//! //.set_default(GooseDefault::Host, "http://dev.local/")?
//! .execute()?;
//!
//! Ok(())
//! }
//!
//! // A task function that loads `/path/to/foo`.
//! async fn loadtest_foo(user: &GooseUser) -> GooseTaskResult {
//! let _goose = user.get("/path/to/foo").await?;
//!
//! Ok(())
//! }
//!
//! // A task function that loads `/path/to/bar`.
//! async fn loadtest_bar(user: &GooseUser) -> GooseTaskResult {
//! let _goose = user.get("/path/to/bar").await?;
//!
//! Ok(())
//! }
//! ```
//!
//! Goose now spins up a configurable number of users, each simulating a user on your
//! website. Thanks to Reqwest, each user maintains its own web client state, handling
//! cookies and more so your "users" can log in, fill out forms, and more, as real users
//! on your sites would do.
//!
//! ### Running the Goose load test
//!
//! Attempts to run our example will result in an error, as we have not yet defined the
//! host against which this load test should be run. We intentionally do not hard code the
//! host in the individual tasks, as this allows us to run the test against different
//! environments, such as local development, staging, and production.
//!
//! ```bash
//! $ cargo run --release
//! Compiling loadtest v0.1.0 (~/loadtest)
//! Finished release [optimized] target(s) in 1.52s
//! Running `target/release/loadtest`
//! Error: InvalidOption { option: "--host", value: "", detail: "A host must be defined via the --host option, the GooseAttack.set_default() function, or the GooseTaskSet.set_host() function (no host defined for WebsiteUser)." }
//! ```
//! Pass in the `-h` flag to see all available run-time options. For now, we'll use a few
//! options to customize our load test.
//!
//! ```bash
//! $ cargo run --release -- --host http://dev.local -t 30s -v
//! ```
//!
//! The first option we specified is `--host`, and in this case tells Goose to run the load test
//! against a VM on my local network. The `-t 30s` option tells Goose to end the load test after 30
//! seconds (for real load tests you'll certainly want to run it longer, you can use `h`, `m`, and
//! `s` to specify hours, minutes and seconds respectively. For example, `-t1h30m` would run the
//! load test for 1 hour 30 minutes). Finally, the `-v` flag tells goose to display INFO and higher
//! level logs to stdout, giving more insight into what is happening. (Additional `-v` flags will
//! result in considerably more debug output, and are not recommended for running actual load tests;
//! they're only useful if you're trying to debug Goose itself.)
//!
//! Running the test results in the following output (broken up to explain it as it goes):
//!
//! ```bash
//! Finished release [optimized] target(s) in 0.05s
//! Running `target/release/loadtest --host 'http://dev.local' -t 30s -v`
//! 15:42:23 [ INFO] Output verbosity level: INFO
//! 15:42:23 [ INFO] Logfile verbosity level: WARN
//! ```
//!
//! If we set the `--log-file` flag, Goose will write a log file with WARN and higher level logs
//! as you run the test from (add a `-g` flag to log all INFO and higher level logs).
//!
//! ```bash
//! 15:42:23 [ INFO] concurrent users defaulted to 8 (number of CPUs)
//! 15:42:23 [ INFO] run_time = 30
//! 15:42:23 [ INFO] hatch_rate = 1
//! ```
//!
//! Goose will default to launching 1 user per available CPU core, and will launch them all in
//! one second. You can change how many users are launched with the `-u` option, and you can
//! change how many users are launched per second with the `-r` option. For example, `-u30 -r2`
//! would launch 30 users over 15 seconds (two users per second).
//!
//! ```bash
//! 15:42:23 [ INFO] global host configured: http://dev.local/
//! 15:42:23 [ INFO] initializing user states...
//! 15:42:23 [ INFO] launching user 1 from LoadtestTasks...
//! 15:42:24 [ INFO] launching user 2 from LoadtestTasks...
//! 15:42:25 [ INFO] launching user 3 from LoadtestTasks...
//! 15:42:26 [ INFO] launching user 4 from LoadtestTasks...
//! 15:42:27 [ INFO] launching user 5 from LoadtestTasks...
//! 15:42:28 [ INFO] launching user 6 from LoadtestTasks...
//! 15:42:29 [ INFO] launching user 7 from LoadtestTasks...
//! 15:42:30 [ INFO] launching user 8 from LoadtestTasks...
//! 15:42:31 [ INFO] launched 8 users...
//! 15:42:31 [ INFO] printing running metrics after 8 seconds...
//! ```
//!
//! Each user is launched in its own thread with its own user state. Goose is able to make
//! very efficient use of server resources. By default Goose resets the metrics after all
//! users are launched, but first it outputs the metrics collected while ramping up:
//!
//! ```bash
//! 15:42:31 [ INFO] printing running metrics after 8 seconds...
//!
//! === PER TASK METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # times run | # fails | task/s | fail/s
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 2,033 | 0 (0%) | 254.12 | 0.00
//! 2: bar | 407 | 0 (0%) | 50.88 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 2,440 | 0 (0%) | 305.00 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 14.23 | 6 | 32 | 14
//! 2: bar | 14.13 | 6 | 30 | 14
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 14.21 | 6 | 32 | 14
//!
//! === PER REQUEST METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # reqs | # fails | req/s | fail/s
//! ------------------------------------------------------------------------------
//! GET / | 2,033 | 0 (0%) | 254.12 | 0.00
//! GET bar | 407 | 0 (0%) | 50.88 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 2,440 | 0 (0%) | 305.00 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! GET / | 14.18 | 6 | 32 | 14
//! GET bar | 14.08 | 6 | 30 | 14
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 14.16 | 6 | 32 | 14
//!
//! All 8 users hatched, resetting metrics (disable with --no-reset-metrics).
//! ```
//!
//! When printing metrics, by default Goose will display running values approximately
//! every 15 seconds. Running metrics are broken into several tables. First are the
//! per-task metrics which are further split into two sections. The first section shows
//! how many requests have been made, how many of them failed (non-2xx response), and
//! the corresponding per-second rates.
//!
//! This table shows details for all Task Sets and all Tasks defined by your load test,
//! regardless of if they actually run. This can be useful to ensure that you have set
//! up weighting as intended, and that you are simulating enough users. As our first
//! task wasn't named, it just showed up as "1:". Our second task was named, so it shows
//! up as the name we gave it, "bar".
//!
//! ```bash
//! 15:42:46 [ INFO] printing running metrics after 15 seconds...
//!
//! === PER TASK METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # times run | # fails | task/s | fail/s
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 4,618 | 0 (0%) | 307.87 | 0.00
//! 2: bar | 924 | 0 (0%) | 61.60 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 5,542 | 0 (0%) | 369.47 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 21.17 | 8 | 151 | 19
//! 2: bar | 21.62 | 9 | 156 | 19
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 21.24 | 8 | 156 | 19
//! ```
//!
//! The second table breaks down the same metrics by Request instead of by Task. For
//! our simple load test, each Task only makes a single Request, so the metrics are
//! the same. There are two main differences. First, metrics are listed by request
//! type and path or name. The first request shows up as `GET /path/to/foo` as the
//! request was not named. The second request shows up as `GET bar` as the request
//! was named. The times to complete each are slightly smaller as this is only the
//! time to make the request, not the time for Goose to execute the entire task.
//!
//! ```bash
//! === PER REQUEST METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # reqs | # fails | req/s | fail/s
//! ------------------------------------------------------------------------------
//! GET /path/to/foo | 4,618 | 0 (0%) | 307.87 | 0.00
//! GET bar | 924 | 0 (0%) | 61.60 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 5,542 | 0 (0%) | 369.47 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! GET /path/to/foo | 21.13 | 8 | 151 | 19
//! GET bar | 21.58 | 9 | 156 | 19
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 21.20 | 8 | 156 | 19
//! ```
//!
//! Note that Goose respected the per-task weights we set, and `foo` (with a weight of
//! 10) is being loaded five times as often as `bar` (with a weight of 2). On average
//! each page is returning within `21.2` milliseconds. The quickest page response was
//! for `foo` in `8` milliseconds. The slowest page response was for `bar` in `156`
//! milliseconds.
//!
//! ```bash
//! 15:43:02 [ INFO] stopping after 30 seconds...
//! 15:43:02 [ INFO] waiting for users to exit
//! 15:43:02 [ INFO] exiting user 3 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 4 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 5 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 8 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 2 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 7 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 6 from LoadtestTasks...
//! 15:43:02 [ INFO] exiting user 1 from LoadtestTasks...
//! 15:43:02 [ INFO] printing metrics after 30 seconds...
//! ```
//!
//! Our example only runs for 30 seconds, so we only see running metrics once. When
//! the test completes, we get more detail in the final summary. The first two tables
//! are the same as what we saw earlier, however now they include all metrics for the
//! entire length of the load test:
//!
//! ```bash
//! === PER TASK METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # times run | # fails | task/s | fail/s
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 9,974 | 0 (0%) | 332.47 | 0.00
//! 2: bar | 1,995 | 0 (0%) | 66.50 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 11,969 | 0 (0%) | 398.97 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! 1: LoadtestTasks |
//! 1: | 19.65 | 8 | 151 | 18
//! 2: bar | 19.92 | 9 | 156 | 18
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 19.69 | 8 | 156 | 18
//!
//! === PER REQUEST METRICS ===
//! ------------------------------------------------------------------------------
//! Name | # reqs | # fails | req/s | fail/s
//! ------------------------------------------------------------------------------
//! GET / | 9,974 | 0 (0%) | 332.47 | 0.00
//! GET bar | 1,995 | 0 (0%) | 66.50 | 0.00
//! -------------------------+---------------+----------------+----------+--------
//! Aggregated | 11,969 | 0 (0%) | 398.97 | 0.00
//! ------------------------------------------------------------------------------
//! Name | Avg (ms) | Min | Max | Median
//! ------------------------------------------------------------------------------
//! GET / | 19.61 | 8 | 151 | 18
//! GET bar | 19.88 | 9 | 156 | 18
//! -------------------------+-------------+------------+-------------+-----------
//! Aggregated | 19.66 | 8 | 156 | 18
//! ------------------------------------------------------------------------------
//! ```
//!
//! The ratio between `foo` and `bar` remained 5:2 as expected.
//!
//! ```bash
//! ------------------------------------------------------------------------------
//! Slowest page load within specified percentile of requests (in ms):
//! ------------------------------------------------------------------------------
//! Name | 50% | 75% | 98% | 99% | 99.9% | 99.99%
//! ------------------------------------------------------------------------------
//! GET / | 18 | 21 | 29 | 79 | 140 | 140
//! GET bar | 18 | 21 | 29 | 120 | 150 | 150
//! -------------------------+--------+--------+--------+--------+--------+-------
//! Aggregated | 18 | 21 | 29 | 84 | 140 | 156
//! ```
//!
//! A new table shows additional information, breaking down response-time by
//! percentile. This shows that the slowest page loads only happened in the
//! slowest 1% of page loads, so were an edge case. 98% of the time page loads
//! happened in 29 milliseconds or less.
//!
//! ## License
//!
//! Copyright 2020 Jeremy Andrews
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
#[macro_use]
extern crate log;
pub mod goose;
pub mod logger;
#[cfg(feature = "gaggle")]
mod manager;
pub mod metrics;
pub mod prelude;
mod throttle;
mod user;
mod util;
#[cfg(feature = "gaggle")]
mod worker;
use gumdrop::Options;
use lazy_static::lazy_static;
#[cfg(feature = "gaggle")]
use nng::Socket;
use serde::{Deserialize, Serialize};
use serde_json::json;
use simplelog::*;
use std::collections::hash_map::DefaultHasher;
use std::collections::{BTreeMap, HashMap};
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::{
atomic::{AtomicBool, AtomicUsize, Ordering},
Arc,
};
use std::{f32, fmt, io, time};
use tokio::fs::File;
use tokio::io::BufWriter;
use tokio::prelude::*;
use tokio::runtime::Runtime;
use tokio::sync::mpsc;
use url::Url;
use crate::goose::{
GooseDebug, GooseRawRequest, GooseRequest, GooseTask, GooseTaskSet, GooseUser, GooseUserCommand,
};
use crate::metrics::{GooseMetric, GooseMetrics};
#[cfg(feature = "gaggle")]
use crate::worker::{register_shutdown_pipe_handler, GaggleMetrics};
/// Constant defining how often metrics should be displayed while load test is running.
const RUNNING_METRICS_EVERY: usize = 15;
/// Constant defining Goose's default port when running a Gaggle.
const DEFAULT_PORT: &str = "5115";
// WORKER_ID is only used when running a gaggle (a distributed load test).
lazy_static! {
static ref WORKER_ID: AtomicUsize = AtomicUsize::new(0);
}
/// Internal representation of a weighted task list.
type WeightedGooseTasks = Vec<Vec<(usize, String)>>;
type DebugLoggerHandle = Option<tokio::task::JoinHandle<()>>;
type DebugLoggerChannel = Option<mpsc::UnboundedSender<Option<GooseDebug>>>;
/// Worker ID to aid in tracing logs when running a Gaggle.
pub fn get_worker_id() -> usize {
WORKER_ID.load(Ordering::Relaxed)
}
#[cfg(not(feature = "gaggle"))]
#[derive(Debug, Clone)]
/// Socket used for coordinating a Gaggle, a distributed load test.
pub struct Socket {}
/// Definition of all errors a GooseAttack can return.
#[derive(Debug)]
pub enum GooseError {
/// Contains an io::Error.
Io(io::Error),
/// Contains a reqwest::Error.
Reqwest(reqwest::Error),
/// Failed attempt to use code that requires a compile-time feature be enabled. The missing
/// feature is named in `.feature`. An optional explanation may be found in `.detail`.
FeatureNotEnabled { feature: String, detail: String },
/// Failed to parse hostname. The invalid hostname that caused this error is found in
/// `.host`. An optional explanation may be found in `.detail`. The lower level
/// `url::ParseError` is contained in `.parse_error`.
InvalidHost {
host: String,
detail: String,
parse_error: url::ParseError,
},
/// Invalid option or value specified, may only be invalid in context. The invalid option
/// is found in `.option`, while the invalid value is found in `.value`. An optional
/// explanation providing context may be found in `.detail`.
InvalidOption {
option: String,
value: String,
detail: String,
},
/// Invalid wait time specified. The minimum wait time and maximum wait time are found in
/// `.min_wait` and `.max_wait` respectively. An optional explanation providing context may
/// be found in `.detail`.
InvalidWaitTime {
min_wait: usize,
max_wait: usize,
detail: String,
},
/// Invalid weight specified. The invalid weight value is found in `.weight`. An optional
// explanation providing context may be found in `.detail`.
InvalidWeight { weight: usize, detail: String },
/// `GooseAttack` has no `GooseTaskSet` defined. An optional explanation may be found in
/// `.detail`.
NoTaskSets { detail: String },
}
impl GooseError {
fn describe(&self) -> &str {
match *self {
GooseError::Io(_) => "io::Error",
GooseError::Reqwest(_) => "reqwest::Error",
GooseError::FeatureNotEnabled { .. } => "required compile-time feature not enabled",
GooseError::InvalidHost { .. } => "failed to parse hostname",
GooseError::InvalidOption { .. } => "invalid option or value specified",
GooseError::InvalidWaitTime { .. } => "invalid wait_time specified",
GooseError::InvalidWeight { .. } => "invalid weight specified",
GooseError::NoTaskSets { .. } => "no task sets defined",
}
}
}
// Define how to display errors.
impl fmt::Display for GooseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
GooseError::Io(ref source) => write!(f, "GooseError: {} ({})", self.describe(), source),
GooseError::Reqwest(ref source) => {
write!(f, "GooseError: {} ({})", self.describe(), source)
}
GooseError::InvalidHost {
ref parse_error, ..
} => write!(f, "GooseError: {} ({})", self.describe(), parse_error),
_ => write!(f, "GooseError: {}", self.describe()),
}
}
}
// Define the lower level source of this error, if any.
impl std::error::Error for GooseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
GooseError::Io(ref source) => Some(source),
GooseError::Reqwest(ref source) => Some(source),
GooseError::InvalidHost {
ref parse_error, ..
} => Some(parse_error),
_ => None,
}
}
}
/// Auto-convert Reqwest errors.
impl From<reqwest::Error> for GooseError {
fn from(err: reqwest::Error) -> GooseError {
GooseError::Reqwest(err)
}
}
/// Auto-convert IO errors.
impl From<io::Error> for GooseError {
fn from(err: io::Error) -> GooseError {
GooseError::Io(err)
}
}
#[derive(Clone, Debug, PartialEq)]
/// A GooseAttack load test can operate in only one mode.
pub enum GooseMode {
/// A mode has not yet been assigned.
Undefined,
/// A single standalone process performing a load test.
StandAlone,
/// The controlling process in a Gaggle distributed load test.
Manager,
/// One of one or more working processes in a Gaggle distributed load test.
Worker,
}
/// Optional default values for Goose run-time options.
#[derive(Clone, Debug, Default)]
pub struct GooseDefaults {
/// An optional default host to run this load test against.
host: Option<String>,
/// An optional default number of users to simulate.
users: Option<usize>,
/// An optional default number of clients to start per second.
hatch_rate: Option<usize>,
/// An optional default number of seconds for the test to run.
run_time: Option<usize>,
/// An optional default log level.
log_level: Option<u8>,
/// An optional default for the log file name.
log_file: Option<String>,
/// An optional default value for verbosity level.
verbose: Option<u8>,
/// An optional default for only printing final summary metrics.
only_summary: Option<bool>,
/// An optional default for not resetting metrics after all users started.
no_reset_metrics: Option<bool>,
/// An optional default for not tracking metrics.
no_metrics: Option<bool>,
/// An optional default for not tracking task metrics.
no_task_metrics: Option<bool>,
/// An optional default for the metrics log file name.
metrics_file: Option<String>,
/// An optional default for the metrics log file format.
metrics_format: Option<String>,
/// An optional default for the debug log file name.
debug_file: Option<String>,
/// An optional default for the debug log format.
debug_format: Option<String>,
/// An optional default to track additional status code metrics.
status_codes: Option<bool>,
/// An optional default maximum requests per second.
throttle_requests: Option<usize>,
/// An optional default to follows base_url redirect with subsequent request.
sticky_follow: Option<bool>,
/// An optional default to enable Manager mode.
manager: Option<bool>,
/// An optional default for number of Workers to expect.
expect_workers: Option<u16>,
/// An optional default for Manager to ignore load test checksum.
no_hash_check: Option<bool>,
/// An optional default for host Manager listens on.
manager_bind_host: Option<String>,
/// An optional default for port Manager listens on.
manager_bind_port: Option<u16>,
/// An optional default to enable Worker mode.
worker: Option<bool>,
/// An optional default for host Worker connects to.
manager_host: Option<String>,
/// An optional default for port Worker connects to.
manager_port: Option<u16>,
}
#[derive(Debug)]
pub enum GooseDefault {
/// An optional default host to run this load test against.
Host,
/// An optional default number of users to simulate.
Users,
/// An optional default number of clients to start per second.
HatchRate,
/// An optional default number of seconds for the test to run.
RunTime,
/// An optional default log level.
LogLevel,
/// An optional default for the log file name.
LogFile,
/// An optional default value for verbosity level.
Verbose,
/// An optional default for only printing final summary metrics.
OnlySummary,
/// An optional default for not resetting metrics after all users started.
NoResetMetrics,
/// An optional default for not tracking metrics.
NoMetrics,
/// An optional default for not tracking task metrics.
NoTaskMetrics,
/// An optional default for the metrics log file name.
MetricsFile,
/// An optional default for the metrics log file format.
MetricsFormat,
/// An optional default for the debug log file name.
DebugFile,
/// An optional default for the debug log format.
DebugFormat,
/// An optional default to track additional status code metrics.
StatusCodes,
/// An optional default maximum requests per second.
ThrottleRequests,
/// An optional default to follows base_url redirect with subsequent request.
StickyFollow,
/// An optional default to enable Manager mode.
Manager,
/// An optional default for number of Workers to expect.
ExpectWorkers,
/// An optional default for Manager to ignore load test checksum.
NoHashCheck,
/// An optional default for host Manager listens on.
ManagerBindHost,
/// An optional default for port Manager listens on.
ManagerBindPort,
/// An optional default to enable Worker mode.
Worker,
/// An optional default for host Worker connects to.
ManagerHost,
/// An optional default for port Worker connects to.
ManagerPort,
}
/// Internal global state for load test.
#[derive(Clone)]
pub struct GooseAttack {
/// An optional task to run one time before starting users and running task sets.
test_start_task: Option<GooseTask>,
/// An optional task to run one time after users have finished running task sets.
test_stop_task: Option<GooseTask>,
/// A vector containing one copy of each GooseTaskSet that will run during this load test.
task_sets: Vec<GooseTaskSet>,
/// A weighted vector containing a GooseUser object for each user that will run during this load test.
weighted_users: Vec<GooseUser>,
/// An optional default host to run this load test against.
defaults: GooseDefaults,
/// Configuration object managed by StructOpt.
configuration: GooseConfiguration,
/// Track how long the load test should run.
run_time: usize,
/// Which mode this GooseAttack is operating in.
attack_mode: GooseMode,
/// When the load test started.
started: Option<time::Instant>,
/// All metrics merged together.
metrics: GooseMetrics,
}
/// Goose's internal global state.
impl GooseAttack {
/// Load configuration from command line and initialize a GooseAttack.
///
/// # Example
/// ```rust,no_run
/// use goose::prelude::*;
///
/// let mut goose_attack = GooseAttack::initialize();
/// ```
pub fn initialize() -> Result<GooseAttack, GooseError> {
Ok(GooseAttack {
test_start_task: None,
test_stop_task: None,
task_sets: Vec::new(),
weighted_users: Vec::new(),
defaults: GooseDefaults::default(),
configuration: GooseConfiguration::parse_args_default_or_exit(),
run_time: 0,
attack_mode: GooseMode::Undefined,
started: None,
metrics: GooseMetrics::default(),
})
}
/// Initialize a GooseAttack with an already loaded configuration.
/// This should only be called by worker instances.
///
/// # Example
/// ```rust,no_run
/// use goose::{GooseAttack, GooseConfiguration};
/// use gumdrop::Options;
///
/// let configuration = GooseConfiguration::parse_args_default_or_exit();
/// let mut goose_attack = GooseAttack::initialize_with_config(configuration);
/// ```
pub fn initialize_with_config(
configuration: GooseConfiguration,
) -> Result<GooseAttack, GooseError> {
Ok(GooseAttack {
test_start_task: None,
test_stop_task: None,
task_sets: Vec::new(),
weighted_users: Vec::new(),
defaults: GooseDefaults::default(),
configuration,
run_time: 0,
attack_mode: GooseMode::Undefined,
started: None,
metrics: GooseMetrics::default(),
})
}
pub fn initialize_logger(&self) {
// Allow optionally controlling debug output level
let debug_level;
match self.configuration.verbose {
0 => debug_level = LevelFilter::Warn,
1 => debug_level = LevelFilter::Info,
2 => debug_level = LevelFilter::Debug,
_ => debug_level = LevelFilter::Trace,
}
// Set log level based on run-time option or default if set.
let log_level_value = if self.configuration.log_level > 0 {
self.configuration.log_level
} else if let Some(default_log_level) = self.defaults.log_level {
default_log_level
} else {
0
};
let log_level = match log_level_value {
0 => LevelFilter::Warn,
1 => LevelFilter::Info,
2 => LevelFilter::Debug,
_ => LevelFilter::Trace,
};
let log_file: Option<PathBuf>;
// Use --log-file if set.
if !self.configuration.log_file.is_empty() {
log_file = Some(PathBuf::from(&self.configuration.log_file));
}
// Otherwise use goose_attack.defaults.log_file if set.
else if let Some(default_log_file) = &self.defaults.log_file {
log_file = Some(PathBuf::from(default_log_file));
}
// Otherwise disable the log.
else {
log_file = None;
}
if let Some(log_to_file) = log_file {
match CombinedLogger::init(vec![
SimpleLogger::new(debug_level, Config::default()),
WriteLogger::new(
log_level,
Config::default(),
std::fs::File::create(&log_to_file).unwrap(),
),
]) {
Ok(_) => (),
Err(e) => {
info!("failed to initialize CombinedLogger: {}", e);
}
}
info!("Writing to log file: {}", log_to_file.display());
} else {
match CombinedLogger::init(vec![SimpleLogger::new(debug_level, Config::default())]) {
Ok(_) => (),
Err(e) => {
info!("failed to initialize CombinedLogger: {}", e);
}
}
}
info!("Output verbosity level: {}", debug_level);
info!("Logfile verbosity level: {}", log_level);
}
/// A load test must contain one or more `GooseTaskSet`s. Each task set must
/// be registered into Goose's global state with this method for it to run.
///
/// # Example
/// ```rust,no_run
/// use goose::prelude::*;
///
/// fn main() -> Result<(), GooseError> {
/// GooseAttack::initialize()?
/// .register_taskset(taskset!("ExampleTasks")
/// .register_task(task!(example_task))
/// )
/// .register_taskset(taskset!("OtherTasks")
/// .register_task(task!(other_task))
/// );
///
/// Ok(())
/// }
///
/// async fn example_task(user: &GooseUser) -> GooseTaskResult {
/// let _goose = user.get("/foo").await?;
///
/// Ok(())
/// }
///
/// async fn other_task(user: &GooseUser) -> GooseTaskResult {
/// let _goose = user.get("/bar").await?;
///
/// Ok(())
/// }
/// ```
pub fn register_taskset(mut self, mut taskset: GooseTaskSet) -> Self {
taskset.task_sets_index = self.task_sets.len();
self.task_sets.push(taskset);
self
}
/// Optionally define a task to run before users are started and all task sets
/// start running. This is would generally be used to set up anything required
/// for the load test.
///
/// The GooseUser used to run the `test_start` tasks is not preserved and does not
/// otherwise affect the subsequent GooseUsers that run the rest of the load test.
/// For example, if the GooseUser logs in during `test_start`, subsequent GooseUsers
/// do not retain this session and are therefor not already logged in.
///
/// When running in a distributed Gaggle, this task is only run one time by the
/// Manager.
///
/// # Example
/// ```rust,no_run
/// use goose::prelude::*;
///
/// fn main() -> Result<(), GooseError> {
/// GooseAttack::initialize()?
/// .test_start(task!(setup));
///
/// Ok(())
/// }
///
/// async fn setup(user: &GooseUser) -> GooseTaskResult {
/// // do stuff to set up load test ...
///
/// Ok(())
/// }
/// ```
pub fn test_start(mut self, task: GooseTask) -> Self {
self.test_start_task = Some(task);
self
}
/// Optionally define a task to run after all users have finished running
/// all defined task sets. This would generally be used to clean up anything
/// that was specifically set up for the load test.
///
/// When running in a distributed Gaggle, this task is only run one time by the
/// Manager.
///
/// # Example
/// ```rust,no_run
/// use goose::prelude::*;
///
/// fn main() -> Result<(), GooseError> {
/// GooseAttack::initialize()?
/// .test_stop(task!(teardown));
///
/// Ok(())
/// }
///
/// async fn teardown(user: &GooseUser) -> GooseTaskResult {
/// // do stuff to tear down the load test ...
///
/// Ok(())
/// }
/// ```
pub fn test_stop(mut self, task: GooseTask) -> Self {
self.test_stop_task = Some(task);
self
}
/// Allocate a vector of weighted GooseUser.
fn weight_task_set_users(&mut self) -> Result<Vec<GooseUser>, GooseError> {
trace!("weight_task_set_users");
let mut u: usize = 0;
let mut v: usize;
for task_set in &self.task_sets {
if u == 0 {
u = task_set.weight;
} else {
v = task_set.weight;
trace!("calculating greatest common denominator of {} and {}", u, v);
u = util::gcd(u, v);
trace!("inner gcd: {}", u);
}
}
// 'u' will always be the greatest common divisor
debug!("gcd: {}", u);
// Build a weighted lists of task sets (identified by index)
let mut weighted_task_sets = Vec::new();
for (index, task_set) in self.task_sets.iter().enumerate() {
// divide by greatest common divisor so vector is as short as possible
let weight = task_set.weight / u;
trace!(
"{}: {} has weight of {} (reduced with gcd to {})",
index,
task_set.name,
task_set.weight,
weight
);
let mut weighted_sets = vec![index; weight];
weighted_task_sets.append(&mut weighted_sets);
}
// Allocate a state for each user that will be hatched.
info!("initializing user states...");
let mut weighted_users = Vec::new();
let mut user_count = 0;
loop {
for task_sets_index in &weighted_task_sets {
let base_url = goose::get_base_url(
self.get_configuration_host(),
self.task_sets[*task_sets_index].host.clone(),
self.defaults.host.clone(),
)?;
weighted_users.push(GooseUser::new(
self.task_sets[*task_sets_index].task_sets_index,
base_url,
self.task_sets[*task_sets_index].min_wait,
self.task_sets[*task_sets_index].max_wait,
&self.configuration,
self.metrics.hash,
)?);
user_count += 1;
// Users are required here so unwrap() is safe.
if user_count >= self.configuration.users.unwrap() {