-
-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathinterrupt.py
More file actions
200 lines (155 loc) · 6.86 KB
/
interrupt.py
File metadata and controls
200 lines (155 loc) · 6.86 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
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
from traceback import format_exc as traceback_format_exc
from commoncode.system import on_windows
"""
This module povides an interruptible() function to run a callable and stop it if
it does not return after a timeout for both Windows (using threads) and
POSIX/Linux/macOS (using signals).
interruptible() calls the `func` function with `args` and `kwargs` arguments and
return a tuple of (error, value). `func` is invoked through an OS-specific
wrapper and will be interrupted if it does not return within `timeout` seconds.
- `func` returned `value` MUST BE pickable.
- `timeout` is an int of seconds defaults to DEFAULT_TIMEOUT.
- `args` and `kwargs` are passed to `func` as *args and **kwarg.
In the returned tuple of (`error`, `value`) we can have these two cases:
- if the function did run correctly and completed within `timeout` seconds then
`error` is None and `value` contains the returned value.
- if the function raised en exception or did not complete within `timeout`
seconds then `error` is a verbose error message that contains a full
traceback and `value` is None.
"""
import threading
class TimeoutError(Exception): # NOQA
pass
DEFAULT_TIMEOUT = 120 # seconds
TIMEOUT_MSG = 'ERROR: Processing interrupted: timeout after %(timeout)d seconds.'
ERROR_MSG = 'ERROR: Unknown error:\n'
NO_ERROR = None
NO_VALUE = None
if not on_windows:
"""
Some code based in part and inspired from the RobotFramework and
heavily modified.
Copyright 2008-2015 Nokia Networks
Copyright 2016- Robot Framework Foundation
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
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License.
"""
from signal import ITIMER_REAL
from signal import SIGALRM
from signal import setitimer
from signal import signal as create_signal
def interruptible(func, args=None, kwargs=None, timeout=DEFAULT_TIMEOUT):
"""
POSIX, signals-based interruptible runner.
Falls back to non-interruptible execution if not in main thread.
"""
# Signals only work in the main thread
if threading.current_thread() is not threading.main_thread():
return NO_ERROR, func(*(args or ()), **(kwargs or {}))
def handler(signum, frame):
raise TimeoutError
try:
create_signal(SIGALRM, handler)
setitimer(ITIMER_REAL, timeout)
return NO_ERROR, func(*(args or ()), **(kwargs or {}))
except TimeoutError:
return TIMEOUT_MSG % locals(), NO_VALUE
except Exception:
return ERROR_MSG + traceback_format_exc(), NO_VALUE
finally:
setitimer(ITIMER_REAL, 0)
elif on_windows:
"""
Run a function in an interruptible thread with a timeout.
Based on an idea of dano "Dan O'Reilly"
http://stackoverflow.com/users/2073595/dano
But no code has been reused from this post.
"""
from ctypes import c_long
from ctypes import py_object
from ctypes import pythonapi
from multiprocessing import TimeoutError as MpTimeoutError
from queue import Empty as Queue_Empty
from queue import Queue
from _thread import start_new_thread
def interruptible(func, args=None, kwargs=None, timeout=DEFAULT_TIMEOUT):
"""
Windows, threads-based interruptible runner. It can work also on
POSIX, but is not reliable and works only if everything is pickable.
"""
# We run `func` in a thread and block on a queue until timeout
results = Queue()
def runner():
"""
Run the func and send results back in a queue as a tuple of
(`error`, `value`)
"""
try:
_res = func(*(args or ()), **(kwargs or {}))
results.put((NO_ERROR, _res,))
except Exception:
results.put((ERROR_MSG + traceback_format_exc(), NO_VALUE,))
tid = start_new_thread(runner, ())
try:
# wait for the queue results up to timeout
err_res = results.get(timeout=timeout)
if not err_res:
return ERROR_MSG, NO_VALUE
return err_res
except (Queue_Empty, MpTimeoutError):
return TIMEOUT_MSG % locals(), NO_VALUE
except Exception:
return ERROR_MSG + traceback_format_exc(), NO_VALUE
finally:
try:
async_raise(tid, Exception)
except (SystemExit, ValueError):
pass
def async_raise(tid, exctype=Exception):
"""
Raise an Exception in the Thread with id `tid`. Perform cleanup if
needed.
Based on Killable Threads By Tomer Filiba
from http://tomerfiliba.com/recipes/Thread2/
license: public domain.
"""
assert isinstance(tid, int), 'Invalid thread id: must an integer'
tid = c_long(tid)
exception = py_object(Exception)
res = pythonapi.PyThreadState_SetAsyncExc(tid, exception)
if res == 0:
raise ValueError('Invalid thread id.')
elif res != 1:
# if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect
pythonapi.PyThreadState_SetAsyncExc(tid, 0)
raise SystemError('PyThreadState_SetAsyncExc failed.')
def fake_interruptible(func, args=None, kwargs=None, timeout=DEFAULT_TIMEOUT):
"""
Fake interruptible that is not interruptible and has no timeout and is using
no threads and no signals This implementation is used for debugging. This
ignores the timeout and just runs the function as-is.
"""
try:
return NO_ERROR, func(*(args or ()), **(kwargs or {}))
except Exception:
return ERROR_MSG + traceback_format_exc(), NO_VALUE