-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
NativeRuntimeEventSourceTest.cs
330 lines (275 loc) · 11.4 KB
/
NativeRuntimeEventSourceTest.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace Tracing.Tests
{
public sealed class NativeRuntimeEventSourceTest
{
[Fact]
public static void TestEntryPoint()
{
// Access ArrayPool.Shared.Rent() before the test to avoid the deadlock reported
// in https://github.com/dotnet/runtime/issues/86233. This is a real issue,
// but only seen if you have a short lived EventListener and create EventSources
// in your OnEventWritten callback so we don't expect customers to hit it.
byte[] localBuffer = ArrayPool<byte>.Shared.Rent(10);
Console.WriteLine($"buffer length={localBuffer.Length}");
// Create deaf listener
Listener.Level = EventLevel.Critical;
Listener.EnableKeywords = EventKeywords.None;
using (Listener noEventsListener = new("NoEvents"))
{
using (NativeOverlappedClass nativeOverlappedClass = new())
{
// Create an EventListener.
Listener.Level = EventLevel.Verbose;
const EventKeywords EventKeywordThreading = (EventKeywords)65536;
Listener.EnableKeywords = (EventKeywords)0x4c14fccbd | EventKeywordThreading;
// Check for events e.g. ThreadPoolIODequeue = 64
// At least some of these events can be found in "src\libraries\System.Private.CoreLib\src\System\Threading\NativeRuntimeEventSource.PortableThreadPool.NativeSinks.cs"
Listener.TargetEventIds(63, 64, 65);
using (Listener listener = new())
{
CancellationTokenSource cts = new();
// Trigger the allocator task.
Task.Run(() =>
{
while (!cts.IsCancellationRequested)
{
for (int i = 0; i < 1000; i++)
{
GC.KeepAlive(new object());
}
Thread.Sleep(10);
}
});
// If on Windows, attempt some Overlapped IO (triggers ThreadPool events)
DoOverlappedIO();
// Trigger EventId 63 and 64
nativeOverlappedClass.ThreadPoolQueue();
// Generate some GC events.
GC.Collect(2, GCCollectionMode.Forced);
Stopwatch sw = Stopwatch.StartNew();
while (sw.Elapsed <= TimeSpan.FromMinutes(1d / 12d))
{
Thread.Sleep(100);
if ((listener.EventsLeft <= 0) || (!OperatingSystem.IsWindows() && listener.EventCount > 0))
{
break;
}
}
cts.Cancel();
Assert2.True("listener.EventCount > 0", listener.EventCount > 0);
if (OperatingSystem.IsWindows())
{
StringBuilder stringBuilder = new();
foreach (var e in listener.GetFailedTargetEvents())
{
stringBuilder.Append((stringBuilder.Length > 0) ? ", " : "");
stringBuilder.Append(e.Key);
}
Assert2.True($"At least one of the EventIds ({stringBuilder}) where heard.", stringBuilder.Length < 1);
}
}
}
// Generate some more GC events.
GC.Collect(2, GCCollectionMode.Forced);
// Ensure that we've seen no events.
Assert2.True("noEventsListener.EventCount == 0", noEventsListener.EventCount == 0);
}
}
private static unsafe void DoOverlappedIO()
{
if (!OperatingSystem.IsWindows())
{
return;
}
Console.WriteLine("DOOVERLAPPEDIO");
Overlapped overlapped = new();
NativeOverlapped* pOverlap = overlapped.Pack(null, null);
Overlapped.Free(pOverlap);
}
private static class Assert2
{
public static void True(string name, bool condition)
{
if (!condition)
{
throw new Exception(
string.Format("Condition '{0}' is not true", name));
}
}
}
}
internal sealed unsafe class NativeOverlappedClass : IDisposable
{
private bool disposedValue;
private readonly NativeOverlapped* nativeOverlapped;
public NativeOverlappedClass()
{
if (OperatingSystem.IsWindows())
{
nativeOverlapped = new Overlapped().Pack(null, null);
}
}
public bool ThreadPoolQueue()
{
return OperatingSystem.IsWindows() && ThreadPool.UnsafeQueueNativeOverlapped(nativeOverlapped);
}
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
}
if (OperatingSystem.IsWindows())
{
Overlapped.Free(nativeOverlapped);
}
disposedValue = true;
}
}
~NativeOverlappedClass()
{
Dispose(disposing: false);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
internal sealed class Listener : EventListener
{
public static string EventSourceName = "Microsoft-Windows-DotNETRuntime";
public static EventLevel Level = EventLevel.Verbose;
public static EventKeywords EnableKeywords = EventKeywords.All;
public int EventCount { get; private set; } = 0;
public int EventsLeft { get; private set; } = 0;
private static readonly ConcurrentBag<int> targetEventIds = new();
private static readonly (string, string) defaultEventSourceNameName = ("Failed to listen", "Was not heard or didn't fire");
private readonly string name = "";
private readonly ConcurrentDictionary<int, (string, string)> eventIdSourceNameNames = new();
public Listener(string name = nameof(Listener))
{
this.name = $"({name}) ";
}
public static void TargetEventIds(params int[] ids)
{
targetEventIds.Clear();
foreach (int id in ids)
{
targetEventIds.Add(id);
}
}
public IEnumerable<KeyValuePair<int, (string, string)>> GetFailedTargetEvents()
{
foreach (KeyValuePair<int, (string, string)> e in eventIdSourceNameNames)
{
if (e.Value == defaultEventSourceNameName)
{
yield return e;
}
}
}
public override void Dispose()
{
base.Dispose();
foreach (KeyValuePair<int, (string, string)> e in eventIdSourceNameNames)
{
WriteLine(e);
}
WriteLine("\n");
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if ((eventSource.Name == EventSourceName) && eventIdSourceNameNames.IsEmpty)
{
foreach (var targetEventId in targetEventIds)
{
eventIdSourceNameNames[targetEventId] = defaultEventSourceNameName;
}
EventsLeft = eventIdSourceNameNames.Count;
EnableEvents(eventSource, Level, EnableKeywords);
}
}
protected override void OnEventWritten(EventWrittenEventArgs eventWrittenEventArgs)
{
EventCount++;
KeyValuePair<int, (string SourceName, string Name)> e = new(
eventWrittenEventArgs.EventId,
(eventWrittenEventArgs.EventSource.Name, eventWrittenEventArgs.EventName ?? ""));
EventsLeft -= (eventIdSourceNameNames.TryGetValue(e.Key, out (string, string) value) && value == defaultEventSourceNameName) ? 1 : 0;
eventIdSourceNameNames[e.Key] = e.Value;
WriteLine(e);
WriteLine($"OSThreadId = {eventWrittenEventArgs.OSThreadId}", ConsoleColor.Yellow);
WriteLine($"TimeStamp: {eventWrittenEventArgs.TimeStamp.ToLocalTime()}");
WriteLine($"local time: {DateTime.Now}");
WriteLine($"Difference: {DateTime.UtcNow - eventWrittenEventArgs.TimeStamp}");
for (int i = 0; (i < eventWrittenEventArgs.PayloadNames?.Count) && (i < eventWrittenEventArgs.Payload?.Count); i++)
{
WriteLine($"{eventWrittenEventArgs.PayloadNames[i]} = {eventWrittenEventArgs.Payload[i]}", ConsoleColor.Magenta);
}
WriteLine("\n");
}
private static bool ConsoleForegroundColorNotSupported =>
OperatingSystem.IsAndroid() ||
OperatingSystem.IsIOS() ||
OperatingSystem.IsTvOS() ||
OperatingSystem.IsBrowser() ||
OperatingSystem.IsWasi();
private ConsoleColor ConsoleForegroundColor
{
get
{
if (ConsoleForegroundColorNotSupported)
return (ConsoleColor)(-1);
return Console.ForegroundColor;
}
set
{
if (ConsoleForegroundColorNotSupported)
return;
Console.ForegroundColor = value;
}
}
private void Write(object? o = null, ConsoleColor? consoleColor = null)
{
ConsoleColor foregroundColor = ConsoleForegroundColor;
if (o is KeyValuePair<int, (string, string)> e)
{
ConsoleForegroundColor = ConsoleColor.Cyan;
Console.Write(name);
ConsoleForegroundColor = (e.Value != defaultEventSourceNameName) ? ConsoleColor.Green : ConsoleColor.Red;
}
else if (consoleColor != null)
{
ConsoleForegroundColor = (ConsoleColor)consoleColor;
}
Console.Write(o);
ConsoleForegroundColor = foregroundColor;
}
private void WriteLine(object? o = null, ConsoleColor? consoleColor = null)
{
Write(o, consoleColor);
Console.WriteLine();
}
}
}