-
Notifications
You must be signed in to change notification settings - Fork 327
Expand file tree
/
Copy pathMonitor.cpp
More file actions
2173 lines (1907 loc) · 75.6 KB
/
Monitor.cpp
File metadata and controls
2173 lines (1907 loc) · 75.6 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License
//--------------------------------------------------------------------
//
// Monitor functions
//
//--------------------------------------------------------------------
#define _Bool bool
#ifdef __linux__
#include "procdump_ebpf.skel.h"
#endif
#include "Includes.h"
#include <vector>
#include <string>
#include <memory>
#ifdef __APPLE__
#include <libproc.h>
#endif
static pthread_t sig_thread_id;
extern struct ProcDumpConfiguration g_config;
extern struct ProcDumpConfiguration * target_config;
extern sigset_t sig_set;
//
// Set when a SIGINT is received.
//
bool g_sigint = false;
//
// List of all active monitor configurations.
// All access to this map must be protected by activeConfigurationMutex
//
std::unordered_map<int, ProcDumpConfiguration*> activeConfigurations;
pthread_mutex_t activeConfigurationsMutex;
//
// Map of which processes are being monitored
//
std::unordered_map<int, MonitoredProcessMapEntry> monitoredProcessMap;
//------------------------------------------------------------------------------------------------------
//
// SignalThread - Thread for handling graceful Async signals (e.g., SIGINT, SIGTERM)
//
// Turn off address sanitation for this function as a result of a likely bug with pthread_cancel. The
// incorrect error that the address sanitizer gives is:
//==314250==AddressSanitizer CHECK failed: ../../../../src/libsanitizer/asan/asan_thread.cpp:367 "((ptr[0] == kCurrentStackFrameMagic)) != (0)" (0x0, 0x0)
// #0 0x7f6cd0a30988 in AsanCheckFailed ../../../../src/libsanitizer/asan/asan_rtl.cpp:74
// #1 0x7f6cd0a5130e in __sanitizer::CheckFailed(char const*, int, char const*, unsigned long long, unsigned long long) ../../../../src/libsanitizer/sanitizer_common/sanitizer_termination.cpp:78
// #2 0x7f6cd0a3610c in __asan::AsanThread::GetStackFrameAccessByAddr(unsigned long, __asan::AsanThread::StackFrameAccess*) ../../../../src/libsanitizer/asan/asan_thread.cpp:367
// #3 0x7f6cd09a0e9b in __asan::GetStackAddressInformation(unsigned long, unsigned long, __asan::StackAddressDescription*) ../../../../src/libsanitizer/asan/asan_descriptions.cpp:203
// #4 0x7f6cd09a22d8 in __asan::AddressDescription::AddressDescription(unsigned long, unsigned long, bool) ../../../../src/libsanitizer/asan/asan_descriptions.cpp:455
// #5 0x7f6cd09a22d8 in __asan::AddressDescription::AddressDescription(unsigned long, unsigned long, bool) ../../../../src/libsanitizer/asan/asan_descriptions.cpp:439
// #6 0x7f6cd09a4a84 in __asan::ErrorGeneric::ErrorGeneric(unsigned int, unsigned long, unsigned long, unsigned long, unsigned long, bool, unsigned long) ../../../../src/libsanitizer/asan/asan_errors.cpp:389
// #7 0x7f6cd0a2ffa5 in __asan::ReportGenericError(unsigned long, unsigned long, unsigned long, unsigned long, bool, unsigned long, unsigned int, bool) ../../../../src/libsanitizer/asan/asan_report.cpp:476
// #8 0x7f6cd09c6fe8 in __interceptor_sigaltstack ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors.inc:9986
// #9 0x7f6cd0a45867 in __sanitizer::UnsetAlternateSignalStack() ../../../../src/libsanitizer/sanitizer_common/sanitizer_posix_libcdep.cpp:195
// #10 0x7f6cd0a3560c in __asan::AsanThread::Destroy() ../../../../src/libsanitizer/asan/asan_thread.cpp:104
// #11 0x7f6cd07dc710 in __GI___nptl_deallocate_tsd nptl/nptl_deallocate_tsd.c:73
// #12 0x7f6cd07dc710 in __GI___nptl_deallocate_tsd nptl/nptl_deallocate_tsd.c:22
// #13 0x7f6cd07df9c9 in start_thread nptl/pthread_create.c:453
// #14 0x7f6cd08719ff (/lib/x86_64-linux-gnu/libc.so.6+0x1269ff)
//------------------------------------------------------------------------------------------------------
__attribute__((no_sanitize("address")))
void* SignalThread(void *input)
{
Trace("SignalThread: Enter [id=%d]", gettid());
int sig_caught, rc;
if ((rc = sigwait(&sig_set, &sig_caught)) != 0) {
Log(error, "Failed to wait on signal");
exit(-1);
}
switch (sig_caught)
{
case SIGINT:
Trace("SignalThread: Got a SIGINT");
g_sigint = true;
// In case of CTRL-C we need to iterate over all the outstanding monitors and handle them appropriately
pthread_mutex_lock(&activeConfigurationsMutex);
for (auto it = activeConfigurations.begin(); it != activeConfigurations.end(); it++)
{
if(!IsQuit(it->second)) SetQuit(it->second, 1);
if(it->second->gcorePid != NO_PID) {
Log(info, "Shutting down gcore");
if((rc = kill(-it->second->gcorePid, SIGKILL)) != 0) { // pass negative PID to kill entire PGRP with value of gcore PID
Log(error, "Failed to shutdown gcore.");
}
}
// Need to make sure we detach from ptrace (if not attached it will silently fail)
// To avoid situations where we have intercepted a signal and CTRL-C is hit, we synchronize
// access to the signal path (in SignalMonitoringThread). Note, there is still a race but
// acceptable since it is very unlikely to occur. We also cancel the SignalMonitorThread to
// break it out of waitpid call.
if(it->second->SignalCount > 0)
{
for(int i=0; i<it->second->nThreads; i++)
{
if(it->second->Threads[i].trigger == Signal)
{
pthread_mutex_lock(&it->second->ptrace_mutex);
#ifdef __linux__
ptrace(PTRACE_DETACH, it->second->ProcessId, 0, 0);
#endif
pthread_mutex_unlock(&it->second->ptrace_mutex);
if ((rc = pthread_cancel(it->second->Threads[i].thread)) != 0) {
Log(error, "An error occurred while cancelling SignalMonitorThread.\n");
exit(-1);
}
}
}
}
}
pthread_mutex_unlock(&activeConfigurationsMutex);
Log(info, "Quit");
SetQuit(&g_config, 1); // Make sure to signal the global config
break;
default:
Trace("Unexpected signal %d", sig_caught);
break;
}
Trace("SignalThread: Exit [id=%d]", gettid());
return NULL;
}
//--------------------------------------------------------------------
//
// GetNewMonitorConfiguration
// Gets a new configuration based off of the passed in config.
// Also adds the configuration to both activeConfigurations and
// monitoredProcessMap meaning it is now considered an active and monitored
// process.
//
//--------------------------------------------------------------------
ProcDumpConfiguration* GetNewMonitorConfiguration(ProcDumpConfiguration* sourceConfig, char* processName, int procPid, unsigned long long starttime)
{
ProcDumpConfiguration* config = CopyProcDumpConfiguration(sourceConfig);
if(config == NULL)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: failed to alloc struct for process.");
return NULL;
}
// populate fields for this target
if(procPid != -1)
{
config->ProcessId = procPid;
}
if(processName != NULL)
{
config->ProcessName = processName;
}
// insert config into queue
pthread_mutex_lock(&activeConfigurationsMutex);
activeConfigurations[config->ProcessId] = config;
monitoredProcessMap[config->ProcessId].active = true;
monitoredProcessMap[config->ProcessId].starttime = starttime;
pthread_mutex_unlock(&activeConfigurationsMutex);
return config;
}
//--------------------------------------------------------------------
//
// CheckAccess
//
// Checks to make sure we have access to the target process.
//
//--------------------------------------------------------------------
bool CheckAccess(struct ProcDumpConfiguration *self)
{
struct ProcessStat proc;
if(GetProcessStat(self->ProcessId, &proc) == false)
{
return false;
}
uid_t euid = geteuid();
if(euid == 0 || euid == proc.effective_uid)
{
return true;
}
return false;
}
//--------------------------------------------------------------------
//
// MonitorProcesses
// MonitorProcess is the starting point of where the monitors get
// created. It uses a list to store all the monitors that are active.
// All monitors must go on this list as there are other places (for
// example, SignalThread) that relies on all active monitors to be part
// of the list.
//
//--------------------------------------------------------------------
void MonitorProcesses(struct ProcDumpConfiguration *self)
{
if (self->WaitingForProcessName) Log(info, "Waiting for processes '%s' to launch\n", self->ProcessName);
if (self->bProcessGroup == true) Log(info, "Monitoring processes of PGID '%d'\n", self->ProcessGroup);
// allocate list of configs for process monitoring
int numMonitoredProcesses = 0;
monitoredProcessMap.reserve(5000); // assume 5000 processes
// Create a signal handler thread where we handle shutdown as a result of SIGINT.
// Note: We only create ONE per instance of procdump rather than per monitor.
if((pthread_create(&sig_thread_id, NULL, SignalThread, (void *)self))!= 0)
{
Log(error, INTERNAL_ERROR);
Trace("CreateMonitorThreads: failed to create SignalThread.");
return;
}
Log(info, "Press Ctrl-C to end monitoring without terminating the process(es).");
if(!self->WaitingForProcessName && !self->bProcessGroup)
{
//
// Monitoring single process (-p)
//
//
// Make sure target process exists
//
// If we have a process name find it to make sure it exists
if(self->ProcessName)
{
if(!LookupProcessByName(self->ProcessName))
{
Log(error, "No process matching the specified name (%s) can be found.", self->ProcessName);
return;
}
// Set the process ID so the monitor can target.
self->ProcessId = LookupProcessPidByName(g_config.ProcessName);
}
else
{
if (self->ProcessId != NO_PID && LookupProcessByPid(self->ProcessId))
{
self->ProcessName = GetProcessName(self->ProcessId);
}
else
{
Log(error, "No process matching the specified PID (%d) can be found.", self->ProcessId);
return;
}
}
ProcDumpConfiguration* config = GetNewMonitorConfiguration(self, NULL, -1, 0);
if(config == NULL)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: failed to get new monitor configuration.");
return;
}
// print config here
PrintConfiguration(config);
if(StartMonitor(config)!=0)
{
Trace("MonitorProcesses: Failed to start the monitor.");
Log(error, "MonitorProcesses: Failed to start the monitor.");
return;
}
WaitForAllMonitorsToTerminate(config);
Log(info, "Stopping monitor for process %s (%d)", config->ProcessName, config->ProcessId);
WaitForSignalThreadToTerminate(config);
pthread_mutex_lock(&activeConfigurationsMutex);
activeConfigurations.erase(config->ProcessId);
monitoredProcessMap[config->ProcessId].active = false;
pthread_mutex_unlock(&activeConfigurationsMutex);
FreeProcDumpConfiguration(config);
free(config);
}
else
{
// print config here
PrintConfiguration(self);
do
{
// Multi process monitoring
// If we are monitoring for PGID, validate the root process exists
if(self->bProcessGroup && !LookupProcessByPgid(self->ProcessGroup)) {
Log(error, "No process matching the specified PGID can be found.");
PrintUsage();
return;
}
// Iterate over all running processes
#ifdef __linux__
struct dirent ** nameList;
int numEntries = scandir("/proc/", &nameList, FilterForPid, alphasort);
#else
pid_t *nameList;
int numEntries = GetRunningPids(&nameList);
#endif
for (int i = 0; i < numEntries; i++)
{
pid_t procPid;
#ifdef __linux__
if(!ConvertToInt(nameList[i]->d_name, &procPid))
{
continue;
}
#else
procPid = nameList[i];
#endif
if(self->bProcessGroup)
{
// We are monitoring a process group (-g)
pid_t pgid = GetProcessPgid(procPid);
if(pgid != NO_PID && pgid == self->ProcessGroup)
{
struct ProcessStat procStat;
bool ret = GetProcessStat(procPid, &procStat);
// Note: To solve the PID reuse case, we uniquely identify an entry via {PID}{starttime}
if(ret && (monitoredProcessMap[procPid].active == false || monitoredProcessMap[procPid].starttime != procStat.starttime))
{
ProcDumpConfiguration* config = GetNewMonitorConfiguration(self, GetProcessName(procPid), procPid, procStat.starttime);
if(config == NULL)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: failed to get new monitor configuration.");
return;
}
if(StartMonitor(config)!=0)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: Failed to start the monitor.");
return;
}
numMonitoredProcesses++;
}
}
}
else if(self->WaitingForProcessName)
{
// We are monitoring for a process name (-w)
char *nameForPid = GetProcessName(procPid);
// check to see if process name matches target
if (nameForPid && strcmp(nameForPid, self->ProcessName) == 0)
{
struct ProcessStat procStat;
bool ret = GetProcessStat(procPid, &procStat);
// Note: To solve the PID reuse case, we uniquely identify an entry via {PID}{starttime}
if(ret && (monitoredProcessMap[procPid].active == false || monitoredProcessMap[procPid].starttime != procStat.starttime))
{
ProcDumpConfiguration* config = GetNewMonitorConfiguration(self, strdup(nameForPid), procPid, procStat.starttime);
if(config == NULL)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: failed to get new monitor configuration.");
return;
}
if(StartMonitor(config)!=0)
{
Log(error, INTERNAL_ERROR);
Trace("MonitorProcesses: Failed to start the monitor.");
return;
}
numMonitoredProcesses++;
}
}
}
}
// clean up namelist
#ifdef __linux__
for (int i = 0; i < numEntries; i++)
{
free(nameList[i]);
}
#endif
if(numEntries!=-1)
{
free(nameList);
}
// cleanup process configs for child processes that have exited or for monitors that have captured N dumps
pthread_mutex_lock(&activeConfigurationsMutex);
for (auto it = activeConfigurations.begin(); it != activeConfigurations.end(); )
{
if (it->second->bTerminated ||
it->second->nQuit ||
it->second->NumberOfDumpsCollected == it->second->NumberOfDumpsToCollect ||
it->second->NumberOfLeakReportsCollected == it->second->NumberOfDumpsToCollect)
{
Log(info, "Stopping monitors for process: %s (%d)", it->second->ProcessName, it->second->ProcessId);
WaitForAllMonitorsToTerminate(it->second);
FreeProcDumpConfiguration(it->second);
delete it->second;
it = activeConfigurations.erase(it);
numMonitoredProcesses--;
}
else
{
++it;
}
}
pthread_mutex_unlock(&activeConfigurationsMutex);
// Exit if we are monitoring PGID and there are no more processes to monitor.
// If we are monitoring for processes based on a process name we keep monitoring
if(numMonitoredProcesses == 0 && self->WaitingForProcessName == false)
{
break;
}
// Wait for the polling interval the user specified before we check again
sleep(g_config.PollingInterval / 1000);
// We keep iterating while we have processes to monitor (in case of -g <pgid>) or if process name has
// been specified (-w) in which case we keep monitoring until CTRL-C or finally if we have a quit signal.
} while ((numMonitoredProcesses >= 0 || self->WaitingForProcessName == true) && !IsQuit(&g_config));
// cleanup monitoring queue
pthread_mutex_lock(&activeConfigurationsMutex);
for (auto it = activeConfigurations.begin(); it != activeConfigurations.end(); )
{
if (it->second->bTerminated ||
it->second->nQuit ||
it->second->NumberOfDumpsCollected == it->second->NumberOfDumpsToCollect ||
it->second->NumberOfLeakReportsCollected == it->second->NumberOfDumpsToCollect)
{
SetQuit(it->second, 1);
WaitForAllMonitorsToTerminate(it->second);
FreeProcDumpConfiguration(it->second);
delete it->second;
it = activeConfigurations.erase(it);
}
else
{
++it;
}
}
pthread_mutex_unlock(&activeConfigurationsMutex);
free(target_config);
}
}
//--------------------------------------------------------------------
//
// MonitorDotNet - Returns true if we are monitoring a dotnet process
//
//--------------------------------------------------------------------
bool MonitorDotNet(struct ProcDumpConfiguration *self)
{
if(self->bDumpOnException || self->bMonitoringGCMemory || self->DumpGCGeneration != -1)
{
return true;
}
return false;
}
//--------------------------------------------------------------------
//
// CreateMonitorThread - Create a specific monitor thread
//
//--------------------------------------------------------------------
int CreateMonitorThread(struct ProcDumpConfiguration *self, enum TriggerType triggerType, void *(*monitorThread) (void *), void *arg)
{
int rc = -1;
if (self->nThreads < MAX_TRIGGERS)
{
if ((rc = pthread_create(&self->Threads[self->nThreads].thread, NULL, monitorThread, arg)) != 0)
{
return rc;
}
self->Threads[self->nThreads].trigger = triggerType;
self->nThreads++;
}
else
{
Trace("CreateMonitorThread: max number of triggers reached.");
}
return rc;
}
//--------------------------------------------------------------------
//
// CreateMonitorThreads - Create each of the threads that will be running as a trigger
//
//--------------------------------------------------------------------
int CreateMonitorThreads(struct ProcDumpConfiguration *self)
{
int rc = 0;
self->nThreads = 0;
// create threads
if (MonitorDotNet(self) == true)
{
if ((rc = CreateMonitorThread(self, Exception, DotNetMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create DotNetMonitoringThread.");
return rc;
}
}
if (self->CpuThreshold != -1)
{
if ((rc = CreateMonitorThread(self, Processor, CpuMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create CpuThread.");
return rc;
}
}
if (self->MemoryThreshold != NULL && self->bMonitoringGCMemory == false)
{
if ((rc = CreateMonitorThread(self, Commit, CommitMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create CommitThread.");
return rc;
}
}
if (self->ThreadThreshold != -1)
{
if ((rc = CreateMonitorThread(self, ThreadCount, ThreadCountMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create ThreadThread.");
return rc;
}
}
if (self->FileDescriptorThreshold != -1)
{
if ((rc = CreateMonitorThread(self, FileDescriptorCount, FileDescriptorCountMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create FileDescriptorThread.");
return rc;
}
}
if (self->SignalCount > 0)
{
if ((rc = CreateMonitorThread(self, Signal, SignalMonitoringThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create SignalMonitoringThread.");
return rc;
}
}
if (self->bTimerThreshold)
{
if ((rc = CreateMonitorThread(self, Timer, TimerThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create TimerThread.");
return rc;
}
}
if (self->bRestrackEnabled)
{
if ((rc = CreateMonitorThread(self, Restrack, RestrackThread, (void *)self)) != 0 )
{
Trace("CreateMonitorThreads: failed to create RestrackThread.");
return rc;
}
// if '-restrack' was enabled without triggers, we wait a manual user input to be the trigger for a restrack snapshot
if ((self->bTimerThreshold == false) &&
(self->CpuThreshold == -1) &&
(self->MemoryThreshold == NULL) &&
(self->ThreadThreshold == -1) &&
(self->FileDescriptorThreshold == -1) &&
(self->DumpGCGeneration == -1) &&
(self->SignalCount == 0))
{
if ((rc = CreateMonitorThread(self, RestrackManual, RestrackManualTriggerThread, (void *)self)) != 0)
{
Trace("CreateMonitorThreads: failed to create RestrackManualTriggerThread.");
return rc;
}
}
}
return 0;
}
//--------------------------------------------------------------------
//
// StartMonitor
// Creates the monitoring threads and begins the monitor based on
// the configuration passed in. In the case of exception monitoring
// we inject the monitor into the target process.
//
//--------------------------------------------------------------------
int StartMonitor(struct ProcDumpConfiguration* monitorConfig)
{
int ret = 0;
if(CheckAccess(monitorConfig) == false)
{
Log(error, "Procdump is not running with elevated credentials or the effective uid does not match the effective uid of the target process (pid %d).", monitorConfig->ProcessId);
return -1;
}
if(CreateMonitorThreads(monitorConfig) != 0)
{
Log(error, INTERNAL_ERROR);
Trace("StartMonitor: failed to create trigger threads.");
return -1;
}
if(BeginMonitoring(monitorConfig) == false)
{
Log(error, INTERNAL_ERROR);
Trace("StartMonitor: failed to start monitoring.");
return -1;
}
Log(info, "Starting monitor for process %s (%d)", monitorConfig->ProcessName, monitorConfig->ProcessId);
return ret;
}
//--------------------------------------------------------------------
//
// WaitForQuit - Wait for Quit Event or just timeout
//
// Timed wait with awareness of quit event
//
// Returns: WAIT_OBJECT_0 - Quit triggered
// WAIT_TIMEOUT - Timeout
// WAIT_ABANDONED - At dump limit or terminated
//
//--------------------------------------------------------------------
int WaitForQuit(struct ProcDumpConfiguration *self, int milliseconds)
{
if (!ContinueMonitoring(self)) {
return WAIT_ABANDONED;
}
int wait = WaitForSingleObject(&self->evtQuit, milliseconds);
if ((wait == WAIT_TIMEOUT) && !ContinueMonitoring(self)) {
return WAIT_ABANDONED;
}
return wait;
}
//--------------------------------------------------------------------
//
// WaitForQuitOrEvent - Wait for Quit Event, an Event, or just timeout
//
// Use to wait for dumps to complete, yet be aware of quit or finished events
//
// Returns: WAIT_OBJECT_0 - Quit triggered
// WAIT_OBJECT_0+1 - Event triggered
// WAIT_TIMEOUT - Timeout
// WAIT_ABANDONED - (Abandonded) At dump limit or terminated
//
//--------------------------------------------------------------------
int WaitForQuitOrEvent(struct ProcDumpConfiguration *self, struct Handle *handle, int milliseconds)
{
struct Handle *waits[2];
waits[0] = &self->evtQuit;
waits[1] = handle;
if (!ContinueMonitoring(self)) {
return WAIT_ABANDONED;
}
int wait = WaitForMultipleObjects(2, waits, false, milliseconds);
if ((wait == WAIT_TIMEOUT) && !ContinueMonitoring(self)) {
return WAIT_ABANDONED;
}
if ((wait == WAIT_OBJECT_0) && !ContinueMonitoring(self)) {
return WAIT_ABANDONED;
}
return wait;
}
pthread_t GetRestrackThread(struct ProcDumpConfiguration *self)
{
pthread_t restrackThread = 0;
for(int i=0; i<self->nThreads; i++)
{
if(self->Threads[i].trigger == Restrack)
{
restrackThread = self->Threads[i].thread;
break;
}
}
return restrackThread;
}
//--------------------------------------------------------------------
//
// CancelRestrackThread - Cancel the restrack thread
//
//--------------------------------------------------------------------
int CancelRestrackThread(struct ProcDumpConfiguration *self)
{
Trace("CancelRestrackThread: Enter [id=%d]", gettid());
int rc = 0;
pthread_t restrackThread = 0;
restrackThread = GetRestrackThread(self);
if(restrackThread != 0)
{
Trace("CancelRestrackThread: cancel restrack thread");
SetQuit(self, 1);
}
Trace("CancelRestrackThread: Exit [id=%d]", gettid());
return rc;
}
//--------------------------------------------------------------------
//
// WaitForAllMonitorsToTerminate - Wait for all monitors to terminate
//
//--------------------------------------------------------------------
int WaitForAllMonitorsToTerminate(struct ProcDumpConfiguration *self)
{
int rc = 0;
pthread_t restrackThread = 0;
// Wait for the other monitoring threads. We exclude restrack
// since we want that thread to exit last
for (int i = 0; i < self->nThreads; i++)
{
if(self->Threads[i].trigger != Restrack)
{
if ((rc = pthread_join(self->Threads[i].thread, NULL)) != 0)
{
Log(error, "An error occurred while joining threads\n");
exit(-1);
}
}
else
{
restrackThread = self->Threads[i].thread;
}
}
//
// If we have a restrack thread, cancel it and wait for it to exit
//
#ifdef __linux__
if(CancelRestrackThread(self) != 0)
{
if ((rc = pthread_join(restrackThread, NULL)) != 0)
{
Log(error, "An error occurred while joining restrack thread\n");
exit(-1);
}
}
#endif
return rc;
}
//--------------------------------------------------------------------
//
// WaitForSignalThreadToTerminate - Wait for signal handler thread to terminate
//
//--------------------------------------------------------------------
int WaitForSignalThreadToTerminate(struct ProcDumpConfiguration *self)
{
int rc = 0;
// Cancel the signal handling thread.
// We dont care about the return since the signal thread might already be gone.
pthread_cancel(sig_thread_id);
// Wait for signal handling thread to complete
if ((rc = pthread_join(sig_thread_id, NULL)) != 0) {
Log(error, "An error occurred while joining SignalThread.\n");
exit(-1);
}
return rc;
}
//--------------------------------------------------------------------
//
// IsQuit - A check on the underlying value of whether we should quit
//
//--------------------------------------------------------------------
bool IsQuit(struct ProcDumpConfiguration *self)
{
return (self->nQuit != 0);
}
//--------------------------------------------------------------------
//
// SetQuit - Sets the quit value and signals the event
//
//--------------------------------------------------------------------
int SetQuit(struct ProcDumpConfiguration *self, int quit)
{
self->nQuit = quit;
SetEvent(&self->evtQuit.event);
return self->nQuit;
}
//--------------------------------------------------------------------
//
// ContinueMonitoring - Should we keep monitoring or should we clean up our thread
//
//--------------------------------------------------------------------
bool ContinueMonitoring(struct ProcDumpConfiguration *self)
{
// Procdump exiting
if (self->nQuit == 1)
{
return false;
}
// Are we generating leak reports?
if (self->bLeakReportInProgress == true)
{
return true;
}
// Have we reached the dump limit?
if (self->NumberOfDumpsCollected >= self->NumberOfDumpsToCollect || self->NumberOfLeakReportsCollected >= self->NumberOfDumpsToCollect)
{
return false;
}
// Do we already know the process is terminated?
if (self->bTerminated)
{
return false;
}
// check if any process are running with PGID
if(self->bProcessGroup && kill(-1 * self->ProcessGroup, 0))
{
self->bTerminated = true;
return false;
}
// Let's check to make sure the process is still alive then
// note: kill([pid], 0) doesn't send a signal but does perform error checking
// therefore, if it returns 0, the process is still alive, -1 means it errored out
if (self->ProcessId != NO_PID && kill(self->ProcessId, 0))
{
self->bTerminated = true;
Log(warn, "Target process %d is no longer alive", self->ProcessId);
return false;
}
// Otherwise, keep going!
return true;
}
//--------------------------------------------------------------------
//
// BeginMonitoring - Sync up monitoring threads
//
//--------------------------------------------------------------------
bool BeginMonitoring(struct ProcDumpConfiguration *self)
{
return SetEvent(&(self->evtStartMonitoring.event));
}
extern long HZ; // clock ticks per second
//--------------------------------------------------------------------
//
// WaitThreads - Cancels the threads and waits for the specified threads
// using join.
//
//--------------------------------------------------------------------
void WaitThreads(std::vector<pthread_t>& threads)
{
for (auto& thread : threads)
{
//
// If user hit CTRL+C, cancel the thread.
//
if(g_sigint == true)
{
pthread_cancel(thread);
}
pthread_join(thread, NULL);
}
}
//--------------------------------------------------------------------
//
// CommitMonitoringThread - Thread monitoring for memory consumption
//
//--------------------------------------------------------------------
void *CommitMonitoringThread(void *thread_args /* struct ProcDumpConfiguration* */)
{
Trace("CommitMonitoringThread: Enter [id=%d]", gettid());
struct ProcDumpConfiguration *config = (struct ProcDumpConfiguration *)thread_args;
long pageSize_kb;
unsigned long memUsage = 0;
struct ProcessStat proc = {0};
int rc = 0;
auto_free struct CoreDumpWriter *writer = NULL;
auto_free char* dumpFileName = NULL;
std::vector<pthread_t> leakReportThreads;
writer = NewCoreDumpWriter(COMMIT, config);
pageSize_kb = sysconf(_SC_PAGESIZE) >> 10; // convert bytes to kilobytes (2^10)
if ((rc = WaitForQuitOrEvent(config, &config->evtStartMonitoring, INFINITE_WAIT)) == WAIT_OBJECT_0 + 1)
{
while ((rc = WaitForQuit(config, config->PollingInterval)) == WAIT_TIMEOUT)
{
if (GetProcessStat(config->ProcessId, &proc))
{
#ifdef __linux__
// Calc Commit
memUsage = (proc.rss * pageSize_kb) >> 10; // get Resident Set Size
memUsage += (proc.nswap * pageSize_kb) >> 10; // get Swap size
#elif __APPLE__
memUsage = proc.rss / (1024.0 * 1024.0); // get Resident Set Size
#endif
// Commit Trigger
if ((config->bMemoryTriggerBelowValue && (memUsage < config->MemoryThreshold[config->MemoryCurrentThreshold])) ||
(!config->bMemoryTriggerBelowValue && (memUsage >= config->MemoryThreshold[config->MemoryCurrentThreshold])))
{
Log(info, "Trigger: Commit usage:%ldMB on process ID: %d", memUsage, config->ProcessId);
if(config->bRestrackGenerateDump == true)
{
// Only generate core dump if user did not specify the "nodump" restrack option
dumpFileName = WriteCoreDump(writer);
if(dumpFileName == NULL)
{
SetQuit(config, 1);
}
}
//
// Check to see if restrack is specified, if so, save current resource usage to file.
//
#ifdef __linux__
if(config->bRestrackEnabled == true)
{
pthread_t id = WriteRestrackSnapshot(config, writer->Type);
if (id == 0)
{