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