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