-
Notifications
You must be signed in to change notification settings - Fork 0
/
procmon.py
298 lines (253 loc) · 10.1 KB
/
procmon.py
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
import threading
import psutil
import time
import os
import shutil
import sys
from decider import *
from libs_procmon import *
import configparser
#XXX how to interrupt this?
class Timer(threading.Thread):
timeout = threading.Event()
time = None
def __init__(self, time):
self.time = time
super().__init__()
def run(self):
#XXX apparently timers are natively implemented in python, you should try that
time.sleep(self.time)
self.timeout.set()
sys.exit(0)
class Listener(threading.Thread):
pipename="/tmp/monitor_pipe0"
target_status = {'alive': None, 'pid': None}
pipe_event=threading.Event()
death_signal=threading.Event()
errorState=0
readInterval=0.5 #seconds , inteval to check pipe
def __init__(self, pipename=None):
if pipename != None:
self.pipename = pipename
super().__init__()
def run(self):
try:
os.mkfifo(self.pipename)
except:
debug_msg("pipe was not created")
try:
pipe=os.open(self.pipename, os.O_RDONLY | os.O_NONBLOCK)
debug_msg("Listener opened pipe")
except:
die("unable to open pipe")
while not self.death_signal.is_set():
try:
buf = os.read(pipe, 100)
except:
debug_msg("pipe read error")
raise
if len(buf) != 0:
self.parse_message(buf.decode('ascii'))
time.sleep(self.readInterval)
try:
os.close(pipe)
os.unlink(self.pipename)
except:
pass
debug_msg("Listener exiting")
def parse_message(self, buf):
lines=buf.splitlines()
for line in lines:
msg=line.split(":")
if msg[0] == 'PID':
self.target_status['alive']=True
self.target_status['pid']=int(msg[1])
self.pipe_event.set()
def get_pid(self):
return self.target_status['pid']
def is_target_alive():
return self.target_status['alive']
def destroy_pipe(self):
#try to close listener in the cool way
self.death_signal.set()
try:
os.close(self.pipename)
os.unlink(self.pipename) #XXX do we have to close the thread?
except:
pass
class Process(object):
proc = None
name = None
args = None
def __init__(self, exename, args):
self.name = exename
self.args = args
#pid has changed, class must be reinitialized with actual process data
def set_pid(self, newpid):
try:
self.proc=psutil.Process(newpid)
#keep original name and args, we don't know what the target might execute, we just want to monitor the right pid
#self.name=self.proc.cmdline()[0]
#self.args=" ".join(self.proc.cmdline()[1:])
except psutil.NoSuchProcess:
debug_msg("trying to switch to a non existent pid")
return False
return True
#we should use more this kind of stuff
def get_pid(self):
return self.proc.pid
def is_running(self):
return self.proc.is_running()
class ProcMon(object):
debugFlag=True
save_arg=False #will affect decision to save or not long running testcases
processTimeout=20
listener=None
process=None
settingsFile = 'settings.ini'
timer = None
searchInterval = 0.5
searchTimeout = 10
def __init__(self, exeFile, exeArgs):
self.exeFile = exeFile
self.exeArgs = exeArgs
self.process = Process(self.exeFile, self.exeArgs)
self.pipename="/tmp/monitor_pipe0"
self.savedir="saved"
self.loadSettings()
self.timer = Timer(self.processTimeout)
self.listener = Listener(self.pipename)
def loadSettings(self):
parser = configparser.SafeConfigParser()
parser.read(self.settingsFile)
try:
if parser.has_option('procmon', 'debug'):
self.debugFlag = parser.getboolean('procmon', 'debug')
if parser.has_option('procmon', 'process_timeout'):
self.processTimeout = parser.getint('procmon', 'process_timeout')
if parser.has_option('procmon', 'pipename'):
self.pipename = parser.get('procmon', 'pipename')
if parser.has_option('procmon', 'savedir'):
self.savedir = parser.get('procmon', 'savedir')
except configparser.NoSectionError as err:
die("settings: " + err)
#search the file in the name, then search other args in the cmdline
def find_proc(self):
pids=[]
for proc in psutil.process_iter():
if any(self.exeFile in s for s in proc.cmdline()): #and not any(sys.argv[0] in s for s in proc.cmdline())
if self.exeFile.find(proc.name()) >= 0:
if any(self.exeArgs in s for s in proc.cmdline()):
debug_msg("process pid is "+str(proc.pid))
pids.append(proc.pid)
if len(pids) == 0:
return None
return pids
#actually populate class finding the pid,
#calls repeatedly do_find_proc which uses psutil to determine the pid, given name of executable and args
#AND see if we have a pid from the pipe (preferred way)
#we use a timer to avoid blocking
def get_proc(self):
searchTimer = Timer(self.searchTimeout)
while not searchTimer.timeout.is_set():
if self.listener.get_pid() != None:
self.process.set_pid(self.listener.get_pid())
self.listener.pipe_event.clear()
break
pids = self.find_proc()
#actually better catch this, even if still early
if pids != None:
if len(pids) > 1:
debug_msg("found %d process, will monitor %d" % (len(pids), pids[0] ))
self.process.set_pid(pids[0])
if not self.process.is_running():
debug_msg('process dead before starting timer')
return
break
if pids == None:
debug_msg("process not found, keep searching")
time.sleep(self.searchInterval)
def update_pid(self):
if self.process.get_pid() != self.listener.get_pid():
debug_msg("target PID changed to %d, updating" % newPid)
#XXX there are no locks on the pid, can change at any time
if self.process.set_pid(self.listener.get_pid()):
self.pipe_event.clear()
def cleanup_and_exit(self, retvalue):
self.listener.destroy_pipe()
debug_msg("exiting")
#self.timer.join()
#this should be called by main thread, will exit from whole process
sys.exit(retvalue)
#immediately kill and exit
def kill_proc_and_exit(self):
#XXX
self.process.proc.kill()
self.cleanup_and_exit(0)
def start(self):
debug_msg("starting search for process %s with args \"%s\"" % (self.exeFile, self.exeArgs))
self.listener.start()
self.get_proc()
debug_msg("pid found: %d ; starting timer thread" % self.process.get_pid())
self.timer.start()
self.wait_for_proc()
def check_dir(self):
if not os.path.exists(self.savedir):
debug_msg("saved dir not found, creating")
try:
os.mkdir(self.savedir)
except PermissionError:
debug_msg("saved dir creation failed, dying")
self.cleanup_and_exit(-1)
def save_testcase(self):
self.check_dir()
casefile=self.exeArgs
strtime=time.strftime('%d-%m-%y_%H%M')
if os.path.isdir(casefile):
savefile="fuzzedcases-"+strtime
debug_msg('passed whole testcases folder, copying everything ')
shutil.copytree(casefile, self.savedir+'/'+savefile)
else:
savefile="fuzzedcase-"+strtime
debug_msg('Saving testcase to ' + savefile)
shutil.copy(casefile, self.savedir+'/'+savefile)
#wait until process is not busy (for definition of busy, see decider.py)
def wait_for_proc(self):
interval=1.0 #in second
nslices=5
decider = Decider(self.save_arg)
#XXX get the internal process obj or proxying calls? maybe better the latter
p=self.process.proc
timecounter = 0
while not self.timer.timeout.is_set():
if self.listener.pipe_event.is_set():
#XXX this will become a huge mess if we create new messages types
self.update_pid()
#XXX this shouldn't be needed
p = self.process.proc
debug_msg("watching now PID %d" % self.process.get_pid())
try:
cpu=[]
for i in range(0,nslices):
cpu.append(p.get_cpu_percent())
time.sleep(interval/nslices)
mean = sum(cpu)/len(cpu)
sigma2 = getSigma2(cpu, mean)
timecounter += 1
debug_msg("avg process CPU usage: %d" % mean)
debug_msg("variance is: %d" % sigma2)
decider.update(mean, sigma2, timecounter)
if decider.isQuorumReached():
debug_msg("Quorum reached, killing process")
self.kill_proc_and_exit()
if self.save_arg and decider.isSaveQuorumReached():
debug_msg("Interesting file found, saving testcase")
self.save_testcase()
except psutil.NoSuchProcess:
debug_msg("Checker lost the process")
self.cleanup_and_exit(0)
debug_msg("timeout reached, killing the process and dying")
if self.save_arg:
debug_msg("Interesting file found, saving testcase")
self.save_testcase()
self.kill_proc_and_exit()