-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
1370 lines (1079 loc) · 58.1 KB
/
Program.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
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
#region Copyright (c) 2012 - 2013, Roland Pihlakas
/////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2012 - 2013, Roland Pihlakas.
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
//
/////////////////////////////////////////////////////////////////////////////////////////
#endregion Copyright (c) 2012 - 2013, Roland Pihlakas
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.Runtime;
using System.Reflection;
using System.Security;
namespace CPUUsageMonitor
{
// Summary:
// Encapsulates a method that takes no parameters and does not return a value.
public delegate void Action(); //.net 3.0 does not contain Action delegate declaration
[SuppressUnmanagedCodeSecurity] //SuppressUnmanagedCodeSecurity - For methods in this particular class, execution time is often critical. Security can be traded for additional speed by applying the SuppressUnmanagedCodeSecurity attribute to the method declaration. This will prevent the runtime from doing a security stack walk at runtime. - MSDN: Generally, whenever managed code calls into unmanaged code (by PInvoke or COM interop into native code), there is a demand for the UnmanagedCode permission to ensure all callers have the necessary permission to allow this. By applying this explicit attribute, developers can suppress the demand at run time. The developer must take responsibility for assuring that the transition into unmanaged code is sufficiently protected by other means. The demand for the UnmanagedCode permission will still occur at link time. For example, if function A calls function B and function B is marked with SuppressUnmanagedCodeSecurityAttribute, function A will be checked for unmanaged code permission during just-in-time compilation, but not subsequently during run time.
partial class Program
{
[DllImport("kernel32.dll")]
internal static extern bool SetProcessWorkingSetSize(IntPtr hProcess, IntPtr dwMinimumWorkingSetSize, IntPtr dwMaximumWorkingSetSize);
[/*DllImport("kernel32.dll")*/DllImport("psapi.dll")]
internal static extern bool EmptyWorkingSet(IntPtr processHandle);
static MultiAdvancedChecker multiChecker = null;
internal static CpuUsageComputer cpuUsageComputer;
// ############################################################################
[STAThread] //prevent message loop creation
static void Main(string[] args)
{
Console.WriteLine();
Console.WriteLine(Application.ProductName + " / Version: " + Application.ProductVersion);
Console.WriteLine();
GetConsoleArgumentsValues(args);
if (ValueShowHelp)
{
OutputConsoleArgumentsHelp();
return;
}
ExitHandler.InitUnhandledExceptionHandler();
ExitHandler.HookSessionEnding();
ExitHandler.ExitEventOnce += ExitEventHandler;
NativeMethods.EnableSeIncBasePriorityPrivilege(null);
Process CurrentProcess = Process.GetCurrentProcess();
IntPtr handle = CurrentProcess.Handle;
CurrentProcess.PriorityClass = ProcessPriorityClass.RealTime;
CurrentProcess.PriorityBoostEnabled = true;
NativeMethods.SetPagePriority(handle, 1); //NB! lowest Page priority
NativeMethods.SetIOPriority(handle, NativeMethods.PROCESSIOPRIORITY.PROCESSIOPRIORITY_NORMAL); //ensure that we do not inherit low IO priority from the parent process or something like that
GC.Collect(2, GCCollectionMode.Forced); //collect now all unused startup info because later we will be relatively steady state and will not need any more much memory management
GCSettings.LatencyMode = GCLatencyMode.Batch; //most intrusive mode - most efficient //This option affects only garbage collections in generation 2; generations 0 and 1 are always non-concurrent because they finish very fast. - http://msdn.microsoft.com/en-us/library/ee787088(v=VS.110).aspx#workstation_and_server_garbage_collection
try
{
//GC.WaitForFullGCComplete(); //cob roland: the exception cannot be caught when the method name is written inline, see also http://stackoverflow.com/questions/3546580/why-is-it-not-possible-to-catch-missingmethodexception
typeof(GC).InvokeMember("WaitForFullGCComplete",
BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod,
null, null, null); //see ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/fxref_mscorlib/html/9926d3b0-b0ef-e965-bc72-9ee34bf84df5.htm
}
catch (MissingMethodException) //GC.WaitForFullGCComplete() is only available on .NET SP1 versions
{
Thread.Sleep(100);
}
AutoResetEvent GC_WaitForPendingFinalizers_done = new AutoResetEvent(false);
Thread thread = new Thread(() =>
{
// Wait for all finalizers to complete before continuing.
// Without this call to GC.WaitForPendingFinalizers,
// the worker loop below might execute at the same time
// as the finalizers.
// With this call, the worker loop executes only after
// all finalizers have been called.
GC.WaitForPendingFinalizers();
GC_WaitForPendingFinalizers_done.Set();
});
thread.Name = "GC.WaitForPendingFinalizers thread";
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true; //Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating.
thread.Start();
GC_WaitForPendingFinalizers_done.WaitOne(10000); //NB! prevent hangs
NativeMethods.SetProcessWorkingSetSize(handle, new IntPtr(-1), new IntPtr(-1)); //empty the working set
NativeMethods.EmptyWorkingSet(handle); //empty the working set
float? cpuUsageThreshold = ValueCpuUsageThreshold;
if (!ValueApplyCpuUsageThresholdPerCpu && cpuUsageThreshold.HasValue)
cpuUsageThreshold *= Environment.ProcessorCount;
startMonitoring:
bool cancelFlag = false;
try
{
int updateInterval = Math.Min(ValuePassedCheckIntervalMs, ValueFailedCheckIntervalMs);
cpuUsageComputer = new CpuUsageComputer(ValueProgramRegExes,
/*updateInterval, */ValueFailedCheckIntervalMs, ValuePassedCheckIntervalMs);
cpuUsageComputer.StartMonitoringThread();
multiChecker = new MultiAdvancedChecker(ValueProgramRegExes);
{
multiChecker.CheckUntilOutageOrCancel
(
ValueOutageTimeBeforeGiveUpSeconds,
ValueOutageConditionNumChecks,
ValuePassedCheckIntervalMs,
ValueFailedCheckIntervalMs,
ValueFailIfNoMatchingProcesses,
ValueFailIfNotResponding,
cpuUsageThreshold,
ValueMemoryCommitThresholdMB,
ValueWorkingSetThresholdMB,
ValueGdiHandlesThreshold,
ValueUserHandlesThreshold,
ValueHandlesThreshold,
ValuePagedPoolThresholdKB,
ValueNonPagedPoolThresholdKB,
/*checkSuccessCallback = */null
);
}
}
finally
{
cancelFlag = multiChecker.GetCancelFlag();
//cpuUsageComputer.exitFlag = true;
if (multiChecker != null)
multiChecker.Dispose();
multiChecker = null;
}
bool exit = true;
if (ValueExecuteCommandOnFail != null && ValueExecuteCommandOnFail.Trim() != "")
{
exit = false;
if (!cancelFlag) //NB!
{
if (ValueExecuteCommandArgsOnFail == null)
ValueExecuteCommandArgsOnFail = string.Empty;
Console.WriteLine(string.Format("Executing command: {0} {1}", ValueExecuteCommandOnFail, ValueExecuteCommandArgsOnFail));
var startInfo = new ProcessStartInfo(ValueExecuteCommandOnFail, ValueExecuteCommandArgsOnFail);
//startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;// true; //needs to be false to redirect steams
//startInfo.UseShellExecute = true;
startInfo.ErrorDialog = false; //NB!
startInfo.RedirectStandardError = true; //TODO: single-char output capture
startInfo.RedirectStandardOutput = true; //TODO: single-char output capture
startInfo.RedirectStandardInput = true; //TODO!!!
using (Process commandProcess = new Process())
{
commandProcess.StartInfo = startInfo;
commandProcess.OutputDataReceived += new DataReceivedEventHandler(commandProcess_OutputDataReceived);
commandProcess.ErrorDataReceived += new DataReceivedEventHandler(commandProcess_ErrorDataReceived);
#if USE_INPUT_REDIRECT
int stopInputThread = 0;
Thread inputThread = new Thread(() =>
{
while (Interlocked.CompareExchange(ref stopInputThread, 0, 0) == 0) //volatile read
{
var keyInfo = Console.ReadKey(/*display = */true);
if (keyInfo.KeyChar != 0)
commandProcess.StandardInput.Write(keyInfo.KeyChar);
else
Thread.Sleep(100);
}
});
inputThread.SetApartmentState(ApartmentState.STA);
#endif
commandProcess.Start();
#if USE_INPUT_REDIRECT
commandProcess.StandardInput.AutoFlush = true; //TODO!!! write here all your keystrokes
inputThread.Start();
#endif
commandProcess.BeginOutputReadLine();
commandProcess.BeginErrorReadLine();
commandProcess.WaitForExit(); //NB!
#if USE_INPUT_REDIRECT
stopInputThread = 1;
inputThread.Join();
#endif
} //using (Process commandProcess = Process.Start(startInfo))
goto startMonitoring; //restart monitoring
} //f (!multiChecker.GetCancelFlag())
} //if (ValueExecuteCommandOnFail != null && ValueExecuteCommandOnFail.Trim() != "")
if (exit)
{
//exit the program...
cpuUsageComputer.exitFlag = true;
}
}
static void commandProcess_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
static void commandProcess_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
// ############################################################################
static void ExitEventHandler(bool hasShutDownStarted)
{
cpuUsageComputer.exitFlag = true;
if (multiChecker != null)
multiChecker.SetCancelFlag();
Console.WriteLine("Exiting...");
ExitHandler.DoExit();
}
} //partial class Program
// ############################################################################
public class MultiAdvancedChecker : IDisposable
{
internal static IntPtr CurrentProcessHandle;
List<AdvancedChecker> advancedCheckers = new List<AdvancedChecker>();
List<Thread> advancedCheckerThreads = new List<Thread>();
volatile bool cancelFlag = false;
volatile int currentOutageHostCount = 0;
// ############################################################################
public MultiAdvancedChecker(List<string> ProgramRegExes)
{
foreach (string ProgramRegEx in ProgramRegExes)
advancedCheckers.Add(new AdvancedChecker(ProgramRegEx));
}
#if false
public MultiAdvancedChecker(IEnumerable<string> hosts, IEnumerable<string> sourceHosts)
{
using (IEnumerator<string> sourceHostEnumerator = sourceHosts.GetEnumerator())
{
foreach (string host in hosts)
{
string sourceHost;
if (sourceHostEnumerator.MoveNext())
sourceHost = sourceHostEnumerator.Current;
else
sourceHost = null;
advancedCheckers.Add(new AdvancedCheckers(host, sourceHost));
}
}
}
#endif
// ############################################################################
public bool GetCancelFlag()
{
return this.cancelFlag;
}
public void SetCancelFlag()
{
this.cancelFlag = true;
foreach (var advancedChecker in advancedCheckers) //propagate cancel flag to all checkers
advancedChecker.SetCancelFlag();
}
// ############################################################################
public void Dispose()
{
if (advancedCheckers != null)
{
//foreach (var advancedChecker in advancedCheckers)
// advancedChecker.Dispose();
advancedCheckers = null;
}
}
// ############################################################################
/// <summary>
///
/// </summary>
/// <param name="outageTimeBeforeGiveUpSeconds"></param>
/// <param name="outageConditionNumChecks"></param>
/// <param name="passedCheckIntervalMs"></param>
/// <param name="failedCheckIntervalMs"></param>
/// <param name="timeoutMs"></param>
/// <param name="checkSuccessCallback">NB! checkSuccessCallback should be <b>threadsafe</b> since it can be called from multiple threads simultaneously</param>
/// <returns></returns>
public bool CheckUntilOutageOrCancel
(
int outageTimeBeforeGiveUpSeconds,
int outageConditionNumChecks,
int passedCheckIntervalMs,
int failedCheckIntervalMs,
bool failIfNoMatchingProcesses,
bool failIfNotResponding,
float? cpuUsageThreshold,
long? memoryCommitThresholdMB,
long? workingSetThresholdMB,
long? gdiHandlesThreshold,
long? userHandlesThreshold,
long? handlesThreshold,
long? pagedPoolThresholdKB,
long? nonPagedPoolThresholdKB,
Action checkSuccessCallback
)
{
currentOutageHostCount = 0;
//start all parallel checker threads
foreach (var advancedChecker1 in advancedCheckers)
{
AdvancedChecker advancedChecker = advancedChecker1; //NB! need to copy so that each thread has separate checker variable instance
Thread thread = new Thread(t =>
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
bool outageBegun = false;
do
{
bool success = advancedChecker.CheckUntilOutageOrCancel
(
outageBegun,
outageTimeBeforeGiveUpSeconds,
outageConditionNumChecks,
passedCheckIntervalMs,
failedCheckIntervalMs,
failIfNoMatchingProcesses,
failIfNotResponding,
cpuUsageThreshold,
memoryCommitThresholdMB,
workingSetThresholdMB,
gdiHandlesThreshold,
userHandlesThreshold,
handlesThreshold,
pagedPoolThresholdKB,
nonPagedPoolThresholdKB,
() =>
{
//Debugger.Break();
if (checkSuccessCallback != null)
checkSuccessCallback();
Debug.Assert(currentOutageHostCount > 0);
#pragma warning disable 0420 //warning CS0420: 'CheckTool.MultiAdvancedChecker.currentOutageHostCount': a reference to a volatile field will not be treated as volatile
Interlocked.Decrement(ref currentOutageHostCount);
#pragma warning restore 0420
Debug.Assert(currentOutageHostCount >= 0);
outageBegun = false; //NB!
}
);
if (this.cancelFlag)
return;
Debug.Assert(!success);
if (!outageBegun) //NB! count each checker's outage only once per outage begin
{
#pragma warning disable 0420 //warning CS0420: 'CheckTool.MultiAdvancedChecker.currentOutageHostCount': a reference to a volatile field will not be treated as volatile
Interlocked.Increment(ref currentOutageHostCount);
#pragma warning restore 0420
outageBegun = true;
}
//check whether there is a global outage occurring
if (currentOutageHostCount == advancedCheckers.Count)
{
foreach (var otherChecker in advancedCheckers) //propagate cancel flag to all checkers but do not set cancel flag in current MultiChecker object. Actually this should not be necessary since all checkers should be exiting anyway
otherChecker.SetCancelFlag();
return; //now here we quit from the loop
} //if (currentOutageHostCount == advancedCheckers.Count)
}
while (true); //NB! repeat the checker even when it encountered an outage
});
thread.Start();
advancedCheckerThreads.Add(thread);
} //foreach (var advancedChecker in advancedCheckers)
Thread.CurrentThread.Priority = ThreadPriority.Highest; //NB! this thread also has highest priority since when something is misbehaving then we need to close this program fast to enable the parent .bat file to continue running
GC.Collect(2, GCCollectionMode.Forced); //collect now all unused startup info because later we will be relatively steady state and will not need any more much memory management
GC.WaitForFullGCComplete();
GCSettings.LatencyMode = GCLatencyMode.Batch; //most intrusive mode - most efficient //This option affects only garbage collections in generation 2; generations 0 and 1 are always non-concurrent because they finish very fast. - http://msdn.microsoft.com/en-us/library/ee787088(v=VS.110).aspx#workstation_and_server_garbage_collection
CurrentProcessHandle = Process.GetCurrentProcess().Handle;
TrimWorkingSet(CurrentProcessHandle);
//sit here until all checker threads have exited
foreach (var thread in advancedCheckerThreads)
{
thread.Join();
}
return this.cancelFlag;
}
internal static void TrimWorkingSet(IntPtr handle)
{
try
{
Program.SetProcessWorkingSetSize(handle, new IntPtr(-1), new IntPtr(-1)); //empty the working set
}
catch
{
}
try
{
Program.EmptyWorkingSet(handle); //empty the working set
}
catch
{
}
}
} //class MultiAdvancedChecker
// ############################################################################
public class AdvancedChecker //: BasicChecker
{
volatile bool cancelFlag = false;
private string ProgramRegEx;
// ############################################################################
public AdvancedChecker(string ProgramRegEx)
//: base(ProgramRegEx)
{
this.ProgramRegEx = ProgramRegEx;
}
#if false
public AdvancedCheckers(string host, string sourceHost)
: base(host, sourceHost)
{
}
#endif
// ############################################################################
public void SetCancelFlag()
{
this.cancelFlag = true;
}
// ############################################################################
/// <summary>
///
/// </summary>
/// <param name="outageTimeBeforeGiveUpSeconds"></param>
/// <param name="outageConditionNumChecks"></param>
/// <param name="passedCheckIntervalMs"></param>
/// <param name="failedCheckIntervalMs"></param>
/// <param name="timeoutMs"></param>
/// <param name="checkSuccessCallback">NB! The callback is called only <b>once</b> after each outage end</param>
/// <returns></returns>
public bool CheckUntilOutageOrCancel
(
bool outer_outageState,
int outageTimeBeforeGiveUpSeconds,
int outageConditionNumChecks,
int passedCheckIntervalMs,
int failedCheckIntervalMs,
bool failIfNoMatchingProcesses,
bool failIfNotResponding,
float? cpuUsageThreshold,
long? memoryCommitThresholdMB,
long? workingSetThresholdMB,
long? gdiHandlesThreshold,
long? userHandlesThreshold,
long? handlesThreshold,
long? pagedPoolThresholdKB,
long? nonPagedPoolThresholdKB,
Action checkSuccessCallback
)
{
DateTime? outageBegin = null;
do
{
bool success = CheckUntilOutageOrCancel
(
outageBegin != null,
outageConditionNumChecks,
passedCheckIntervalMs,
failedCheckIntervalMs,
failIfNoMatchingProcesses,
failIfNotResponding,
cpuUsageThreshold,
memoryCommitThresholdMB,
workingSetThresholdMB,
gdiHandlesThreshold,
userHandlesThreshold,
handlesThreshold,
pagedPoolThresholdKB,
nonPagedPoolThresholdKB,
() =>
{
if (outer_outageState) //NB! propagate the success message only when the outage was started
{
//Debugger.Break();
if (checkSuccessCallback != null)
checkSuccessCallback();
outer_outageState = false;
}
outageBegin = null; //reset outage status
}
);
if (this.cancelFlag)
break;
Debug.Assert(!success);
DateTime now = DateTime.UtcNow;
if (outageBegin == null)
{
outageBegin = now;
}
else
{
TimeSpan outageDuration = now - outageBegin.Value;
if (outageDuration.TotalSeconds >= outageTimeBeforeGiveUpSeconds) //should we give up?
break;
}
}
while (true);
return this.cancelFlag;
}
// ############################################################################
/// <summary>
///
/// </summary>
/// <param name="outageConditionNumChecks"></param>
/// <param name="passedCheckIntervalMs"></param>
/// <param name="failedCheckIntervalMs"></param>
/// <param name="timeoutMs"></param>
/// <param name="checkSuccessCallback">NB! The callback is called only <b>once</b> after each outage end</param>
/// <returns></returns>
public bool CheckUntilOutageOrCancel
(
bool outer_outageState,
int outageConditionNumChecks,
int passedCheckIntervalMs,
int failedCheckIntervalMs,
bool failIfNoMatchingProcesses,
bool failIfNotResponding,
float? cpuUsageThreshold,
long? memoryCommitThresholdMB,
long? workingSetThresholdMB,
long? gdiHandlesThreshold,
long? userHandlesThreshold,
long? handlesThreshold,
long? pagedPoolThresholdKB,
long? nonPagedPoolThresholdKB,
Action checkSuccessCallback
)
{
this.cancelFlag = false;
int outageCount = 0;
bool success;
int last_expectedTimeDiffMs = 0;
do
{
//success = base.CheckHost(cpuUsageThreshold);
long? memoryCommitMB;
long? workingSetMB;
long? gdiHandles;
long? userHandles;
long? handles;
long? pagedPoolKB;
long? nonPagedPoolKB;
bool notRunning;
bool notResponding;
double? cpu_usage = Program.cpuUsageComputer.GetCpuUsageForRegex
(
out memoryCommitMB,
out workingSetMB,
out gdiHandles,
out userHandles,
out handles,
out pagedPoolKB,
out nonPagedPoolKB,
out notRunning,
out notResponding,
ProgramRegEx,
last_expectedTimeDiffMs,
failIfNoMatchingProcesses,
failIfNotResponding
);
success = true;
if (failIfNoMatchingProcesses && !cpu_usage.HasValue)
success = false;
else if (notResponding)
success = false;
else if (cpu_usage.HasValue && cpuUsageThreshold.HasValue && cpu_usage >= cpuUsageThreshold)
success = false;
else if (memoryCommitMB.HasValue && memoryCommitThresholdMB.HasValue && memoryCommitMB >= workingSetThresholdMB)
success = false;
else if (workingSetMB.HasValue && workingSetThresholdMB.HasValue && workingSetMB >= workingSetThresholdMB)
success = false;
else if (gdiHandles.HasValue && gdiHandlesThreshold.HasValue && gdiHandles >= gdiHandlesThreshold)
success = false;
else if (userHandles.HasValue && userHandlesThreshold.HasValue && userHandles >= userHandlesThreshold)
success = false;
else if (handles.HasValue && handlesThreshold.HasValue && handles >= handlesThreshold)
success = false;
else if (pagedPoolKB.HasValue && pagedPoolThresholdKB.HasValue && pagedPoolKB >= pagedPoolThresholdKB)
success = false;
else if (nonPagedPoolKB.HasValue && nonPagedPoolThresholdKB.HasValue && nonPagedPoolKB >= nonPagedPoolThresholdKB)
success = false;
if (success)
{
Console.WriteLine(string.Format("Check OK: {0} - {1} % {2} MB Commit {3} MB WS {4} GDI {5} User {6} Handles {7} KB Paged Pool {8} KB NP Pool",
ProgramRegEx,
(cpu_usage.HasValue ? cpu_usage.Value.ToString("F2") : "N/A"),
(memoryCommitMB.HasValue ? memoryCommitMB.Value.ToString() : "N/A"),
(workingSetMB.HasValue ? workingSetMB.Value.ToString() : "N/A"),
(gdiHandles.HasValue ? gdiHandles.Value.ToString() : "N/A"),
(userHandles.HasValue ? userHandles.Value.ToString() : "N/A"),
(handles.HasValue ? handles.Value.ToString() : "N/A"),
(pagedPoolKB.HasValue ? pagedPoolKB.Value.ToString() : "N/A"),
(nonPagedPoolKB.HasValue ? nonPagedPoolKB.Value.ToString() : "N/A")
));
if (outer_outageState)
{
Program.cpuUsageComputer.DecrementFailedCheckersCount();
}
if (outageCount == 1) //NB! separate decrement of failure counter
{
Program.cpuUsageComputer.DecrementFailedCheckersCount();
}
if (outer_outageState) //NB! propagate the success message only when the outage was started
{
//Debugger.Break();
if (checkSuccessCallback != null)
checkSuccessCallback();
outer_outageState = false;
}
outageCount = Math.Max(0, outageCount - 1);
if (!this.cancelFlag)
{
if (outageCount == 0) //roland 4.06.2013
{
//Thread.Sleep(passedCheckIntervalMs);
int sleepStep = 1000;
for (int i = 0; i < passedCheckIntervalMs; i += sleepStep)
{
if (!this.cancelFlag)
Thread.Sleep(Math.Min(sleepStep, passedCheckIntervalMs - i));
}
last_expectedTimeDiffMs = passedCheckIntervalMs;
}
else //if (outageCount == 0)
{
//Thread.Sleep(passedCheckIntervalMs);
int sleepStep = 1000;
for (int i = 0; i < failedCheckIntervalMs; i += sleepStep)
{
if (!this.cancelFlag)
Thread.Sleep(Math.Min(sleepStep, failedCheckIntervalMs - i));
}
last_expectedTimeDiffMs = failedCheckIntervalMs;
}
} //if (!this.cancelFlag)
}
else //if (success)
{
if (
cpu_usage.HasValue
|| memoryCommitMB.HasValue
|| workingSetMB.HasValue
|| gdiHandles.HasValue
|| userHandles.HasValue
|| handles.HasValue
|| pagedPoolKB.HasValue
|| nonPagedPoolKB.HasValue
)
{
Console.WriteLine(string.Format("Check FAILED: {0} - {1} % {2} MB Commit {3} MB WS {4} GDI {5} User {6} Handles {7} KB Paged Pool {8} KB NP Pool {9}",
ProgramRegEx,
(cpu_usage.HasValue ? cpu_usage.Value.ToString("F2") : "N/A"),
(memoryCommitMB.HasValue ? memoryCommitMB.Value.ToString() : "N/A"),
(workingSetMB.HasValue ? workingSetMB.Value.ToString() : "N/A"),
(gdiHandles.HasValue ? gdiHandles.Value.ToString() : "N/A"),
(userHandles.HasValue ? userHandles.Value.ToString() : "N/A"),
(handles.HasValue ? handles.Value.ToString() : "N/A"),
(pagedPoolKB.HasValue ? pagedPoolKB.Value.ToString() : "N/A"),
(nonPagedPoolKB.HasValue ? nonPagedPoolKB.Value.ToString() : "N/A"),
notResponding ? "NOT RESPONDING" : ""
));
}
else
{
Console.WriteLine(string.Format("Check N/A: {0} - PROGRAM NOT RUNNING", ProgramRegEx));
}
if (outageCount == 0)
Program.cpuUsageComputer.IncrementFailedCheckersCount();
outageCount++;
if (!this.cancelFlag
//&& outageCount < outageConditionNumChecks) //sleep only when outage count not exceeded //cob roland: sleep also when outage count is exceeded since we are likely going to repeat the loop
)
{
//Thread.Sleep(failedCheckIntervalMs);
int sleepStep = 1000;
for (int i = 0; i < failedCheckIntervalMs; i += sleepStep)
{
if (!this.cancelFlag)
Thread.Sleep(Math.Min(sleepStep, failedCheckIntervalMs - i));
}
last_expectedTimeDiffMs = failedCheckIntervalMs;
}
} //if (success)
MultiAdvancedChecker.TrimWorkingSet(MultiAdvancedChecker.CurrentProcessHandle);
}
while (outageCount < outageConditionNumChecks && !this.cancelFlag);
return this.cancelFlag;
} //public bool CheckUntilOutageOrCancel()
} //class AdvancedChecker
// ############################################################################
public class ObjRef<T>
{
public T Value;
public ObjRef(T value_in)
{
Value = value_in;
}
}
// ############################################################################
public class CpuUsageComputer
{
public volatile bool exitFlag = false;
//private readonly int sleepMs;
private readonly bool AllRegexesAlphaNumericOnly = true;
private readonly List<string> regex_strings = null;
private List<KeyValuePair<string, Regex>> regexes_compiled;
private Dictionary<int, TimeSpan> prev_cpu_times = new Dictionary<int, TimeSpan>();
private volatile Dictionary<string, double> cpu_usages = null; // = new Dictionary<string, double>();
private bool firstLoop = true;
private volatile Dictionary<string, long> memoryCommitsInMB = new Dictionary<string, long>();
private volatile Dictionary<string, long> workingSetInMB = new Dictionary<string, long>();
private volatile Dictionary<string, long> gdiHandlesDict = new Dictionary<string, long>();
private volatile Dictionary<string, long> userHandlesDict = new Dictionary<string, long>();
private volatile Dictionary<string, long> handlesDict = new Dictionary<string, long>();
private volatile Dictionary<string, long> pagedPoolInKB = new Dictionary<string, long>();
private volatile Dictionary<string, long> nonPagedPoolInKB = new Dictionary<string, long>();
private volatile Dictionary<string, bool> notRespondingProcesses = null; //this dictionary is actually used as hashset
private readonly ManualResetEvent updatedEvent = new ManualResetEvent(false);
private volatile ObjRef<long> prev_stopWatch_time = null;
private readonly object measurementTimeDiff_lock = new object();
private volatile int FailedCheckersCount = 0;
private readonly int FailedCheckIntervalMs;
private readonly int PassedCheckIntervalMs;
private volatile int currSleepMs = 0;
// ############################################################################
public void IncrementFailedCheckersCount()
{
Interlocked.Increment(ref FailedCheckersCount);
}
public void DecrementFailedCheckersCount()
{
Interlocked.Decrement(ref FailedCheckersCount);
Debug.Assert(FailedCheckersCount >= 0);
}
// ############################################################################
public CpuUsageComputer(List<string> regExes, /*int sleepMs, */int FailedCheckIntervalMs, int PassedCheckIntervalMs)
{
//this.sleepMs = sleepMs;
this.FailedCheckIntervalMs = FailedCheckIntervalMs;
this.PassedCheckIntervalMs = PassedCheckIntervalMs;
Regex alphaNumericCheck = new Regex("^[a-z0-9_-]+$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.regexes_compiled = new List<KeyValuePair<string, Regex>>(regExes.Count);
foreach (var regex_str in regExes)
{
var add_regex = new Regex
(
"^" + regex_str + "$", //auto-lock the regex endpoints
RegexOptions.Compiled
//| RegexOptions.CultureInvariant
| RegexOptions.ExplicitCapture
| RegexOptions.IgnoreCase
);
this.regexes_compiled.Add(new KeyValuePair<string, Regex>(regex_str, add_regex));
if (!alphaNumericCheck.IsMatch(regex_str))
{
this.AllRegexesAlphaNumericOnly = false;
}
} //foreach (var regex_str in regExes)
this.regex_strings = regExes;
#if false
if (this.AllRegexesAlphaNumericOnly)
Console.WriteLine("All regexes are alphanumeric only. This saves CPU due to the possibility to take list of only matching processes.");
else
Console.WriteLine("All regexes are NOT alphanumeric only. Checking for such regex takes more CPU due to the need to take list of all running processes.");
#endif
} //public CpuUsageComputer(List<string> regExes)
// ############################################################################
public double? GetCpuUsageForRegex
(
out long? memoryCommitMB,
out long? workingSetMB,
out long? gdiHandles,
out long? userHandles,
out long? handles,
out long? pagedPoolKB,
out long? nonPagedPoolKB,
out bool notRunning,
out bool notResponding,
string regex, int expectedTimeDiffMs,
bool failIfNoMatchingProcesses, bool failIfNotResponding
)
{
Monitor.Enter(measurementTimeDiff_lock); //We need this lock in order to prevent race condition resetting the updatedEvent immediately AFTER it has been set by monitoring thread.
TimeSpan measurementTimeDiff = GetMeasurementTimeDiff(); //time since previous measurement
//if (measurementTimeDiff < TimeSpan.FromMilliseconds(expectedTimeDiffMs / 2))
if (measurementTimeDiff < TimeSpan.FromMilliseconds(currSleepMs / 2))
{
Monitor.Exit(measurementTimeDiff_lock);
//return previous result
}
else
{
updatedEvent.Reset();
Monitor.Exit(measurementTimeDiff_lock); //NB! exit lock only after resetting the event
//wait for update and return updated result
//updatedEvent.WaitOne();
int sleepStep = 1000;
while (!exitFlag && !updatedEvent.WaitOne(0))
{
if (!exitFlag)
Thread.Sleep(sleepStep); //use coarse wait
}
}