blob: f56873fbeadef61e8b763f4ab4319323434ccb49 [file] [log] [blame]
Guido van Rossum0016e1d2013-10-30 14:56:49 -07001import collections
2import subprocess
Victor Stinner978a9af2015-01-29 17:50:58 +01003import sys
4import warnings
Guido van Rossum0016e1d2013-10-30 14:56:49 -07005
Victor Stinner47cd10d2015-01-30 00:05:19 +01006from . import futures
Guido van Rossum0016e1d2013-10-30 14:56:49 -07007from . import protocols
Guido van Rossum0016e1d2013-10-30 14:56:49 -07008from . import transports
Victor Stinnerf951d282014-06-29 00:46:45 +02009from .coroutines import coroutine
Victor Stinneracdb7822014-07-14 18:33:40 +020010from .log import logger
Guido van Rossum0016e1d2013-10-30 14:56:49 -070011
12
Guido van Rossum0016e1d2013-10-30 14:56:49 -070013class BaseSubprocessTransport(transports.SubprocessTransport):
14
15 def __init__(self, loop, protocol, args, shell,
16 stdin, stdout, stderr, bufsize,
Victor Stinner47cd10d2015-01-30 00:05:19 +010017 waiter=None, extra=None, **kwargs):
Guido van Rossum0016e1d2013-10-30 14:56:49 -070018 super().__init__(extra)
Victor Stinner978a9af2015-01-29 17:50:58 +010019 self._closed = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -070020 self._protocol = protocol
21 self._loop = loop
Victor Stinner47cd10d2015-01-30 00:05:19 +010022 self._proc = None
Victor Stinneracdb7822014-07-14 18:33:40 +020023 self._pid = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010024 self._returncode = None
25 self._exit_waiters = []
26 self._pending_calls = collections.deque()
Guido van Rossum0016e1d2013-10-30 14:56:49 -070027 self._pipes = {}
Victor Stinner47cd10d2015-01-30 00:05:19 +010028 self._finished = False
29
Guido van Rossum0016e1d2013-10-30 14:56:49 -070030 if stdin == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010031 self._pipes[0] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070032 if stdout == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010033 self._pipes[1] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070034 if stderr == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010035 self._pipes[2] = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010036
37 # Create the child process: set the _proc attribute
Guido van Rossum0016e1d2013-10-30 14:56:49 -070038 self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
39 stderr=stderr, bufsize=bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +020040 self._pid = self._proc.pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -070041 self._extra['subprocess'] = self._proc
Victor Stinner47cd10d2015-01-30 00:05:19 +010042
Victor Stinneracdb7822014-07-14 18:33:40 +020043 if self._loop.get_debug():
44 if isinstance(args, (bytes, str)):
45 program = args
46 else:
47 program = args[0]
48 logger.debug('process %r created: pid %s',
49 program, self._pid)
50
Victor Stinner47cd10d2015-01-30 00:05:19 +010051 self._loop.create_task(self._connect_pipes(waiter))
52
Victor Stinneracdb7822014-07-14 18:33:40 +020053 def __repr__(self):
Victor Stinner978a9af2015-01-29 17:50:58 +010054 info = [self.__class__.__name__]
55 if self._closed:
56 info.append('closed')
57 info.append('pid=%s' % self._pid)
Victor Stinneracdb7822014-07-14 18:33:40 +020058 if self._returncode is not None:
59 info.append('returncode=%s' % self._returncode)
Victor Stinner4e82fb92015-02-17 22:50:33 +010060 else:
61 info.append('running')
Victor Stinneracdb7822014-07-14 18:33:40 +020062
63 stdin = self._pipes.get(0)
64 if stdin is not None:
65 info.append('stdin=%s' % stdin.pipe)
66
67 stdout = self._pipes.get(1)
68 stderr = self._pipes.get(2)
69 if stdout is not None and stderr is stdout:
70 info.append('stdout=stderr=%s' % stdout.pipe)
71 else:
72 if stdout is not None:
73 info.append('stdout=%s' % stdout.pipe)
74 if stderr is not None:
75 info.append('stderr=%s' % stderr.pipe)
76
77 return '<%s>' % ' '.join(info)
Guido van Rossum0016e1d2013-10-30 14:56:49 -070078
79 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
80 raise NotImplementedError
81
82 def _make_write_subprocess_pipe_proto(self, fd):
83 raise NotImplementedError
84
85 def _make_read_subprocess_pipe_proto(self, fd):
86 raise NotImplementedError
87
88 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +010089 if self._closed:
90 return
Victor Stinner978a9af2015-01-29 17:50:58 +010091 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +010092
Guido van Rossum0016e1d2013-10-30 14:56:49 -070093 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +010094 if proto is None:
95 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -070096 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +010097
Victor Stinner8e368122015-02-10 14:49:32 +010098 if (self._proc is not None
99 # the child process finished?
100 and self._returncode is None
101 # the child process finished but the transport was not notified yet?
102 and self._proc.poll() is None
103 ):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100104 if self._loop.get_debug():
105 logger.warning('Close running child process: kill %r', self)
106
107 try:
108 self._proc.kill()
109 except ProcessLookupError:
110 pass
111
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100112 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700113
Victor Stinner978a9af2015-01-29 17:50:58 +0100114 # On Python 3.3 and older, objects with a destructor part of a reference
115 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
116 # to the PEP 442.
117 if sys.version_info >= (3, 4):
118 def __del__(self):
119 if not self._closed:
120 warnings.warn("unclosed transport %r" % self, ResourceWarning)
121 self.close()
122
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700123 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200124 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700125
126 def get_returncode(self):
127 return self._returncode
128
129 def get_pipe_transport(self, fd):
130 if fd in self._pipes:
131 return self._pipes[fd].pipe
132 else:
133 return None
134
Victor Stinner47cd10d2015-01-30 00:05:19 +0100135 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100136 if self._proc is None:
137 raise ProcessLookupError()
138
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700139 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100140 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700141 self._proc.send_signal(signal)
142
143 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100144 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700145 self._proc.terminate()
146
147 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100148 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700149 self._proc.kill()
150
Victor Stinnerf951d282014-06-29 00:46:45 +0200151 @coroutine
Victor Stinner47cd10d2015-01-30 00:05:19 +0100152 def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100153 try:
154 proc = self._proc
155 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100156
Victor Stinnerf651a602015-01-14 02:10:33 +0100157 if proc.stdin is not None:
158 _, pipe = yield from loop.connect_write_pipe(
159 lambda: WriteSubprocessPipeProto(self, 0),
160 proc.stdin)
161 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100162
Victor Stinnerf651a602015-01-14 02:10:33 +0100163 if proc.stdout is not None:
164 _, pipe = yield from loop.connect_read_pipe(
165 lambda: ReadSubprocessPipeProto(self, 1),
166 proc.stdout)
167 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100168
Victor Stinnerf651a602015-01-14 02:10:33 +0100169 if proc.stderr is not None:
170 _, pipe = yield from loop.connect_read_pipe(
171 lambda: ReadSubprocessPipeProto(self, 2),
172 proc.stderr)
173 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800174
Victor Stinnerf651a602015-01-14 02:10:33 +0100175 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800176
Victor Stinner47cd10d2015-01-30 00:05:19 +0100177 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100178 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100179 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100180 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100181 except Exception as exc:
182 if waiter is not None and not waiter.cancelled():
183 waiter.set_exception(exc)
184 else:
185 if waiter is not None and not waiter.cancelled():
186 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700187
188 def _call(self, cb, *data):
189 if self._pending_calls is not None:
190 self._pending_calls.append((cb, data))
191 else:
192 self._loop.call_soon(cb, *data)
193
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700194 def _pipe_connection_lost(self, fd, exc):
195 self._call(self._protocol.pipe_connection_lost, fd, exc)
196 self._try_finish()
197
198 def _pipe_data_received(self, fd, data):
199 self._call(self._protocol.pipe_data_received, fd, data)
200
201 def _process_exited(self, returncode):
202 assert returncode is not None, returncode
203 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200204 if self._loop.get_debug():
205 logger.info('%r exited with return code %r',
206 self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700207 self._returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700208 self._call(self._protocol.process_exited)
209 self._try_finish()
210
Victor Stinner47cd10d2015-01-30 00:05:19 +0100211 # wake up futures waiting for wait()
212 for waiter in self._exit_waiters:
213 if not waiter.cancelled():
214 waiter.set_result(returncode)
215 self._exit_waiters = None
216
Victor Stinner1241ecc2015-01-30 00:16:14 +0100217 def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100218 """Wait until the process exit and return the process return code.
219
220 This method is a coroutine."""
221 if self._returncode is not None:
222 return self._returncode
223
224 waiter = futures.Future(loop=self._loop)
225 self._exit_waiters.append(waiter)
226 return (yield from waiter)
227
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700228 def _try_finish(self):
229 assert not self._finished
230 if self._returncode is None:
231 return
232 if all(p is not None and p.disconnected
233 for p in self._pipes.values()):
234 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100235 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700236
237 def _call_connection_lost(self, exc):
238 try:
239 self._protocol.connection_lost(exc)
240 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100241 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700242 self._proc = None
243 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700244
245
246class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700247
248 def __init__(self, proc, fd):
249 self.proc = proc
250 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800251 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700252 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700253
254 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700255 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700256
Victor Stinneracdb7822014-07-14 18:33:40 +0200257 def __repr__(self):
258 return ('<%s fd=%s pipe=%r>'
259 % (self.__class__.__name__, self.fd, self.pipe))
260
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700261 def connection_lost(self, exc):
262 self.disconnected = True
263 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100264 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700265
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800266 def pause_writing(self):
267 self.proc._protocol.pause_writing()
268
269 def resume_writing(self):
270 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700271
272
273class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
274 protocols.Protocol):
275
276 def data_received(self, data):
277 self.proc._pipe_data_received(self.fd, data)