-
Notifications
You must be signed in to change notification settings - Fork 10
/
networkQuality.go
1305 lines (1159 loc) · 46.3 KB
/
networkQuality.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
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
/*
* This file is part of Go Responsiveness.
*
* Go Responsiveness is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software Foundation,
* either version 2 of the License, or (at your option) any later version.
* Go Responsiveness 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with Go Responsiveness. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bytes"
"context"
"flag"
"fmt"
"net/url"
"os"
"runtime/pprof"
"strings"
"time"
"github.com/network-quality/goresponsiveness/ccw"
"github.com/network-quality/goresponsiveness/config"
"github.com/network-quality/goresponsiveness/constants"
"github.com/network-quality/goresponsiveness/datalogger"
"github.com/network-quality/goresponsiveness/debug"
"github.com/network-quality/goresponsiveness/direction"
"github.com/network-quality/goresponsiveness/executor"
"github.com/network-quality/goresponsiveness/extendedstats"
"github.com/network-quality/goresponsiveness/lgc"
"github.com/network-quality/goresponsiveness/probe"
"github.com/network-quality/goresponsiveness/qualityattenuation"
"github.com/network-quality/goresponsiveness/rpm"
"github.com/network-quality/goresponsiveness/series"
"github.com/network-quality/goresponsiveness/stabilizer"
"github.com/network-quality/goresponsiveness/timeoutat"
"github.com/network-quality/goresponsiveness/utilities"
)
var (
// Variables to hold CLI arguments.
configHost = flag.String(
"config",
constants.DefaultConfigHost,
"name/IP of responsiveness configuration server.",
)
configPort = flag.Int(
"port",
constants.DefaultPortNumber,
"port number on which to access responsiveness configuration server.",
)
configPath = flag.String(
"path",
"config",
"path on the server to the configuration endpoint.",
)
configURL = flag.String(
"url",
"",
"configuration URL (takes precedence over other configuration parts)",
)
debugCliFlag = flag.Bool(
"debug",
constants.DefaultDebug,
"Enable debugging.",
)
rpmtimeout = flag.Int(
"rpm.timeout",
constants.DefaultTestTime,
"Maximum time (in seconds) to spend calculating RPM (i.e., total test time.).",
)
rpmmad = flag.Int(
"rpm.mad",
constants.SpecParameterCliOptionsDefaults.Mad,
"Moving average distance -- number of intervals considered during stability calculations.",
)
rpmid = flag.Int(
"rpm.id",
constants.SpecParameterCliOptionsDefaults.Id,
"Duration of the interval between re-evaluating the network conditions (in seconds).",
)
rpmtmp = flag.Uint(
"rpm.tmp",
constants.SpecParameterCliOptionsDefaults.Tmp,
"Percent of measurements to trim when calculating statistics about network conditions (between 0 and 100).",
)
rpmsdt = flag.Float64(
"rpm.sdt",
constants.SpecParameterCliOptionsDefaults.Sdt,
"Cutoff in the standard deviation of measured values about network conditions between unstable and stable.",
)
rpmmnp = flag.Int(
"rpm.mnp",
constants.SpecParameterCliOptionsDefaults.Mnp,
"Maximimum number of parallel connections to establish when attempting to reach working conditions.",
)
rpmmps = flag.Int(
"rpm.mps",
constants.SpecParameterCliOptionsDefaults.Mps,
"Maximimum number of probes to send per second.",
)
rpmptc = flag.Float64(
"rpm.ptc",
constants.SpecParameterCliOptionsDefaults.Ptc,
"Percentage of the (discovered) total network capacity that probes are allowed to consume.",
)
rpmp = flag.Int(
"rpm.p",
constants.SpecParameterCliOptionsDefaults.P,
"Percentile of results to consider when calculating responsiveness.",
)
sslKeyFileName = flag.String(
"ssl-key-file",
"",
"Store the per-session SSL key files in this file.",
)
profile = flag.String(
"profile",
"",
"Enable client runtime profiling and specify storage location. Disabled by default.",
)
calculateExtendedStats = flag.Bool(
"extended-stats",
false,
"Enable the collection and display of extended statistics -- may not be available on certain platforms.",
)
printQualityAttenuation = flag.Bool(
"quality-attenuation",
false,
"Print quality attenuation information.",
)
dataLoggerBaseFileName = flag.String(
"logger-filename",
"",
"Store granular information about tests results in files with this basename. Time and information type will be appended (before the first .) to create separate log files. Disabled by default.",
)
connectToAddr = flag.String(
"connect-to",
"",
"address (hostname or IP) to connect to (overriding DNS). Disabled by default.",
)
insecureSkipVerify = flag.Bool(
"insecure-skip-verify",
constants.DefaultInsecureSkipVerify,
"Enable server certificate validation.",
)
prometheusStatsFilename = flag.String(
"prometheus-stats-filename",
"",
"If filename specified, prometheus stats will be written. If specified file exists, it will be overwritten.",
)
showVersion = flag.Bool(
"version",
false,
"Show version.",
)
calculateRelativeRpm = flag.Bool(
"relative-rpm",
false,
"Calculate a relative RPM.",
)
withL4S = flag.Bool("with-l4s", false, "Use L4S (with default TCP prague congestion control algorithm.)")
withL4SAlgorithm = flag.String("with-l4s-algorithm", "", "Use L4S (with specified congestion control algorithm.)")
parallelTestExecutionPolicy = constants.DefaultTestExecutionPolicy
)
func main() {
// Add one final command-line argument
flag.BoolFunc("rpm.parallel", "Parallel test execution policy.", func(value string) error {
if value != "true" {
return fmt.Errorf("-parallel can only be used to enable parallel test execution policy")
}
parallelTestExecutionPolicy = executor.Parallel
return nil
})
flag.Parse()
if *showVersion {
fmt.Fprintf(os.Stdout, "goresponsiveness %s\n", utilities.GitVersion)
os.Exit(0)
}
var debugLevel debug.DebugLevel = debug.Error
if *debugCliFlag {
debugLevel = debug.Debug
}
specParameters, err := rpm.SpecParametersFromArguments(*rpmtimeout, *rpmmad, *rpmid,
*rpmtmp, *rpmsdt, *rpmmnp, *rpmmps, *rpmptc, *rpmp, parallelTestExecutionPolicy)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Error: There was an error configuring the test with user-supplied parameters: %v\n",
err,
)
os.Exit(1)
}
if debug.IsDebug(debugLevel) {
fmt.Printf("Running the test according to the following spec parameters:\n%v\n", specParameters.ToString())
}
var configHostPort string
// if user specified a full URL, use that and set the various parts we need out of it
if len(*configURL) > 0 {
parsedURL, err := url.ParseRequestURI(*configURL)
if err != nil {
fmt.Printf("Error: Could not parse %q: %s", *configURL, err)
os.Exit(1)
}
*configHost = parsedURL.Hostname()
*configPath = parsedURL.Path
// We don't explicitly care about configuring the *configPort.
configHostPort = parsedURL.Host // host or host:port
} else {
configHostPort = fmt.Sprintf("%s:%d", *configHost, *configPort)
}
// This is the overall operating context of the program. All other
// contexts descend from this one. Canceling this one cancels all
// the others.
operatingCtx, operatingCtxCancel := context.WithCancel(context.Background())
config := &config.Config{
ConnectToAddr: *connectToAddr,
}
if *calculateExtendedStats && !extendedstats.ExtendedStatsAvailable() {
*calculateExtendedStats = false
fmt.Fprintf(
os.Stderr,
"Warning: Calculation of extended statistics was requested but is not supported on this platform.\n",
)
}
var sslKeyFileConcurrentWriter *ccw.ConcurrentWriter = nil
if *sslKeyFileName != "" {
if sslKeyFileHandle, err := os.OpenFile(*sslKeyFileName, os.O_RDWR|os.O_CREATE, os.FileMode(0o600)); err != nil {
fmt.Printf("Could not open the requested SSL key logging file for writing: %v!\n", err)
sslKeyFileConcurrentWriter = nil
} else {
if err = utilities.SeekForAppend(sslKeyFileHandle); err != nil {
fmt.Printf("Could not seek to the end of the SSL key logging file: %v!\n", err)
sslKeyFileConcurrentWriter = nil
} else {
if debug.IsDebug(debugLevel) {
fmt.Printf("Doing SSL key logging through file %v\n", *sslKeyFileName)
}
sslKeyFileConcurrentWriter = ccw.NewConcurrentFileWriter(sslKeyFileHandle)
defer sslKeyFileHandle.Close()
}
}
}
var congestionControlChosen *string = nil
if *withL4S || *withL4SAlgorithm != "" {
congestionControlChosen = &constants.DefaultL4SCongestionControlAlgorithm
if *withL4SAlgorithm != "" {
congestionControlChosen = withL4SAlgorithm
}
}
if congestionControlChosen != nil && debug.IsDebug(debugLevel) {
fmt.Printf("Doing congestion control with the %v algorithm.\n", *congestionControlChosen)
}
if err := config.Get(configHostPort, *configPath, *insecureSkipVerify,
sslKeyFileConcurrentWriter); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
if err := config.IsValid(); err != nil {
fmt.Fprintf(
os.Stderr,
"Error: Invalid configuration returned from %s: %v\n",
config.Source,
err,
)
os.Exit(1)
}
if debug.IsDebug(debugLevel) {
fmt.Printf("Configuration: %s\n", config)
}
downloadDirection := direction.Direction{}
uploadDirection := direction.Direction{}
// User wants to log data
if *dataLoggerBaseFileName != "" {
var err error = nil
unique := time.Now().UTC().Format("01-02-2006-15-04-05")
dataLoggerDownloadThroughputFilename := utilities.FilenameAppend(
*dataLoggerBaseFileName,
"-throughput-download-"+unique,
)
dataLoggerUploadThroughputFilename := utilities.FilenameAppend(
*dataLoggerBaseFileName,
"-throughput-upload-"+unique,
)
dataLoggerDownloadGranularThroughputFilename := utilities.FilenameAppend(
*dataLoggerBaseFileName,
"-throughput-download-granular-"+unique,
)
dataLoggerUploadGranularThroughputFilename := utilities.FilenameAppend(
*dataLoggerBaseFileName,
"-throughput-upload-granular-"+unique,
)
dataLoggerSelfFilename := utilities.FilenameAppend(*dataLoggerBaseFileName, "-self-"+unique)
dataLoggerForeignFilename := utilities.FilenameAppend(
*dataLoggerBaseFileName,
"-foreign-"+unique,
)
selfProbeDataLogger, err := datalogger.CreateCSVDataLogger[probe.ProbeDataPoint](
dataLoggerSelfFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing self probe results (%s). Disabling functionality.\n",
dataLoggerSelfFilename,
)
selfProbeDataLogger = nil
}
uploadDirection.SelfProbeDataLogger = selfProbeDataLogger
downloadDirection.SelfProbeDataLogger = selfProbeDataLogger
foreignProbeDataLogger, err := datalogger.CreateCSVDataLogger[probe.ProbeDataPoint](
dataLoggerForeignFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing foreign probe results (%s). Disabling functionality.\n",
dataLoggerForeignFilename,
)
foreignProbeDataLogger = nil
}
uploadDirection.ForeignProbeDataLogger = foreignProbeDataLogger
downloadDirection.ForeignProbeDataLogger = foreignProbeDataLogger
downloadDirection.ThroughputDataLogger, err = datalogger.CreateCSVDataLogger[rpm.ThroughputDataPoint](
dataLoggerDownloadThroughputFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing download throughput results (%s). Disabling functionality.\n",
dataLoggerDownloadThroughputFilename,
)
downloadDirection.ThroughputDataLogger = nil
}
uploadDirection.ThroughputDataLogger, err = datalogger.CreateCSVDataLogger[rpm.ThroughputDataPoint](
dataLoggerUploadThroughputFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing upload throughput results (%s). Disabling functionality.\n",
dataLoggerUploadThroughputFilename,
)
uploadDirection.ThroughputDataLogger = nil
}
downloadDirection.GranularThroughputDataLogger, err = datalogger.CreateCSVDataLogger[rpm.GranularThroughputDataPoint](
dataLoggerDownloadGranularThroughputFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing download granular throughput results (%s). Disabling functionality.\n",
dataLoggerDownloadGranularThroughputFilename,
)
downloadDirection.GranularThroughputDataLogger = nil
}
uploadDirection.GranularThroughputDataLogger, err = datalogger.CreateCSVDataLogger[rpm.GranularThroughputDataPoint](
dataLoggerUploadGranularThroughputFilename,
)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Warning: Could not create the file for storing upload granular throughput results (%s). Disabling functionality.\n",
dataLoggerUploadGranularThroughputFilename,
)
uploadDirection.GranularThroughputDataLogger = nil
}
}
// If, for some reason, the data loggers are nil, make them Null Data Loggers so that we don't have conditional
// code later.
if downloadDirection.SelfProbeDataLogger == nil {
downloadDirection.SelfProbeDataLogger = datalogger.CreateNullDataLogger[probe.ProbeDataPoint]()
}
if uploadDirection.SelfProbeDataLogger == nil {
uploadDirection.SelfProbeDataLogger = datalogger.CreateNullDataLogger[probe.ProbeDataPoint]()
}
if downloadDirection.ForeignProbeDataLogger == nil {
downloadDirection.ForeignProbeDataLogger = datalogger.CreateNullDataLogger[probe.ProbeDataPoint]()
}
if uploadDirection.ForeignProbeDataLogger == nil {
uploadDirection.ForeignProbeDataLogger = datalogger.CreateNullDataLogger[probe.ProbeDataPoint]()
}
if downloadDirection.ThroughputDataLogger == nil {
downloadDirection.ThroughputDataLogger = datalogger.CreateNullDataLogger[rpm.ThroughputDataPoint]()
}
if uploadDirection.ThroughputDataLogger == nil {
uploadDirection.ThroughputDataLogger = datalogger.CreateNullDataLogger[rpm.ThroughputDataPoint]()
}
if downloadDirection.GranularThroughputDataLogger == nil {
downloadDirection.GranularThroughputDataLogger =
datalogger.CreateNullDataLogger[rpm.GranularThroughputDataPoint]()
}
if uploadDirection.GranularThroughputDataLogger == nil {
uploadDirection.GranularThroughputDataLogger =
datalogger.CreateNullDataLogger[rpm.GranularThroughputDataPoint]()
}
/*
* Create (and then, ironically, name) two anonymous functions that, when invoked,
* will create load-generating connections for upload/download
*/
downloadDirection.CreateLgdc = func() lgc.LoadGeneratingConnection {
lgd := lgc.NewLoadGeneratingConnectionDownload(config.Urls.LargeUrl,
sslKeyFileConcurrentWriter, config.ConnectToAddr, *insecureSkipVerify, congestionControlChosen)
return &lgd
}
uploadDirection.CreateLgdc = func() lgc.LoadGeneratingConnection {
lgu := lgc.NewLoadGeneratingConnectionUpload(config.Urls.UploadUrl,
sslKeyFileConcurrentWriter, config.ConnectToAddr, *insecureSkipVerify, congestionControlChosen)
return &lgu
}
downloadDirection.DirectionDebugging = debug.NewDebugWithPrefix(debugLevel, "download")
downloadDirection.ProbeDebugging = debug.NewDebugWithPrefix(debugLevel, "download probe")
uploadDirection.DirectionDebugging = debug.NewDebugWithPrefix(debugLevel, "upload")
uploadDirection.ProbeDebugging = debug.NewDebugWithPrefix(debugLevel, "upload probe")
downloadDirection.Lgcc = lgc.NewLoadGeneratingConnectionCollection()
uploadDirection.Lgcc = lgc.NewLoadGeneratingConnectionCollection()
uploadDirection.ExtendedStatsEligible = true
downloadDirection.ExtendedStatsEligible = true
generateSelfProbeConfiguration := func() probe.ProbeConfiguration {
return probe.ProbeConfiguration{
URL: config.Urls.SmallUrl,
ConnectToAddr: config.ConnectToAddr,
InsecureSkipVerify: *insecureSkipVerify,
CongestionControl: congestionControlChosen,
}
}
generateForeignProbeConfiguration := func() probe.ProbeConfiguration {
return probe.ProbeConfiguration{
URL: config.Urls.SmallUrl,
ConnectToAddr: config.ConnectToAddr,
InsecureSkipVerify: *insecureSkipVerify,
CongestionControl: congestionControlChosen,
}
}
downloadDirection.DirectionLabel = "Download"
uploadDirection.DirectionLabel = "Upload"
directions := []*direction.Direction{&downloadDirection, &uploadDirection}
// print the banner
dt := time.Now().UTC()
fmt.Printf(
"%s UTC Go Responsiveness to %s...\n",
dt.Format("01-02-2006 15:04:05"),
configHostPort,
)
if len(*profile) != 0 {
f, err := os.Create(*profile)
if err != nil {
fmt.Fprintf(
os.Stderr,
"Error: Profiling requested but could not open the log file ( %s ) for writing: %v\n",
*profile,
err,
)
os.Exit(1)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
globalNumericBucketGenerator := series.NewNumericBucketGenerator[uint64](0)
var baselineRpm *rpm.Rpm[float64] = nil
if *calculateRelativeRpm {
baselineForeignDownloadRtts := series.NewWindowSeries[float64, uint64](series.Forever, 0)
baselineFauxSelfDownloadRtts := series.NewWindowSeries[float64, uint64](series.Forever, 0)
baselineStableResponsiveness := false
baselineProbeDebugging := debug.NewDebugWithPrefix(debugLevel, "Baseline RPM Calculation Probe")
timeoutDuration := specParameters.TestTimeout
timeoutAbsoluteTime := time.Now().Add(timeoutDuration)
timeoutChannel := timeoutat.TimeoutAt(
operatingCtx,
timeoutAbsoluteTime,
debugLevel,
)
if debug.IsDebug(debugLevel) {
fmt.Printf("Baseline RPM calculation will end no later than %v\n", timeoutAbsoluteTime)
}
baselineProberOperatorCtx, baselineProberOperatorCtxCancel := context.WithCancel(operatingCtx)
// This context is used to control the network activity (i.e., it controls all
// the connections that are open to do load generation and probing).
baselineNetworkActivityCtx, baselineNetworkActivityCtxCancel := context.WithCancel(operatingCtx)
baselineResponsivenessStabilizerDebugConfig :=
debug.NewDebugWithPrefix(debug.Debug, "Baseline Responsiveness Stabilizer")
baselineResponsivenessStabilizerDebugLevel := debug.Error
if *debugCliFlag {
baselineResponsivenessStabilizerDebugLevel = debug.Debug
}
baselineResponsivenessStabilizer := stabilizer.NewStabilizer[int64, uint64](
specParameters.MovingAvgDist, specParameters.StdDevTolerance,
specParameters.TrimmedMeanPct, "milliseconds",
baselineResponsivenessStabilizerDebugLevel,
baselineResponsivenessStabilizerDebugConfig)
baselineStabilityCheckTime := time.Now().Add(specParameters.EvalInterval)
baselineStabilityCheckTimeChannel := timeoutat.TimeoutAt(
operatingCtx,
baselineStabilityCheckTime,
debugLevel,
)
responsivenessStabilizationCommunicationChannel := rpm.ResponsivenessProber(
baselineProberOperatorCtx,
baselineNetworkActivityCtx,
generateForeignProbeConfiguration,
generateSelfProbeConfiguration,
nil,
&globalNumericBucketGenerator,
lgc.LGC_DOWN,
specParameters.ProbeInterval,
sslKeyFileConcurrentWriter,
*calculateExtendedStats,
baselineProbeDebugging,
)
lowerBucketBound, upperBucketBound := uint64(0), uint64(0)
baseline_responsiveness_timeout:
for !baselineStableResponsiveness {
select {
case probeMeasurement := <-responsivenessStabilizationCommunicationChannel:
{
switch probeMeasurement.Type {
case series.SeriesMessageReserve:
{
bucket := probeMeasurement.Bucket
if *debugCliFlag {
fmt.Printf("baseline: Reserving a responsiveness bucket with id %v.\n", bucket)
}
baselineResponsivenessStabilizer.Reserve(bucket)
baselineForeignDownloadRtts.Reserve(bucket)
baselineFauxSelfDownloadRtts.Reserve(bucket)
}
case series.SeriesMessageMeasure:
{
bucket := probeMeasurement.Bucket
measurement := utilities.GetSome(probeMeasurement.Measure)
foreignDataPoint := measurement.Foreign
if *debugCliFlag {
fmt.Printf(
"baseline: Filling a responsiveness bucket with id %v with value %v.\n", bucket, measurement)
}
baselineResponsivenessStabilizer.AddMeasurement(
bucket, foreignDataPoint.Duration.Milliseconds())
if err := baselineForeignDownloadRtts.Fill(
bucket, foreignDataPoint.Duration.Seconds()); err != nil {
fmt.Printf("Attempting to fill a bucket (id: %d) that does not exist (baselineForeignDownloadRtts)\n", bucket)
}
if err := baselineFauxSelfDownloadRtts.Fill(
bucket, foreignDataPoint.Duration.Seconds()/3.0); err != nil {
fmt.Printf("Attempting to fill a bucket (id: %d) that does not exist (baselineFauxSelfDownloadRtts)\n", bucket)
}
}
}
}
case <-timeoutChannel:
{
break baseline_responsiveness_timeout
}
case <-baselineStabilityCheckTimeChannel:
{
if *debugCliFlag {
fmt.Printf("baseline responsiveness stability interval is complete.\n")
}
baselineStabilityCheckTime = time.Now().Add(specParameters.EvalInterval)
baselineStabilityCheckTimeChannel = timeoutat.TimeoutAt(
operatingCtx,
baselineStabilityCheckTime,
debugLevel,
)
// Check stabilization immediately -- this could change if we wait. Not sure if the immediacy
// is *actually* important, but it can't hurt?
baselineStableResponsiveness = baselineResponsivenessStabilizer.IsStable()
if *debugCliFlag {
fmt.Printf(
"baseline responsiveness is instantaneously %s.\n",
utilities.Conditional(baselineStableResponsiveness, "stable", "unstable"))
}
// Do not tick an interval if we are stable. Doing so would expel one of the
// intervals that we need for our RPM calculations!
if !baselineStableResponsiveness {
baselineResponsivenessStabilizer.Interval()
}
}
}
}
baselineNetworkActivityCtxCancel()
baselineProberOperatorCtxCancel()
lowerBucketBound, upperBucketBound = baselineResponsivenessStabilizer.GetBounds()
if *debugCliFlag {
fmt.Printf("Baseline responsiveness stablizer bucket bounds: (%v, %v)\n", lowerBucketBound, upperBucketBound)
}
for _, label := range []string{"Unbounded ", ""} {
baselineRpm = rpm.CalculateRpm(baselineFauxSelfDownloadRtts,
baselineForeignDownloadRtts, specParameters.TrimmedMeanPct, specParameters.Percentile)
fmt.Printf("%vBaseline RPM: %5.0f (P%d)\n", label, baselineRpm.PNRpm, specParameters.Percentile)
fmt.Printf("%vBaseline RPM: %5.0f (Single-Sided %v%% Trimmed Mean)\n",
label, baselineRpm.MeanRpm, specParameters.TrimmedMeanPct)
baselineFauxSelfDownloadRtts.SetTrimmingBucketBounds(lowerBucketBound, upperBucketBound)
baselineForeignDownloadRtts.SetTrimmingBucketBounds(lowerBucketBound, upperBucketBound)
}
}
var selfRttsQualityAttenuation *qualityattenuation.SimpleQualityAttenuation = nil
if *printQualityAttenuation {
selfRttsQualityAttenuation = qualityattenuation.NewSimpleQualityAttenuation()
}
directionExecutionUnits := make([]executor.ExecutionUnit, 0)
for _, direction := range directions {
// Make a copy here to make sure that we do not get go-wierdness in our closure (see https://github.com/golang/go/discussions/56010).
direction := direction
directionExecutionUnit := func() {
timeoutDuration := specParameters.TestTimeout
timeoutAbsoluteTime := time.Now().Add(timeoutDuration)
timeoutChannel := timeoutat.TimeoutAt(
operatingCtx,
timeoutAbsoluteTime,
debugLevel,
)
if debug.IsDebug(debugLevel) {
fmt.Printf("%s Test will end no later than %v\n",
direction.DirectionLabel, timeoutAbsoluteTime)
}
throughputOperatorCtx, throughputOperatorCtxCancel := context.WithCancel(operatingCtx)
proberOperatorCtx, proberOperatorCtxCancel := context.WithCancel(operatingCtx)
// This context is used to control the network activity (i.e., it controls all
// the connections that are open to do load generation and probing). Cancelling this context will close
// all the network connections that are responsible for generating the load.
probeNetworkActivityCtx, probeNetworkActivityCtxCancel := context.WithCancel(operatingCtx)
throughputCtx, throughputCtxCancel := context.WithCancel(operatingCtx)
direction.ThroughputActivityCtx, direction.ThroughputActivityCtxCancel = &throughputCtx, &throughputCtxCancel
lgStabilizationCommunicationChannel := rpm.LoadGenerator(
throughputOperatorCtx,
*direction.ThroughputActivityCtx,
specParameters.EvalInterval,
direction.CreateLgdc,
&direction.Lgcc,
&globalNumericBucketGenerator,
specParameters.MaxParallelConns,
specParameters.EvalInterval,
*calculateExtendedStats,
direction.DirectionDebugging,
)
throughputStabilizerDebugConfig := debug.NewDebugWithPrefix(debug.Debug,
fmt.Sprintf("%v Throughput Stabilizer", direction.DirectionLabel))
downloadThroughputStabilizerDebugLevel := debug.Error
if *debugCliFlag {
downloadThroughputStabilizerDebugLevel = debug.Debug
}
throughputStabilizer := stabilizer.NewStabilizer[float64, uint64](
specParameters.MovingAvgDist, specParameters.StdDevTolerance, 0, "bytes",
downloadThroughputStabilizerDebugLevel, throughputStabilizerDebugConfig)
responsivenessStabilizerDebugConfig := debug.NewDebugWithPrefix(debug.Debug,
fmt.Sprintf("%v Responsiveness Stabilizer", direction.DirectionLabel))
responsivenessStabilizerDebugLevel := debug.Error
if *debugCliFlag {
responsivenessStabilizerDebugLevel = debug.Debug
}
responsivenessStabilizer := stabilizer.NewStabilizer[int64, uint64](
specParameters.MovingAvgDist, specParameters.StdDevTolerance,
specParameters.TrimmedMeanPct, "milliseconds",
responsivenessStabilizerDebugLevel, responsivenessStabilizerDebugConfig)
// For later debugging output, record the last throughputs on load-generating connectings
// and the number of open connections.
lastThroughputRate := float64(0)
lastThroughputOpenConnectionCount := int(0)
stabilityCheckTime := time.Now().Add(specParameters.EvalInterval)
stabilityCheckTimeChannel := timeoutat.TimeoutAt(
operatingCtx,
stabilityCheckTime,
debugLevel,
)
lg_timeout:
for !direction.StableThroughput {
select {
case throughputMeasurement := <-lgStabilizationCommunicationChannel:
{
switch throughputMeasurement.Type {
case series.SeriesMessageReserve:
{
throughputStabilizer.Reserve(throughputMeasurement.Bucket)
if *debugCliFlag {
fmt.Printf(
"%s: Reserving a throughput bucket with id %v.\n",
direction.DirectionLabel, throughputMeasurement.Bucket)
}
}
case series.SeriesMessageMeasure:
{
bucket := throughputMeasurement.Bucket
measurement := utilities.GetSome(throughputMeasurement.Measure)
throughputStabilizer.AddMeasurement(bucket, measurement.Throughput)
direction.ThroughputDataLogger.LogRecord(measurement)
for _, v := range measurement.GranularThroughputDataPoints {
v.Direction = "Download"
direction.GranularThroughputDataLogger.LogRecord(v)
}
lastThroughputRate = measurement.Throughput
lastThroughputOpenConnectionCount = measurement.Connections
}
}
}
case <-stabilityCheckTimeChannel:
{
if *debugCliFlag {
fmt.Printf(
"%v throughput stability interval is complete.\n", direction.DirectionLabel)
}
stabilityCheckTime = time.Now().Add(specParameters.EvalInterval)
stabilityCheckTimeChannel = timeoutat.TimeoutAt(
operatingCtx,
stabilityCheckTime,
debugLevel,
)
direction.StableThroughput = throughputStabilizer.IsStable()
if *debugCliFlag {
fmt.Printf(
"%v is instantaneously %s.\n", direction.DirectionLabel,
utilities.Conditional(direction.StableThroughput, "stable", "unstable"))
}
throughputStabilizer.Interval()
}
case <-timeoutChannel:
{
break lg_timeout
}
}
}
if direction.StableThroughput {
if *debugCliFlag {
fmt.Printf("Throughput is stable; beginning responsiveness testing.\n")
}
} else {
fmt.Fprintf(os.Stderr, "Warning: Throughput stability could not be reached. Making the test 15 seconds longer to calculate speculative RPM results.\n")
speculativeTimeoutDuration := time.Second * 15
speculativeAbsoluteTimeoutTime := time.Now().Add(speculativeTimeoutDuration)
timeoutChannel = timeoutat.TimeoutAt(
operatingCtx,
speculativeAbsoluteTimeoutTime,
debugLevel,
)
}
direction.SelfRtts = series.NewWindowSeries[float64, uint64](series.Forever, 0)
direction.ForeignRtts = series.NewWindowSeries[float64, uint64](series.Forever, 0)
responsivenessStabilizationCommunicationChannel := rpm.ResponsivenessProber(
proberOperatorCtx,
probeNetworkActivityCtx,
generateForeignProbeConfiguration,
generateSelfProbeConfiguration,
&direction.Lgcc,
&globalNumericBucketGenerator,
direction.CreateLgdc().Direction(), // TODO: This could be better!
specParameters.ProbeInterval,
sslKeyFileConcurrentWriter,
*calculateExtendedStats,
direction.ProbeDebugging,
)
responsiveness_timeout:
for !direction.StableResponsiveness {
select {
case probeMeasurement := <-responsivenessStabilizationCommunicationChannel:
{
switch probeMeasurement.Type {
case series.SeriesMessageReserve:
{
bucket := probeMeasurement.Bucket
if *debugCliFlag {
fmt.Printf(
"%s: Reserving a responsiveness bucket with id %v.\n", direction.DirectionLabel, bucket)
}
responsivenessStabilizer.Reserve(bucket)
direction.ForeignRtts.Reserve(bucket)
direction.SelfRtts.Reserve(bucket)
}
case series.SeriesMessageMeasure:
{
bucket := probeMeasurement.Bucket
measurement := utilities.GetSome(probeMeasurement.Measure)
foreignDataPoint := measurement.Foreign
selfDataPoint := measurement.Self
if *debugCliFlag {
fmt.Printf(
"%s: Filling a responsiveness bucket with id %v with value %v.\n",
direction.DirectionLabel, bucket, measurement)
}
responsivenessStabilizer.AddMeasurement(bucket,
(foreignDataPoint.Duration + selfDataPoint.Duration).Milliseconds())
if err := direction.SelfRtts.Fill(bucket,
selfDataPoint.Duration.Seconds()); err != nil {
fmt.Printf("Attempting to fill a bucket (id: %d) that does not exist (perDirectionSelfRtts)\n", bucket)
}
if err := direction.ForeignRtts.Fill(bucket,
foreignDataPoint.Duration.Seconds()); err != nil {
fmt.Printf("Attempting to fill a bucket (id: %d) that does not exist (perDirectionForeignRtts)\n", bucket)
}
if selfRttsQualityAttenuation != nil {
selfRttsQualityAttenuation.AddSample(selfDataPoint.Duration.Seconds())
}
direction.ForeignProbeDataLogger.LogRecord(*foreignDataPoint)
direction.SelfProbeDataLogger.LogRecord(*selfDataPoint)
}
}
}
case throughputMeasurement := <-lgStabilizationCommunicationChannel:
{
switch throughputMeasurement.Type {
case series.SeriesMessageReserve:
{
// We are no longer tracking stability, so reservation messages are useless!
if *debugCliFlag {
fmt.Printf(
"%s: Discarding a throughput bucket with id %v when ascertaining responsiveness.\n",
direction.DirectionLabel, throughputMeasurement.Bucket)
}
}
case series.SeriesMessageMeasure:
{
measurement := utilities.GetSome(throughputMeasurement.Measure)
if *debugCliFlag {
fmt.Printf("Adding a throughput measurement (while ascertaining responsiveness).\n")
}
// There may be more than one round trip accumulated together. If that is the case,
direction.ThroughputDataLogger.LogRecord(measurement)
for _, v := range measurement.GranularThroughputDataPoints {
v.Direction = direction.DirectionLabel
direction.GranularThroughputDataLogger.LogRecord(v)
}
lastThroughputRate = measurement.Throughput
lastThroughputOpenConnectionCount = measurement.Connections
}
}
}
case <-timeoutChannel:
{
if *debugCliFlag {
fmt.Printf("%v responsiveness seeking interval has expired.\n", direction.DirectionLabel)
}
break responsiveness_timeout
}
case <-stabilityCheckTimeChannel:
{
if *debugCliFlag {
fmt.Printf(
"%v responsiveness stability interval is complete.\n", direction.DirectionLabel)
}
stabilityCheckTime = time.Now().Add(specParameters.EvalInterval)
stabilityCheckTimeChannel = timeoutat.TimeoutAt(
operatingCtx,
stabilityCheckTime,
debugLevel,
)
// Check stabilization immediately -- this could change if we wait. Not sure if the immediacy
// is *actually* important, but it can't hurt?
direction.StableResponsiveness = responsivenessStabilizer.IsStable()
if *debugCliFlag {
fmt.Printf(
"%v responsiveness is instantaneously %s.\n", direction.DirectionLabel,
utilities.Conditional(direction.StableResponsiveness, "stable", "unstable"))
}
// Do not tick an interval if we are stable. Doing so would expel one of the
// intervals that we need for our RPM calculations!
if !direction.StableResponsiveness {
responsivenessStabilizer.Interval()
}
}
}
}
// Did the test run to stability?
testRanToStability := direction.StableThroughput && direction.StableResponsiveness
if *debugCliFlag {
fmt.Printf("Stopping all the load generating data generators (stability: %s).\n",
utilities.Conditional(testRanToStability, "success", "failure"))
}
/* At this point there are
1. Load generators running
-- uploadLoadGeneratorOperatorCtx
-- downloadLoadGeneratorOperatorCtx
2. Network connections opened by those load generators:
-- lgNetworkActivityCtx
3. Probes
-- proberCtx
*/
// First, stop the load generator and the probe operators (but *not* the network activity)
proberOperatorCtxCancel()
throughputOperatorCtxCancel()
// Second, calculate the extended stats (if the user requested and they are available for the direction)
extendedStats := extendedstats.AggregateExtendedStats{}
if *calculateExtendedStats && direction.ExtendedStatsEligible {
if extendedstats.ExtendedStatsAvailable() {
func() {
// Put inside an IIFE so that we can use a defer!
direction.Lgcc.Lock.Lock()
defer direction.Lgcc.Lock.Unlock()
lgcCount, err := direction.Lgcc.Len()
if err != nil {
fmt.Fprintf(