-
Notifications
You must be signed in to change notification settings - Fork 92
/
delegator.py
322 lines (260 loc) · 8.72 KB
/
delegator.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import os
import subprocess
import shlex
import signal
import sys
import locale
import errno
from pexpect.popen_spawn import PopenSpawn
# Include `unicode` in STR_TYPES for Python 2.X
try:
STR_TYPES = (str, unicode)
except NameError:
STR_TYPES = (str,)
TIMEOUT = 30
def pid_exists(pid):
"""Check whether pid exists in the current process table."""
if pid == 0:
# According to "man 2 kill" PID 0 has a special meaning:
# it refers to <<every process in the process group of the
# calling process>> so we don't want to go any further.
# If we get here it means this UNIX platform *does* have
# a process with id 0.
return True
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH) therefore we should never get
# here. If we do let's be explicit in considering this
# an error.
raise err
else:
return True
class Command(object):
def __init__(self, cmd, timeout=TIMEOUT):
super(Command, self).__init__()
self.cmd = cmd
self.timeout = timeout
self.subprocess = None
self.blocking = None
self.was_run = False
self.__out = None
self.__err = None
def __repr__(self):
return "<Command {!r}>".format(self.cmd)
@property
def _popen_args(self):
return self.cmd
@property
def _default_popen_kwargs(self):
return {
"env": os.environ.copy(),
"stdin": subprocess.PIPE,
"stdout": subprocess.PIPE,
"stderr": subprocess.PIPE,
"shell": True,
"universal_newlines": True,
"bufsize": 0,
}
@property
def _default_pexpect_kwargs(self):
encoding = "utf-8"
if sys.platform == "win32":
default_encoding = locale.getdefaultlocale()[1]
if default_encoding is not None:
encoding = default_encoding
return {"env": os.environ.copy(), "encoding": encoding, "timeout": self.timeout}
@property
def _uses_subprocess(self):
return isinstance(self.subprocess, subprocess.Popen)
@property
def _uses_pexpect(self):
return isinstance(self.subprocess, PopenSpawn)
@property
def std_out(self):
return self.subprocess.stdout
@property
def ok(self):
return self.return_code == 0
@property
def _pexpect_out(self):
if self.subprocess.encoding:
result = ""
else:
result = b""
if self.subprocess.before:
result += self.subprocess.before
if self.subprocess.after:
result += self.subprocess.after
result += self.subprocess.read()
return result
@property
def out(self):
"""Std/out output (cached)"""
if self.__out is not None:
return self.__out
if self._uses_subprocess:
self.__out = self.std_out.read()
else:
self.__out = self._pexpect_out
return self.__out
@property
def std_err(self):
return self.subprocess.stderr
@property
def err(self):
"""Std/err output (cached)"""
if self.__err is not None:
return self.__err
if self._uses_subprocess:
self.__err = self.std_err.read()
return self.__err
else:
return self._pexpect_out
@property
def pid(self):
"""The process' PID."""
# Support for pexpect's functionality.
if hasattr(self.subprocess, "proc"):
return self.subprocess.proc.pid
# Standard subprocess method.
return self.subprocess.pid
@property
def is_alive(self):
"""Is the process alive?"""
return pid_exists(self.pid)
@property
def return_code(self):
# Support for pexpect's functionality.
if self._uses_pexpect:
return self.subprocess.exitstatus
# Standard subprocess method.
return self.subprocess.returncode
@property
def std_in(self):
return self.subprocess.stdin
def run(self, block=True, binary=False, cwd=None, env=None):
"""Runs the given command, with or without pexpect functionality enabled."""
self.blocking = block
# Use subprocess.
if self.blocking:
popen_kwargs = self._default_popen_kwargs.copy()
popen_kwargs["universal_newlines"] = not binary
if cwd:
popen_kwargs["cwd"] = cwd
if env:
popen_kwargs["env"].update(env)
s = subprocess.Popen(self._popen_args, **popen_kwargs)
# Otherwise, use pexpect.
else:
pexpect_kwargs = self._default_pexpect_kwargs.copy()
if binary:
pexpect_kwargs["encoding"] = None
if cwd:
pexpect_kwargs["cwd"] = cwd
if env:
pexpect_kwargs["env"].update(env)
# Enable Python subprocesses to work with expect functionality.
pexpect_kwargs["env"]["PYTHONUNBUFFERED"] = "1"
s = PopenSpawn(self._popen_args, **pexpect_kwargs)
self.subprocess = s
self.was_run = True
def expect(self, pattern, timeout=-1):
"""Waits on the given pattern to appear in std_out"""
if self.blocking:
raise RuntimeError("expect can only be used on non-blocking commands.")
self.subprocess.expect(pattern=pattern, timeout=timeout)
def send(self, s, end=os.linesep, signal=False):
"""Sends the given string or signal to std_in."""
if self.blocking:
raise RuntimeError("send can only be used on non-blocking commands.")
if not signal:
if self._uses_subprocess:
return self.subprocess.communicate(s + end)
else:
return self.subprocess.send(s + end)
else:
self.subprocess.send_signal(s)
def terminate(self):
self.subprocess.terminate()
def kill(self):
if self._uses_pexpect:
self.subprocess.kill(signal.SIGINT)
else:
self.subprocess.send_signal(signal.SIGINT)
def block(self):
"""Blocks until process is complete."""
if self._uses_subprocess:
# consume stdout and stderr
try:
stdout, stderr = self.subprocess.communicate()
self.__out = stdout
self.__err = stderr
except ValueError:
pass # Don't read from finished subprocesses.
else:
self.subprocess.wait()
def pipe(self, command, timeout=None, cwd=None):
"""Runs the current command and passes its output to the next
given process.
"""
if not timeout:
timeout = self.timeout
if not self.was_run:
self.run(block=False, cwd=cwd)
data = self.out
if timeout:
c = Command(command, timeout)
else:
c = Command(command)
c.run(block=False, cwd=cwd)
if data:
c.send(data)
c.subprocess.sendeof()
c.block()
return c
def _expand_args(command):
"""Parses command strings and returns a Popen-ready list."""
# Prepare arguments.
if isinstance(command, STR_TYPES):
if sys.version_info[0] == 2:
splitter = shlex.shlex(command.encode("utf-8"))
elif sys.version_info[0] == 3:
splitter = shlex.shlex(command)
else:
splitter = shlex.shlex(command.encode("utf-8"))
splitter.whitespace = "|"
splitter.whitespace_split = True
command = []
while True:
token = splitter.get_token()
if token:
command.append(token)
else:
break
command = list(map(shlex.split, command))
return command
def chain(command, timeout=TIMEOUT, cwd=None, env=None):
commands = _expand_args(command)
data = None
for command in commands:
c = run(command, block=False, timeout=timeout, cwd=cwd, env=env)
if data:
c.send(data)
c.subprocess.sendeof()
data = c.out
return c
def run(command, block=True, binary=False, timeout=TIMEOUT, cwd=None, env=None):
c = Command(command, timeout=timeout)
c.run(block=block, binary=binary, cwd=cwd, env=env)
if block:
c.block()
return c