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 StringBuilder StandardOutput { get; set; } = new StringBuilder ();
42 public StringBuilder StandardError { get; set; } = new StringBuilder ();
45 static class Program {
47 static readonly string[] _options = new [] {
57 // "calls", // Way too heavy.
67 static readonly TimeSpan _timeout = TimeSpan.FromHours (6);
69 static string FilterInvalidXmlChars (string text) {
70 return Regex.Replace (text, @"[^\x09\x0A\x0D\x20-\uD7FF\uE000-\uFFFD\u10000-\u10FFFF]", string.Empty);
75 var depDir = Path.Combine ("..", "external", "benchmarker");
76 var benchDir = Path.Combine (depDir, "benchmarks");
77 var testDir = Path.Combine (depDir, "tests");
79 var benchmarks = Directory.EnumerateFiles (benchDir, "*.benchmark")
80 .Select (Benchmark.Load)
81 .Where (b => !b.OnlyExplicit && b.ClientCommandLine == null)
82 .OrderBy (b => b.Name)
85 var monoPath = Path.GetFullPath (Path.Combine ("..", "..", "runtime", "mono-wrapper"));
86 var classDir = Path.GetFullPath (Path.Combine ("..", "..", "mcs", "class", "lib", "net_4_x"));
88 var rand = new Random ();
89 var cpus = Environment.ProcessorCount;
91 var results = new List<TestResult> (benchmarks.Length);
93 var sw = Stopwatch.StartNew ();
95 for (var i = 0; i < benchmarks.Length; i++) {
96 var bench = benchmarks [i];
98 var sampleFreq = rand.Next (0, 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 (0, 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)
107 var profOptions = $"sample={sampleFreq},sampling-{sampleMode},maxsamples={maxSamples},heapshot={heapShotFreq}gc,maxframes={maxFrames},{string.Join (",", options)},output=/dev/null";
109 var info = new ProcessStartInfo {
110 UseShellExecute = false,
111 WorkingDirectory = Path.Combine (testDir, bench.TestDirectory),
113 Arguments = $"--debug --profile=log:{profOptions} " + string.Join (" ", bench.CommandLine),
114 RedirectStandardOutput = true,
115 RedirectStandardError = true,
118 info.EnvironmentVariables.Clear ();
119 info.EnvironmentVariables.Add ("MONO_PATH", classDir);
121 var progress = $"({i + 1}/{benchmarks.Length})";
123 Console.ForegroundColor = ConsoleColor.Blue;
124 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} Running {bench.Name} with profiler options: {profOptions}");
125 Console.ResetColor ();
127 var result = new TestResult {
132 using (var proc = new Process ()) {
133 proc.StartInfo = info;
135 proc.OutputDataReceived += (sender, args) => {
136 if (args.Data != null)
137 result.StandardOutput.AppendLine (args.Data);
140 proc.ErrorDataReceived += (sender, args) => {
141 if (args.Data != null)
142 result.StandardError.AppendLine (args.Data);
145 result.Stopwatch.Start ();
149 proc.BeginOutputReadLine ();
150 proc.BeginErrorReadLine ();
152 if (!proc.WaitForExit ((int) _timeout.TotalMilliseconds)) {
153 // Force a thread dump.
154 Syscall.kill (proc.Id, Signum.SIGQUIT);
159 } catch (Exception) {
162 result.ExitCode = proc.ExitCode;
164 result.Stopwatch.Stop ();
167 var resultStr = result.ExitCode == null ? "timed out" : $"exited with code: {result.ExitCode}";
169 Console.ForegroundColor = result.ExitCode != 0 ? ConsoleColor.Red : ConsoleColor.Green;
170 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] {progress} {bench.Name} took {result.Stopwatch.Elapsed.ToString ("G")} and {resultStr}");
171 Console.ResetColor ();
173 if (result.ExitCode != 0) {
174 Console.ForegroundColor = ConsoleColor.Red;
175 Console.WriteLine ("===== stdout =====");
176 Console.ResetColor ();
178 Console.WriteLine (result.StandardOutput.ToString ());
180 Console.ForegroundColor = ConsoleColor.Red;
181 Console.WriteLine ("===== stderr =====");
182 Console.ResetColor ();
184 Console.WriteLine (result.StandardError.ToString ());
187 results.Add (result);
192 var successes = results.Count (r => r.ExitCode == 0);
193 var failures = results.Count (r => r.ExitCode != null && r.ExitCode != 0);
194 var timeouts = results.Count (r => r.ExitCode == null);
196 var settings = new XmlWriterSettings {
197 NewLineOnAttributes = true,
201 using (var writer = XmlWriter.Create ("TestResult-profiler-stress.xml", settings)) {
202 writer.WriteStartDocument ();
203 writer.WriteComment ("This file represents the results of running a test suite");
205 writer.WriteStartElement ("test-results");
206 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
207 writer.WriteAttributeString ("total", results.Count.ToString ());
208 writer.WriteAttributeString ("failures", failures.ToString ());
209 writer.WriteAttributeString ("not-run", "0");
210 writer.WriteAttributeString ("date", DateTime.Now.ToString ("yyyy-MM-dd"));
211 writer.WriteAttributeString ("time", DateTime.Now.ToString ("HH:mm:ss"));
213 writer.WriteStartElement ("environment");
214 writer.WriteAttributeString ("nunit-version", "2.4.8.0");
215 writer.WriteAttributeString ("clr-version", Environment.Version.ToString ());
216 writer.WriteAttributeString ("os-version", Environment.OSVersion.ToString ());
217 writer.WriteAttributeString ("platform", Environment.OSVersion.Platform.ToString ());
218 writer.WriteAttributeString ("cwd", Environment.CurrentDirectory);
219 writer.WriteAttributeString ("machine-name", Environment.MachineName);
220 writer.WriteAttributeString ("user", Environment.UserName);
221 writer.WriteAttributeString ("user-domain", Environment.UserDomainName);
222 writer.WriteEndElement ();
224 writer.WriteStartElement ("culture-info");
225 writer.WriteAttributeString ("current-culture", CultureInfo.CurrentCulture.Name);
226 writer.WriteAttributeString ("current-uiculture", CultureInfo.CurrentUICulture.Name);
227 writer.WriteEndElement ();
229 writer.WriteStartElement ("test-suite");
230 writer.WriteAttributeString ("name", "profiler-stress-tests.dummy");
231 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
232 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
233 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
234 writer.WriteStartElement ("results");
236 writer.WriteStartElement ("test-suite");
237 writer.WriteAttributeString ("name", "MonoTests");
238 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
239 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
240 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
241 writer.WriteStartElement ("results");
243 writer.WriteStartElement ("test-suite");
244 writer.WriteAttributeString ("name", "profiler-stress");
245 writer.WriteAttributeString ("success", (failures + timeouts == 0).ToString ());
246 writer.WriteAttributeString ("time", ((int) sw.Elapsed.TotalSeconds).ToString ());
247 writer.WriteAttributeString ("asserts", (failures + timeouts).ToString ());
248 writer.WriteStartElement ("results");
250 foreach (var result in results) {
251 var timeoutStr = result.ExitCode == null ? "_timeout" : string.Empty;
253 writer.WriteStartElement ("test-case");
254 writer.WriteAttributeString ("name", $"MonoTests.profiler-stress.{result.Benchmark.Name}{timeoutStr}");
255 writer.WriteAttributeString ("executed", "True");
256 writer.WriteAttributeString ("success", (result.ExitCode == 0).ToString ());
257 writer.WriteAttributeString ("time", ((int) result.Stopwatch.Elapsed.TotalSeconds).ToString ());
258 writer.WriteAttributeString ("asserts", result.ExitCode == 0 ? "0" : "1");
260 if (result.ExitCode != 0) {
261 writer.WriteStartElement ("failure");
263 writer.WriteStartElement ("message");
264 writer.WriteCData (FilterInvalidXmlChars (result.StandardOutput.ToString ()));
265 writer.WriteEndElement ();
267 writer.WriteStartElement ("stack-trace");
268 writer.WriteCData (FilterInvalidXmlChars (result.StandardError.ToString ()));
269 writer.WriteEndElement ();
271 writer.WriteEndElement ();
274 writer.WriteEndElement ();
277 writer.WriteEndElement ();
278 writer.WriteEndElement ();
280 writer.WriteEndElement ();
281 writer.WriteEndElement ();
283 writer.WriteEndElement ();
284 writer.WriteEndElement ();
286 writer.WriteEndElement ();
288 writer.WriteEndDocument ();
291 var failureStr = failures + timeouts != 0 ? $" ({failures} failures, {timeouts} timeouts)" : string.Empty;
293 Console.ForegroundColor = failures + timeouts != 0 ? ConsoleColor.Red : ConsoleColor.Green;
294 Console.WriteLine ($"[{sw.Elapsed.ToString ("G")}] Finished with {successes}/{results.Count} passing tests{failureStr}");
295 Console.ResetColor ();
297 return failures + timeouts;