forked from PanDAWMS/pilot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimerCommand.py
114 lines (100 loc) · 3.46 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
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
#!/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
import traceback
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
self.is_timeout = False
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():
self.is_timeout = True
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()
if not self.stdout:
self.stdout = ''
self.stdout += "Command time-out: %s s" % timeout
if self.process:
returncode = self.process.returncode
else:
returncode = 1
if returncode != 1 and 'Command time-out' in self.stdout:
returncode = 1
if returncode == None:
returncode = 0
return returncode, self.stdout
def runFunction(self, func, args, timeout=3600):
def target(func, args, retQ):
error = ''
try:
signal.signal(signal.SIGTERM, signal.SIG_DFL)
except:
error = error + '%s\n' % traceback.format_exc()
try:
ret= func(*args)
retQ.put(ret)
except:
retQ.put((-1, error + '%s\n' % traceback.format_exc()))
retQ = Queue()
process = Process(target=target, args=(func, args, retQ))
try:
process.start()
except:
timeout = 1
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.terminate()
process.join(2)
except:
if process.is_alive():
try:
# os.kill(int(process.pid), signal.SIGKILL)
process.terminate()
except:
pass
process.join(2)
return ret