[acceptance-tests] Don't pass a zero sampling/heapshot frequency in the profiler...
[mono.git] / acceptance-tests / profiler-stress / runner.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Diagnostics;
4 using System.Globalization;
5 using System.IO;
6 using System.Linq;
7 using System.Text;
8 using System.Text.RegularExpressions;
9 using System.Threading;
10 using System.Xml;
11 using Mono.Unix.Native;
12 using Newtonsoft.Json;
13
14 // Shut up CLS compliance warnings from Json.NET.
15 [assembly: CLSCompliant (true)]
16
17 namespace Mono.Profiling.Tests.Stress {
18
19         // https://github.com/xamarin/benchmarker/blob/master/tools/libdbmodel/Benchmark.cs
20         sealed class Benchmark {
21
22                 public string Name { get; set; }
23                 public string TestDirectory { get; set; }
24                 public bool OnlyExplicit { get; set; }
25                 public string[] CommandLine { get; set; }
26                 public string[] ClientCommandLine { get; set; }
27                 public string[] AOTAssemblies { get; set; }
28
29                 public static Benchmark Load (string file)
30                 {
31                         return JsonConvert.DeserializeObject<Benchmark> (File.ReadAllText (file));
32                 }
33         }
34
35         sealed class TestResult {
36
37                 public Benchmark Benchmark { get; set; }
38                 public ProcessStartInfo StartInfo { get; set; }
39                 public Stopwatch Stopwatch { get; set; } = new Stopwatch ();
40                 public int? ExitCode { get; set; }
41                 public StringBuilder StandardOutput { get; set; } = new StringBuilder ();
42                 public StringBuilder StandardError { get; set; } = new StringBuilder ();
43         }
44
45         static class Program {
46
47                 static readonly string[] _options = new [] {
48                         "domain",
49                         "assembly",
50                         "module",
51                         "class",
52                         "jit",
53                         "exception",
54                         "gcalloc",
55                         "gc",
56                         "thread",
57                         // "calls", // Way too heavy.
58                         "monitor",
59                         "gcmove",
60                         "gcroot",
61                         "context",
62                         "finalization",
63                         "counter",
64                         "gchandle",
65                 };
66
67                 static readonly TimeSpan _timeout = TimeSpan.FromHours (6);
68
69                 static string FilterInvalidXmlChars (string text) {
70                         return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", string.Empty);
71                 }
72
73                 static int Main ()
74                 {
75                         var depDir = Path.Combine ("..", "external", "benchmarker");
76                         var benchDir = Path.Combine (depDir, "benchmarks");
77                         var testDir = Path.Combine (depDir, "tests");
78
79                         var benchmarks = Directory.EnumerateFiles (benchDir, "*.benchmark")
80                                          .Select (Benchmark.Load)
81                                          .Where (b => !b.OnlyExplicit && b.ClientCommandLine == null)
82                                          .OrderBy (b => b.Name)
83                                          .ToArray ();
84
85                         var monoPath = Path.GetFullPath (Path.Combine ("..", "..", "runtime", "mono-wrapper"));
86                         var classDir = Path.GetFullPath (Path.Combine ("..", "..", "mcs", "class", "lib", "net_4_x"));
87
88                         var rand = new Random ();
89                         var cpus = Environment.ProcessorCount;
90
91                         var results = new List<TestResult> (benchmarks.Length);
92
93                         var sw = Stopwatch.StartNew ();
94
95                         for (var i = 0; i < benchmarks.Length; i++) {
96                                 var bench = benchmarks [i];
97
98                                 var sampleFreq = rand.Next (-1000, 1001);
99                                 var sampleMode = rand.Next (0, 2) == 1 ? "real" : "process";
100                                 var maxSamples = rand.Next (0, cpus * 2000 + 1);
101                                 var heapShotFreq = rand.Next (-10, 11);
102                                 var maxFrames = rand.Next (0, 33);
103                                 var options = _options.ToDictionary (x => x, _ => rand.Next (0, 2) == 1)
104                                                       .Select (x => (x.Value ? string.Empty : "no") + x.Key)
105                                                       .ToArray ();
106
107                                 var profOptions = $"maxframes={maxFrames},{string.Join (",", options)},output=/dev/null";
108
109                                 if (sampleFreq > 0)
110                                         profOptions += $",sample={sampleFreq},sampling-{sampleMode},maxsamples={maxSamples}";
111
112                                 if (heapShotFreq > 0)
113                                         profOptions += $",heapshot={heapShotFreq}gc";
114
115                                 var info = new ProcessStartInfo {
116                                         UseShellExecute = false,
117                                         WorkingDirectory = Path.Combine (testDir, bench.TestDirectory),
118                                         FileName = monoPath,
119                                         Arguments = $"--debug --profile=log:{profOptions} " + string.Join (" ", bench.CommandLine),
120                                         RedirectStandardOutput = true,
121                                         RedirectStandardError = true,
122                                 };
123
124                                 info.EnvironmentVariables.Clear ();
125                                 info.EnvironmentVariables.Add ("MONO_PATH", classDir);
126
127                                 var progress = $"({i + 1}/{benchmarks.Length})";
128
129                                 Console.ForegroundColor = ConsoleColor.Blue;
130                                 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} Running {bench.Name} with profiler options: {profOptions}");
131                                 Console.ResetColor ();
132
133                                 var result = new TestResult {
134                                         Benchmark = bench,
135                                         StartInfo = info,
136                                 };
137
138                                 using (var proc = new Process ()) {
139                                         proc.StartInfo = info;
140
141                                         proc.OutputDataReceived += (sender, args) => {
142                                                 if (args.Data != null)
143                                                         result.StandardOutput.AppendLine (args.Data);
144                                         };
145
146                                         proc.ErrorDataReceived += (sender, args) => {
147                                                 if (args.Data != null)
148                                                         result.StandardError.AppendLine (args.Data);
149                                         };
150
151                                         result.Stopwatch.Start ();
152
153                                         proc.Start ();
154
155                                         proc.BeginOutputReadLine ();
156                                         proc.BeginErrorReadLine ();
157
158                                         if (!proc.WaitForExit ((int) _timeout.TotalMilliseconds)) {
159                                                 // Force a thread dump.
160                                                 Syscall.kill (proc.Id, Signum.SIGQUIT);
161                                                 Thread.Sleep (1000);
162
163                                                 try {
164                                                         proc.Kill ();
165                                                 } catch (Exception) {
166                                                 }
167                                         } else
168                                                 result.ExitCode = proc.ExitCode;
169
170                                         result.Stopwatch.Stop ();
171                                 }
172
173                                 var resultStr = result.ExitCode == null ? "timed out" : $"exited with code: {result.ExitCode}";
174
175                                 Console.ForegroundColor = result.ExitCode != 0 ? ConsoleColor.Red : ConsoleColor.Green;
176                                 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} {bench.Name} took {result.Stopwatch.Elapsed.ToString ("G")} and {resultStr}");
177                                 Console.ResetColor ();
178
179                                 if (result.ExitCode != 0) {
180                                         Console.ForegroundColor = ConsoleColor.Red;
181                                         Console.WriteLine ("===== stdout =====");
182                                         Console.ResetColor ();
183
184                                         Console.WriteLine (result.StandardOutput.ToString ());
185
186                                         Console.ForegroundColor = ConsoleColor.Red;
187                                         Console.WriteLine ("===== stderr =====");
188                                         Console.ResetColor ();
189
190                                         Console.WriteLine (result.StandardError.ToString ());
191                                 }
192
193                                 results.Add (result);
194                         }
195
196                         sw.Stop ();
197
198                         var successes = results.Count (r => r.ExitCode == 0);
199                         var failures = results.Count (r => r.ExitCode != null && r.ExitCode != 0);
200                         var timeouts = results.Count (r => r.ExitCode == null);
201
202                         var settings = new XmlWriterSettings {
203                                 NewLineOnAttributes = true,
204                                 Indent = true,
205                         };
206
207                         using (var writer = XmlWriter.Create ("TestResult-profiler-stress.xml", settings)) {
208                                 writer.WriteStartDocument ();
209                                 writer.WriteComment ("This file represents the results of running a test suite");
210
211                                 writer.WriteStartElement ("test-results");
212                                 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
213                                 writer.WriteAttributeString ("total", results.Count.ToString ());
214                                 writer.WriteAttributeString ("failures", failures.ToString ());
215                                 writer.WriteAttributeString ("not-run", "0");
216                                 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
217                                 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
218
219                                 writer.WriteStartElement ("environment");
220                                 writer.WriteAttributeString ("nunit-version", "2.4.8.0");
221                                 writer.WriteAttributeString ("clr-version", Environment.Version.ToString ());
222                                 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString ());
223                                 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString ());
224                                 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory);
225                                 writer.WriteAttributeString ("machine-name", Environment.MachineName);
226                                 writer.WriteAttributeString ("user", Environment.UserName);
227                                 writer.WriteAttributeString ("user-domain", Environment.UserDomainName);
228                                 writer.WriteEndElement ();
229
230                                 writer.WriteStartElement ("culture-info");
231                                 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name);
232                                 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name);
233                                 writer.WriteEndElement ();
234
235                                 writer.WriteStartElement ("test-suite");
236                                 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
237                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
238                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
239                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
240                                 writer.WriteStartElement ("results");
241
242                                 writer.WriteStartElement ("test-suite");
243                                 writer.WriteAttributeString ("name", "MonoTests");
244                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
245                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
246                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
247                                 writer.WriteStartElement ("results");
248
249                                 writer.WriteStartElement ("test-suite");
250                                 writer.WriteAttributeString ("name", "profiler-stress");
251                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
252                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
253                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
254                                 writer.WriteStartElement ("results");
255
256                                 foreach (var result in results) {
257                                         var timeoutStr = result.ExitCode == null ? "_timeout" : string.Empty;
258
259                                         writer.WriteStartElement ("test-case");
260                                         writer.WriteAttributeString ("name", $"MonoTests.profiler-stress.{result.Benchmark.Name}{timeoutStr}");
261                                         writer.WriteAttributeString ("executed", "True");
262                                         writer.WriteAttributeString ("success", (result.ExitCode == 0).ToString ());
263                                         writer.WriteAttributeString ("time", ((int) result.Stopwatch.Elapsed.TotalSeconds).ToString ());
264                                         writer.WriteAttributeString ("asserts", result.ExitCode == 0 ? "0" : "1");
265
266                                         if (result.ExitCode != 0) {
267                                                 writer.WriteStartElement ("failure");
268
269                                                 writer.WriteStartElement ("message");
270                                                 writer.WriteCData (FilterInvalidXmlChars (result.StandardOutput.ToString ()));
271                                                 writer.WriteEndElement ();
272
273                                                 writer.WriteStartElement ("stack-trace");
274                                                 writer.WriteCData (FilterInvalidXmlChars (result.StandardError.ToString ()));
275                                                 writer.WriteEndElement ();
276
277                                                 writer.WriteEndElement ();
278                                         }
279
280                                         writer.WriteEndElement ();
281                                 }
282
283                                 writer.WriteEndElement ();
284                                 writer.WriteEndElement ();
285
286                                 writer.WriteEndElement ();
287                                 writer.WriteEndElement ();
288
289                                 writer.WriteEndElement ();
290                                 writer.WriteEndElement ();
291
292                                 writer.WriteEndElement ();
293
294                                 writer.WriteEndDocument ();
295                         }
296
297                         var failureStr = failures + timeouts != 0 ? $" ({failures} failures, {timeouts} timeouts)" : string.Empty;
298
299                         Console.ForegroundColor = failures + timeouts != 0 ? ConsoleColor.Red : ConsoleColor.Green;
300                         Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] Finished with {successes}/{results.Count} passing tests{failureStr}");
301                         Console.ResetColor ();
302
303                         return failures + timeouts;
304                 }
305         }
306 }