forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEventCache.cs
282 lines (261 loc) · 11.2 KB
/
EventCache.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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Diagnostics.Tracing.EventPipe
{
unsafe delegate void ParseBufferItemFunction(ref EventPipeEventHeader header);
internal class EventCache
{
public event ParseBufferItemFunction OnEvent;
public event Action<int> OnEventsDropped;
public unsafe void ProcessEventBlock(byte[] eventBlockData)
{
// parse the header
if(eventBlockData.Length < 20)
{
Debug.Assert(false, "Expected EventBlock of at least 20 bytes");
return;
}
ushort headerSize = BitConverter.ToUInt16(eventBlockData, 0);
if(headerSize < 20 || headerSize > eventBlockData.Length)
{
Debug.Assert(false, "Invalid EventBlock header size");
return;
}
ushort flags = BitConverter.ToUInt16(eventBlockData, 2);
bool useHeaderCompression = (flags & (ushort)EventBlockFlags.HeaderCompression) != 0;
// parse the events
PinnedBuffer buffer = new PinnedBuffer(eventBlockData);
byte* cursor = (byte*)buffer.PinningHandle.AddrOfPinnedObject();
byte* end = cursor + eventBlockData.Length;
cursor += headerSize;
EventMarker eventMarker = new EventMarker(buffer);
long timestamp = 0;
EventPipeEventHeader.ReadFromFormatV4(cursor, useHeaderCompression, ref eventMarker.Header);
if (!_threads.TryGetValue(eventMarker.Header.CaptureThreadId, out EventCacheThread thread))
{
thread = new EventCacheThread();
thread.SequenceNumber = eventMarker.Header.SequenceNumber - 1;
AddThread(eventMarker.Header.CaptureThreadId, thread);
}
eventMarker = new EventMarker(buffer);
while (cursor < end)
{
EventPipeEventHeader.ReadFromFormatV4(cursor, useHeaderCompression, ref eventMarker.Header);
bool isSortedEvent = eventMarker.Header.IsSorted;
timestamp = eventMarker.Header.TimeStamp;
int sequenceNumber = eventMarker.Header.SequenceNumber;
if (isSortedEvent)
{
thread.LastCachedEventTimestamp = timestamp;
// sorted events are the only time the captureThreadId should change
long captureThreadId = eventMarker.Header.CaptureThreadId;
if (!_threads.TryGetValue(captureThreadId, out thread))
{
thread = new EventCacheThread();
thread.SequenceNumber = sequenceNumber - 1;
AddThread(captureThreadId, thread);
}
}
int droppedEvents = (int)Math.Min(int.MaxValue, sequenceNumber - thread.SequenceNumber - 1);
if(droppedEvents > 0)
{
OnEventsDropped?.Invoke(droppedEvents);
}
else
{
// When a thread id is recycled the sequenceNumber can abruptly reset to 1 which
// makes droppedEvents go negative
Debug.Assert(droppedEvents == 0 || sequenceNumber == 1);
}
thread.SequenceNumber = sequenceNumber;
if(isSortedEvent)
{
SortAndDispatch(timestamp);
OnEvent?.Invoke(ref eventMarker.Header);
}
else
{
thread.Events.Enqueue(eventMarker);
}
cursor += eventMarker.Header.TotalNonHeaderSize + eventMarker.Header.HeaderSize;
EventMarker lastEvent = eventMarker;
eventMarker = new EventMarker(buffer);
eventMarker.Header = lastEvent.Header;
}
thread.LastCachedEventTimestamp = timestamp;
}
public unsafe void ProcessSequencePointBlock(byte[] sequencePointBytes)
{
const int SizeOfTimestampAndThreadCount = 12;
const int SizeOfThreadIdAndSequenceNumber = 12;
if(sequencePointBytes.Length < SizeOfTimestampAndThreadCount)
{
Debug.Assert(false, "Bad sequence point block length");
return;
}
long timestamp = BitConverter.ToInt64(sequencePointBytes, 0);
int threadCount = BitConverter.ToInt32(sequencePointBytes, 8);
if(sequencePointBytes.Length < SizeOfTimestampAndThreadCount + threadCount*SizeOfThreadIdAndSequenceNumber)
{
Debug.Assert(false, "Bad sequence point block length");
return;
}
SortAndDispatch(timestamp);
foreach(EventCacheThread thread in _threads.Values)
{
Debug.Assert(thread.Events.Count == 0, "There shouldn't be any pending events after a sequence point");
thread.Events.Clear();
thread.Events.TrimExcess();
}
int cursor = SizeOfTimestampAndThreadCount;
for(int i = 0; i < threadCount; i++)
{
long captureThreadId = BitConverter.ToInt64(sequencePointBytes, cursor);
int sequenceNumber = BitConverter.ToInt32(sequencePointBytes, cursor + 8);
if (!_threads.TryGetValue(captureThreadId, out EventCacheThread thread))
{
if(sequenceNumber > 0)
{
OnEventsDropped?.Invoke(sequenceNumber);
}
thread = new EventCacheThread();
thread.SequenceNumber = sequenceNumber;
AddThread(captureThreadId, thread);
}
else
{
int droppedEvents = unchecked(sequenceNumber - thread.SequenceNumber);
if (droppedEvents > 0)
{
OnEventsDropped?.Invoke(droppedEvents);
}
else
{
// When a thread id is recycled the sequenceNumber can abruptly reset to 1 which
// makes droppedEvents go negative
Debug.Assert(droppedEvents == 0 || sequenceNumber == 1);
}
thread.SequenceNumber = sequenceNumber;
}
cursor += SizeOfThreadIdAndSequenceNumber;
}
}
/// <summary>
/// After all events have been parsed we could have some straglers that weren't
/// earlier than any sorted event. Sort and dispatch those now.
/// </summary>
public void Flush()
{
SortAndDispatch(long.MaxValue);
}
private unsafe void SortAndDispatch(long stopTimestamp)
{
// This sort could be made faster by using a min-heap but this is a simple place to start
List<Queue<EventMarker>> threadQueues = new List<Queue<EventMarker>>(_threads.Values.Select(t => t.Events));
while(true)
{
long lowestTimestamp = stopTimestamp;
Queue<EventMarker> oldestEventQueue = null;
foreach(Queue<EventMarker> threadQueue in threadQueues)
{
if(threadQueue.Count == 0)
{
continue;
}
long eventTimestamp = threadQueue.Peek().Header.TimeStamp;
if (eventTimestamp < lowestTimestamp)
{
oldestEventQueue = threadQueue;
lowestTimestamp = eventTimestamp;
}
}
if(oldestEventQueue == null)
{
break;
}
else
{
EventMarker eventMarker = oldestEventQueue.Dequeue();
OnEvent?.Invoke(ref eventMarker.Header);
GC.KeepAlive(eventMarker);
}
}
// If the app creates and destroys threads over time we need to flush old threads
// from the cache or memory usage will grow unbounded. AddThread handles the
// the thread objects but the storage for the queue elements also does not shrink
// below the high water mark unless we free it explicitly.
foreach(Queue<EventMarker> q in threadQueues)
{
if(q.Count == 0)
{
q.TrimExcess();
}
}
}
private void AddThread(long captureThreadId, EventCacheThread thread)
{
// To ensure we don't have unbounded growth we evict old threads to make room
// for new ones. Evicted threads can always be re-added later if they log again
// but there are two consequences:
// a) We won't detect lost events on that thread after eviction
// b) If the thread still had events pending dispatch they will be lost
// We pick the thread that has gone the longest since it last logged an event
// under the presumption that it is probably dead, has no events, and won't
// log again.
//
// In the future if we had explicit thread death notification events we could keep
// this cache leaner.
if(_threads.Count >= 5000)
{
long oldestThreadCaptureId = -1;
long smallestTimestamp = long.MaxValue;
foreach(var kv in _threads)
{
if(kv.Value.LastCachedEventTimestamp < smallestTimestamp)
{
smallestTimestamp = kv.Value.LastCachedEventTimestamp;
oldestThreadCaptureId = kv.Key;
}
}
Debug.Assert(oldestThreadCaptureId != -1);
_threads.Remove(oldestThreadCaptureId);
}
_threads[captureThreadId] = thread;
}
Dictionary<long, EventCacheThread> _threads = new Dictionary<long, EventCacheThread>();
}
internal class EventCacheThread
{
public Queue<EventMarker> Events = new Queue<EventMarker>();
public int SequenceNumber;
public long LastCachedEventTimestamp;
}
internal class EventMarker
{
public EventMarker(PinnedBuffer buffer)
{
Buffer = buffer;
}
public EventPipeEventHeader Header;
public PinnedBuffer Buffer;
}
internal class PinnedBuffer
{
public PinnedBuffer(byte[] data)
{
Data = data;
PinningHandle = GCHandle.Alloc(data, GCHandleType.Pinned);
}
~PinnedBuffer()
{
PinningHandle.Free();
}
public byte[] Data { get; private set; }
public GCHandle PinningHandle { get; private set; }
}
}