forked from dotnet/crank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
3006 lines (2424 loc) · 124 KB
/
Program.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Crank.Models;
using Microsoft.Crank.Controller.Serializers;
using Fluid;
using Fluid.Values;
using McMaster.Extensions.CommandLineUtils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using YamlDotNet.Serialization;
using System.Text;
using Manatee.Json.Schema;
using Manatee.Json;
using Jint;
using System.Security.Cryptography;
using Microsoft.Azure.Relay;
namespace Microsoft.Crank.Controller
{
public class Program
{
private static readonly HttpClient _httpClient;
private static readonly HttpClientHandler _httpClientHandler;
private static readonly FluidParser FluidParser = new FluidParser();
private static string _tableName = "Benchmarks";
private static string _sqlConnectionString = "";
private const string DefaultBenchmarkDotNetArguments = "--inProcess --cli {{benchmarks-cli}} --join --exporters briefjson markdown";
// Default to arguments which should be sufficient for collecting trace of default Plaintext run
// c.f. https://github.com/Microsoft/perfview/blob/main/src/PerfView/CommandLineArgs.cs
private const string _defaultTraceArguments = "BufferSizeMB=1024;CircularMB=4096;TplEvents=None;Providers=Microsoft-Diagnostics-DiagnosticSource:0:0;KernelEvents=default+ThreadTime-NetworkTCPIP";
private static ScriptConsole _scriptConsole = new ScriptConsole();
private static CommandOption
_configOption,
_scenarioOption,
_jobOption,
_profileOption,
_jsonOption,
_csvOption,
_compareOption,
_variableOption,
_sqlConnectionStringOption,
_sqlTableOption,
_relayConnectionStringOption,
_sessionOption,
_descriptionOption,
_propertyOption,
_excludeMetadataOption,
_excludeMeasurementsOption,
_autoflushOption,
_repeatOption,
_spanOption,
_renderChartOption,
_chartTypeOption,
_chartScaleOption,
_iterationsOption,
_intervalOption,
_verboseOption,
_quietOption,
_scriptOption,
_excludeOption,
_excludeOrderOption,
_debugOption
;
// The dynamic arguments that will alter the configurations
private static List<KeyValuePair<string, string>> Arguments = new List<KeyValuePair<string, string>>();
private static Dictionary<string, string> _deprecatedArguments = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "--output", "--json" }, { "-o", "-j" } // todo: remove in subsequent version prefix
};
private static Dictionary<string, string> _synonymArguments = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
};
static Program()
{
// Configuring the http client to trust the self-signed certificate
_httpClientHandler = new HttpClientHandler();
_httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
_httpClientHandler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
_httpClient = new HttpClient(_httpClientHandler);
TemplateOptions.Default.MemberAccessStrategy.Register<JObject, object>((obj, name) => obj[name]);
TemplateOptions.Default.ValueConverters.Add(x => x is JObject o ? new ObjectValue(o) : null);
TemplateOptions.Default.ValueConverters.Add(x => x is JValue v ? v.Value : null);
TemplateOptions.Default.ValueConverters.Add(x => x is DateTime v ? new ObjectValue(v) : null);
}
private static char[] barChartChars = " ▁▂▃▄▅▆▇█".ToCharArray();
private static char[] hexChartChars = " 123456789ABCDEF".ToCharArray();
public static int Main(string[] args)
{
// Replace deprecated arguments with new ones
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (_deprecatedArguments.TryGetValue(arg, out var mappedArg))
{
Log.WriteWarning($"WARNING: '{arg}' has been deprecated, in the future please use '{mappedArg}'.");
args[i] = mappedArg;
}
else if (_synonymArguments.TryGetValue(arg, out var synonymArg))
{
// We don't need to display a warning
args[i] = synonymArg;
}
}
var app = new CommandLineApplication()
{
Name = "crank",
FullName = "Crank Benchmarks Controller",
ExtendedHelpText = Documentation.Content,
Description = "The Crank controller orchestrates benchmark jobs on Crank agents.",
ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated,
OptionsComparison = StringComparison.OrdinalIgnoreCase,
};
app.HelpOption("-?|-h|--help");
_configOption = app.Option("-c|--config", "Configuration file or url", CommandOptionType.MultipleValue);
_scenarioOption = app.Option("-s|--scenario", "Scenario to execute", CommandOptionType.SingleValue);
_jobOption = app.Option("-j|--job", "Name of job to define", CommandOptionType.MultipleValue);
_profileOption = app.Option("--profile", "Profile name", CommandOptionType.MultipleValue);
_scriptOption = app.Option("--script", "Execute a named script available in the configuration files. Can be used multiple times.", CommandOptionType.MultipleValue);
_jsonOption = app.Option("-j|--json", "Saves the results as json in the specified file.", CommandOptionType.SingleValue);
_csvOption = app.Option("--csv", "Saves the results as csv in the specified file.", CommandOptionType.SingleValue);
_compareOption = app.Option("--compare", "An optional filename to compare the results to. Can be used multiple times.", CommandOptionType.MultipleValue);
_variableOption = app.Option("--variable", "Variable", CommandOptionType.MultipleValue);
_sqlConnectionStringOption = app.Option("--sql",
"Connection string or environment variable name of the SQL Server Database to store results in.", CommandOptionType.SingleValue);
_sqlTableOption = app.Option("--table",
"Table name or environment variable name of the SQL table to store results in.", CommandOptionType.SingleValue);
_relayConnectionStringOption = app.Option("--relay", "Connection string or environment variable name of the Azure Relay namespace used to access the Crank Agent endpoints. e.g., 'Endpoint=sb://mynamespace.servicebus.windows.net;...', 'MY_AZURE_RELAY_ENV'", CommandOptionType.SingleValue);
_sessionOption = app.Option("--session", "A logical identifier to group related jobs.", CommandOptionType.SingleValue);
_descriptionOption = app.Option("--description", "A string describing the job.", CommandOptionType.SingleValue);
_propertyOption = app.Option("-p|--property", "Some custom key/value that will be added to the results, .e.g. --property arch=arm --property os=linux", CommandOptionType.MultipleValue);
_excludeMeasurementsOption = app.Option("--no-measurements", "Remove all measurements from the stored results. For instance, all samples of a measure won't be stored, only the final value.", CommandOptionType.SingleOrNoValue);
_excludeMetadataOption = app.Option("--no-metadata", "Remove all metadata from the stored results. The metadata is only necessary for being to generate friendly outputs.", CommandOptionType.SingleOrNoValue);
_autoflushOption = app.Option("--auto-flush", "Runs a single long-running job and flushes measurements automatically.", CommandOptionType.NoValue);
_repeatOption = app.Option("--repeat", "The job to repeat using the '--span' or '--iterations' argument.", CommandOptionType.SingleValue);
_spanOption = app.Option("--span", "The duration while the job is repeated.", CommandOptionType.SingleValue);
_renderChartOption = app.Option("--chart", "Renders a chart for multi-value results.", CommandOptionType.NoValue);
_chartTypeOption = app.Option("--chart-type", "Type of chart to render. Values are 'bar' (default) or 'hex'", CommandOptionType.SingleValue);
_chartScaleOption = app.Option("--chart-scale", "Scale for chart. Values are 'off' (default) or 'auto'. When scale is off, the min value starts at 0.", CommandOptionType.SingleValue);
_iterationsOption = app.Option("-i|--iterations", "The number of iterations.", CommandOptionType.SingleValue);
_intervalOption = app.Option("-m|--interval", "The measurements interval in seconds. Default is 1.", CommandOptionType.SingleValue);
_verboseOption = app.Option("-v|--verbose", "Verbose output", CommandOptionType.NoValue);
_quietOption = app.Option("--quiet", "Quiet output, only the results are displayed", CommandOptionType.NoValue);
_excludeOption = app.Option("-x|--exclude", "Excludes the specified number of high and low results, e.g., 1, 1:0 (exclude the lowest), 0:3 (exclude the 3 highest)", CommandOptionType.SingleValue);
_excludeOrderOption = app.Option("-xo|--exclude-order", "The result to use to detect the high and low results, e.g., 'load:http/rps/mean'", CommandOptionType.SingleValue);
_debugOption = app.Option("-d|--debug", "Saves the final configuration to a file and skips the execution of the benchmark, e.g., '-d debug.json'", CommandOptionType.SingleValue);
app.Command("compare", compareCmd =>
{
compareCmd.Description = "Compares result files";
var files = compareCmd.Argument("Files", "Files to compare", multipleValues: true).IsRequired();
compareCmd.OnExecute(() =>
{
return ResultComparer.Compare(files.Values);
});
});
// Store arguments before the dynamic ones are removed
var commandLineArguments = String.Join(' ', args.Where(x => !String.IsNullOrWhiteSpace(x)).Select(x => x.StartsWith('-') ? x : '"' + x + '"'));
// Extract dynamic arguments
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.StartsWith("--") && !app.Options.Any(option => arg.StartsWith("--" + option.LongName)))
{
// Remove this argument from the command line
args[i] = "";
// Dynamic arguments always come in pairs
if (i + 1 < args.Length)
{
Arguments.Add(KeyValuePair.Create(arg.Substring(2), args[i + 1]));
args[i + 1] = "";
i++;
}
}
}
app.OnExecuteAsync(async (t) =>
{
Log.IsQuiet = _quietOption.HasValue();
Log.IsVerbose = _verboseOption.HasValue();
var session = _sessionOption.Value();
var iterations = 1;
var exclude = ExcludeOptions.Empty;
var span = TimeSpan.Zero;
if (string.IsNullOrEmpty(session))
{
session = Guid.NewGuid().ToString("n");
}
var description = _descriptionOption.Value() ?? "";
var interval = 1;
if (_intervalOption.HasValue())
{
if (!int.TryParse(_intervalOption.Value(), out interval))
{
Console.WriteLine($"The option --interval must be a valid integer.");
return -1;
}
else
{
if (interval < 1)
{
Console.WriteLine($"The option --interval must be greater than 1.");
return -1;
}
}
}
if (_iterationsOption.HasValue())
{
if (_spanOption.HasValue())
{
Console.WriteLine($"The options --iterations and --span can't be used together.");
return -1;
}
if (!Int32.TryParse(_iterationsOption.Value(), out iterations) || iterations < 1)
{
Console.WriteLine($"Invalid value for iterations arguments. A positive integer was expected.");
return -1;
}
}
var excludeOptions =
Convert.ToInt32(_excludeOption.HasValue())
+ Convert.ToInt32(_excludeOrderOption.HasValue())
;
if (_excludeOrderOption.HasValue() && !_excludeOption.HasValue())
{
Console.WriteLine("--exclude [hi:low] needs to be set when using --exclude-order.");
return -1;
}
if (_excludeOption.HasValue() && !_excludeOrderOption.HasValue())
{
Console.WriteLine("--exclude can't be used without --exclude-order. e.g., --exclude-order load:http/rps/mean");
return -1;
}
int excludeLow = 0, excludeHigh = 0;
if (_excludeOption.HasValue())
{
if (!_iterationsOption.HasValue())
{
Console.WriteLine("The option --exclude can only be used with --iterations.");
return -1;
}
var segments = _excludeOption.Value().Split(':', 2, StringSplitOptions.RemoveEmptyEntries);
if (segments.Length == 1)
{
if (!Int32.TryParse(segments[0], out excludeLow) || excludeLow < 0)
{
Console.WriteLine($"Invalid value for --exclude <x> option. An integer value greater or equal to 0 was expected.");
return -1;
}
excludeHigh = excludeLow;
}
else if (segments.Length == 2)
{
if (!Int32.TryParse(segments[0], out excludeLow) || excludeLow < 0)
{
Console.WriteLine($"Invalid value for --exclude <low:high> option. An integer value greater or equal to 0 was expected.");
return -1;
}
if (!Int32.TryParse(segments[1], out excludeHigh) || excludeHigh < 0)
{
Console.WriteLine($"Invalid value for --exclude <low:high> option. An integer value greater or equal to 0 was expected.");
return -1;
}
}
if (iterations <= excludeLow + excludeHigh)
{
Console.WriteLine($"Invalid value for --exclude option. Can't exclude more results than the iterations.");
return -1;
}
var excludeOrder = _excludeOrderOption.Value().Split(':', 2, StringSplitOptions.RemoveEmptyEntries);
if (excludeOrder.Length != 2)
{
Console.WriteLine("The option -xo|--exclude-order format is <job>:<result>, e.g., 'load:http/rps/mean'");
return -1;
}
exclude.Low = excludeLow;
exclude.High = excludeHigh;
exclude.Job = excludeOrder[0];
exclude.Result = excludeOrder[1];
}
if (_spanOption.HasValue() && !TimeSpan.TryParse(_spanOption.Value(), out span))
{
Console.WriteLine($"Invalid value for --span. Format is 'HH:mm:ss'");
return -1;
}
if (_sqlTableOption.HasValue())
{
_tableName = _sqlTableOption.Value();
if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable(_tableName)))
{
_tableName = Environment.GetEnvironmentVariable(_tableName);
}
}
if (_sqlConnectionStringOption.HasValue())
{
_sqlConnectionString = _sqlConnectionStringOption.Value();
if (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable(_sqlConnectionString)))
{
_sqlConnectionString = Environment.GetEnvironmentVariable(_sqlConnectionString);
}
}
if (!_configOption.HasValue())
{
if (!_jobOption.HasValue())
{
app.ShowHelp();
return 1;
}
}
else
{
if (!_scenarioOption.HasValue())
{
Console.Error.WriteLine("No jobs were found. Are you missing the --scenario argument?");
return 1;
}
}
if (_scenarioOption.HasValue() && _jobOption.HasValue())
{
Console.Error.WriteLine("The arguments --scenario and --job can't be used together. They both define which jobs to run.");
return 1;
}
var results = new ExecutionResult();
var scenarioName = _scenarioOption.Value();
var jobNames = _jobOption.Values;
var variables = new JObject();
foreach (var variable in _variableOption.Values)
{
var segments = variable.Split('=', 2);
if (segments.Length != 2)
{
Console.WriteLine($"Invalid variable argument: '{variable}', format is \"[NAME]=[VALUE]\"");
app.ShowHelp();
return -1;
}
// Try to parse as integer, or the value would be a string
if (long.TryParse(segments[1], out var intVariable))
{
variables[segments[0]] = intVariable;
}
else
{
variables[segments[0]] = segments[1];
}
}
foreach (var property in _propertyOption.Values)
{
var segments = property.Split('=', 2);
if (segments.Length != 2)
{
Console.WriteLine($"Invalid property argument: '{property}', format is \"[NAME]=[VALUE]\"");
app.ShowHelp();
return -1;
}
}
var configuration = await BuildConfigurationAsync(_configOption.Values, scenarioName, _jobOption.Values, Arguments, variables, _profileOption.Values, _scriptOption.Values, interval);
// Storing the list of services to run as part of the selected scenario
var dependencies = String.IsNullOrEmpty(scenarioName)
? _jobOption.Values.ToArray()
: configuration.Scenarios[scenarioName].Select(x => x.Key).ToArray()
;
var serializer = new Serializer();
string groupId = Guid.NewGuid().ToString("n");
// Verifying jobs
foreach (var jobName in dependencies)
{
var service = configuration.Jobs[jobName];
service.RunId = groupId;
service.Origin = Environment.MachineName;
service.CrankArguments = commandLineArguments;
if (String.IsNullOrEmpty(service.Source.Project) &&
String.IsNullOrEmpty(service.Source.DockerFile) &&
String.IsNullOrEmpty(service.Source.DockerLoad) &&
String.IsNullOrEmpty(service.Executable))
{
Console.WriteLine($"The service '{jobName}' is missing some properties to start the job.");
Console.WriteLine($"Check that any of these properties is set: project, executable, dockerFile, dockerLoad");
return -1;
}
if (!service.Endpoints.Any())
{
Console.WriteLine($"The service '{jobName}' is missing an endpoint to deploy on.");
// Only display as a warning if in debug mode
if (!_debugOption.HasValue())
{
return -1;
}
}
foreach (var endpoint in service.Endpoints)
{
try
{
using (var cts = new CancellationTokenSource(10000))
{
var response = await _httpClient.GetAsync(endpoint, cts.Token);
if (!_relayConnectionStringOption.HasValue())
{
response.EnsureSuccessStatusCode();
}
}
}
catch (Exception e)
{
Console.WriteLine($"The specified endpoint url '{endpoint}' for '{jobName}' is invalid or not responsive: \"{e.Message}\"");
// Only display as a warning if in debug mode
if (!_debugOption.HasValue())
{
return -1;
}
}
}
}
if (_debugOption.HasValue())
{
File.WriteAllText(_debugOption.Value(), JsonConvert.SerializeObject(configuration, Formatting.Indented));
Console.WriteLine($"Configuration saved in file {Path.GetFullPath(_debugOption.Value())}");
return 0;
}
// Initialize database
if (!String.IsNullOrWhiteSpace(_sqlConnectionString))
{
await JobSerializer.InitializeDatabaseAsync(_sqlConnectionString, _tableName);
}
#pragma warning disable CS4014
// Don't block on version checks
VersionChecker.CheckUpdateAsync(_httpClient);
#pragma warning restore CS4014
Log.Write($"Running session '{session}' with description '{_descriptionOption.Value()}'");
var isBenchmarkDotNet = dependencies.Any(x => configuration.Jobs[x].Options.BenchmarkDotNet);
if (_autoflushOption.HasValue())
{
// No job is restarted, but a snapshot of results is done
// after "span" has passed.
results = await RunAutoFlush(
configuration,
dependencies,
session,
span
);
}
else if (isBenchmarkDotNet)
{
results = await RunBenchmarkDotNet(
configuration,
dependencies,
session
);
}
else
{
results = await Run(
configuration,
dependencies,
session,
iterations,
exclude,
_scriptOption.Values
);
}
// Display diff
if (_compareOption.HasValue())
{
var jobName = "Current";
if (_scenarioOption.HasValue())
{
if (_jsonOption.HasValue())
{
jobName = Path.GetFileNameWithoutExtension(_jsonOption.Value());
}
else if (_csvOption.HasValue())
{
jobName = Path.GetFileNameWithoutExtension(_csvOption.Value());
}
}
ResultComparer.Compare(_compareOption.Values, results.JobResults, results.Benchmarks, jobName);
}
return results.ReturnCode;
});
try
{
return app.Execute(args.Where(x => !String.IsNullOrEmpty(x)).ToArray());
}
catch (ControllerException e)
{
Console.WriteLine(e.Message);
return -1;
}
catch (CommandParsingException e)
{
Console.WriteLine(e.Message);
return -1;
}
}
private static async Task<ExecutionResult> Run(
Configuration configuration,
string[] dependencies,
string session,
int iterations,
ExcludeOptions exclude,
IEnumerable<string> scripts
)
{
var executionResults = new List<ExecutionResult>();
var iterationStart = DateTime.UtcNow;
var jobsByDependency = new Dictionary<string, List<JobConnection>>();
var i = 1; // current iteration
do
{
var executionResult = new ExecutionResult();
if (iterations > 1)
{
Log.Write($"Iteration {i} of {iterations}");
}
// Deadlock detection loop
while (true)
{
var deadlockDetected = false;
try
{
foreach (var jobName in dependencies)
{
var service = configuration.Jobs[jobName];
service.DriverVersion = 2;
List<JobConnection> jobs;
// Create a new list of JobConnection instances if the service is
// not already running from a previous loop
if (jobsByDependency.ContainsKey(jobName) && SpanShouldKeepJobRunning(jobName))
{
jobs = jobsByDependency[jobName];
// Clear measurements, only if the service is not a console app as it
// would already be stopped
if (!service.WaitForExit)
{
await Task.WhenAll(jobs.Select(job => job.ClearMeasurements()));
}
}
else
{
jobs = service.Endpoints.Select(endpoint => new JobConnection(service, new Uri(endpoint))).ToList();
foreach (var jobConnection in jobs)
{
var relayToken = await GetRelayTokenAsync(jobConnection.ServerUri);
if (!String.IsNullOrEmpty(relayToken))
{
jobConnection.ConfigureRelay(relayToken);
}
}
jobsByDependency[jobName] = jobs;
// Check os and architecture requirements
if (!await EnsureServerRequirementsAsync(jobs, service))
{
Log.Write($"Scenario skipped as the agent doesn't match the operating and architecture constraints for '{jobName}' ({String.Join("/", new[] { service.Options.RequiredArchitecture, service.Options.RequiredOperatingSystem })})");
return new ExecutionResult { ReturnCode = 0 };
}
// Check that we are not creating a deadlock by starting this job
// Start this service on all configured agent endpoints
await Task.WhenAll(
jobs.Select(async job =>
{
// Before starting a job, we need to check if it could block another run
var queue = await job.GetQueueAsync();
var runningJob = queue.FirstOrDefault(x => x.State == "Running" && x.RunId != job.Job.RunId);
// If there is a running job, we check if we are not blocking another one from the same run
if (runningJob != null)
{
foreach (var jobName in dependencies)
{
if (jobsByDependency.ContainsKey(jobName))
{
foreach (var j in jobsByDependency[jobName])
{
var otherRunningJobs = await j.GetQueueAsync();
// Find a job waiting for us on the other endpoint
var jobA = otherRunningJobs.FirstOrDefault(x => x.State == "New" && x.RunId == runningJob.RunId);
// If the job we are running is waitForExit, we don't need to interrupt it
// as it will stop by itself
var jobB = otherRunningJobs.FirstOrDefault(x => x.State == "Running" && x.RunId == j.Job.RunId && !j.Job.WaitForExit);
if (jobA != null && jobB != null)
{
Log.Write($"Found deadlock on {j.ServerJobUri}, interrupting ...");
foreach (var name in dependencies.Reverse())
{
var service = configuration.Jobs[name];
// Skip failed jobs
if (!jobsByDependency.ContainsKey(name))
{
continue;
}
var jobs = jobsByDependency[name];
if (!service.WaitForExit)
{
await Task.WhenAll(jobs.Select(job => job.StopAsync()));
await Task.WhenAll(jobs.Select(job => job.DeleteAsync()));
}
}
// Wait until another runId has started, or the current runId could still be picked up
var queueStarted = DateTime.UtcNow;
while (true)
{
otherRunningJobs = await j.GetQueueAsync();
var otherRunningJob = otherRunningJobs.FirstOrDefault(x => x.State == "Running" || x.State == "Initializing" || x.State == "Starting" && x.RunId != job.Job.RunId);
if (otherRunningJob != null || (DateTime.UtcNow - queueStarted > TimeSpan.FromSeconds(3)))
{
break;
}
}
throw new JobDeadlockException();
}
}
}
}
}
// Start job on agent
return await job.StartAsync(jobName);
})
);
if (service.WaitForExit)
{
// Wait for all clients to stop
while (true)
{
var stop = true;
foreach (var job in jobs)
{
var state = await job.GetStateAsync();
stop = stop && (
state == JobState.Stopped ||
state == JobState.Failed ||
state == JobState.Deleted
);
}
if (stop)
{
break;
}
await Task.Delay(1000);
}
// Stop a blocking job
await Task.WhenAll(jobs.Select(job => job.StopAsync()));
await Task.WhenAll(jobs.Select(job => job.TryUpdateJobAsync()));
// Display error message if job failed
foreach (var job in jobs)
{
if (!String.IsNullOrEmpty(job.Job.Error))
{
Log.WriteError(job.Job.Error, notime: true);
// It might be necessary to get the formal exit code from the remove job
executionResult.ReturnCode = 1;
}
}
await Task.WhenAll(jobs.Select(job => job.DownloadDumpAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadTraceAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadBuildLogAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadOutputAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadAssetsAsync(jobName)));
await Task.WhenAll(jobs.Select(job => job.DeleteAsync()));
}
}
var aJobFailed = false;
// Skipped other services if a job has failed
foreach (var job in jobs)
{
var state = await job.GetStateAsync();
if (state == JobState.Failed)
{
aJobFailed = true;
break;
}
}
if (aJobFailed)
{
Log.Write($"Job has failed, interrupting benchmarks ...");
executionResult.ReturnCode = 1;
break;
}
}
}
catch (JobDeadlockException)
{
deadlockDetected = true;
Log.Write("Deadlock detected, restarting scenario ...");
}
if (!deadlockDetected)
{
break;
}
}
// Stop all non-blocking jobs in reverse dependency order (clients first)
foreach (var jobName in dependencies.Reverse())
{
var service = configuration.Jobs[jobName];
// Skip failed jobs
if (!jobsByDependency.ContainsKey(jobName))
{
continue;
}
var jobs = jobsByDependency[jobName];
if (!service.WaitForExit)
{
// Unless the jobs can't be stopped
if (!SpanShouldKeepJobRunning(jobName) || IsLastIteration())
{
await Task.WhenAll(jobs.Select(job => job.StopAsync()));
}
await Task.WhenAll(jobs.Select(job => job.TryUpdateJobAsync()));
// Unless the jobs can't be stopped
if (!SpanShouldKeepJobRunning(jobName) || IsLastIteration())
{
await Task.WhenAll(jobs.Select(job => job.DownloadDumpAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadBuildLogAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadOutputAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadTraceAsync()));
await Task.WhenAll(jobs.Select(job => job.DownloadAssetsAsync(jobName)));
await Task.WhenAll(jobs.Select(job => job.DeleteAsync()));
}
}
}
// Normalize results
foreach (var jobName in dependencies)
{
var service = configuration.Jobs[jobName];
// Skip failed jobs
if (!jobsByDependency.TryGetValue(jobName, out var jobConnections))
{
continue;
}
// Convert any json result to an object
NormalizeResults(jobConnections);
}
var jobResults = await CreateJobResultsAsync(configuration, dependencies, jobsByDependency);
// Display results
foreach (var jobName in dependencies)
{
var service = configuration.Jobs[jobName];
if (service.Options.DiscardResults)
{
continue;
}
// The subsequent jobs of a failed job might not have run
if (jobResults.Jobs.TryGetValue(jobName, out var job))
{
Console.WriteLine();
WriteResults(jobName, job);
}
}
foreach (var property in _propertyOption.Values)
{
var segments = property.Split('=', 2);
jobResults.Properties[segments[0]] = segments[1];
}
executionResult.JobResults = jobResults;
executionResults.Add(executionResult);
// If last iteration, create average and display results
if (iterations > 1 && i == iterations)
{
// Exclude highs and lows
if (exclude.High + exclude.Low > 0)
{
if (executionResults.Any(x => !x.JobResults.Jobs.ContainsKey(exclude.Job)))
{
Log.WriteWarning($"A benchmark didn't contain the expected job '{exclude.Job}', the exclusion will be ignored.");
}
else
{
if (executionResults.Any(x => !x.JobResults.Jobs[exclude.Job].Results.ContainsKey(exclude.Result)))
{
Log.WriteWarning($"A benchmark didn't contain the expected result ('{exclude.Result}'), the iteration will be ignored.");
}
// Keep the iterations with the results it can be ordered on
var validResults = executionResults.Where(x => x.JobResults.Jobs[exclude.Job].Results.ContainsKey(exclude.Result)).ToArray();
var orderedResults = validResults.OrderBy(x => x.JobResults.Jobs[exclude.Job].Results[exclude.Result]).ToArray();
var includedResults = orderedResults.Skip(exclude.Low).SkipLast(exclude.High).ToList();
var excludedresults = validResults.Except(includedResults).ToArray();
Console.WriteLine();
Console.WriteLine($"Values of {exclude.Job}->{exclude.Result}:");
Console.WriteLine();
for (var iter = 0; iter < executionResults.Count; iter++)
{
var result = executionResults[iter];
if (!result.JobResults.Jobs[exclude.Job].Results.ContainsKey(exclude.Result))
{
Console.WriteLine($"{iter + 1}/{iterations}: No result - Skipped");
}
else if (includedResults.Contains(result))
{
Console.WriteLine($"{iter + 1}/{iterations}: {result.JobResults.Jobs[exclude.Job].Results[exclude.Result]} - Included");
}
else
{
Console.WriteLine($"{iter + 1}/{iterations}: {result.JobResults.Jobs[exclude.Job].Results[exclude.Result]} - Excluded");
}
}
executionResults = includedResults;
}
}
// Compute averages
executionResult = ComputeAverages(executionResults);
executionResults.Clear();
executionResults.Add(executionResult);
// Display results
Console.WriteLine();
Console.WriteLine("Average results:");
Console.WriteLine();
WriteExecutionResults(executionResult);
}
// Save results
if (i == iterations)
{
CleanMeasurements(jobResults);
}