-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathmetrics.rs
3850 lines (3607 loc) · 158 KB
/
metrics.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
//! Optional metrics collected and aggregated during load tests.
//!
//! By default, Goose collects a large number of metrics while performing a load test.
//! When [`GooseAttack::execute()`](../struct.GooseAttack.html#method.execute) completes
//! it returns a [`GooseMetrics`] object.
//!
//! When the [`GooseMetrics`] object is viewed with [`std::fmt::Display`], the
//! contained [`TransactionMetrics`], [`GooseRequestMetrics`], and
//! [`GooseErrorMetrics`] are displayed in tables.
mod common;
pub(crate) use common::ReportData;
use crate::config::GooseDefaults;
use crate::goose::{get_base_url, GooseMethod, Scenario};
use crate::logger::GooseLog;
use crate::metrics::common::ReportOptions;
use crate::report;
use crate::test_plan::{TestPlanHistory, TestPlanStepAction};
use crate::util;
use crate::{GooseAttack, GooseAttackRunState, GooseConfiguration, GooseError};
use chrono::prelude::*;
use itertools::Itertools;
use num_format::{Locale, ToFormattedString};
use regex::RegexSet;
use reqwest::StatusCode;
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ffi::OsStr;
use std::fmt::Write;
use std::io::BufWriter;
use std::path::PathBuf;
use std::str::FromStr;
use std::{f32, fmt};
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
/// Used to send metrics from [`GooseUser`](../goose/struct.GooseUser.html) threads
/// to the parent Goose process.
///
/// [`GooseUser`](../goose/struct.GooseUser.html) threads send these metrics to the
/// Goose parent process using an
/// [`unbounded Flume channel`](https://docs.rs/flume/*/flume/fn.unbounded.html).
///
/// The parent process will spend up to 80% of its time receiving and aggregating
/// these metrics. The parent process aggregates [`GooseRequestMetric`]s into
/// [`GooseRequestMetricAggregate`], [`TransactionMetric`]s into [`TransactionMetricAggregate`],
/// and [`GooseErrorMetric`]s into [`GooseErrorMetricAggregate`]. Aggregation happens in the
/// parent process so the individual [`GooseUser`](../goose/struct.GooseUser.html) threads
/// can spend all their time generating and validating load.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum GooseMetric {
Request(Box<GooseRequestMetric>),
Transaction(TransactionMetric),
Scenario(ScenarioMetric),
}
/// THIS IS AN EXPERIMENTAL FEATURE, DISABLED BY DEFAULT. Optionally mitigate the loss of data
/// (coordinated omission) due to stalls on the upstream server.
///
/// Stalling can happen for many reasons, for example: garbage collection, a cache stampede,
/// even unrelated load on the same server. Without any mitigation, Goose loses
/// statistically relevant information as [`GooseUser`](../goose/struct.GooseUser.html)
/// threads are unable to make additional requests while they are blocked by an upstream stall.
/// Goose mitigates this by backfilling the requests that would have been made during that time.
/// Backfilled requests show up in the `--request-file` if enabled, though they were not actually
/// sent to the server.
///
/// Goose can be configured to backfill requests based on the expected
/// [`user_cadence`](struct.GooseRequestMetric.html#structfield.user_cadence). The expected
/// cadence can be automatically calculated with any of the following configuration options.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub enum GooseCoordinatedOmissionMitigation {
/// Backfill based on the average
/// [`user_cadence`](struct.GooseRequestMetric.html#structfield.user_cadence) for this
/// [`GooseUser`](../goose/struct.GooseUser.html).
Average,
/// Backfill based on the maximum
/// [`user_cadence`](struct.GooseRequestMetric.html#structfield.user_cadence) for this
/// [`GooseUser`](../goose/struct.GooseUser.html).
Maximum,
/// Backfill based on the minimum
/// [`user_cadence`](struct.GooseRequestMetric.html#structfield.user_cadence) for this
/// [`GooseUser`](../goose/struct.GooseUser.html).
Minimum,
/// Completely disable coordinated omission mitigation (default).
Disabled,
}
/// Allow `--co-mitigation` from the command line using text variations on supported
/// `GooseCoordinatedOmissionMitigation`s by implementing [`FromStr`].
impl FromStr for GooseCoordinatedOmissionMitigation {
type Err = GooseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Use a [`RegexSet`] to match string representations of `GooseCoordinatedOmissionMitigation`,
// returning the appropriate enum value. Also match a wide range of abbreviations and synonyms.
let co_mitigation = RegexSet::new([
r"(?i)^(average|ave|aver|avg|mean)$",
r"(?i)^(maximum|ma|max|maxi)$",
r"(?i)^(minimum|mi|min|mini)$",
r"(?i)^(disabled|di|dis|disable|none|no)$",
])
.expect("failed to compile co_mitigation RegexSet");
let matches = co_mitigation.matches(s);
if matches.matched(0) {
Ok(GooseCoordinatedOmissionMitigation::Average)
} else if matches.matched(1) {
Ok(GooseCoordinatedOmissionMitigation::Maximum)
} else if matches.matched(2) {
Ok(GooseCoordinatedOmissionMitigation::Minimum)
} else if matches.matched(3) {
Ok(GooseCoordinatedOmissionMitigation::Disabled)
} else {
Err(GooseError::InvalidOption {
option: format!("GooseCoordinatedOmissionMitigation::{:?}", s),
value: s.to_string(),
detail:
"Invalid co_mitigation, expected: average, disabled, maximum, median, or minimum"
.to_string(),
})
}
}
}
/// All requests made during a load test.
///
/// Goose optionally tracks metrics about requests made during a load test. The
/// metrics can be disabled with the `--no-metrics` run-time option, or with
/// [`GooseDefault::NoMetrics`](../config/enum.GooseDefault.html#variant.NoMetrics).
///
/// Aggregated requests ([`GooseRequestMetricAggregate`]) are stored in a HashMap
/// with they key `method request-name`, for example `GET /`.
///
/// # Example
/// When viewed with [`std::fmt::Display`], [`GooseRequestMetrics`] are displayed in
/// a table:
/// ```text
/// === PER REQUEST METRICS ===
/// ------------------------------------------------------------------------------
/// Name | # reqs | # fails | req/s | fail/s
/// ------------------------------------------------------------------------------
/// GET (Anon) front page | 438 | 0 (0%) | 43.80 | 0.00
/// GET (Anon) node page | 296 | 0 (0%) | 29.60 | 0.00
/// GET (Anon) user page | 90 | 0 (0%) | 9.00 | 0.00
/// GET (Auth) comment form | 19 | 0 (0%) | 1.90 | 0.00
/// GET (Auth) front page | 108 | 0 (0%) | 10.80 | 0.00
/// GET (Auth) node page | 74 | 0 (0%) | 7.40 | 0.00
/// GET (Auth) user page | 19 | 0 (0%) | 1.90 | 0.00
/// GET static asset | 3,288 | 0 (0%) | 328.80 | 0.00
/// POST (Auth) comment form | 20 | 0 (0%) | 2.00 | 0.00
/// -------------------------+---------------+----------------+----------+--------
/// Aggregated | 4,352 | 0 (0%) | 435.20 | 0.00
/// ------------------------------------------------------------------------------
/// Name | Avg (ms) | Min | Max | Median
/// ------------------------------------------------------------------------------
/// GET (Anon) front page | 14.22 | 2 | 211 | 14
/// GET (Anon) node page | 53.26 | 3 | 96 | 53
/// GET (Anon) user page | 32.97 | 17 | 221 | 30
/// GET (Auth) comment form | 54.32 | 36 | 88 | 50
/// GET (Auth) front page | 39.02 | 25 | 232 | 38
/// GET (Auth) node page | 52.08 | 36 | 81 | 51
/// GET (Auth) user page | 31.21 | 25 | 40 | 31
/// GET static asset | 11.55 | 3 | 217 | 8
/// POST (Auth) comment form | 54.30 | 41 | 73 | 52
/// -------------------------+-------------+------------+-------------+-----------
/// Aggregated | 16.94 | 2 | 232 | 10
/// ------------------------------------------------------------------------------
/// Slowest page load within specified percentile of requests (in ms):
/// ------------------------------------------------------------------------------
/// Name | 50% | 75% | 98% | 99% | 99.9% | 99.99%
/// ------------------------------------------------------------------------------
/// GET (Anon) front page | 14 | 18 | 30 | 43 | 210 | 210
/// GET (Anon) node page | 53 | 62 | 78 | 86 | 96 | 96
/// GET (Anon) user page | 30 | 33 | 43 | 53 | 220 | 220
/// GET (Auth) comment form | 50 | 65 | 88 | 88 | 88 | 88
/// GET (Auth) front page | 38 | 43 | 58 | 59 | 230 | 230
/// GET (Auth) node page | 51 | 58 | 72 | 72 | 81 | 81
/// GET (Auth) user page | 31 | 33 | 40 | 40 | 40 | 40
/// GET static asset | 8 | 16 | 30 | 36 | 210 | 210
/// POST (Auth) comment form | 52 | 59 | 73 | 73 | 73 | 73
/// -------------------------+--------+--------+--------+--------+--------+-------
/// Aggregated | 10 | 20 | 64 | 71 | 210 | 230
/// ```
pub type GooseRequestMetrics = HashMap<String, GooseRequestMetricAggregate>;
/// All transactions executed during a load test.
///
/// Goose optionally tracks metrics about transactions executed during a load test. The
/// metrics can be disabled with either the `--no-transaction-metrics` or the `--no-metrics`
/// run-time option, or with either
/// [`GooseDefault::NoTransactionMetrics`](../config/enum.GooseDefault.html#variant.NoTransactionMetrics) or
/// [`GooseDefault::NoMetrics`](../config/enum.GooseDefault.html#variant.NoMetrics).
///
/// Aggregated transactions ([`TransactionMetricAggregate`]) are stored in a Vector of Vectors
/// keyed to the order the transaction is created in the load test.
///
/// # Example
/// When viewed with [`std::fmt::Display`], [`TransactionMetrics`] are displayed in
/// a table:
/// ```text
/// === PER TRANSACTION METRICS ===
/// ------------------------------------------------------------------------------
/// Name | # times run | # fails | trans/s | fail/s
/// ------------------------------------------------------------------------------
/// 1: AnonBrowsingUser |
/// 1: (Anon) front page | 440 | 0 (0%) | 44.00 | 0.00
/// 2: (Anon) node page | 296 | 0 (0%) | 29.60 | 0.00
/// 3: (Anon) user page | 90 | 0 (0%) | 9.00 | 0.00
/// 2: AuthBrowsingUser |
/// 1: (Auth) login | 0 | 0 (0%) | 0.00 | 0.00
/// 2: (Auth) front page | 109 | 0 (0%) | 10.90 | 0.00
/// 3: (Auth) node page | 74 | 0 (0%) | 7.40 | 0.00
/// 4: (Auth) user page | 19 | 0 (0%) | 1.90 | 0.00
/// 5: (Auth) comment form | 20 | 0 (0%) | 2.00 | 0.00
/// -------------------------+---------------+----------------+----------+--------
/// Aggregated | 1,048 | 0 (0%) | 104.80 | 0.00
/// ------------------------------------------------------------------------------
/// Name | Avg (ms) | Min | Max | Median
/// ------------------------------------------------------------------------------
/// 1: AnonBrowsingUser |
/// 1: (Anon) front page | 94.41 | 59 | 294 | 88
/// 2: (Anon) node page | 53.29 | 3 | 96 | 53
/// 3: (Anon) user page | 33.02 | 17 | 221 | 30
/// 2: AuthBrowsingUser |
/// 1: (Auth) login | 0.00 | 0 | 0 | 0
/// 2: (Auth) front page | 119.45 | 84 | 307 | 110
/// 3: (Auth) node page | 52.16 | 37 | 81 | 51
/// 4: (Auth) user page | 31.21 | 25 | 40 | 31
/// 5: (Auth) comment form | 135.10 | 107 | 175 | 130
/// -------------------------+-------------+------------+-------------+-----------
/// Aggregated | 76.78 | 3 | 307 | 74
/// ```
pub type TransactionMetrics = Vec<Vec<TransactionMetricAggregate>>;
/// All scenarios executed during a load test.
///
/// Goose optionally tracks metrics about scenarios executed during a load test. The
/// metrics can be disabled with either the `--no-scenario-metrics` or the `--no-metrics`
/// run-time option, or with either
/// [`GooseDefault::NoScenarioMetrics`](../config/enum.GooseDefault.html#variant.NoScenarioMetrics) or
/// [`GooseDefault::NoMetrics`](../config/enum.GooseDefault.html#variant.NoMetrics).
///
/// Aggregated scenarios ([`ScenarioMetricAggregate`]) are stored in a Vector keyed to the order the
/// scenario is created in the load test.
///
/// # Example
/// When viewed with [`std::fmt::Display`], [`TransactionMetrics`] are displayed in
/// a table:
/// ```text
/// === PER SCENARIO METRICS ===
/// ------------------------------------------------------------------------------
/// Name | # users | # times run | scenarios/s | iterations
/// ------------------------------------------------------------------------------
/// 1: AnonBrowsingUser | 9 | 224 | 6.40 | 24.89
/// 2: AuthBrowsingUser | 3 | 51 | 1.46 | 17.00
/// -------------------------+----------+--------------+-------------+------------
/// Aggregated | 12 | 275 | 7.86 | 22.92
/// ------------------------------------------------------------------------------
/// Name | Avg (ms) | Min | Max | Median
/// ------------------------------------------------------------------------------
/// 1: AnonBrowsingUser | 1293 | 1,067 | 1,672 | 1,067
/// 2: AuthBrowsingUser | 1895 | 1,505 | 2,235 | 1,505
/// -------------------------+-------------+------------+-------------+-----------
/// Aggregated | 1405 | 1,067 | 2,235 | 1,067
/// ```
pub type ScenarioMetrics = Vec<ScenarioMetricAggregate>;
/// All errors detected during a load test.
///
/// By default Goose tracks all errors detected during the load test. Each error is stored
/// as a [`GooseErrorMetricAggregate`](./struct.GooseErrorMetricAggregate.html), and they
/// are all stored together within a `BTreeMap` which is returned by
/// [`GooseAttack::execute()`](../struct.GooseAttack.html#method.execute) when a load test
/// completes.
///
/// `GooseErrorMetrics` can be disabled with the `--no-error-summary` run-time option, or with
/// [GooseDefault::NoErrorSummary](../config/enum.GooseDefault.html#variant.NoErrorSummary).
///
/// # Example
/// When viewed with [`std::fmt::Display`], [`GooseErrorMetrics`] are displayed in
/// a table:
/// ```text
/// === ERRORS ===
/// ------------------------------------------------------------------------------
/// Count | Error
/// ------------------------------------------------------------------------------
/// 924 GET (Auth) front page: 503 Service Unavailable: /
/// 715 POST (Auth) front page: 503 Service Unavailable: /user
/// 36 GET (Anon) front page: error sending request for url (http://example.com/): connection closed before message completed
/// ```
pub type GooseErrorMetrics = BTreeMap<String, GooseErrorMetricAggregate>;
/// For tracking and logging requests made during a load test.
///
/// The raw request that the GooseClient is making. Is included in the [`GooseRequestMetric`]
/// when metrics are enabled.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GooseRawRequest {
/// The method being used (ie, Get, Post, etc).
pub method: GooseMethod,
/// The full URL that was requested.
pub url: String,
/// Any headers set by the client when making the request.
pub headers: Vec<String>,
/// The body of the request made, if `--request-body` is enabled.
pub body: String,
}
impl GooseRawRequest {
pub(crate) fn new(
method: GooseMethod,
url: &str,
headers: Vec<String>,
body: &str,
) -> GooseRawRequest {
GooseRawRequest {
method,
url: url.to_string(),
headers,
body: body.to_string(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionDetail<'a> {
/// An index into [`GooseAttack`]`.scenarios`, indicating which scenario this is.
pub scenario_index: usize,
/// The scenario name.
pub scenario_name: &'a str,
/// An optional index into [`Scenario`]`.transaction`, indicating which transaction this is.
pub transaction_index: &'a str,
/// An optional name for the transaction.
pub transaction_name: &'a str,
}
/// How many milliseconds the load test has been running.
/// For tracking and counting requests made during a load test.
///
/// The request that Goose is making. User threads send this data to the parent thread
/// when metrics are enabled. This request object must be provided to calls to
/// [`set_success`](../goose/struct.GooseUser.html#method.set_success) or
/// [`set_failure`](../goose/struct.GooseUser.html#method.set_failure) so Goose
/// knows which request is being updated.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GooseRequestMetric {
/// How many milliseconds the load test has been running.
pub elapsed: u64,
/// An index into [`GooseAttack`]`.scenarios`, indicating which scenario this is.
pub scenario_index: usize,
/// The scenario name.
pub scenario_name: String,
/// An optional index into [`Scenario`]`.transaction`, indicating which transaction this is.
/// Stored as string, `""` is no transaction, while `0` is the first `Scenario.transaction`.
pub transaction_index: String,
/// The optional transaction name.
pub transaction_name: String,
/// The raw request that the GooseClient made.
pub raw: GooseRawRequest,
/// The optional name of the request.
pub name: String,
/// The final full URL that was requested, after redirects.
pub final_url: String,
/// Whether or not the request was redirected.
pub redirected: bool,
/// How many milliseconds the request took.
pub response_time: u64,
/// The HTTP response code (optional).
pub status_code: u16,
/// Whether or not the request was successful.
pub success: bool,
/// Whether or not we're updating a previous request, modifies how the parent thread records it.
pub update: bool,
/// Which [`GooseUser`](../goose/struct.GooseUser.html) thread processed the request.
pub user: usize,
/// The optional error caused by this request.
pub error: String,
/// If non-zero, Coordinated Omission Mitigation detected an abnormally long response time on
/// the upstream server, blocking requests from being made.
pub coordinated_omission_elapsed: u64,
/// If non-zero, the calculated cadence of looping through all
/// [`Transaction`](../goose/struct.Transaction.html)s by this
/// [`GooseUser`](../goose/struct.GooseUser.html) thread.
pub user_cadence: u64,
}
impl GooseRequestMetric {
pub(crate) fn new(
raw: GooseRawRequest,
transaction_detail: TransactionDetail,
name: &str,
elapsed: u128,
user: usize,
) -> Self {
GooseRequestMetric {
elapsed: elapsed as u64,
scenario_index: transaction_detail.scenario_index,
scenario_name: transaction_detail.scenario_name.to_string(),
transaction_index: transaction_detail.transaction_index.to_string(),
transaction_name: transaction_detail.transaction_name.to_string(),
raw,
name: name.to_string(),
final_url: "".to_string(),
redirected: false,
response_time: 0,
status_code: 0,
success: true,
update: false,
user,
error: "".to_string(),
coordinated_omission_elapsed: 0,
user_cadence: 0,
}
}
// Record the final URL returned.
pub(crate) fn set_final_url(&mut self, final_url: &str) {
self.final_url = final_url.to_string();
if self.final_url != self.raw.url {
self.redirected = true;
}
}
// Record how long the `response_time` took.
pub(crate) fn set_response_time(&mut self, response_time: u128) {
self.response_time = response_time as u64;
}
// Record the returned `status_code`.
pub(crate) fn set_status_code(&mut self, status_code: Option<StatusCode>) {
self.status_code = match status_code {
Some(status_code) => status_code.as_u16(),
None => 0,
};
}
}
/// Metrics collected about a method-path pair, (for example `GET /index`).
///
/// [`GooseRequestMetric`]s are sent by [`GooseUser`](../goose/struct.GooseUser.html)
/// threads to the Goose parent process where they are aggregated together into this
/// structure, and stored in [`GooseMetrics::requests`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct GooseRequestMetricAggregate {
/// The request path for which metrics are being collected.
///
/// For example: "/".
pub path: String,
/// The method for which metrics are being collected.
///
/// For example: [`GooseMethod::Get`].
pub method: GooseMethod,
/// The raw data seen from actual requests.
pub raw_data: GooseRequestMetricTimingData,
/// Combines the raw data with statistically generated Coordinated Omission Metrics.
pub coordinated_omission_data: Option<GooseRequestMetricTimingData>,
/// Per-status-code counters, tracking how often each response code was returned for this request.
pub status_code_counts: HashMap<u16, usize>,
/// Total number of times this path-method request resulted in a successful (2xx) status code.
///
/// A count of how many requests resulted in a 2xx status code.
pub success_count: usize,
/// Total number of times this path-method request resulted in a non-successful (non-2xx) status code.
///
/// A count of how many requests resulted in a non-2xx status code.
pub fail_count: usize,
/// Load test hash.
///
/// The hash is primarily used when running a distributed Gaggle, allowing the Manager to confirm
/// that all Workers are running the same load test plan.
pub load_test_hash: u64,
}
impl GooseRequestMetricAggregate {
/// Create a new GooseRequestMetricAggregate object.
pub(crate) fn new(path: &str, method: GooseMethod, load_test_hash: u64) -> Self {
trace!("new request");
GooseRequestMetricAggregate {
path: path.to_string(),
method,
raw_data: GooseRequestMetricTimingData::new(None),
coordinated_omission_data: None,
status_code_counts: HashMap::new(),
success_count: 0,
fail_count: 0,
load_test_hash,
}
}
pub(crate) fn record_time(&mut self, time_elapsed: u64, coordinated_omission_mitigation: bool) {
// Only add time_elapsed to raw_data if the time wasn't generated by Coordinated
// Omission Mitigation.
if !coordinated_omission_mitigation {
self.raw_data.record_time(time_elapsed);
}
// A Coordinated Omission data object already exists, add a new time into the data.
if let Some(coordinated_omission_data) = self.coordinated_omission_data.as_mut() {
coordinated_omission_data.record_time(time_elapsed);
}
// Create a new Coordinated Omission data object by cloning the raw data.
else if coordinated_omission_mitigation {
// If this time_elapsed was generated by Coordinated Omission Mitigation, it doesn't
// exist in the raw_data, so add it.
let mut coordinated_omission_data = self.raw_data.clone();
coordinated_omission_data.record_time(time_elapsed);
self.coordinated_omission_data = Some(coordinated_omission_data);
}
}
/// Increment counter for status code, creating new counter if first time seeing status code.
pub(crate) fn set_status_code(&mut self, status_code: u16) {
let counter = match self.status_code_counts.get(&status_code) {
// We've seen this status code before, increment counter.
Some(c) => {
debug!("got {:?} counter: {}", status_code, c);
*c + 1
}
// First time we've seen this status code, initialize counter.
None => {
debug!("no match for counter: {}", status_code);
1
}
};
self.status_code_counts.insert(status_code, counter);
debug!("incremented {} counter: {}", status_code, counter);
}
}
/// Implement equality for GooseRequestMetricAggregate. We can't simply derive since
/// we have floats in the struct.
///
/// `Eq` trait has no functions on it - it is there only to inform the compiler
/// that this is an equivalence rather than a partial equivalence.
///
/// See <https://doc.rust-lang.org/std/cmp/trait.Eq.html> for more information.
impl Eq for GooseRequestMetricAggregate {}
/// Implement ordering for GooseRequestMetricAggregate.
impl Ord for GooseRequestMetricAggregate {
fn cmp(&self, other: &Self) -> Ordering {
(&self.method, &self.path).cmp(&(&other.method, &other.path))
}
}
/// Implement partial-ordering for GooseRequestMetricAggregate.
impl PartialOrd for GooseRequestMetricAggregate {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
/// Collects per-request timing metrics.
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct GooseRequestMetricTimingData {
/// Per-response-time counters, tracking how often pages are returned with this response time.
///
/// All response times between 1 and 100ms are stored without any rounding. Response times between
/// 100 and 500ms are rounded to the nearest 10ms and then stored. Response times betwee 500 and
/// 1000ms are rounded to the nearest 100ms. Response times larger than 1000ms are rounded to the
/// nearest 1000ms.
pub times: BTreeMap<usize, usize>,
/// The shortest response time seen so far.
///
/// For example a `min_response_time` of `3` means the quickest response for this method-path
/// pair returned in 3 milliseconds. This value is not rounded.
pub minimum_time: usize,
/// The longest response time seen so far.
///
/// For example a `max_response_time` of `2013` means the slowest response for this method-path
/// pair returned in 2013 milliseconds. This value is not rounded.
pub maximum_time: usize,
/// Total combined response times seen so far.
///
/// A running total of all response times returned for this method-path pair.
pub total_time: usize,
/// Total number of response times seen so far.
///
/// A count of how many requests have been tracked for this method-path pair.
pub counter: usize,
}
impl GooseRequestMetricTimingData {
/// Create a new GooseRequestMetricAggregate object.
pub(crate) fn new(metric_data: Option<&GooseRequestMetricTimingData>) -> Self {
trace!("new GooseRequestMetricTimingData");
// Simply clone the exiting metric_data.
if let Some(data) = metric_data {
data.clone()
// Create a new empty metric_data.
} else {
GooseRequestMetricTimingData {
times: BTreeMap::new(),
minimum_time: 0,
maximum_time: 0,
total_time: 0,
counter: 0,
}
}
}
/// Record a new time.
pub(crate) fn record_time(&mut self, time_elapsed: u64) {
// Perform this conversin only once, then re-use throughout this funciton.
let time = time_elapsed as usize;
// Update minimum if this one is fastest yet.
if time > 0 && (self.minimum_time == 0 || time < self.minimum_time) {
self.minimum_time = time;
}
// Update maximum if this one is slowest yet.
if time > self.maximum_time {
self.maximum_time = time;
}
// Update total time, adding in this one.
self.total_time += time;
// Each time we store a new time, increment counter by one.
self.counter += 1;
// Round the time so we can combine similar times together and
// minimize required memory to store and push upstream to the parent.
// No rounding for 1-100ms times.
let rounded_time = if time_elapsed < 100 {
time
}
// Round to nearest 10 for 100-500ms times.
else if time_elapsed < 500 {
((time_elapsed as f64 / 10.0).round() * 10.0) as usize
}
// Round to nearest 100 for 500-1000ms times.
else if time_elapsed < 1000 {
((time_elapsed as f64 / 100.0).round() * 100.0) as usize
}
// Round to nearest 1000 for all larger times.
else {
((time_elapsed as f64 / 1000.0).round() * 1000.0) as usize
};
let counter = match self.times.get(&rounded_time) {
// We've seen this elapsed time before, increment counter.
Some(c) => {
debug!("got {:?} counter: {}", rounded_time, c);
*c + 1
}
// First time we've seen this elapsed time, initialize counter.
None => {
debug!("no match for counter: {}", rounded_time);
1
}
};
debug!("incremented {} counter: {}", rounded_time, counter);
self.times.insert(rounded_time, counter);
}
}
/// The per-scenario metrics collected each time a scenario is run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScenarioMetric {
/// How many milliseconds the load test has been running.
pub elapsed: u64,
/// The name of the scenario.
pub name: String,
/// An index into [`GooseAttack`]`.scenarios`, indicating which scenario this is.
pub index: usize,
/// How long scenario ran.
pub run_time: u64,
/// Which GooseUser thread processed the request.
pub user: usize,
}
impl ScenarioMetric {
/// Create a new Scenario metric.
pub(crate) fn new(
elapsed: u128,
scenario_name: &str,
index: usize,
run_time: u128,
user: usize,
) -> Self {
ScenarioMetric {
elapsed: elapsed as u64,
name: scenario_name.to_string(),
index,
run_time: run_time as u64,
user,
}
}
}
/// The per-transaction metrics collected each time a transaction is invoked.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TransactionMetric {
/// How many milliseconds the load test has been running.
pub elapsed: u64,
/// An index into [`GooseAttack`]`.scenarios`, indicating which transaction set this is.
pub scenario_index: usize,
/// An index into [`Scenario`]`.transaction`, indicating which transaction this is.
pub transaction_index: usize,
/// The optional name of the transaction.
pub name: String,
/// How long transaction ran.
pub run_time: u64,
/// Whether or not the request was successful.
pub success: bool,
/// Which GooseUser thread processed the request.
pub user: usize,
}
impl TransactionMetric {
/// Create a new TransactionMetric metric.
pub(crate) fn new(
elapsed: u128,
scenario_index: usize,
transaction_index: usize,
name: String,
user: usize,
) -> Self {
TransactionMetric {
elapsed: elapsed as u64,
scenario_index,
transaction_index,
name,
run_time: 0,
success: true,
user,
}
}
/// Update a TransactionMetric metric.
pub(crate) fn set_time(&mut self, time: u128, success: bool) {
self.run_time = time as u64;
self.success = success;
}
}
/// Aggregated per-transaction metrics updated each time a transaction is invoked.
///
/// [`TransactionMetric`]s are sent by [`GooseUser`](../goose/struct.GooseUser.html)
/// threads to the Goose parent process where they are aggregated together into this
/// structure, and stored in [`GooseMetrics::transactions`].
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct TransactionMetricAggregate {
/// An index into [`GooseAttack`](../struct.GooseAttack.html)`.scenarios`,
/// indicating which scenario this is.
pub scenario_index: usize,
/// The scenario name.
pub scenario_name: String,
/// An index into [`Scenario`](../goose/struct.Scenario.html)`.transaction`,
/// indicating which transaction this is.
pub transaction_index: usize,
/// An optional name for the transaction.
pub transaction_name: String,
/// Per-run-time counters, tracking how often transactions take a given time to complete.
pub times: BTreeMap<usize, usize>,
/// The shortest run-time for this transaction.
pub min_time: usize,
/// The longest run-time for this transaction.
pub max_time: usize,
/// Total combined run-times for this transaction.
pub total_time: usize,
/// Total number of times transaction has run.
pub counter: usize,
/// Total number of times transaction has run successfully.
pub success_count: usize,
/// Total number of times transaction has failed.
pub fail_count: usize,
}
impl TransactionMetricAggregate {
/// Create a new TransactionMetricAggregate.
pub(crate) fn new(
scenario_index: usize,
scenario_name: &str,
transaction_index: usize,
transaction_name: &str,
) -> Self {
TransactionMetricAggregate {
scenario_index,
scenario_name: scenario_name.to_string(),
transaction_index,
transaction_name: transaction_name.to_string(),
times: BTreeMap::new(),
min_time: 0,
max_time: 0,
total_time: 0,
counter: 0,
success_count: 0,
fail_count: 0,
}
}
/// Track transaction function elapsed time in milliseconds.
pub(crate) fn set_time(&mut self, time: u64, success: bool) {
// Perform this conversion only once, then re-use throughout this function.
let time_usize = time as usize;
// Update minimum if this one is fastest yet.
if self.min_time == 0 || time_usize < self.min_time {
self.min_time = time_usize;
}
// Update maximum if this one is slowest yet.
if time_usize > self.max_time {
self.max_time = time_usize;
}
// Update total_time, adding in this one.
self.total_time += time_usize;
// Each time we store a new time, increment counter by one.
self.counter += 1;
if success {
self.success_count += 1;
} else {
self.fail_count += 1;
}
// Round the time so we can combine similar times together and
// minimize required memory to store and push upstream to the parent.
let rounded_time = match time {
// No rounding for times 0-100 ms.
0..=100 => time_usize,
// Round to nearest 10 for times 100-500 ms.
101..=500 => ((time as f64 / 10.0).round() * 10.0) as usize,
// Round to nearest 100 for times 500-1000 ms.
501..=1000 => ((time as f64 / 100.0).round() * 10.0) as usize,
// Round to nearest 1000 for larger times.
_ => ((time as f64 / 1000.0).round() * 10.0) as usize,
};
let counter = match self.times.get(&rounded_time) {
// We've seen this time before, increment counter.
Some(c) => *c + 1,
// First time we've seen this time, initialize counter.
None => 1,
};
self.times.insert(rounded_time, counter);
debug!("incremented {} counter: {}", rounded_time, counter);
}
}
/// Aggregated per-scenario metrics updated each time a scenario is run.
///
/// [`ScenarioMetric`]s are sent by [`GooseUser`](../goose/struct.GooseUser.html)
/// threads to the Goose parent process where they are aggregated together into this
/// structure, and stored in [`GooseMetrics::transactions`].
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)]
pub struct ScenarioMetricAggregate {
/// An index into [`GooseAttack`](../struct.GooseAttack.html)`.scenarios`,
/// indicating which scenario this is.
pub index: usize,
/// The scenario name.
pub name: String,
/// List of users running this scenario.
pub users: HashSet<usize>,
/// Per-run-time counters, tracking how often scenario takes a given time to complete.
pub times: BTreeMap<usize, usize>,
/// The shortest run-time for this scenario.
pub min_time: usize,
/// The longest run-time for this scenario.
pub max_time: usize,
/// Total combined run-times for this scenario.
pub total_time: usize,
/// Total number of times scenario has run.
pub counter: usize,
}
impl ScenarioMetricAggregate {
/// Create a new ScenarioMetricAggregate.
pub(crate) fn new(index: usize, name: &str) -> Self {
ScenarioMetricAggregate {
index,
name: name.to_string(),
users: HashSet::new(),
times: BTreeMap::new(),
min_time: 0,
max_time: 0,
total_time: 0,
counter: 0,
}
}
/// Track scenario function elapsed time in milliseconds.
pub(crate) fn update(&mut self, time: u64, user: usize) {
// Record each different user running this scenario.
self.users.insert(user);
// Perform this conversion only once, then re-use throughout this function.
let time_usize = time as usize;
// Update minimum if this one is fastest yet.
if self.min_time == 0 || time_usize < self.min_time {
self.min_time = time_usize;
}
// Update maximum if this one is slowest yet.
if time_usize > self.max_time {
self.max_time = time_usize;
}
// Update total_time, adding in this one.
self.total_time += time_usize;
// Each time we store a new time, increment counter by one.
self.counter += 1;
// Round the time so we can combine similar times together and
// minimize required memory to store and push upstream to the parent.
let rounded_time = match time {
// No rounding for times 0-100 ms.
0..=100 => time_usize,
// Round to nearest 10 for times 100-500 ms.
101..=500 => ((time as f64 / 10.0).round() * 10.0) as usize,
// Round to nearest 100 for times 500-1000 ms.
501..=1000 => ((time as f64 / 100.0).round() * 10.0) as usize,
// Round to nearest 1000 for larger times.
_ => ((time as f64 / 1000.0).round() * 10.0) as usize,
};
let counter = match self.times.get(&rounded_time) {
// We've seen this time before, increment counter.
Some(c) => *c + 1,
// First time we've seen this time, initialize counter.
None => 1,
};
self.times.insert(rounded_time, counter);
debug!("incremented {} counter: {}", rounded_time, counter);
}
}
/// All metrics optionally collected during a Goose load test.
///
/// By default, Goose collects metrics during a load test in a `GooseMetrics` object
/// that is returned by
/// [`GooseAttack::execute()`](../struct.GooseAttack.html#method.execute) when a load
/// test finishes.
///
/// # Example
/// ```rust
/// use goose::prelude::*;
///
/// #[tokio::main]
/// async fn main() -> Result<(), GooseError> {
/// let goose_metrics: GooseMetrics = GooseAttack::initialize()?
/// .register_scenario(scenario!("ExampleUsers")
/// .register_transaction(transaction!(example_transaction))
/// )
/// // Set a default host so the load test will start.
/// .set_default(GooseDefault::Host, "http://localhost/")?
/// // Set a default run time so this test runs to completion.
/// .set_default(GooseDefault::RunTime, 1)?
/// .execute()
/// .await?;
///
/// // It is now possible to do something with the metrics collected by Goose.
/// // For now, we'll just pretty-print the entire object.
/// println!("{:#?}", goose_metrics);
///
/// /**
/// // For example:
/// $ cargo run -- -H http://example.com -u1 -t1
/// GooseMetrics {
/// hash: 0,
/// started: Some(
/// 2021-06-15T09:32:49.888147+02:00,
/// ),
/// duration: 1,
/// users: 1,
/// requests: {
/// "GET /": GooseRequestMetricAggregate {
/// path: "/",
/// method: Get,
/// response_times: {
/// 3: 14,
/// 4: 163,
/// 5: 36,
/// 6: 8,
/// },
/// min_response_time: 3,
/// max_response_time: 6,
/// total_response_time: 922,
/// response_time_counter: 221,
/// status_code_counts: {},
/// success_count: 0,
/// fail_count: 221,
/// load_test_hash: 0,
/// },
/// },
/// transactions: [
/// [
/// TransactionMetricAggregate {
/// scenario_index: 0,
/// scenario_name: "ExampleUsers",
/// transaction_index: 0,
/// transaction_name: "",
/// times: {
/// 3: 14,
/// 4: 161,
/// 5: 38,
/// 6: 8,
/// },
/// min_time: 3,
/// max_time: 6,
/// total_time: 924,
/// counter: 221,