-
Notifications
You must be signed in to change notification settings - Fork 1
/
TimerCommand.py
86 lines (77 loc) · 2.76 KB
/
TimerCommand.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
#!/usr/bin/env python
# Copyright European Organization for Nuclear Research (CERN)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Wen Guan, <[email protected]>, 2014
import os
import signal
import time
from Queue import Empty, Full
import subprocess, threading
from multiprocessing import Process, Queue
class TimerCommand(object):
def __init__(self, cmd=None):
self.cmd = cmd
self.process = None
self.stdout = None
self.stderr = None
def run(self, timeout=3600):
def target():
# print 'Thread started'
self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
self.stdout, self.stderr = self.process.communicate()
# print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
if self.stdout:
self.stdout += "Command Timeout(%s seconds)." % timeout
else:
self.stdout = "Command Timeout(%s seconds)." % timeout
try:
# print 'TimeOut. Terminating process'
self.process.terminate()
thread.join(2)
if thread.is_alive():
os.kill(int(self.process.pid), signal.SIGKILL)
thread.join(2)
except:
if thread.is_alive():
try:
os.kill(int(self.process.pid), signal.SIGKILL)
except:
pass
thread.join()
return self.process.returncode, self.stdout
def runFunction(self, func, args, timeout=3600):
def target(func, args, retQ):
ret= func(*args)
retQ.put(ret)
retQ = Queue()
process = Process(target=target, args=(func, args, retQ))
process.start()
try:
ret = retQ.get(block=True, timeout=timeout)
except Empty:
ret = (-1, "function timeout, killed")
try:
if process.is_alive():
process.terminate()
process.join(2)
if process.is_alive():
os.kill(int(process.pid), signal.SIGKILL)
process.join(2)
except:
if process.is_alive():
try:
os.kill(int(process.pid), signal.SIGKILL)
except:
pass
process.join(2)
return ret