-
Notifications
You must be signed in to change notification settings - Fork 354
/
TraceEventExtensions.cs
445 lines (369 loc) · 18.6 KB
/
TraceEventExtensions.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
// 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.Collections.Generic;
using System.Globalization;
using System.Text;
using Microsoft.Diagnostics.Tracing;
namespace Microsoft.Diagnostics.Monitoring.EventPipe
{
internal static class TraceEventExtensions
{
private static HashSet<string> inactiveSharedSessions = new(StringComparer.OrdinalIgnoreCase);
public static bool TryGetCounterPayload(this TraceEvent traceEvent, CounterFilter filter, string sessionId, string clientId, out ICounterPayload payload)
{
payload = null;
if ("EventCounters".Equals(traceEvent.EventName))
{
IDictionary<string, object> payloadVal = (IDictionary<string, object>)(traceEvent.PayloadValue(0));
IDictionary<string, object> payloadFields = (IDictionary<string, object>)(payloadVal["Payload"]);
//Make sure we are part of the requested series. If multiple clients request metrics, all of them get the metrics.
string series = payloadFields["Series"].ToString();
string counterName = payloadFields["Name"].ToString();
string metadata = payloadFields["Metadata"].ToString();
//CONSIDER
//Concurrent counter sessions do not each get a separate interval. Instead the payload
//for _all_ the counters changes the Series to be the lowest specified interval, on a per provider basis.
//Currently the CounterFilter will remove any data whose Series doesn't match the requested interval.
if (!filter.IsIncluded(traceEvent.ProviderName, counterName, GetInterval(series)))
{
return false;
}
float intervalSec = (float)payloadFields["IntervalSec"];
string displayName = payloadFields["DisplayName"].ToString();
string displayUnits = payloadFields["DisplayUnits"].ToString();
double value = 0;
CounterType counterType = CounterType.Metric;
if (payloadFields["CounterType"].Equals("Mean"))
{
value = (double)payloadFields["Mean"];
}
else if (payloadFields["CounterType"].Equals("Sum"))
{
counterType = CounterType.Rate;
value = (double)payloadFields["Increment"];
if (string.IsNullOrEmpty(displayUnits))
{
displayUnits = "count";
}
//TODO Should we make these /sec like the dotnet-counters tool?
}
// Note that dimensional data such as pod and namespace are automatically added in prometheus and azure monitor scenarios.
// We no longer added it here.
payload = new CounterPayload(
traceEvent.TimeStamp,
traceEvent.ProviderName,
counterName, displayName,
displayUnits,
value,
counterType,
intervalSec,
metadata);
return true;
}
if (clientId != null && !inactiveSharedSessions.Contains(clientId) && MonitoringSourceConfiguration.SystemDiagnosticsMetricsProviderName.Equals(traceEvent.ProviderName))
{
if (traceEvent.EventName == "BeginInstrumentReporting")
{
// Do we want to log something for this?
//HandleBeginInstrumentReporting(traceEvent);
}
if (traceEvent.EventName == "HistogramValuePublished")
{
HandleHistogram(traceEvent, filter, sessionId, out payload);
}
else if (traceEvent.EventName == "GaugeValuePublished")
{
HandleGauge(traceEvent, filter, sessionId, out payload);
}
else if (traceEvent.EventName == "CounterRateValuePublished")
{
HandleCounterRate(traceEvent, filter, sessionId, out payload);
}
else if (traceEvent.EventName == "UpDownCounterRateValuePublished")
{
HandleUpDownCounterValue(traceEvent, filter, sessionId, out payload);
}
else if (traceEvent.EventName == "TimeSeriesLimitReached")
{
HandleTimeSeriesLimitReached(traceEvent, sessionId, out payload);
}
else if (traceEvent.EventName == "HistogramLimitReached")
{
HandleHistogramLimitReached(traceEvent, sessionId, out payload);
}
else if (traceEvent.EventName == "Error")
{
HandleError(traceEvent, sessionId, out payload);
}
else if (traceEvent.EventName == "ObservableInstrumentCallbackError")
{
HandleObservableInstrumentCallbackError(traceEvent, sessionId, out payload);
}
else if (traceEvent.EventName == "MultipleSessionsNotSupportedError")
{
HandleMultipleSessionsNotSupportedError(traceEvent, sessionId, out payload);
}
else if (traceEvent.EventName == "MultipleSessionsConfiguredIncorrectlyError")
{
HandleMultipleSessionsConfiguredIncorrectlyError(traceEvent, clientId, out payload);
}
return payload != null;
}
return false;
}
private static void HandleGauge(TraceEvent obj, CounterFilter filter, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId != sessionId)
{
return;
}
string meterName = (string)obj.PayloadValue(1);
//string meterVersion = (string)obj.PayloadValue(2);
string instrumentName = (string)obj.PayloadValue(3);
string unit = (string)obj.PayloadValue(4);
string tags = (string)obj.PayloadValue(5);
string lastValueText = (string)obj.PayloadValue(6);
if (!filter.IsIncluded(meterName, instrumentName))
{
return;
}
// the value might be an empty string indicating no measurement was provided this collection interval
if (double.TryParse(lastValueText, NumberStyles.Number | NumberStyles.Float, CultureInfo.InvariantCulture, out double lastValue))
{
payload = new GaugePayload(meterName, instrumentName, null, unit, tags, lastValue, obj.TimeStamp);
}
else
{
// for observable instruments we assume the lack of data is meaningful and remove it from the UI
// this happens when the Gauge callback function throws an exception.
payload = new CounterEndedPayload(meterName, instrumentName, obj.TimeStamp);
}
}
private static void HandleCounterRate(TraceEvent traceEvent, CounterFilter filter, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)traceEvent.PayloadValue(0);
if (payloadSessionId != sessionId)
{
return;
}
string meterName = (string)traceEvent.PayloadValue(1);
//string meterVersion = (string)obj.PayloadValue(2);
string instrumentName = (string)traceEvent.PayloadValue(3);
string unit = (string)traceEvent.PayloadValue(4);
string tags = (string)traceEvent.PayloadValue(5);
string rateText = (string)traceEvent.PayloadValue(6);
if (!filter.IsIncluded(meterName, instrumentName))
{
return;
}
if (double.TryParse(rateText, NumberStyles.Number | NumberStyles.Float, CultureInfo.InvariantCulture, out double rate))
{
payload = new RatePayload(meterName, instrumentName, null, unit, tags, rate, filter.DefaultIntervalSeconds, traceEvent.TimeStamp);
}
else
{
// for observable instruments we assume the lack of data is meaningful and remove it from the UI
// this happens when the ObservableCounter callback function throws an exception
// or when the ObservableCounter doesn't include a measurement for a particular set of tag values.
payload = new CounterEndedPayload(meterName, instrumentName, traceEvent.TimeStamp);
}
}
private static void HandleUpDownCounterValue(TraceEvent traceEvent, CounterFilter filter, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)traceEvent.PayloadValue(0);
if (payloadSessionId != sessionId || traceEvent.Version < 1) // Version 1 added the value field.
{
return;
}
string meterName = (string)traceEvent.PayloadValue(1);
//string meterVersion = (string)obj.PayloadValue(2);
string instrumentName = (string)traceEvent.PayloadValue(3);
string unit = (string)traceEvent.PayloadValue(4);
string tags = (string)traceEvent.PayloadValue(5);
//string rateText = (string)traceEvent.PayloadValue(6); // Not currently using rate for UpDownCounters.
string valueText = (string)traceEvent.PayloadValue(7);
if (!filter.IsIncluded(meterName, instrumentName))
{
return;
}
if (double.TryParse(valueText, NumberStyles.Number | NumberStyles.Float, CultureInfo.InvariantCulture, out double value))
{
// UpDownCounter reports the value, not the rate - this is different than how Counter behaves.
payload = new UpDownCounterPayload(meterName, instrumentName, null, unit, tags, value, traceEvent.TimeStamp);
}
else
{
// for observable instruments we assume the lack of data is meaningful and remove it from the UI
// this happens when the ObservableUpDownCounter callback function throws an exception
// or when the ObservableUpDownCounter doesn't include a measurement for a particular set of tag values.
payload = new CounterEndedPayload(meterName, instrumentName, traceEvent.TimeStamp);
}
}
private static void HandleHistogram(TraceEvent obj, CounterFilter filter, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId != sessionId)
{
return;
}
string meterName = (string)obj.PayloadValue(1);
//string meterVersion = (string)obj.PayloadValue(2);
string instrumentName = (string)obj.PayloadValue(3);
string unit = (string)obj.PayloadValue(4);
string tags = (string)obj.PayloadValue(5);
string quantilesText = (string)obj.PayloadValue(6);
if (!filter.IsIncluded(meterName, instrumentName))
{
return;
}
//Note quantiles can be empty.
IList<Quantile> quantiles = ParseQuantiles(quantilesText);
payload = new PercentilePayload(meterName, instrumentName, null, unit, tags, quantiles, obj.TimeStamp);
}
private static void HandleHistogramLimitReached(TraceEvent obj, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId != sessionId)
{
return;
}
string errorMessage = $"Warning: Histogram tracking limit reached. Not all data is being shown. The limit can be changed with maxHistograms but will use more memory in the target process.";
payload = new ErrorPayload(errorMessage);
}
private static void HandleTimeSeriesLimitReached(TraceEvent obj, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId != sessionId)
{
return;
}
string errorMessage = "Warning: Time series tracking limit reached. Not all data is being shown. The limit can be changed with maxTimeSeries but will use more memory in the target process.";
payload = new ErrorPayload(errorMessage, obj.TimeStamp);
}
private static void HandleError(TraceEvent obj, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
string error = (string)obj.PayloadValue(1);
if (payloadSessionId != sessionId)
{
return;
}
string errorMessage = "Error reported from target process:" + Environment.NewLine + error;
payload = new ErrorPayload(errorMessage, obj.TimeStamp);
}
private static void HandleMultipleSessionsNotSupportedError(TraceEvent obj, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId == sessionId)
{
// If our session is the one that is running then the error is not for us,
// it is for some other session that came later
return;
}
else
{
string errorMessage = "Error: Another metrics collection session is already in progress for the target process." + Environment.NewLine +
"Concurrent sessions are not supported.";
payload = new ErrorPayload(errorMessage, obj.TimeStamp);
}
}
internal static bool TryCreateSharedSessionConfiguredIncorrectlyMessage(TraceEvent obj, string clientId, out string message)
{
message = string.Empty;
string payloadSessionId = (string)obj.PayloadValue(0);
if (payloadSessionId != clientId)
{
// If our session is not the one that is running then the error is not for us,
// it is for some other session that came later
return false;
}
string expectedMaxHistograms = (string)obj.PayloadValue(1);
string actualMaxHistograms = (string)obj.PayloadValue(2);
string expectedMaxTimeSeries = (string)obj.PayloadValue(3);
string actualMaxTimeSeries = (string)obj.PayloadValue(4);
string expectedRefreshInterval = (string)obj.PayloadValue(5);
string actualRefreshInterval = (string)obj.PayloadValue(6);
StringBuilder errorMessage = new("Error: Another shared metrics collection session is already in progress for the target process." + Environment.NewLine +
"To enable this metrics session alongside the existing session, update the following values:" + Environment.NewLine);
if (expectedMaxHistograms != actualMaxHistograms)
{
errorMessage.Append($"MaxHistograms: {expectedMaxHistograms}" + Environment.NewLine);
}
if (expectedMaxTimeSeries != actualMaxTimeSeries)
{
errorMessage.Append($"MaxTimeSeries: {expectedMaxTimeSeries}" + Environment.NewLine);
}
if (expectedRefreshInterval != actualRefreshInterval)
{
errorMessage.Append($"IntervalSeconds: {expectedRefreshInterval}" + Environment.NewLine);
}
message = errorMessage.ToString();
return true;
}
private static void HandleMultipleSessionsConfiguredIncorrectlyError(TraceEvent obj, string clientId, out ICounterPayload payload)
{
payload = null;
if (TryCreateSharedSessionConfiguredIncorrectlyMessage(obj, clientId, out string message))
{
payload = new ErrorPayload(message.ToString(), obj.TimeStamp);
inactiveSharedSessions.Add(clientId);
}
}
private static void HandleObservableInstrumentCallbackError(TraceEvent obj, string sessionId, out ICounterPayload payload)
{
payload = null;
string payloadSessionId = (string)obj.PayloadValue(0);
string error = (string)obj.PayloadValue(1);
if (payloadSessionId != sessionId)
{
return;
}
string errorMessage = "Exception thrown from an observable instrument callback in the target process:" + Environment.NewLine +
error;
payload = new ErrorPayload(errorMessage, obj.TimeStamp);
}
private static IList<Quantile> ParseQuantiles(string quantileList)
{
string[] quantileParts = quantileList.Split(';', StringSplitOptions.RemoveEmptyEntries);
List<Quantile> quantiles = new();
foreach (string quantile in quantileParts)
{
string[] keyValParts = quantile.Split('=', StringSplitOptions.RemoveEmptyEntries);
if (keyValParts.Length != 2)
{
continue;
}
if (!double.TryParse(keyValParts[0], out double key))
{
continue;
}
if (!double.TryParse(keyValParts[1], out double val))
{
continue;
}
quantiles.Add(new Quantile(key, val));
}
return quantiles;
}
private static int GetInterval(string series)
{
const string comparison = "Interval=";
int interval = 0;
if (series.StartsWith(comparison, StringComparison.OrdinalIgnoreCase))
{
int.TryParse(series.AsSpan(comparison.Length), out interval);
}
return interval;
}
}
}