forked from microsoft/perfview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTriggers.cs
More file actions
1638 lines (1488 loc) · 68.8 KB
/
Triggers.cs
File metadata and controls
1638 lines (1488 loc) · 68.8 KB
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Diagnostics.Tracing;
using Microsoft.Diagnostics.Tracing.Parsers;
using Microsoft.Diagnostics.Tracing.Parsers.Clr;
using Microsoft.Diagnostics.Tracing.Parsers.Kernel;
using Microsoft.Diagnostics.Tracing.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
// Triggers are things that wait for some interesting event to condition to occur and execute a callback when that happens.
namespace Triggers
{
/// <summary>
/// Things that any Trigger needs to implement. Basically you need to be able to stop it (IDispose)
/// and you need to ask its status (which allows the user to see that the trigger is monitoring things
/// properly.
///
/// Note that Triggers will NOT die on their own, since they are MONITORS and are kept alive by the
/// monitoring thread they start. You can only kill them by disposing them.
/// </summary>
internal abstract class Trigger : IDisposable
{
/// <summary>
/// Get something useful about the state of the trigger, can return the empty string if there
/// is nothing useful to say.
/// </summary>
public virtual string Status { get { return ""; } }
/// <summary>
/// Used to stop the trigger (Triggers must be disposed explicitly since the timer keeps them
/// alive unless disposed).
/// </summary>
public virtual void Dispose() { }
}
#if !DOTNET_CORE // perfCounters don't exist on .NET Core
/// <summary>
/// PerformanceCounterTrigger is a class that knows how to determine if a particular performance counter has
/// exceeded a particular threshold.
/// </summary>
internal class PerformanceCounterTrigger : Trigger
{
/// <summary>
/// Creates a new PerformanceCounterTrigger based on a specification. Basically this specification is
/// a condition which is either true or false at any particular time. Once the PerformanceCounterTrigger
/// has been created, you can call 'IsCurrentlyTrue()' to see if the condition holds.
/// </summary>
/// <param name="spec">This is of the form CATEGORY:COUNTERNAME:INSTANCE OP NUM where OP is either a
/// greater than or less than sign, NUM is a floating point number and CATEGORY:COUNTERNAME:INSTANCE
/// identify the performance counter to use (same as PerfMon). For example
///
/// .NET CLR Memory:% Time in GC:_Global_>20
///
/// Will trigger when the % Time in GC for the _Global_ instance (which represents all processes) is
/// greater than 20.
///
/// Processor:% Processor Time:_Total>90
///
/// Will trigger when the % processor time exceeds 90%.
/// </param>
/// <param name="decayToZeroHours">If nonzero, the threshold will decay to 0 in this amount of time.</param>
/// <param name="log">A place to write messages.</param>
/// <param name="onTriggered">A delegate to call when the threshold is exceeded</param>
public PerformanceCounterTrigger(string spec, float decayToZeroHours, TextWriter log, Action<PerformanceCounterTrigger> onTriggered)
{
m_spec = spec;
m_log = log;
m_triggered = onTriggered;
m_startTimeUtc = DateTime.UtcNow;
DecayToZeroHours = decayToZeroHours;
MinSecForTrigger = 3;
var m = Regex.Match(spec, @"^\s*(.*?):(.*?):(.*?)\s*([<>])\s*(\d+\.?\d*)\s*$");
if (!m.Success)
{
throw new ApplicationException(
"Performance monitor specification '" + spec + "' does not match syntax CATEGORY:COUNTER:INSTANCE [<>] NUM (i.e. 0.12 or 12)");
}
var categoryName = m.Groups[1].Value;
var counterName = m.Groups[2].Value;
var instanceName = m.Groups[3].Value;
var op = m.Groups[4].Value;
var threashold = m.Groups[5].Value;
IsGreaterThan = (op == ">");
Threshold = float.Parse(threashold);
try { m_category = new PerformanceCounterCategory(categoryName); }
catch (Exception) { throw new ApplicationException("Could not start performance counter " + m_spec); }
if (!m_category.CounterExists(counterName))
{
throw new ApplicationException("Count not find performance counter " + counterName + " in category " + categoryName);
}
if (categoryName.StartsWith(".NET")) // TODO FIX NOW, remove this condition after we are confident of it.
{
if (SpawnCounterIn64BitProcessIfNecessary())
{
return;
}
}
// If the instance does not exist, you won't discover it until we fetch the counter later.
m_counter = new PerformanceCounter(categoryName, counterName, instanceName);
m_task = Task.Factory.StartNew(delegate
{
var desiredDirection = IsGreaterThan ? "above" : "below";
var otherDirection = IsGreaterThan ? "below" : "above";
while (!m_monitoringDone)
{
var isTriggered = IsCurrentlyTrue();
if (isTriggered)
{
if (m_wasUntriggered)
{
m_log.WriteLine($"[Counter is at {CurrentValue:n1} which is {desiredDirection} the threshold for {m_count} sec. Need {MinSecForTrigger} sec to trigger.]");
// Perf counters are noisy, only trigger if we get MinSecForTrigger consecutive counts that are above/below the threshold.
m_count++;
if (m_count > MinSecForTrigger)
{
m_triggered?.Invoke(this);
}
}
else
{
if (!m_warnedAboutUntriggered)
{
m_log.WriteLine($"[WARNING: {Status}: Counter is {desiredDirection} the trigger level initially!]");
m_log.WriteLine($"[WARNING: PerfView will not trigger until the counter moves from {otherDirection} the trigger level to {desiredDirection} the level.]");
m_warnedAboutUntriggered = true;
}
m_count = 0;
}
}
else
{
if (!m_wasUntriggered)
{
m_count++;
if (m_count > MinSecForTrigger)
{
m_count = 0;
m_wasUntriggered = true;
m_log.WriteLine($"[{Status}: Waiting for trigger of {EffectiveThreshold}, CurVal {CurrentValue:n1}]");
}
}
else
{
m_count = 0;
}
}
Thread.Sleep(1000); // Check every second
}
});
}
/// <summary>
/// The specification of the Performance counter trigger that was given when it was constructed.
/// </summary>
public string Spec { get { return m_spec; } }
/// <summary>
/// The threshold number that got passed in the spec in the constructor. This never changes over time.
/// </summary>
public float Threshold { get; private set; }
/// <summary>
/// Returns true if the perf counter must be great than the threshold to trigger.
/// </summary>
public bool IsGreaterThan { get; private set; }
/// <summary>
/// The value of DecayToZeroHours parameter passed to the constructor of the trigger.
/// </summary>
public float DecayToZeroHours { get; set; }
/// <summary>
/// The amount of time in seconds that the performance counter needs to be above the threshold to be considered triggered
/// This allows you to ignore transients. By default the value is 3 seconds.
/// </summary>
public int MinSecForTrigger { get; set; }
/// <summary>
/// If DecayToZeroHours is set, the threshold changes over time. This property returns the value after
/// being adjusted by DecayToZeroHours.
/// </summary>
public float EffectiveThreshold
{
get
{
var threshold = Threshold;
if (DecayToZeroHours != 0)
{
threshold = (float)(threshold * (1 - (DateTime.UtcNow - m_startTimeUtc).TotalHours / DecayToZeroHours));
}
return threshold;
}
}
/// <summary>
/// This is the value of the performance counter since the last tie 'Update()' was called.
/// </summary>
public float CurrentValue { get; private set; }
public override void Dispose()
{
m_monitoringDone = true;
#if PERFVIEW
var cmd = m_cmd;
if (cmd != null)
{
cmd.Kill();
}
#endif
}
public override string Status
{
get
{
var exception = m_task.Exception;
if (exception != null)
{
return string.Format("Error: Exception thrown during monitoring: {0}", exception.InnerException.Message);
}
if (m_counter == null)
{
return "";
}
var instanceExists = "";
if (!m_instanceExists)
{
instanceExists = " " + m_counter.InstanceName + " does not exist";
}
return string.Format("{0}:{1}:{2}={3:n1}{4}",
m_counter.CategoryName, m_counter.CounterName, m_counter.InstanceName, CurrentValue, instanceExists);
}
}
#region private
/// <summary>
/// If you are in a 32 bit process you don't see 64 bit perf counters. Returns true if we needed to do this.
/// </summary>
private bool SpawnCounterIn64BitProcessIfNecessary()
{
#if PERFVIEW // TODO FIX NOW turn this on and test.
// Do we have to do this?
if (m_triggered == null)
{
return false;
}
if (!(Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess))
{
return false;
}
m_task = Task.Factory.StartNew(delegate
{
m_log.WriteLine("To allow 64 bit processes to participate in the perf counters, we launch a 64 bit process to do the monitoring");
string heapDumpExe = Path.Combine(Utilities.SupportFiles.SupportFileDir, @"AMD64\HeapDump.exe");
string commandLine = heapDumpExe + " \"/StopOnPerfCounter:" + m_spec + "\"";
m_log.WriteLine("Exec: {0}", commandLine);
var options = new Utilities.CommandOptions().AddNoThrow().AddTimeout(Utilities.CommandOptions.Infinite).AddOutputStream(m_log);
m_cmd = Utilities.Command.Run(commandLine, options);
if (m_cmd.ExitCode != 0)
{
m_log.WriteLine("Error: heapdump failed with error code {0}", m_cmd.ExitCode);
}
else
{
m_triggered?.Invoke(this);
}
m_cmd = null;
});
return true;
#else
return false;
#endif
}
private bool IsCurrentlyTrue()
{
Update();
if (IsGreaterThan)
{
return CurrentValue > EffectiveThreshold;
}
else
{
return CurrentValue < EffectiveThreshold;
}
}
/// <summary>
/// Update 'CurrentValue' to the live value of the performance counter.
/// </summary>
private float Update()
{
CurrentValue = 0;
m_instanceExists = m_category.InstanceExists(m_counter.InstanceName);
if (m_instanceExists || m_counter.InstanceName.Length == 0)
{
// There is a race here where the instance dies, so we need to protect against this and ignore any failures
// because the instance does not exist.
try
{
CurrentValue = m_counter.NextValue();
m_instanceExists = true;
}
catch (InvalidOperationException e)
{
// ignore any 'does not exist exceptions
if (!e.Message.Contains("does not exist") || m_counter.InstanceName.Length == 0)
{
throw;
}
}
}
return CurrentValue;
}
private string m_spec;
private PerformanceCounterCategory m_category;
private PerformanceCounter m_counter;
private bool m_instanceExists;
private TextWriter m_log;
public event Action<PerformanceCounterTrigger> m_triggered;
#if PERFVIEW
private Utilities.Command m_cmd;
#endif
private Task m_task;
private volatile bool m_monitoringDone;
// Perf Counters can be noisy, be default we require 3 consecutive samples that succeed.
// This variable keeps track of this.
private int m_count;
private bool m_wasUntriggered; // We only trigger if we go from untriggered to triggered.
private bool m_warnedAboutUntriggered;
private DateTime m_startTimeUtc;
#endregion
}
#endif
/// <summary>
/// A class that triggers when
/// </summary>
internal class ETWEventTrigger : Trigger
{
// Convenience methods.
/// <summary>
/// Triggers on a .NET Exception of a particular name.
/// </summary>
public static ETWEventTrigger StopOnException(string exceptionRegEx, string processFilter, TextWriter log, Action<ETWEventTrigger> onTriggered)
{
var ret = new ETWEventTrigger(log);
ret.OnTriggered = onTriggered;
ret.m_triggerName = "StopOnException " + exceptionRegEx;
ret.ProcessFilter = processFilter;
ret.ProviderGuid = ClrTraceEventParser.ProviderGuid;
ret.ProviderLevel = TraceEventLevel.Informational;
ret.ProviderKeywords = (ulong)ClrTraceEventParser.Keywords.Exception;
ret.TriggerPredicate = delegate (TraceEvent e)
{
log.WriteLine("Got a CLR Exception");
if (exceptionRegEx.Length == 0)
{
return true;
}
var asException = (ExceptionTraceData)e;
if (asException == null)
{
return false;
}
if (string.IsNullOrEmpty(asException.ExceptionType) || string.IsNullOrEmpty(asException.ExceptionMessage))
{
return false;
}
string fullMessage = asException.ExceptionType + ": " + asException.ExceptionMessage;
log.WriteLine("Exception: {0}", fullMessage);
log.WriteLine("Exception Pattern: {0}", exceptionRegEx);
return Regex.IsMatch(fullMessage, exceptionRegEx);
};
ret.StartEvent = "Exception/Start";
ret.Start();
return ret;
}
/// <summary>
/// Triggers if an .NET GC takes longer than triggerDurationMSec
/// </summary>
public static ETWEventTrigger GCTooLong(int triggerDurationMSec, float decayToZeroHours, string processFilter, TextWriter log, Action<ETWEventTrigger> onTriggered)
{
var ret = new ETWEventTrigger(log);
ret.TriggerMSec = triggerDurationMSec;
ret.DecayToZeroHours = decayToZeroHours;
ret.OnTriggered = onTriggered;
ret.m_triggerName = "StopOnGCOverMSec";
ret.ProcessFilter = processFilter;
// ret.m_verbose = true;
ret.ProviderGuid = ClrTraceEventParser.ProviderGuid;
ret.ProviderLevel = TraceEventLevel.Informational;
ret.ProviderKeywords = (ulong)ClrTraceEventParser.Keywords.GC;
ret.StartEvent = "GC/Start";
ret.TriggerPredicate = delegate (TraceEvent data)
{
var asGCStart = (Microsoft.Diagnostics.Tracing.Parsers.Clr.GCStartTraceData)data;
if (asGCStart.Type == GCType.BackgroundGC)
{
log.WriteLine("Got a GC, It is a background GC");
return false;
}
return true;
};
log.WriteLine("WARNING: on V3.5 runtimes StopOnGCOverMSec will cause CLR events to NOT be logged to the ETL file!");
ret.Start();
return ret;
}
public static ETWEventTrigger BgcFinalPauseTooLong(int triggerDurationMSec, float decayToZeroHours, string processFilter, TextWriter log, Action<ETWEventTrigger> onTriggered)
{
var ret = new ETWEventTrigger(log);
ret.TriggerMSec = triggerDurationMSec;
ret.DecayToZeroHours = decayToZeroHours;
ret.OnTriggered = onTriggered;
ret.m_triggerName = "StopOnBGCFinalPauseOverMsec";
ret.ProcessFilter = processFilter;
ret.StartStopID = "ThreadID";
ret.ProviderGuid = ClrTraceEventParser.ProviderGuid;
ret.ProviderLevel = TraceEventLevel.Informational;
ret.ProviderKeywords = (ulong)ClrTraceEventParser.Keywords.GC;
ret.StartEvent = "GC/SuspendEEStart";
ret.StopEvent = "GC/RestartEEStop";
ret.TriggerPredicate = delegate (TraceEvent data)
{
var suspendEETraceData = (Microsoft.Diagnostics.Tracing.Parsers.Clr.GCSuspendEETraceData)data;
return suspendEETraceData.Reason == GCSuspendEEReason.SuspendForGCPrep;
};
ret.Start();
return ret;
}
/// <summary>
/// Stops on a Gen 2 GC.
/// </summary>
public static ETWEventTrigger StopOnGen2GC(string processFilter, TextWriter log, Action<ETWEventTrigger> onTriggered)
{
var ret = new ETWEventTrigger(log);
ret.OnTriggered = onTriggered;
ret.m_triggerName = "StopOnGen2GC";
ret.ProcessFilter = processFilter;
ret.ProviderGuid = ClrTraceEventParser.ProviderGuid;
ret.ProviderLevel = TraceEventLevel.Informational;
ret.ProviderKeywords = (ulong)ClrTraceEventParser.Keywords.GC;
ret.StartEvent = "GC/Start";
ret.TriggerPredicate = delegate (TraceEvent data)
{
var asGCStart = (Microsoft.Diagnostics.Tracing.Parsers.Clr.GCStartTraceData)data;
if (asGCStart.Depth < 2)
{
log.WriteLine("Got a GC, not a Gen2");
return false;
}
if (asGCStart.Type == GCType.BackgroundGC)
{
log.WriteLine("Got a GC, It is s a background GC");
return false;
}
return true;
};
ret.Start();
return ret;
}
/// <summary>
/// Triggers if AppFabric Cache service takes longer than triggerDurationMSec
/// </summary>
public static ETWEventTrigger AppFabricTooLong(int triggerDurationMSec, float decayToZeroHours, string processFilter, TextWriter log, Action<ETWEventTrigger> onTriggered)
{
var ret = new ETWEventTrigger(log);
ret.TriggerMSec = triggerDurationMSec;
ret.DecayToZeroHours = decayToZeroHours;
ret.OnTriggered = onTriggered;
ret.m_triggerName = "StopOnAppFabricOverMSec";
ret.ProcessFilter = processFilter;
ret.ProviderGuid = new Guid("A77DCF21-545F-4191-B3D0-C396CF2683F2");
ret.ProviderLevel = TraceEventLevel.Verbose;
ret.ProviderKeywords = ulong.MaxValue;
ret.StartEvent = "EventID(123)";
ret.StopEvent = "EventID(127)";
ret.StartStopID = "1"; // TODO FIX NOW: Don't know what the first arg is.
ret.Start();
return ret;
}
/// <summary>
/// Create a new trigger that uses a specification to indicate what ETW events to trigger on.
///
/// spec Syntax
/// PROVIDER/TASK/OPCODE;NAME1=VALUE1;NAME2=VALUE2 ... // Opcode is optional and defaults to Info
/// PROVIDER/EVENTNAME;NAME1=VALUE1;NAME2=VALUE2 ...
///
/// TASK can be Task(NNN)
/// OPCODE can be Opcode(NNN)
/// EVENTNAME can be EventID(NNN)
///
/// Names can begin with @ which mean they are reserved for the implementation. Defined ones are
/// Keywords=XXXX // In hex, default ulong.MaxValue.
/// Level=XXXX // 1 (Critical) - 5 (Verbose) Default = 4 (Info)
/// Process=ProcessNameOrID // restricts to a particular process
/// FieldFilter=FieldName Op Value // Allows you to filter on a particular field value OP can be < > = and ~ (which means RegEx match)
/// // You can repeat this and you get the logical AND operator (sorry no OR operator right now).
/// BufferSizeMB=NNN // Size of buffer used for trigger session.
/// If TriggerMSec is non-zero then it measures the duration of a start-stop pair.
/// TriggerMSec=NNN // Number of milliseconds to trigger on.
/// DecayToZeroHours=NNN // Trigger decays to 0 in this amount of time.
/// StopEvent=PROVIDER/TASK/OPOCDE // Default is stop if event is a start, otherwise it is 1 opcode larger (unless 0 in which case 1 event ID larger).
/// StartStopID=XXXX // Indicates the payload field name that is used as the correlation ID to pair up start-stop pairs
/// // can be 'ThreadID' or ActivityID if those are to be used.
/// </summary>
public ETWEventTrigger(string spec, TextWriter log, Action<ETWEventTrigger> onTriggered)
: this(log)
{
OnTriggered = onTriggered;
ParseSpec(spec);
Start();
}
/// <summary>
/// Actually starts listening for ETW events. Stops when 'Dispose()' is called.
/// </summary>
public void Start()
{
bool listening = false;
m_requestCount = 0;
m_requestMaxMSec = 0;
m_requestTotalMSec = 0;
m_sessionEventCount = 0;
string sessionName = SessionNamePrefix + "_" + Process.GetCurrentProcess().Id.ToString() + "_" + Interlocked.Increment(ref s_maxSessionName).ToString();
m_readerTask = Task.Factory.StartNew(delegate
{
using (m_session = new TraceEventSession(sessionName, null))
{
if (ProcessFilter != null)
{
if (int.TryParse(ProcessFilter, out m_processID))
{
m_log.WriteLine("[Only allowing process with ID {0} to stop the trace.]", m_processID);
}
else
{
m_processID = WaitingForProcessID; // WaitingForProcessID is an illegal process ID
// monitor kernel process events to late bind the process name
if (ProviderGuid != KernelTraceEventParser.ProviderGuid)
{
m_session.EnableKernelProvider(KernelTraceEventParser.Keywords.Process);
}
m_log.WriteLine("[Only allowing process with Name {0} to stop the trace.]", ProcessFilter);
}
}
if (BufferSizeMB != 0)
{
m_session.BufferSizeMB = BufferSizeMB;
}
m_log.WriteLine("Additional Trigger debugging messages are logged to the ETL file as PerfView/StopTriggerDebugMessage events.");
using (m_source = new ETWTraceEventSource(sessionName, TraceEventSourceType.Session))
{
Dictionary<StartStopKey, StartEventData> startStopRecords = null;
if (TriggerMSec != 0)
{
startStopRecords = new Dictionary<StartStopKey, StartEventData>(20);
}
if (m_processID == WaitingForProcessID)
{
m_source.Kernel.ProcessStop += delegate (ProcessTraceData data)
{
if (m_processID == data.ProcessID)
{
m_processID = WaitingForProcessID;
}
};
m_source.Kernel.ProcessStartGroup += delegate (ProcessTraceData data)
{
if (string.Compare(data.ProcessName, ProcessFilter, StringComparison.OrdinalIgnoreCase) == 0)
{
m_processID = data.ProcessID;
m_log.WriteLine("[Only allowing process {0} with ID {1} stop the trace.]", data.ProcessName, m_processID);
}
else
{
if (ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Process " + data.ProcessName + " does not match process filter " + ProcessFilter);
}
}
};
}
Action<TraceEvent> onEvent = delegate (TraceEvent data)
{
if (m_session == null || m_source == null)
{
return;
}
m_sessionEventCount++;
if (m_sessionEventCount <= 3)
{
m_log.WriteLine("Got event {0} from trigger session: {1}", m_sessionEventCount, data.EventName);
}
// Do we have a process filter?
if (m_processID != 0)
{
if (m_processID == WaitingForProcessID)
{
if (ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Dropping event, we have not mapped " + ProcessFilter + " to a process ID yet");
}
return;
}
if (m_processID != data.ProcessID)
{
if (ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Dropping event because process ID " + data.ProcessID + " != " + m_processID);
}
return;
}
}
// Are we doing the case where we are looking for a single event?
if (startStopRecords == null)
{
if (m_startEvent.Matches(data))
{
// Track that we got an event of interest. Helps to debug why a trigger may not be firing.
m_requestCount++;
// Check field filters
if (!PassesFieldFilters(data))
{
return;
}
// Yeah we triggered for the single event case.
if (OnTriggered != null)
{
if (TriggerPredicate != null && !TriggerPredicate(data))
{
m_log.WriteLine("Trigger predicate failed, continuing to search.");
return;
}
TriggeredMessage = string.Format("{0} triggered by event at Process {1}({2}) Thread {3} at {4:HH:mm:ss.ffffff} approximately {5:f3} Msec ago.",
m_triggerName, data.ProcessName, data.ProcessID, data.ThreadID, data.TimeStamp, (DateTime.Now - data.TimeStamp).TotalMilliseconds);
m_log.WriteLine("[{0}]", TriggeredMessage);
PerfViewLogger.Log.EventStopTrigger(data.TimeStamp.ToUniversalTime(), data.ProcessID, data.ThreadID, data.ProcessName, data.EventName, 0);
OnTriggered(this);
OnTriggered = null; // we only trigger at most once.
}
}
if (ShouldLogVerbose)
{
// Optimization, we can have a fair number of these
if (data.EventName != "GC/GenerationRange")
{
LogVerbose(data.TimeStamp, "Dropping event because name " + data.EventName + " != " + m_startEvent);
}
}
return; // Did not see the event we want.
}
// If we reach this point, we are doing a start-stop over a trigger time.
bool matchesStart = m_startEvent.Matches(data);
if (!matchesStart && (m_stopEvent == null || !m_stopEvent.Matches(data)))
{
if (ShouldLogVerbose)
{
string tail = "";
if (m_stopEvent != null)
{
tail = " or " + m_stopEvent.ToString();
}
LogVerbose(data.TimeStamp, "Dropping event because name " + data.EventName + " != " + m_startEvent + tail);
}
return;
}
// We have a start or stop
// Get the context ID that will correlate the start and stop time
Guid contextID = GetContextIDForEvent(data);
var key = new StartStopKey(data.ProviderGuid, data.Task, contextID);
if (matchesStart)
{
// Check field filters
if (!PassesFieldFilters(data))
{
return;
}
// If the user did not specify a stop event provide a default.
if (m_stopEvent == null)
{
m_stopEvent = m_startEvent.DefaultStopEvent();
m_log.WriteLine("Seen Trigger Start Event {0} Defining Stop Event to be {1}",
m_startEvent, m_stopEvent);
}
if (TriggerPredicate != null && !TriggerPredicate(data))
{
m_log.WriteLine("Trigger predicate failed, continuing to search.");
return;
}
if (ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Start Request Context: " + contextID.ToString() + " Thread " + data.ThreadID);
}
startStopRecords[key] = new StartEventData(data.TimeStampRelativeMSec);
return; // Once we have logged the start, we are done.
}
StartEventData startEventData;
if (!startStopRecords.TryGetValue(key, out startEventData))
{
// We don't warn on orphans if there is a trigger predicate because predicates create orphans.
if (TriggerPredicate == null && ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Dropped Orphan Stop Request Context: " + contextID.ToString() + " ignoring");
}
return;
}
startStopRecords.Remove(key);
var durationMSec = data.TimeStampRelativeMSec - startEventData.StartTime;
// Compute aggregate stats.
m_requestCount++;
m_requestTotalMSec += (int)durationMSec;
if (m_requestMaxMSec < durationMSec)
{
m_requestMaxMSec = durationMSec;
}
// See if we should trigger.
var triggerMSec = EffectiveTriggerDurationMSec;
if (ShouldLogVerbose)
{
LogVerbose(data.TimeStamp, "Stop Request Context " + contextID.ToString() + " Thread " + data.ThreadID + " Duration " + durationMSec.ToString("f2") + " Trigger: " + triggerMSec.ToString("f1") + " MSec");
}
if (durationMSec <= triggerMSec)
{
return;
}
// Yeah we get to trigger.
if (OnTriggered != null)
{
if (m_triggerName == null)
{
m_triggerName = "Stop";
}
var triggerMessage = "";
if (DecayToZeroHours != 0)
{
triggerMessage = " (orig " + TriggerMSec.ToString() + " msec)";
}
TriggeredMessage = string.Format("{0} triggered. Duration {1:f0} > {2} Msec{3}. Triggering by Process {4}({5}) Thread {6} at {7:HH:mm:ss.ffffff} approximately {8:f3} Msec ago.",
m_triggerName, durationMSec, triggerMSec, triggerMessage, data.ProcessName, data.ProcessID, data.ThreadID,
data.TimeStamp, (DateTime.Now - data.TimeStamp).TotalMilliseconds);
PerfViewLogger.Log.EventStopTrigger(data.TimeStamp.ToUniversalTime(), data.ProcessID, data.ThreadID, data.ProcessName, data.EventName, durationMSec);
OnTriggered(this);
m_log.WriteLine("[{0}]", TriggeredMessage);
OnTriggered = null; // we only trigger at most once.
}
};
// m_source.Registered.All += onEvent;
m_source.Kernel.All += onEvent;
m_source.Clr.All += onEvent;
m_source.Dynamic.All += onEvent;
m_log.WriteLine("[Enabling ETW session for monitoring requests.]");
m_log.WriteLine("In Trigger session {0} enabling Provider {1} ({2}) Level {3} Keywords 0x{4:x}",
sessionName, ProviderName, ProviderGuid, ProviderLevel, ProviderKeywords);
// Windows Kernel Trace has to be enabled via EnableKernelProvider
if (ProviderGuid == KernelTraceEventParser.ProviderGuid)
{
var kernelKeywords = KernelTraceEventParser.Keywords.Default & ~KernelTraceEventParser.Keywords.Profile;
if (ProviderKeywords != ulong.MaxValue)
{
kernelKeywords = (KernelTraceEventParser.Keywords)ProviderKeywords;
}
if (m_processID == WaitingForProcessID) // need to add process events to late bind ProcessFilter
{
kernelKeywords |= KernelTraceEventParser.Keywords.Process;
}
m_session.EnableKernelProvider(kernelKeywords);
}
else
{
m_session.EnableProvider(ProviderGuid, ProviderLevel, ProviderKeywords);
}
LogVerbose(DateTime.Now, "Starting Provider " + ProviderName + " GUID " + ProviderGuid);
listening = true;
m_source.Process();
}
}
});
while (!listening)
{
m_readerTask.Wait(1);
}
}
/// <summary>
/// Returns true of 'data' passes any field filters we might have.
/// </summary>
private unsafe bool PassesFieldFilters(TraceEvent data)
{
// Do we have any field filters?
if (FieldFilters != null)
{
foreach (var fieldFilter in FieldFilters)
{
int fieldIndex = data.PayloadIndex(fieldFilter.FieldName);
if (fieldIndex < 0)
{
if (ShouldLogVerbose)
{
m_log.WriteLine("Dropping event {0} could not find field {1}", data.EventName, fieldFilter.FieldName);
}
return false;
}
string payloadValue = data.PayloadString(fieldIndex);
if (!fieldFilter.Succeeds(payloadValue))
{
if (ShouldLogVerbose)
{
m_log.WriteLine("Dropping event {0} field filter {1} does not succeed on event value {2}",
data.EventName, fieldFilter, payloadValue);
}
return false;
}
m_log.WriteLine("FieldFilter {0} passes with event value {1}", fieldFilter, payloadValue);
}
}
return true;
}
/// <summary>
/// The ETWEventTrigger has a bunch of configuration options. You set them and then call 'Start()' to begin
/// waiting for the proper ETW event.
/// </summary>
public ETWEventTrigger(TextWriter log)
{
m_log = log;
m_startTimeUtc = DateTime.UtcNow;
TriggeredMessage = "Not Triggered";
ProviderLevel = TraceEventLevel.Informational;
ProviderKeywords = ulong.MaxValue;
}
public string ProviderName
{
get
{
if (m_providerName == null)
{
m_providerName = ProviderGuid.ToString();
}
return m_providerName;
}
}
/// <summary>
/// The provider to listen for
/// </summary>
public Guid ProviderGuid { get; set; }
/// <summary>
/// Only used if OpcodeName is null (assumed to be 'Stop') and this is the duration between start and stop.
/// </summary>
public int TriggerMSec { get; set; }
public ulong ProviderKeywords { get; set; }
public TraceEventLevel ProviderLevel { get; set; }
public string StartEvent { set { m_startEvent = new ETWEventTriggerInfo(value); } }
public string StopEvent { set { m_stopEvent = new ETWEventTriggerInfo(value); } }
/// <summary>
/// This is the name of the argument that correlates start-stop pairs.
/// It can be ThreadID as well as ActivityID as well as payload field names, If null it uses the first argument.
/// </summary>
public string StartStopID { get; set; }
/// <summary>
/// Called when Task/Opcode is matched to see if you really want to trigger
/// </summary>
public Predicate<TraceEvent> TriggerPredicate { get; set; }
/// <summary>
/// If non-null, this string is process ID or the name of the process (exe name without path or extension)
/// If this is present only processes that match this filter will trigger the stop. Note that if a
/// process name is given, only one process with that name (at any one time) will trigger the stop.
/// </summary>
public string ProcessFilter { get; set; }
/// <summary>
/// The buffer size used for the session that listens for the ETW trigger.
/// </summary>
public int BufferSizeMB { get; set; }
/// <summary>
/// If TriggerForceToZeroHours is set then the effective TriggerDurationMSec is decrease over time so
/// that it is 0 after TriggerForceToZeroHours. Thus if TriggerDurationMSec is 10,000 and TriggerForceToZeroHours
/// is 24 after 6 hours the trigger will be 7,500 and after 6 hourse it is 5000. This insures that eventually
/// you will trigger.
/// </summary>
public double DecayToZeroHours { get; set; }
/// <summary>
/// This is the callback when something is finally triggered.
/// </summary>
private Action<ETWEventTrigger> OnTriggered { get; set; }
/// <summary>
/// These represent filters (they are logically AND if there is more than one) that
/// operatin on field values of the event.
/// </summary>
private IList<EventFieldFilter> FieldFilters { get; set; }
/// <summary>
/// Returns the actual threshold that will trigger a stop taking TriggerForceToZeroHours in to account
/// </summary>
public int EffectiveTriggerDurationMSec
{
get
{
var triggerMSec = TriggerMSec;
if (DecayToZeroHours != 0)
{
triggerMSec = (int)(triggerMSec * (1 - (DateTime.UtcNow - m_startTimeUtc).TotalHours / DecayToZeroHours));
}
return triggerMSec;
}
}
/// <summary>
/// A detailed message about exactly what caused the triggering. Useful to display to the user after the trigger has fired.
/// </summary>
public string TriggeredMessage { get; private set; }
public override string Status
{
get
{
var exception = m_readerTask.Exception;
if (exception != null)
{
return string.Format("Error: Exception thrown during monitoring: {0}", exception.InnerException.Message);
}
string extraData = "";
var ret = string.Format("Requests: {0:n0} AverageDuration: {1:n1} MSec MaxDuration: {2:n1} Trigger: {3} MSec{4}",
m_requestCount, m_requestTotalMSec / m_requestCount, m_requestMaxMSec, EffectiveTriggerDurationMSec, extraData);
m_requestMaxMSec = 0;
m_requestCount = 0;