forked from aspnet/Benchmarks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1617 lines (1388 loc) · 77.6 KB
/
Program.cs
File metadata and controls
1617 lines (1388 loc) · 77.6 KB
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Benchmarks.ClientJob;
using Benchmarks.ServerJob;
using BenchmarksDriver.Serializers;
using McMaster.Extensions.CommandLineUtils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace BenchmarksDriver
{
public class Program
{
private static bool _verbose;
private static readonly HttpClient _httpClient = new HttpClient();
private static ClientJob _clientJob;
private static string _tableName = "AspNetBenchmarks";
// Default to arguments which should be sufficient for collecting trace of default Plaintext run
private const string _defaultTraceArguments = "BufferSizeMB=1024;CircularMB=1024";
public static int Main(string[] args)
{
var app = new CommandLineApplication()
{
Name = "BenchmarksDriver",
FullName = "ASP.NET Benchmark Driver",
Description = "Driver for ASP.NET Benchmarks",
ResponseFileHandling = ResponseFileHandling.ParseArgsAsSpaceSeparated,
OptionsComparison = StringComparison.OrdinalIgnoreCase
};
app.HelpOption("-?|-h|--help");
// Driver Options
var clientOption = app.Option("-c|--client",
"URL of benchmark client", CommandOptionType.SingleValue);
var clientNameOption = app.Option("--clientName",
"Name of client to use for testing, e.g. Wrk", CommandOptionType.SingleValue);
var serverOption = app.Option("-s|--server",
"URL of benchmark server", CommandOptionType.SingleValue);
var sqlConnectionStringOption = app.Option("-q|--sql",
"Connection string of SQL Database to store results", CommandOptionType.SingleValue);
var sqlTableOption = app.Option("-t|--table",
"Table name of the SQL Database to store results", CommandOptionType.SingleValue);
var verboseOption = app.Option("-v|--verbose",
"Verbose output", CommandOptionType.NoValue);
var sessionOption = app.Option("--session",
"A logical identifier to group related jobs.", CommandOptionType.SingleValue);
var descriptionOption = app.Option("--description",
"The description of the job.", CommandOptionType.SingleValue);
var iterationsOption = app.Option("-i|--iterations",
"The number of iterations.", CommandOptionType.SingleValue);
var excludeOption = app.Option("-x|--exclude",
"The number of best and worst and jobs to skip.", CommandOptionType.SingleValue);
var shutdownOption = app.Option("--before-shutdown",
"An endpoint to call before the application has shut down.", CommandOptionType.SingleValue);
var spanOption = app.Option("-sp|--span",
"The time during which the client jobs are repeated, in 'HH:mm:ss' format. e.g., 48:00:00 for 2 days.", CommandOptionType.SingleValue);
var markdownOption = app.Option("-md|--markdown",
"Formats the output in markdown", CommandOptionType.NoValue);
var writeToFileOption = app.Option("-wf|--write-file",
"Writes the results to a file", CommandOptionType.NoValue);
var windowsOnlyOption = app.Option("--windows-only",
"Don't execute the job if the server is not running on Windows", CommandOptionType.NoValue);
var linuxOnlyOption = app.Option("--linux-only",
"Don't execute the job if the server is not running on Linux", CommandOptionType.NoValue);
// ServerJob Options
var databaseOption = app.Option("--database",
"The type of database to run the benchmarks with (PostgreSql, SqlServer or MySql). Default is PostgreSql.", CommandOptionType.SingleValue);
var connectionFilterOption = app.Option("-cf|--connectionFilter",
"Assembly-qualified name of the ConnectionFilter", CommandOptionType.SingleValue);
var kestrelThreadCountOption = app.Option("--kestrelThreadCount",
"Maps to KestrelServerOptions.ThreadCount.",
CommandOptionType.SingleValue);
var scenarioOption = app.Option("-n|--scenario",
"Benchmark scenario to run", CommandOptionType.SingleValue);
var schemeOption = app.Option("-m|--scheme",
"Scheme (http or https). Default is http.", CommandOptionType.SingleValue);
var webHostOption = app.Option(
"-w|--webHost",
"WebHost (e.g., KestrelLibuv, KestrelSockets, HttpSys). Default is KestrelSockets.",
CommandOptionType.SingleValue);
var aspnetCoreVersionOption = app.Option("--aspnetCoreVersion",
"ASP.NET Core packages version (Current, Latest, or custom value). Current is the latest public version (2.0.*), Latest is the currently developped one. Default is Latest (2.1-*).", CommandOptionType.SingleValue);
var runtimeVersionOption = app.Option("--runtimeVersion",
".NET Core Runtime version (Current, Latest, Edge or custom value). Current is the latest public version, Latest is the one enlisted, Edge is the latest available. Default is Latest (2.1.0-*).", CommandOptionType.SingleValue);
var argumentsOption = app.Option("--arguments",
"Arguments to pass to the application. (e.g., \"--raw true\")", CommandOptionType.SingleValue);
var portOption = app.Option("--port",
"The port used to request the benchmarked application. Default is 5000.", CommandOptionType.SingleValue);
var readyTextOption = app.Option("--ready-text",
"The text that is displayed when the application is ready to accept requests. (e.g., \"Application started.\")", CommandOptionType.SingleValue);
var repositoryOption = app.Option("-r|--repository",
"Git repository containing the project to test.", CommandOptionType.SingleValue);
var dockerFileOption = app.Option("-df|--docker-file",
"File path of the Docker script. (e.g, \"frameworks/CSharp/aspnetcore/aspcore.dockerfile\")", CommandOptionType.SingleValue);
var dockerContextOption = app.Option("-dc|--docker-context",
"Docker context directory. Defaults to the Docker file directory. (e.g., \"frameworks/CSharp/aspnetcore/\")", CommandOptionType.SingleValue);
var dockerImageOption = app.Option("-di|--docker-image",
"The name of the Docker image to create. If not net one will be created from the Docker file name. (e.g., \"aspnetcore21\")", CommandOptionType.SingleValue);
var projectOption = app.Option("--projectFile",
"Relative path of the project to test in the repository. (e.g., \"src/Benchmarks/Benchmarks.csproj)\"", CommandOptionType.SingleValue);
var useRuntimeStoreOption = app.Option("--runtime-store",
"Runs the benchmarks using the runtime store (2.0) or shared aspnet framework (2.1).", CommandOptionType.NoValue);
var selfContainedOption = app.Option("--self-contained",
"Publishes the .NET Core runtime with the application.", CommandOptionType.NoValue);
var outputFileOption = app.Option("--outputFile",
"Output file attachment. Format is 'path[;destination]'. FilePath can be a URL. e.g., " +
"\"--outputFile c:\\build\\Microsoft.AspNetCore.Mvc.dll\", " +
"\"--outputFile c:\\files\\samples\\picture.png;wwwroot\\picture.png\"",
CommandOptionType.MultipleValue);
var scriptFileOption = app.Option("--script",
"WRK script path. File path can be a URL. e.g., " +
"\"--script c:\\scripts\\post.lua\"",
CommandOptionType.MultipleValue);
var runtimeFileOption = app.Option("--runtimeFile",
"Runtime file attachment. Format is 'path[;destination]', e.g., " +
"\"--runtimeFile c:\\build\\System.Net.Security.dll\"",
CommandOptionType.MultipleValue);
var collectTraceOption = app.Option("--collect-trace",
"Collect a PerfView trace.", CommandOptionType.NoValue);
var traceArgumentsOption = app.Option("--trace-arguments",
$"Arguments used when collecting a PerfView trace. Defaults to \"{_defaultTraceArguments}\".",
CommandOptionType.SingleValue);
var traceOutputOption = app.Option("--trace-output",
@"Can be a file prefix (app will add *.DATE.RPS*.etl.zip) , or a specific name (end in *.etl.zip) and no DATE.RPS* will be added e.g. --trace-output c:\traces\myTrace", CommandOptionType.SingleValue);
var disableR2ROption = app.Option("--no-crossgen",
"Disables Ready To Run (aka crossgen), in order to use the JITed version of the assemblies.", CommandOptionType.NoValue);
var tieredCompilationOption = app.Option("--tiered-compilation",
"Enables tiered-compilation.", CommandOptionType.NoValue);
var collectR2RLogOption = app.Option("--collect-crossgen",
"Download the Ready To Run log.", CommandOptionType.NoValue);
var environmentVariablesOption = app.Option("-e|--env",
"Defines custom environment variables to use with the benchmarked application e.g., -e \"KEY=VALUE\" -e \"A=B\"", CommandOptionType.MultipleValue);
var downloadFilesOption = app.Option("-d|--download",
"Downloads specific server files. This argument can be used multiple times. e.g., -d \"published/wwwroot/picture.png\"", CommandOptionType.MultipleValue);
var noCleanOption = app.Option("--no-clean",
"Don't delete the application on the server.", CommandOptionType.NoValue);
var fetchOption = app.Option("--fetch",
"Downloads the published application locally.", CommandOptionType.NoValue);
var fetchOutputOption = app.Option("--fetch-output",
@"Can be a file prefix (app will add *.DATE*.zip) , or a specific name (end in *.zip) and no DATE* will be added e.g. --fetch-output c:\publishedapps\myApp", CommandOptionType.SingleValue);
// ClientJob Options
var clientThreadsOption = app.Option("--clientThreads",
"Number of threads used by client. Default is 32.", CommandOptionType.SingleValue);
var connectionsOption = app.Option("--connections",
"Number of connections used by client. Default is 256.", CommandOptionType.SingleValue);
var durationOption = app.Option("--duration",
"Duration of client job in seconds. Default is 15.", CommandOptionType.SingleValue);
var warmupOption = app.Option("--warmup",
"Duration of warmup in seconds. Default is 15. 0 disables the warmup and is equivalent to --no-warmup.", CommandOptionType.SingleValue);
var noWarmupOption = app.Option("--no-warmup",
"Disables the warmup phase.", CommandOptionType.NoValue);
var headerOption = app.Option("--header",
"Header added to request.", CommandOptionType.MultipleValue);
var headersOption = app.Option("--headers",
"Default set of HTTP headers added to request (None, Plaintext, Json, Html). Default is Html.", CommandOptionType.SingleValue);
var methodOption = app.Option("--method",
"HTTP method of the request. Default is GET.", CommandOptionType.SingleValue);
var clientProperties = app.Option("-p|--properties",
"Key value pairs of properties specific to the client running. e.g., -p ScriptName=pipeline -p PipelineDepth=16", CommandOptionType.MultipleValue);
var pathOption = app.Option(
"--path",
"Relative URL where the client should send requests.",
CommandOptionType.SingleValue);
var querystringOption = app.Option(
"--querystring",
"Querystring to add to the requests. (e.g., \"?page=1\")",
CommandOptionType.SingleValue);
var jobsOptions = app.Option("-j|--jobs",
"The path or url to the jobs definition.", CommandOptionType.SingleValue);
app.OnExecute(() =>
{
_verbose = verboseOption.HasValue();
var schemeValue = schemeOption.Value();
if (string.IsNullOrEmpty(schemeValue))
{
schemeValue = "http";
}
var webHostValue = webHostOption.Value();
if (string.IsNullOrEmpty(webHostValue))
{
webHostValue = "KestrelSockets";
}
var session = sessionOption.Value();
if (String.IsNullOrEmpty(session))
{
session = Guid.NewGuid().ToString("n");
}
var description = descriptionOption.Value() ?? "";
if (iterationsOption.HasValue() && spanOption.HasValue())
{
Console.WriteLine($"The options --iterations and --span can't be used together.");
app.ShowHelp();
return 10;
}
var server = serverOption.Value();
var client = clientOption.Value();
var headers = Headers.Html;
var jobDefinitionPathOrUrl = jobsOptions.Value();
var iterations = 1;
var exclude = 0;
var sqlConnectionString = sqlConnectionStringOption.Value();
TimeSpan span = TimeSpan.Zero;
if (!Enum.TryParse(schemeValue, ignoreCase: true, result: out Scheme scheme) ||
!Enum.TryParse(webHostValue, ignoreCase: true, result: out WebHost webHost) ||
(headersOption.HasValue() && !Enum.TryParse(headersOption.Value(), ignoreCase: true, result: out headers)) ||
(databaseOption.HasValue() && !Enum.TryParse(databaseOption.Value(), ignoreCase: true, result: out Database database)) ||
string.IsNullOrWhiteSpace(server) ||
string.IsNullOrWhiteSpace(client) ||
(spanOption.HasValue() && !TimeSpan.TryParse(spanOption.Value(), result: out span)) ||
(iterationsOption.HasValue() && !int.TryParse(iterationsOption.Value(), result: out iterations)) ||
(excludeOption.HasValue() && !int.TryParse(excludeOption.Value(), result: out exclude)))
{
app.ShowHelp();
return 2;
}
if (sqlTableOption.HasValue())
{
_tableName = sqlTableOption.Value();
}
var scenarioName = scenarioOption.Value() ?? "Default";
JobDefinition jobDefinitions;
if (!string.IsNullOrWhiteSpace(jobDefinitionPathOrUrl))
{
string jobDefinitionContent;
// Load the job definition from a url or locally
try
{
if (jobDefinitionPathOrUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
jobDefinitionContent = _httpClient.GetStringAsync(jobDefinitionPathOrUrl).GetAwaiter().GetResult();
}
else
{
jobDefinitionContent = File.ReadAllText(jobDefinitionPathOrUrl);
}
}
catch
{
Console.WriteLine($"Job definition '{jobDefinitionPathOrUrl}' could not be loaded.");
return 7;
}
jobDefinitions = JsonConvert.DeserializeObject<JobDefinition>(jobDefinitionContent);
if (!jobDefinitions.ContainsKey(scenarioName))
{
if (scenarioName == "Default")
{
Console.WriteLine($"Default job not found in the job definition file.");
}
else
{
Console.WriteLine($"Job named '{scenarioName}' not found in the job definition file.");
}
return 7;
}
else
{
// Normalizes the scenario name by using the one from the job definition
scenarioName = jobDefinitions.First(x => String.Equals(x.Key, scenarioName, StringComparison.OrdinalIgnoreCase)).Key;
}
}
else
{
if (scenarioOption.HasValue())
{
Console.WriteLine($"Job named '{scenarioName}' was specified but no job definition argument.");
return 8;
}
if ((!repositoryOption.HasValue() ||
!projectOption.HasValue()) &&
!dockerFileOption.HasValue())
{
Console.WriteLine($"Repository and project are mandatory when no job definition is specified.");
return 9;
}
jobDefinitions = new JobDefinition();
jobDefinitions.Add("Default", new JObject());
}
var mergeOptions = new JsonMergeSettings { MergeArrayHandling = MergeArrayHandling.Replace, MergeNullValueHandling = MergeNullValueHandling.Merge };
if (!jobDefinitions.TryGetValue("Default", out var defaultJob))
{
defaultJob = new JObject();
}
var job = jobDefinitions[scenarioName];
// Building ServerJob
var mergedServerJob = new JObject(defaultJob);
mergedServerJob.Merge(job);
var serverJob = mergedServerJob.ToObject<ServerJob>();
var jobOptions = mergedServerJob.ToObject<JobOptions>();
if (pathOption.HasValue() && jobOptions.Paths != null && jobOptions.Paths.Count > 0)
{
jobOptions.Paths.Add(serverJob.Path);
if (!jobOptions.Paths.Any(p => string.Equals(p, serverJob.Path, StringComparison.OrdinalIgnoreCase)) &&
!jobOptions.Paths.Any(p => string.Equals(p, "/" + serverJob.Path, StringComparison.OrdinalIgnoreCase)))
{
Console.WriteLine($"Scenario '{scenarioName}' does not support {pathOption.LongName} '{pathOption.Value()}'. Choose from:");
Console.WriteLine($"'{string.Join("', '", jobOptions.Paths)}'");
return 6;
}
}
// If the KnownHeaders property of the job definition is a string, fetch it from the Headers enum
if (!String.IsNullOrEmpty(jobOptions.PresetHeaders))
{
if (!Enum.TryParse(jobOptions.PresetHeaders, ignoreCase: true, result: out headers))
{
Console.WriteLine($"Unknown KnownHeaders value: '{jobOptions.PresetHeaders}'. Choose from: None, Html, Json, Plaintext.");
}
}
// Scenario can't be set in job definitions
serverJob.Scenario = scenarioName;
serverJob.WebHost = webHost;
if (databaseOption.HasValue())
{
serverJob.Database = Enum.Parse<Database>(databaseOption.Value(), ignoreCase: true);
}
if (pathOption.HasValue())
{
serverJob.Path = pathOption.Value();
}
if (connectionFilterOption.HasValue())
{
serverJob.ConnectionFilter = connectionFilterOption.Value();
}
if (schemeOption.HasValue())
{
serverJob.Scheme = scheme;
}
if (useRuntimeStoreOption.HasValue())
{
serverJob.UseRuntimeStore = true;
}
if (selfContainedOption.HasValue())
{
serverJob.SelfContained = true;
}
if (kestrelThreadCountOption.HasValue())
{
serverJob.KestrelThreadCount = int.Parse(kestrelThreadCountOption.Value());
}
if (argumentsOption.HasValue())
{
serverJob.Arguments = argumentsOption.Value();
}
if (portOption.HasValue())
{
serverJob.Port = int.Parse(portOption.Value());
}
if (aspnetCoreVersionOption.HasValue())
{
serverJob.AspNetCoreVersion = aspnetCoreVersionOption.Value();
}
if (runtimeVersionOption.HasValue())
{
serverJob.RuntimeVersion = runtimeVersionOption.Value();
}
if (repositoryOption.HasValue())
{
var source = repositoryOption.Value();
var split = source.IndexOf('@');
var repository = (split == -1) ? source : source.Substring(0, split);
serverJob.Source.BranchOrCommit = (split == -1) ? null : source.Substring(split + 1);
if (!repository.Contains(":"))
{
repository = $"https://github.com/aspnet/{repository}.git";
}
serverJob.Source.Repository = repository;
}
if (dockerFileOption.HasValue())
{
serverJob.Source.DockerFile = dockerFileOption.Value();
if (dockerContextOption.HasValue())
{
serverJob.Source.DockerContextDirectory = dockerContextOption.Value();
}
else
{
serverJob.Source.DockerContextDirectory = Path.GetDirectoryName(serverJob.Source.DockerFile).Replace("\\", "/");
}
if (dockerImageOption.HasValue())
{
serverJob.Source.DockerImageName = dockerImageOption.Value();
}
else
{
serverJob.Source.DockerImageName = Path.GetFileNameWithoutExtension(serverJob.Source.DockerFile).Replace("-", "_").Replace("\\", "/").ToLowerInvariant();
}
}
if (projectOption.HasValue())
{
serverJob.Source.Project = projectOption.Value();
}
if (noCleanOption.HasValue())
{
serverJob.NoClean = true;
}
if (collectTraceOption.HasValue())
{
serverJob.Collect = true;
serverJob.CollectArguments = _defaultTraceArguments;
if (traceArgumentsOption.HasValue())
{
serverJob.CollectArguments = string.Join(';', serverJob.CollectArguments, traceArgumentsOption.Value());
}
}
if (disableR2ROption.HasValue())
{
serverJob.EnvironmentVariables.Add("COMPlus_ReadyToRun", "0");
}
if (collectR2RLogOption.HasValue())
{
serverJob.EnvironmentVariables.Add("COMPlus_ReadyToRunLogFile", "r2r");
}
if (tieredCompilationOption.HasValue())
{
serverJob.EnvironmentVariables.Add("COMPlus_TieredCompilation", "1");
}
if (environmentVariablesOption.HasValue())
{
foreach(var env in environmentVariablesOption.Values)
{
var index = env.IndexOf('=');
if (index == -1)
{
if (index == -1)
{
Console.WriteLine($"Invalid environment variable, '=' not found: '{env}'");
return 9;
}
}
else if (index == env.Length - 1)
{
serverJob.EnvironmentVariables.Add(env.Substring(0, index), "");
}
else
{
serverJob.EnvironmentVariables.Add(env.Substring(0, index), env.Substring(index + 1));
}
}
}
// Check all attachments exist
if (outputFileOption.HasValue())
{
foreach (var outputFile in outputFileOption.Values)
{
var fileSegments = outputFile.Split(';');
var filename = fileSegments[0];
if (!File.Exists(filename))
{
Console.WriteLine($"Output File '{filename}' could not be loaded.");
return 8;
}
}
}
// Check all scripts exist
if (scriptFileOption.HasValue())
{
foreach (var scriptFile in scriptFileOption.Values)
{
if (!File.Exists(scriptFile))
{
Console.WriteLine($"Script file '{scriptFile}' could not be loaded.");
return 8;
}
}
}
if (runtimeFileOption.HasValue())
{
foreach (var runtimeFile in runtimeFileOption.Values)
{
var fileSegments = runtimeFile.Split(';');
var filename = fileSegments[0];
if (!File.Exists(filename))
{
Console.WriteLine($"Runtime File '{filename}' could not be loaded.");
return 8;
}
}
}
// Building ClientJob
var mergedClientJob = new JObject(defaultJob);
mergedClientJob.Merge(job);
_clientJob = mergedClientJob.ToObject<ClientJob>();
if (clientNameOption.HasValue())
{
if (!Enum.TryParse<Worker>(clientNameOption.Value(), ignoreCase: true, result: out var worker))
{
Log($"Could not find worker {clientNameOption.Value()}");
return 9;
}
_clientJob.Client = worker;
}
Log($"Using worker {_clientJob.Client}");
// Override default ClientJob settings if options are set
if (connectionsOption.HasValue())
{
_clientJob.Connections = int.Parse(connectionsOption.Value());
}
if (clientThreadsOption.HasValue())
{
_clientJob.Threads = int.Parse(clientThreadsOption.Value());
}
if (durationOption.HasValue())
{
_clientJob.Duration = int.Parse(durationOption.Value());
}
if (warmupOption.HasValue())
{
_clientJob.Warmup = int.Parse(warmupOption.Value());
}
if (noWarmupOption.HasValue())
{
_clientJob.Warmup = 0;
}
if (clientProperties.HasValue())
{
foreach (var property in clientProperties.Values)
{
var index = property.IndexOf('=');
if (index == -1)
{
Console.WriteLine($"Invalid property variable, '=' not found: '{property}'");
return 9;
}
else
{
_clientJob.ClientProperties[property.Substring(0, index)] = property.Substring(index + 1);
}
}
}
if (methodOption.HasValue())
{
_clientJob.Method = methodOption.Value();
}
if (querystringOption.HasValue())
{
_clientJob.Query = querystringOption.Value();
}
if (span > TimeSpan.Zero)
{
_clientJob.SpanId = Guid.NewGuid().ToString("n");
}
switch (headers)
{
case Headers.None:
break;
case Headers.Html:
_clientJob.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
_clientJob.Headers["Connection"] = "keep-alive";
break;
case Headers.Json:
_clientJob.Headers["Accept"] = "application/json,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7";
_clientJob.Headers["Connection"] = "keep-alive";
break;
case Headers.Plaintext:
_clientJob.Headers["Accept"] = "text/plain,text/html;q=0.9,application/xhtml+xml;q=0.9,application/xml;q=0.8,*/*;q=0.7";
_clientJob.Headers["Connection"] = "keep-alive";
break;
}
if (headerOption.HasValue())
{
foreach (var header in headerOption.Values)
{
var index = header.IndexOf('=');
if (index == -1)
{
Console.WriteLine($"Invalid http header, '=' not found: '{header}'");
return 9;
}
_clientJob.Headers[header.Substring(0, index)] = header.Substring(index + 1, header.Length - index - 1);
}
}
Benchmarks.ServerJob.OperatingSystem? requiredOperatingSystem = null;
if (windowsOnlyOption.HasValue())
{
requiredOperatingSystem = Benchmarks.ServerJob.OperatingSystem.Windows;
}
if (linuxOnlyOption.HasValue())
{
requiredOperatingSystem = Benchmarks.ServerJob.OperatingSystem.Linux;
}
return Run(
new Uri(server),
new Uri(client),
sqlConnectionString,
serverJob,
session,
description,
iterations,
exclude,
shutdownOption.Value(),
span,
downloadFilesOption.Values,
fetchOption.HasValue() || fetchOutputOption.HasValue(),
fetchOutputOption.Value(),
collectR2RLogOption.HasValue(),
traceOutputOption.Value(),
outputFileOption,
scriptFileOption,
runtimeFileOption,
markdownOption,
writeToFileOption,
requiredOperatingSystem).Result;
});
// Resolve reponse files from urls
for (var i = 0; i < args.Length; i++)
{
if (args[i].StartsWith("@http", StringComparison.OrdinalIgnoreCase))
{
try
{
var tempFilename = Path.GetTempFileName();
var filecontent = _httpClient.GetStringAsync(args[i].Substring(1)).GetAwaiter().GetResult();
File.WriteAllText(tempFilename, filecontent);
args[i] = "@" + tempFilename;
}
catch
{
Console.WriteLine($"Invalid reponse file url '{args[i].Substring(1)}'");
return -1;
}
}
}
return app.Execute(args);
}
private static async Task<int> Run(
Uri serverUri,
Uri clientUri,
string sqlConnectionString,
ServerJob serverJob,
string session,
string description,
int iterations,
int exclude,
string shutdownEndpoint,
TimeSpan span,
List<string> downloadFiles,
bool fetch,
string fetchDestination,
bool collectR2RLog,
string traceDestination,
CommandOption outputFileOption,
CommandOption scriptFileOption,
CommandOption runtimeFileOption,
CommandOption markdownOption,
CommandOption writeToFileOption,
Benchmarks.ServerJob.OperatingSystem? requiredOperatingSystem
)
{
var scenario = serverJob.Scenario;
var serverJobsUri = new Uri(serverUri, "/jobs");
Uri serverJobUri = null;
HttpResponseMessage response = null;
string responseContent = null;
var results = new List<Statistics>();
ClientJob clientJob = null;
var serializer = WorkerFactory.CreateResultSerializer(_clientJob);
if (serializer != null && !string.IsNullOrWhiteSpace(sqlConnectionString))
{
await serializer.InitializeDatabaseAsync(sqlConnectionString, _tableName);
}
var content = JsonConvert.SerializeObject(serverJob);
Log($"Running session '{session}' with description '{description}'");
for (var i = 1; i <= iterations; i++)
{
if (iterations > 1)
{
Log($"Job {i} of {iterations}");
}
try
{
Log($"Starting scenario {scenario} on benchmark server...");
LogVerbose($"POST {serverJobsUri} {content}...");
response = await _httpClient.PostAsync(serverJobsUri, new StringContent(content, Encoding.UTF8, "application/json"));
responseContent = await response.Content.ReadAsStringAsync();
LogVerbose($"{(int)response.StatusCode} {response.StatusCode}");
response.EnsureSuccessStatusCode();
serverJobUri = new Uri(serverUri, response.Headers.Location);
while (true)
{
LogVerbose($"GET {serverJobUri}...");
response = await _httpClient.GetAsync(serverJobUri);
responseContent = await response.Content.ReadAsStringAsync();
LogVerbose($"{(int)response.StatusCode} {response.StatusCode} {responseContent}");
serverJob = JsonConvert.DeserializeObject<ServerJob>(responseContent);
if (!serverJob.Hardware.HasValue)
{
throw new InvalidOperationException("Server is required to set ServerJob.Hardware.");
}
if (String.IsNullOrWhiteSpace(serverJob.HardwareVersion))
{
throw new InvalidOperationException("Server is required to set ServerJob.HardwareVersion.");
}
if (!serverJob.OperatingSystem.HasValue)
{
throw new InvalidOperationException("Server is required to set ServerJob.OperatingSystem.");
}
if (requiredOperatingSystem.HasValue && requiredOperatingSystem.Value != serverJob.OperatingSystem)
{
Log($"Job ignored on this OS, stopping job ...");
response = await _httpClient.PostAsync(serverJobUri + "/stop", new StringContent(""));
LogVerbose($"{(int)response.StatusCode} {response.StatusCode}");
return 0;
}
if (serverJob.State == ServerState.Initializing)
{
// Uploading attachments
if (outputFileOption.HasValue())
{
foreach (var outputFile in outputFileOption.Values)
{
var result = await UploadFileAsync(outputFile, AttachmentLocation.Output, serverJob, serverJobUri);
if (result != 0)
{
return result;
}
}
}
if (runtimeFileOption.HasValue())
{
foreach (var runtimeFile in runtimeFileOption.Values)
{
var result = await UploadFileAsync(runtimeFile, AttachmentLocation.Runtime, serverJob, serverJobUri);
if (result != 0)
{
return result;
}
}
}
response = await _httpClient.PostAsync(serverJobUri + "/start", new StringContent(""));
responseContent = await response.Content.ReadAsStringAsync();
LogVerbose($"{(int)response.StatusCode} {response.StatusCode}");
response.EnsureSuccessStatusCode();
Log($"Server Job ready: {serverJobUri}");
break;
}
else
{
await Task.Delay(1000);
}
}
var serverBenchmarkUri = (string)null;
while (true)
{
LogVerbose($"GET {serverJobUri}...");
response = await _httpClient.GetAsync(serverJobUri);
responseContent = await response.Content.ReadAsStringAsync();
LogVerbose($"{(int)response.StatusCode} {response.StatusCode} {responseContent}");
if (response.StatusCode == HttpStatusCode.NotFound)
{
return -1;
}
serverJob = JsonConvert.DeserializeObject<ServerJob>(responseContent);
if (!serverJob.Hardware.HasValue)
{
throw new InvalidOperationException("Server is required to set ServerJob.Hardware.");
}
if (String.IsNullOrWhiteSpace(serverJob.HardwareVersion))
{
throw new InvalidOperationException("Server is required to set ServerJob.HardwareVersion.");
}
if (!serverJob.OperatingSystem.HasValue)
{
throw new InvalidOperationException("Server is required to set ServerJob.OperatingSystem.");
}
if (serverJob.State == ServerState.Running)
{
serverBenchmarkUri = serverJob.Url;
break;
}
else if (serverJob.State == ServerState.Failed)
{
Log($"Job failed on benchmark server, stopping...");
Console.WriteLine(serverJob.Error);
// Returning will also send a Delete message to the server
return -1;
}
else if (serverJob.State == ServerState.NotSupported)
{
Log("Server does not support this job configuration.");
return 0;
}
else if (serverJob.State == ServerState.Stopped)
{
return -1;
}
else
{
await Task.Delay(1000);
}
}
System.Threading.Thread.Sleep(200); // Make it clear on traces when startup has finished and warmup begins.
TimeSpan latencyNoLoad = TimeSpan.Zero, latencyFirstRequest = TimeSpan.Zero;
if (_clientJob.Warmup != 0)
{
Log("Warmup");
var duration = _clientJob.Duration;
_clientJob.Duration = _clientJob.Warmup;
clientJob = await RunClientJob(scenario, clientUri, serverJobUri, serverBenchmarkUri, scriptFileOption);
// Store the latency as measured on the warmup job
latencyNoLoad = clientJob.LatencyNoLoad;
latencyFirstRequest = clientJob.LatencyFirstRequest;
_clientJob.SkipStartupLatencies = false;
_clientJob.Duration = duration;
System.Threading.Thread.Sleep(200); // Make it clear on traces when warmup stops and measuring begins.
}
Log("Measuring");
var startTime = DateTime.UtcNow;
var spanLoop = 0;
var sqlTask = Task.CompletedTask;
do
{
if (span > TimeSpan.Zero)
{
Log($"Starting client job iteration {spanLoop}. Running since {startTime.ToLocalTime()}, with {((startTime + span) - DateTime.UtcNow):c} remaining.");
// Clear the measures from the server job and update it on the server
if (spanLoop > 0)
{
results.Clear();
response = await _httpClient.PostAsync(serverJobUri + "/resetstats", new StringContent(""));
response.EnsureSuccessStatusCode();
}
}
clientJob = await RunClientJob(scenario, clientUri, serverJobUri, serverBenchmarkUri, scriptFileOption);
if (clientJob.State == ClientState.Completed)
{
LogVerbose($"Client Job completed");
if (span == TimeSpan.Zero && i == iterations && !String.IsNullOrEmpty(shutdownEndpoint))
{
Log($"Invoking '{shutdownEndpoint}' on benchmarked application...");
await InvokeApplicationEndpoint(serverJobUri, shutdownEndpoint);
}
// Load latest state of server job
LogVerbose($"GET {serverJobUri}...");
response = await _httpClient.GetAsync(serverJobUri);
response.EnsureSuccessStatusCode();
responseContent = await response.Content.ReadAsStringAsync();
LogVerbose($"{(int)response.StatusCode} {response.StatusCode} {responseContent}");
serverJob = JsonConvert.DeserializeObject<ServerJob>(responseContent);
// Download R2R log
if (collectR2RLog)
{
downloadFiles.Add("r2r." + serverJob.ProcessId);
}
if (clientJob.Warmup == 0)
{
latencyNoLoad = clientJob.LatencyNoLoad;
latencyFirstRequest = clientJob.LatencyFirstRequest;
}
var serverCounters = serverJob.ServerCounters;
var workingSet = Math.Round(((double)serverCounters.Select(x => x.WorkingSet).DefaultIfEmpty(0).Max()) / (1024 * 1024), 3);
var cpu = serverCounters.Select(x => x.CpuPercentage).DefaultIfEmpty(0).Max();
var statistics = new Statistics
{
RequestsPerSecond = clientJob.RequestsPerSecond,
LatencyOnLoad = clientJob.Latency.Average,
Cpu = cpu,
WorkingSet = workingSet,
StartupMain = serverJob.StartupMainMethod.TotalMilliseconds,
FirstRequest = latencyFirstRequest.TotalMilliseconds,
Latency = latencyNoLoad.TotalMilliseconds,
SocketErrors = clientJob.SocketErrors,
BadResponses = clientJob.BadResponses,
LatencyAverage = clientJob.Latency.Average,
Latency50Percentile = clientJob.Latency.Within50thPercentile,
Latency75Percentile = clientJob.Latency.Within75thPercentile,
Latency90Percentile = clientJob.Latency.Within90thPercentile,
Latency99Percentile = clientJob.Latency.Within99thPercentile,