2 using System.Collections.Generic;
3 using System.Diagnostics;
4 using System.Globalization;
8 using System.Text.RegularExpressions;
9 using System.Threading;
11 using Mono.Unix.Native;
12 using Newtonsoft.Json;
14 // Shut up CLS compliance warnings from Json.NET.
15 [assembly: CLSCompliant (true)]
17 namespace Mono.Profiling.Tests.Stress {
19 // https://github.com/xamarin/benchmarker/blob/master/tools/libdbmodel/Benchmark.cs
20 sealed class Benchmark {
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; }
29 public static Benchmark Load (string file)
31 return JsonConvert.DeserializeObject<Benchmark> (File.ReadAllText (file));
35 sealed class TestResult {
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; }
45 static class Program {
47 static readonly string[] _options = new [] {
60 static readonly TimeSpan _timeout = TimeSpan.FromHours (8);
62 static readonly Dictionary<string, Action<TestResult>> _processors = new Dictionary<string, Action<TestResult>> () {
63 { "msbiology", Process32BitOutOfMemory },
66 static string FilterInvalidXmlChars (string text) {
67 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", string.Empty);
70 static void Process32BitOutOfMemory (TestResult result)
72 if (Environment.Is64BitProcess)
75 if (result.ExitCode == null || result.ExitCode == 0)
78 if (result.StandardError.Contains ("OutOfMemoryException"))
84 var depDir = Path.Combine ("..", "external", "benchmarker");
85 var benchDir = Path.Combine (depDir, "benchmarks");
86 var testDir = Path.Combine (depDir, "tests");
88 var benchmarks = Directory.EnumerateFiles (benchDir, "*.benchmark")
89 .Select (Benchmark.Load)
90 .Where (b => !b.OnlyExplicit && b.ClientCommandLine == null)
91 .OrderBy (b => b.Name)
94 var monoPath = Path.GetFullPath (Path.Combine ("..", "..", "runtime", "mono-wrapper"));
95 var classDir = Path.GetFullPath (Path.Combine ("..", "..", "mcs", "class", "lib", "net_4_x"));
97 var rand = new Random ();
98 var cpus = Environment.ProcessorCount;
100 var results = new List<TestResult> (benchmarks.Length);
102 var sw = Stopwatch.StartNew ();
104 for (var i = 0; i < benchmarks.Length; i++) {
105 var bench = benchmarks [i];
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)
116 var profOptions = $"maxframes={maxFrames},{string.Join (",", options)},output=/dev/null";
119 profOptions += $",sample{sampleMode}={sampleFreq},maxsamples={maxSamples}";
121 if (heapShotFreq > 0)
122 profOptions += $",heapshot={heapShotFreq}gc";
124 var info = new ProcessStartInfo {
125 UseShellExecute = false,
126 WorkingDirectory = Path.Combine (testDir, bench.TestDirectory),
128 Arguments = $"--debug --profile=log:{profOptions} " + string.Join (" ", bench.CommandLine),
129 RedirectStandardOutput = true,
130 RedirectStandardError = true,
133 info.EnvironmentVariables.Clear ();
134 info.EnvironmentVariables.Add ("MONO_PATH", classDir);
136 var progress = $"({i + 1}/{benchmarks.Length})";
138 Console.ForegroundColor = ConsoleColor.Blue;
139 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} Running {bench.Name} with profiler options: {profOptions}");
140 Console.ResetColor ();
142 var result = new TestResult {
147 using (var proc = new Process ()) {
148 proc.StartInfo = info;
150 var stdout = new StringBuilder ();
151 var stderr = new StringBuilder ();
153 proc.OutputDataReceived += (sender, args) => {
154 if (args.Data != null)
156 stdout.AppendLine (args.Data);
159 proc.ErrorDataReceived += (sender, args) => {
160 if (args.Data != null)
162 stderr.AppendLine (args.Data);
165 result.Stopwatch.Start ();
169 proc.BeginOutputReadLine ();
170 proc.BeginErrorReadLine ();
172 if (!proc.WaitForExit ((int) _timeout.TotalMilliseconds)) {
173 // Force a thread dump.
174 Syscall.kill (proc.Id, Signum.SIGQUIT);
179 } catch (Exception) {
182 result.ExitCode = proc.ExitCode;
184 result.Stopwatch.Stop ();
186 result.StandardOutput = stdout.ToString ();
187 result.StandardError = stderr.ToString ();
190 var resultStr = result.ExitCode == null ? "timed out" : $"exited with code: {result.ExitCode}";
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 ();
196 if (result.ExitCode != 0) {
197 Console.ForegroundColor = ConsoleColor.Red;
198 Console.WriteLine ("===== stdout =====");
199 Console.ResetColor ();
201 Console.WriteLine (result.StandardOutput);
203 Console.ForegroundColor = ConsoleColor.Red;
204 Console.WriteLine ("===== stderr =====");
205 Console.ResetColor ();
207 Console.WriteLine (result.StandardError);
210 if (_processors.TryGetValue (bench.Name, out var processor))
213 results.Add (result);
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);
222 var settings = new XmlWriterSettings {
223 NewLineOnAttributes = true,
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");
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"));
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 ();
250 writer.WriteStartElement ("culture-info");
251 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name);
252 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name);
253 writer.WriteEndElement ();
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");
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");
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");
276 foreach (var result in results) {
277 var timeoutStr = result.ExitCode == null ? "_timeout" : string.Empty;
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");
286 if (result.ExitCode != 0) {
287 writer.WriteStartElement ("failure");
289 writer.WriteStartElement ("message");
290 writer.WriteCData (FilterInvalidXmlChars (result.StandardOutput));
291 writer.WriteEndElement ();
293 writer.WriteStartElement ("stack-trace");
294 writer.WriteCData (FilterInvalidXmlChars (result.StandardError));
295 writer.WriteEndElement ();
297 writer.WriteEndElement ();
300 writer.WriteEndElement ();
303 writer.WriteEndElement ();
304 writer.WriteEndElement ();
306 writer.WriteEndElement ();
307 writer.WriteEndElement ();
309 writer.WriteEndElement ();
310 writer.WriteEndElement ();
312 writer.WriteEndElement ();
314 writer.WriteEndDocument ();
317 var failureStr = failures + timeouts != 0 ? $" ({failures} failures, {timeouts} timeouts)" : string.Empty;
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 ();
323 return failures + timeouts;