-
Notifications
You must be signed in to change notification settings - Fork 315
/
EventLogDataCollector.cs
586 lines (494 loc) · 20.3 KB
/
EventLogDataCollector.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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Xml;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers;
using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces;
using Resource = Microsoft.TestPlatform.Extensions.EventLogCollector.Resources.Resources;
namespace Microsoft.TestPlatform.Extensions.EventLogCollector;
/// <summary>
/// A data collector that collects event log data
/// </summary>
[DataCollectorTypeUri(DefaultUri)]
[DataCollectorFriendlyName("Event Log")]
public class EventLogDataCollector : DataCollector
{
/// <summary>
/// The event log file name.
/// </summary>
private const string EventLogFileName = "Event Log";
/// <summary>
/// DataCollector URI.
/// </summary>
private const string DefaultUri = @"datacollector://Microsoft/EventLog/2.0";
/// <summary>
/// Event handler delegate for the SessionStart event
/// </summary>
private readonly EventHandler<SessionStartEventArgs> _sessionStartEventHandler;
/// <summary>
/// Event handler delegate for the SessionEnd event
/// </summary>
private readonly EventHandler<SessionEndEventArgs> _sessionEndEventHandler;
/// <summary>
/// Event handler delegate for the TestCaseStart event
/// </summary>
private readonly EventHandler<TestCaseStartEventArgs> _testCaseStartEventHandler;
/// <summary>
/// Event handler delegate for the TestCaseEnd event
/// </summary>
private readonly EventHandler<TestCaseEndEventArgs> _testCaseEndEventHandler;
/// <summary>
/// The event log directories.
/// </summary>
private readonly List<string> _eventLogDirectories;
/// <summary>
/// Object containing the execution events the data collector registers for
/// </summary>
private DataCollectionEvents? _events;
/// <summary>
/// The sink used by the data collector to send its data
/// </summary>
private DataCollectionSink? _dataSink;
/// <summary>
/// The data collector context.
/// </summary>
private DataCollectionContext? _dataCollectorContext;
/// <summary>
/// Used by the data collector to send warnings, errors, or other messages
/// </summary>
private DataCollectionLogger? _logger;
/// <summary>
/// The file helper.
/// </summary>
private readonly IFileHelper _fileHelper;
/// <summary>
/// The event log map.
/// </summary>
private readonly IDictionary<string, IEventLogContainer> _eventLogContainerMap = new Dictionary<string, IEventLogContainer>();
private bool _isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="EventLogDataCollector"/> class.
/// </summary>
public EventLogDataCollector()
: this(new FileHelper())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="EventLogDataCollector"/> class.
/// </summary>
/// <param name="fileHelper">
/// File Helper.
/// </param>
internal EventLogDataCollector(IFileHelper fileHelper)
{
_sessionStartEventHandler = OnSessionStart;
_sessionEndEventHandler = OnSessionEnd;
_testCaseStartEventHandler = OnTestCaseStart;
_testCaseEndEventHandler = OnTestCaseEnd;
_eventLogDirectories = new List<string>();
ContextMap = new Dictionary<DataCollectionContext, EventLogSessionContext>();
_fileHelper = fileHelper;
}
internal int MaxEntries { get; private set; }
internal ISet<string>? EventSources { get; private set; }
internal ISet<EventLogEntryType>? EntryTypes { get; private set; }
internal ISet<string>? EventLogNames { get; private set; }
/// <summary>
/// Gets the context data.
/// </summary>
internal Dictionary<DataCollectionContext, EventLogSessionContext> ContextMap { get; }
#region DataCollector Members
/// <summary>
/// Initializes the data collector
/// </summary>
/// <param name="configurationElement">
/// The XML element containing configuration information for the data collector. Currently,
/// this data collector does not have any configuration, so we ignore this parameter.
/// </param>
/// <param name="events">
/// Object containing the execution events the data collector registers for
/// </param>
/// <param name="dataSink">The sink used by the data collector to send its data</param>
/// <param name="logger">
/// Used by the data collector to send warnings, errors, or other messages
/// </param>
/// <param name="dataCollectionEnvironmentContext">Provides contextual information about the agent environment</param>
[MemberNotNull(nameof(_events), nameof(_dataSink), nameof(_logger), nameof(_dataCollectorContext))]
public override void Initialize(
XmlElement? configurationElement,
DataCollectionEvents events,
DataCollectionSink dataSink,
DataCollectionLogger logger,
DataCollectionEnvironmentContext? dataCollectionEnvironmentContext)
{
ValidateArg.NotNull(events, nameof(events));
ValidateArg.NotNull(dataSink, nameof(dataSink));
ValidateArg.NotNull(logger, nameof(logger));
ValidateArg.NotNull(dataCollectionEnvironmentContext, nameof(dataCollectionEnvironmentContext));
_events = events;
_dataSink = dataSink;
_logger = logger;
_dataCollectorContext = dataCollectionEnvironmentContext!.SessionDataCollectionContext;
// Load the configuration
CollectorNameValueConfigurationManager nameValueSettings =
new(configurationElement);
// Apply the configuration
ConfigureEventSources(nameValueSettings);
ConfigureEntryTypes(nameValueSettings);
ConfigureMaxEntries(nameValueSettings);
ConfigureEventLogNames(nameValueSettings, _dataCollectorContext);
// Register for events
events.SessionStart += _sessionStartEventHandler;
events.SessionEnd += _sessionEndEventHandler;
events.TestCaseStart += _testCaseStartEventHandler;
events.TestCaseEnd += _testCaseEndEventHandler;
}
#endregion
/// <summary>
/// The write event logs.
/// </summary>
/// <param name="eventLogEntries">
/// The event log entries.
/// </param>
/// <param name="maxLogEntries">
/// Max Log Entries.
/// </param>
/// <param name="dataCollectionContext">
/// The data collection context.
/// </param>
/// <param name="requestedDuration">
/// The requested duration.
/// </param>
/// <param name="timeRequestReceived">
/// The time request received.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
internal string WriteEventLogs(List<EventLogEntry> eventLogEntries, int maxLogEntries, DataCollectionContext dataCollectionContext, TimeSpan requestedDuration, DateTime timeRequestReceived)
{
// Generate a unique but friendly Directory name in the temp directory
string eventLogDirName = string.Format(
CultureInfo.InvariantCulture,
"{0}-{1}-{2:yyyy}{2:MM}{2:dd}-{2:HH}{2:mm}{2:ss}.{2:fff}",
"Event Log",
Environment.MachineName,
DateTime.UtcNow);
string eventLogDirPath = Path.Combine(Path.GetTempPath(), eventLogDirName);
// Create the directory
_fileHelper.CreateDirectory(eventLogDirPath);
string eventLogBasePath = Path.Combine(eventLogDirPath, EventLogFileName);
bool unusedFilenameFound = false;
string eventLogPath = eventLogBasePath + ".xml";
if (_fileHelper.Exists(eventLogPath))
{
for (int i = 1; !unusedFilenameFound; i++)
{
eventLogPath = $"{eventLogBasePath}-{i.ToString(CultureInfo.InvariantCulture)}.xml";
if (!_fileHelper.Exists(eventLogPath))
{
unusedFilenameFound = true;
}
}
}
DateTime minDate = DateTime.MinValue;
// Limit entries to a certain time range if requested
if (requestedDuration < TimeSpan.MaxValue)
{
try
{
minDate = timeRequestReceived - requestedDuration;
}
catch (ArgumentOutOfRangeException)
{
minDate = DateTime.MinValue;
}
}
Stopwatch stopwatch = new();
stopwatch.Start();
EventLogXmlWriter.WriteEventLogEntriesToXmlFile(
eventLogPath,
eventLogEntries.Where(
entry => entry.TimeGenerated > minDate && entry.TimeGenerated < DateTime.MaxValue).OrderBy(x => x.TimeGenerated).Take(maxLogEntries).ToList(),
_fileHelper);
stopwatch.Stop();
EqtTrace.Verbose(
"EventLogDataContainer: Wrote {0} event log entries to file '{1}' in {2} seconds",
eventLogEntries.Count,
eventLogPath,
stopwatch.Elapsed.TotalSeconds.ToString(CultureInfo.InvariantCulture));
// Write the event log file
FileTransferInformation fileTransferInformation =
new(dataCollectionContext, eventLogPath, true, _fileHelper);
TPDebug.Assert(_dataSink != null, "Initialize should have been called.");
_dataSink.SendFileAsync(fileTransferInformation);
EqtTrace.Verbose(
"EventLogDataContainer: Event log successfully sent for data collection context '{0}'.",
dataCollectionContext.ToString());
return eventLogPath;
}
#region IDisposable Members
/// <summary>
/// Cleans up resources allocated by the data collector
/// </summary>
/// <param name="disposing">Not used since this class does not have a finalizer.</param>
protected override void Dispose(bool disposing)
{
if (_isDisposed)
return;
base.Dispose(disposing);
if (disposing)
{
// Unregister events
if (_events != null)
{
_events.SessionStart -= _sessionStartEventHandler;
_events.SessionEnd -= _sessionEndEventHandler;
_events.TestCaseStart -= _testCaseStartEventHandler;
_events.TestCaseEnd -= _testCaseEndEventHandler;
}
// Unregister EventLogEntry Written.
foreach (var eventLogContainer in _eventLogContainerMap.Values)
{
eventLogContainer.Dispose();
}
// Delete all the temp event log directories
RemoveTempEventLogDirs(_eventLogDirectories);
}
_isDisposed = true;
}
#endregion
private static ISet<string> ParseCommaSeparatedList(string commaSeparatedList)
{
ISet<string> strings = new HashSet<string>();
string[] items = commaSeparatedList.Split(new char[] { ',' });
foreach (string item in items)
{
strings.Add(item.Trim());
}
return strings;
}
private void OnSessionStart(object? sender, SessionStartEventArgs e)
{
ValidateArg.NotNull(e, nameof(e));
ValidateArg.NotNull(e.Context, "SessionStartEventArgs.Context");
EqtTrace.Verbose("EventLogDataCollector: SessionStart received");
StartCollectionForContext(e.Context);
}
private void OnSessionEnd(object? sender, SessionEndEventArgs e)
{
ValidateArg.NotNull(e, nameof(e));
ValidateArg.NotNull(e.Context, "SessionEndEventArgs.Context");
EqtTrace.Verbose("EventLogDataCollector: SessionEnd received");
WriteCollectedEventLogEntries(e.Context, true, TimeSpan.MaxValue, DateTime.UtcNow);
}
private void OnTestCaseStart(object? sender, TestCaseStartEventArgs e)
{
ValidateArg.NotNull(e, nameof(e));
ValidateArg.NotNull(e.Context, "TestCaseStartEventArgs.Context");
if (!e.Context.HasTestCase)
{
Debug.Fail("Context is not for a test case");
ValidateArg.NotNull(e.Context.TestExecId, "TestCaseStartEventArgs.Context.HasTestCase");
}
EqtTrace.Verbose("EventLogDataCollector: TestCaseStart received for test '{0}'.", e.TestCaseName);
StartCollectionForContext(e.Context);
}
private void OnTestCaseEnd(object? sender, TestCaseEndEventArgs e)
{
ValidateArg.NotNull(e, nameof(e));
TPDebug.Assert(e.Context != null, "Context is null");
TPDebug.Assert(e.Context.HasTestCase, "Context is not for a test case");
EqtTrace.Verbose(
"EventLogDataCollector: TestCaseEnd received for test '{0}' with Test Outcome: {1}.",
e.TestCaseName,
e.TestOutcome);
WriteCollectedEventLogEntries(e.Context, false, TimeSpan.MaxValue, DateTime.UtcNow);
}
private void RemoveTempEventLogDirs(List<string> tempDirs)
{
if (tempDirs != null)
{
foreach (string dir in tempDirs)
{
// Delete only if the directory is empty
_fileHelper.DeleteEmptyDirectroy(dir);
}
}
}
private void StartCollectionForContext(DataCollectionContext dataCollectionContext)
{
lock (ContextMap)
{
var eventLogSessionContext = new EventLogSessionContext(_eventLogContainerMap);
ContextMap.Add(dataCollectionContext, eventLogSessionContext);
}
}
private void WriteCollectedEventLogEntries(
DataCollectionContext dataCollectionContext,
bool isSessionEnd,
TimeSpan requestedDuration,
DateTime timeRequestReceived)
{
var context = GetEventLogSessionContext(dataCollectionContext);
context.CreateEventLogContainerEndIndexMap();
List<EventLogEntry> eventLogEntries = new();
foreach (KeyValuePair<string, IEventLogContainer> kvp in _eventLogContainerMap)
{
try
{
if (isSessionEnd)
{
kvp.Value.EventLog.EnableRaisingEvents = false;
}
for (int i = context.EventLogContainerStartIndexMap[kvp.Key]; i <= context.EventLogContainerEndIndexMap[kvp.Key]; i++)
{
eventLogEntries.Add(kvp.Value.EventLogEntries[i]);
}
}
catch (Exception e)
{
TPDebug.Assert(_logger != null, "Initialize should have been called.");
_logger.LogWarning(
dataCollectionContext,
string.Format(
CultureInfo.InvariantCulture,
Resource.CleanupException,
kvp.Value.EventLog,
e.ToString()));
}
}
var fileName = WriteEventLogs(eventLogEntries, isSessionEnd ? int.MaxValue : MaxEntries, dataCollectionContext, requestedDuration, timeRequestReceived);
// Add the directory to the list
_eventLogDirectories.Add(Path.GetDirectoryName(fileName)!);
lock (ContextMap)
{
ContextMap.Remove(dataCollectionContext);
}
}
[MemberNotNull(nameof(EventLogNames))]
private void ConfigureEventLogNames(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager, DataCollectionContext dataCollectorContext)
{
EventLogNames = new HashSet<string>();
string? eventLogs = collectorNameValueConfigurationManager[EventLogConstants.SettingEventLogs];
if (eventLogs != null)
{
EventLogNames = ParseCommaSeparatedList(eventLogs);
EqtTrace.Verbose(
$"EventLogDataCollector configuration: {EventLogConstants.SettingEventLogs}={eventLogs}");
}
else
{
// Default to collecting these standard logs
EventLogNames.Add("System");
EventLogNames.Add("Application");
}
TPDebug.Assert(_logger != null && EntryTypes != null, "Initialize should have been called.");
foreach (string eventLogName in EventLogNames)
{
try
{
// Create an EventLog object and add it to the eventLogContext if one does not already exist
if (!_eventLogContainerMap.ContainsKey(eventLogName))
{
IEventLogContainer eventLogContainer = new EventLogContainer(
eventLogName,
EventSources,
EntryTypes,
int.MaxValue,
_logger,
dataCollectorContext);
_eventLogContainerMap.Add(eventLogName, eventLogContainer);
}
EqtTrace.Verbose("EventLogDataCollector: Created EventSource '{0}'", eventLogName);
}
catch (Exception ex)
{
_logger.LogError(
dataCollectorContext,
new EventLogCollectorException(string.Format(CultureInfo.CurrentCulture, Resource.ReadError, eventLogName, Environment.MachineName), ex));
}
}
}
private void ConfigureEventSources(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)
{
string? eventSourcesStr = collectorNameValueConfigurationManager[EventLogConstants.SettingEventSources];
if (!eventSourcesStr.IsNullOrEmpty())
{
EventSources = ParseCommaSeparatedList(eventSourcesStr);
EqtTrace.Verbose(
$"EventLogDataCollector configuration: {EventLogConstants.SettingEventSources}={EventSources}");
}
}
[MemberNotNull(nameof(EntryTypes))]
private void ConfigureEntryTypes(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)
{
EntryTypes = new HashSet<EventLogEntryType>();
string? entryTypesStr = collectorNameValueConfigurationManager[EventLogConstants.SettingEntryTypes];
if (entryTypesStr != null)
{
foreach (string entryTypestring in ParseCommaSeparatedList(entryTypesStr))
{
EntryTypes.Add(
(EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), entryTypestring, true));
}
EqtTrace.Verbose(
$"EventLogDataCollector configuration: {EventLogConstants.SettingEntryTypes}={EntryTypes}");
}
else
{
EntryTypes.Add(EventLogEntryType.Error);
EntryTypes.Add(EventLogEntryType.Warning);
EntryTypes.Add(EventLogEntryType.FailureAudit);
}
}
private void ConfigureMaxEntries(CollectorNameValueConfigurationManager collectorNameValueConfigurationManager)
{
string? maxEntriesstring = collectorNameValueConfigurationManager[EventLogConstants.SettingMaxEntries];
if (maxEntriesstring != null)
{
try
{
MaxEntries = int.Parse(maxEntriesstring, CultureInfo.InvariantCulture);
// A negative or 0 value means no maximum
if (MaxEntries <= 0)
{
MaxEntries = int.MaxValue;
}
}
catch (FormatException)
{
MaxEntries = EventLogConstants.DefaultMaxEntries;
}
EqtTrace.Verbose(
$"EventLogDataCollector configuration: {EventLogConstants.SettingMaxEntries}={MaxEntries}");
}
else
{
MaxEntries = EventLogConstants.DefaultMaxEntries;
}
}
private EventLogSessionContext GetEventLogSessionContext(DataCollectionContext dataCollectionContext)
{
lock (ContextMap)
{
if (ContextMap.TryGetValue(dataCollectionContext, out var eventLogSessionContext))
{
return eventLogSessionContext;
}
}
string msg = string.Format(
CultureInfo.CurrentCulture,
Resource.ContextNotFoundException,
dataCollectionContext.ToString());
throw new EventLogCollectorException(msg, null);
}
}