-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtimed_run.py
More file actions
243 lines (203 loc) · 7 KB
/
timed_run.py
File metadata and controls
243 lines (203 loc) · 7 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
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""Run a subprocess with timeout"""
from __future__ import annotations
import argparse
import enum
import logging
import os
import platform
import signal
import sys
import time
from contextlib import contextmanager
from pathlib import Path
from subprocess import PIPE, Popen, TimeoutExpired
from typing import TYPE_CHECKING, BinaryIO
from ffpuppet import SanitizerOptions
if TYPE_CHECKING:
from collections.abc import Callable, Generator
LOG = logging.getLogger(__name__)
ERROR_CODE = 77
class BaseParser(argparse.ArgumentParser):
"""Argument parser with `timeout` and `cmd_with_args`"""
def __init__(self, *args, **kwds) -> None: # type: ignore
super().__init__(*args, **kwds)
self.add_argument(
"-t",
"--timeout",
default=120,
dest="timeout",
type=int,
help="Set the timeout. Defaults to '%(default)s' seconds.",
)
self.add_argument("cmd_with_flags", nargs=argparse.REMAINDER)
class ExitStatus(enum.IntEnum):
"""Enum for recording exit status"""
NORMAL = 1
ABNORMAL = 2
CRASH = 3
TIMEOUT = 4
class RunData:
"""Class for storing run data"""
def __init__(
self,
pid: int,
status: ExitStatus,
return_code: int | None,
message: str,
elapsed: float,
out: bytes | str,
err: bytes | str,
):
self.pid = pid
self.status = status
self.return_code = return_code
self.message = message
self.elapsed = elapsed
self.out = out
self.err = err
def _configure_sanitizers(orig_env: dict[str, str]) -> dict[str, str]:
"""Copy environment and update default values in *SAN_OPTIONS entries.
Args:
orig_env: Current environment.
Returns:
Environment with *SAN_OPTIONS defaults set.
"""
env: dict[str, str] = dict(orig_env)
# https://github.com/google/sanitizers/wiki/SanitizerCommonFlags
common_flags = [
("abort_on_error", "false"),
("allocator_may_return_null", "true"),
("disable_coredump", "true"),
("exitcode", str(ERROR_CODE)), # use unique exitcode
("handle_abort", "true"), # if true, abort_on_error=false to prevent hangs
("handle_sigbus", "true"), # set to be safe
("handle_sigfpe", "true"), # set to be safe
("handle_sigill", "true"), # set to be safe
("symbolize", "true"),
]
sanitizer_env_variables = (
"ASAN_OPTIONS",
"UBSAN_OPTIONS",
"LSAN_OPTIONS",
"TSAN_OPTIONS",
)
for sanitizer in sanitizer_env_variables:
config = SanitizerOptions(env.get(sanitizer))
for flag in common_flags:
config.add(*flag)
env[sanitizer] = str(config)
return env
def _get_signal_name(signum: int, default: str = "Unknown signal") -> str:
"""Stringify a signal number
Args:
signum: Signal number to lookup
default: Default to return if signal isn't recognized.
Returns:
String description of the signal.
"""
if sys.version_info[:2] >= (3, 8) and platform.system() != "Windows":
return signal.strsignal(signum) or default
for member in dir(signal):
if (
member.startswith("SIG")
and not member.startswith("SIG_")
and getattr(signal, member) == signum
):
return member
return default
@contextmanager
def file_or_pipe(log_prefix: str | None, name: str) -> Generator[BinaryIO | int]:
"""Context manager for an optional file handle or PIPE"""
if log_prefix is None:
yield PIPE
else:
with open(f"{log_prefix}-{name}.txt", "wb") as f:
yield f
def timed_run(
cmd_with_args: list[str],
timeout: int,
log_prefix: str | None = None,
env: dict[str, str] | None = None,
inp: str = "",
preexec_fn: Callable[[], None] | None = None,
) -> RunData:
"""If log_prefix is None, uses pipes instead of files for all output.
Args:
cmd_with_args: List of command and parameters to be executed
timeout: Timeout for the command to be run, in seconds
log_prefix: Prefix string of the log files
env: Environment for the command to be executed in
inp: stdin to be passed to the command
preexec_fn: called in child process after fork, prior to exec
Raises:
OSError: Raises if timed_run is attempted to be used with gdb
Returns:
A RunData instance containing run information.
"""
if len(cmd_with_args) == 0:
raise ValueError("Command not specified!")
prog = Path(cmd_with_args[0]).resolve()
if prog.stem == "gdb":
raise OSError(
"Do not use this with gdb, because kill in timed_run will "
"kill gdb but leave the process within gdb still running"
)
status = None
env = _configure_sanitizers(os.environ.copy() if env is None else env)
with (
file_or_pipe(log_prefix, "out") as child_stdout,
file_or_pipe(log_prefix, "err") as child_stderr,
):
start_time = time.time()
# pylint: disable=consider-using-with,subprocess-popen-preexec-fn
LOG.info(f"Running: {' '.join(cmd_with_args)}")
child = Popen(
cmd_with_args,
env=env,
stdin=PIPE,
stderr=child_stderr,
stdout=child_stdout,
preexec_fn=preexec_fn,
)
try:
stdout, stderr = child.communicate(
input=inp.encode("utf-8"),
timeout=timeout,
)
except TimeoutExpired:
child.kill()
stdout, stderr = child.communicate()
status = ExitStatus.TIMEOUT
except Exception as exc: # pylint: disable=broad-except
LOG.error(exc)
sys.exit(2)
elapsed_time = time.time() - start_time
if status == ExitStatus.TIMEOUT:
message = "TIMED OUT"
elif child.returncode == 0:
message = "NORMAL"
status = ExitStatus.NORMAL
elif child.returncode != ERROR_CODE and 0 < child.returncode < 0x80000000:
message = f"ABNORMAL exit code {child.returncode}"
status = ExitStatus.ABNORMAL
else:
# The program was terminated by a signal or by the sanitizer (ERROR_CODE)
# Mac/Linux only!
if child.returncode < 0:
signum = abs(child.returncode)
message = f"CRASHED with {_get_signal_name(signum)}"
else:
message = "CRASHED"
status = ExitStatus.CRASH
return RunData(
child.pid,
status,
child.returncode if status != ExitStatus.TIMEOUT else None,
message,
elapsed_time,
stdout if log_prefix is None else f"{log_prefix}-out.txt",
stderr if log_prefix is None else f"{log_prefix}-err.txt",
)