[acceptance-tests] Temporarily increase the profiler stress timeout to 24 hours.
[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 (24);
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                                                         stdout.AppendLine (args.Data);
156                                         };
157
158                                         proc.ErrorDataReceived += (sender, args) => {
159                                                 if (args.Data != null)
160                                                         stderr.AppendLine (args.Data);
161                                         };
162
163                                         result.Stopwatch.Start ();
164
165                                         proc.Start ();
166
167                                         proc.BeginOutputReadLine ();
168                                         proc.BeginErrorReadLine ();
169
170                                         if (!proc.WaitForExit ((int) _timeout.TotalMilliseconds)) {
171                                                 // Force a thread dump.
172                                                 Syscall.kill (proc.Id, Signum.SIGQUIT);
173                                                 Thread.Sleep (1000);
174
175                                                 try {
176                                                         proc.Kill ();
177                                                 } catch (Exception) {
178                                                 }
179                                         } else
180                                                 result.ExitCode = proc.ExitCode;
181
182                                         result.Stopwatch.Stop ();
183
184                                         result.StandardOutput = stdout.ToString ();
185                                         result.StandardError = stderr.ToString ();
186                                 }
187
188                                 var resultStr = result.ExitCode == null ? "timed out" : $"exited with code: {result.ExitCode}";
189
190                                 Console.ForegroundColor = result.ExitCode != 0 ? ConsoleColor.Red : ConsoleColor.Green;
191                                 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} {bench.Name} took {result.Stopwatch.Elapsed.ToString ("G")} and {resultStr}");
192                                 Console.ResetColor ();
193
194                                 if (result.ExitCode != 0) {
195                                         Console.ForegroundColor = ConsoleColor.Red;
196                                         Console.WriteLine ("===== stdout =====");
197                                         Console.ResetColor ();
198
199                                         Console.WriteLine (result.StandardOutput);
200
201                                         Console.ForegroundColor = ConsoleColor.Red;
202                                         Console.WriteLine ("===== stderr =====");
203                                         Console.ResetColor ();
204
205                                         Console.WriteLine (result.StandardError);
206                                 }
207
208                                 if (_processors.TryGetValue (bench.Name, out var processor))
209                                         processor (result);
210
211                                 results.Add (result);
212                         }
213
214                         sw.Stop ();
215
216                         var successes = results.Count (r => r.ExitCode == 0);
217                         var failures = results.Count (r => r.ExitCode != null && r.ExitCode != 0);
218                         var timeouts = results.Count (r => r.ExitCode == null);
219
220                         var settings = new XmlWriterSettings {
221                                 NewLineOnAttributes = true,
222                                 Indent = true,
223                         };
224
225                         using (var writer = XmlWriter.Create ("TestResult-profiler-stress.xml", settings)) {
226                                 writer.WriteStartDocument ();
227                                 writer.WriteComment ("This file represents the results of running a test suite");
228
229                                 writer.WriteStartElement ("test-results");
230                                 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
231                                 writer.WriteAttributeString ("total", results.Count.ToString ());
232                                 writer.WriteAttributeString ("failures", failures.ToString ());
233                                 writer.WriteAttributeString ("not-run", "0");
234                                 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
235                                 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
236
237                                 writer.WriteStartElement ("environment");
238                                 writer.WriteAttributeString ("nunit-version", "2.4.8.0");
239                                 writer.WriteAttributeString ("clr-version", Environment.Version.ToString ());
240                                 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString ());
241                                 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString ());
242                                 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory);
243                                 writer.WriteAttributeString ("machine-name", Environment.MachineName);
244                                 writer.WriteAttributeString ("user", Environment.UserName);
245                                 writer.WriteAttributeString ("user-domain", Environment.UserDomainName);
246                                 writer.WriteEndElement ();
247
248                                 writer.WriteStartElement ("culture-info");
249                                 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name);
250                                 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name);
251                                 writer.WriteEndElement ();
252
253                                 writer.WriteStartElement ("test-suite");
254                                 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
255                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
256                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
257                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
258                                 writer.WriteStartElement ("results");
259
260                                 writer.WriteStartElement ("test-suite");
261                                 writer.WriteAttributeString ("name", "MonoTests");
262                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
263                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
264                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
265                                 writer.WriteStartElement ("results");
266
267                                 writer.WriteStartElement ("test-suite");
268                                 writer.WriteAttributeString ("name", "profiler-stress");
269                                 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
270                                 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
271                                 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
272                                 writer.WriteStartElement ("results");
273
274                                 foreach (var result in results) {
275                                         var timeoutStr = result.ExitCode == null ? "_timeout" : string.Empty;
276
277                                         writer.WriteStartElement ("test-case");
278                                         writer.WriteAttributeString ("name", $"MonoTests.profiler-stress.{result.Benchmark.Name}{timeoutStr}");
279                                         writer.WriteAttributeString ("executed", "True");
280                                         writer.WriteAttributeString ("success", (result.ExitCode == 0).ToString ());
281                                         writer.WriteAttributeString ("time", ((int) result.Stopwatch.Elapsed.TotalSeconds).ToString ());
282                                         writer.WriteAttributeString ("asserts", result.ExitCode == 0 ? "0" : "1");
283
284                                         if (result.ExitCode != 0) {
285                                                 writer.WriteStartElement ("failure");
286
287                                                 writer.WriteStartElement ("message");
288                                                 writer.WriteCData (FilterInvalidXmlChars (result.StandardOutput));
289                                                 writer.WriteEndElement ();
290
291                                                 writer.WriteStartElement ("stack-trace");
292                                                 writer.WriteCData (FilterInvalidXmlChars (result.StandardError));
293                                                 writer.WriteEndElement ();
294
295                                                 writer.WriteEndElement ();
296                                         }
297
298                                         writer.WriteEndElement ();
299                                 }
300
301                                 writer.WriteEndElement ();
302                                 writer.WriteEndElement ();
303
304                                 writer.WriteEndElement ();
305                                 writer.WriteEndElement ();
306
307                                 writer.WriteEndElement ();
308                                 writer.WriteEndElement ();
309
310                                 writer.WriteEndElement ();
311
312                                 writer.WriteEndDocument ();
313                         }
314
315                         var failureStr = failures + timeouts != 0 ? $" ({failures} failures, {timeouts} timeouts)" : string.Empty;
316
317                         Console.ForegroundColor = failures + timeouts != 0 ? ConsoleColor.Red : ConsoleColor.Green;
318                         Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] Finished with {successes}/{results.Count} passing tests{failureStr}");
319                         Console.ResetColor ();
320
321                         return failures + timeouts;
322                 }
323         }
324 }