blob: c1477b8248db4ea87589658fdcf4c413582d408a [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')
Victor Stinner7a82afe2015-03-10 16:32:29 +010057 if self._pid is not None:
58 info.append('pid=%s' % self._pid)
Victor Stinneracdb7822014-07-14 18:33:40 +020059 if self._returncode is not None:
60 info.append('returncode=%s' % self._returncode)
Victor Stinner7a82afe2015-03-10 16:32:29 +010061 elif self._pid is not None:
Victor Stinner4e82fb92015-02-17 22:50:33 +010062 info.append('running')
Victor Stinner7a82afe2015-03-10 16:32:29 +010063 else:
64 info.append('not started')
Victor Stinneracdb7822014-07-14 18:33:40 +020065
66 stdin = self._pipes.get(0)
67 if stdin is not None:
68 info.append('stdin=%s' % stdin.pipe)
69
70 stdout = self._pipes.get(1)
71 stderr = self._pipes.get(2)
72 if stdout is not None and stderr is stdout:
73 info.append('stdout=stderr=%s' % stdout.pipe)
74 else:
75 if stdout is not None:
76 info.append('stdout=%s' % stdout.pipe)
77 if stderr is not None:
78 info.append('stderr=%s' % stderr.pipe)
79
80 return '<%s>' % ' '.join(info)
Guido van Rossum0016e1d2013-10-30 14:56:49 -070081
82 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
83 raise NotImplementedError
84
Guido van Rossum0016e1d2013-10-30 14:56:49 -070085 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +010086 if self._closed:
87 return
Victor Stinner978a9af2015-01-29 17:50:58 +010088 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +010089
Guido van Rossum0016e1d2013-10-30 14:56:49 -070090 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +010091 if proto is None:
92 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -070093 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +010094
Victor Stinner8e368122015-02-10 14:49:32 +010095 if (self._proc is not None
96 # the child process finished?
97 and self._returncode is None
98 # the child process finished but the transport was not notified yet?
99 and self._proc.poll() is None
100 ):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100101 if self._loop.get_debug():
102 logger.warning('Close running child process: kill %r', self)
103
104 try:
105 self._proc.kill()
106 except ProcessLookupError:
107 pass
108
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100109 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700110
Victor Stinner978a9af2015-01-29 17:50:58 +0100111 # On Python 3.3 and older, objects with a destructor part of a reference
112 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
113 # to the PEP 442.
114 if sys.version_info >= (3, 4):
115 def __del__(self):
116 if not self._closed:
117 warnings.warn("unclosed transport %r" % self, ResourceWarning)
118 self.close()
119
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700120 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200121 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700122
123 def get_returncode(self):
124 return self._returncode
125
126 def get_pipe_transport(self, fd):
127 if fd in self._pipes:
128 return self._pipes[fd].pipe
129 else:
130 return None
131
Victor Stinner47cd10d2015-01-30 00:05:19 +0100132 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100133 if self._proc is None:
134 raise ProcessLookupError()
135
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700136 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100137 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700138 self._proc.send_signal(signal)
139
140 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100141 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700142 self._proc.terminate()
143
144 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100145 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700146 self._proc.kill()
147
Victor Stinnerf951d282014-06-29 00:46:45 +0200148 @coroutine
Victor Stinner47cd10d2015-01-30 00:05:19 +0100149 def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100150 try:
151 proc = self._proc
152 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100153
Victor Stinnerf651a602015-01-14 02:10:33 +0100154 if proc.stdin is not None:
155 _, pipe = yield from loop.connect_write_pipe(
156 lambda: WriteSubprocessPipeProto(self, 0),
157 proc.stdin)
158 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100159
Victor Stinnerf651a602015-01-14 02:10:33 +0100160 if proc.stdout is not None:
161 _, pipe = yield from loop.connect_read_pipe(
162 lambda: ReadSubprocessPipeProto(self, 1),
163 proc.stdout)
164 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100165
Victor Stinnerf651a602015-01-14 02:10:33 +0100166 if proc.stderr is not None:
167 _, pipe = yield from loop.connect_read_pipe(
168 lambda: ReadSubprocessPipeProto(self, 2),
169 proc.stderr)
170 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800171
Victor Stinnerf651a602015-01-14 02:10:33 +0100172 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800173
Victor Stinner47cd10d2015-01-30 00:05:19 +0100174 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100175 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100176 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100177 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100178 except Exception as exc:
179 if waiter is not None and not waiter.cancelled():
180 waiter.set_exception(exc)
181 else:
182 if waiter is not None and not waiter.cancelled():
183 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700184
185 def _call(self, cb, *data):
186 if self._pending_calls is not None:
187 self._pending_calls.append((cb, data))
188 else:
189 self._loop.call_soon(cb, *data)
190
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700191 def _pipe_connection_lost(self, fd, exc):
192 self._call(self._protocol.pipe_connection_lost, fd, exc)
193 self._try_finish()
194
195 def _pipe_data_received(self, fd, data):
196 self._call(self._protocol.pipe_data_received, fd, data)
197
198 def _process_exited(self, returncode):
199 assert returncode is not None, returncode
200 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200201 if self._loop.get_debug():
202 logger.info('%r exited with return code %r',
203 self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700204 self._returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700205 self._call(self._protocol.process_exited)
206 self._try_finish()
207
Victor Stinner47cd10d2015-01-30 00:05:19 +0100208 # wake up futures waiting for wait()
209 for waiter in self._exit_waiters:
210 if not waiter.cancelled():
211 waiter.set_result(returncode)
212 self._exit_waiters = None
213
Victor Stinnerd6dc7bd2015-03-18 11:37:42 +0100214 @coroutine
Victor Stinner1241ecc2015-01-30 00:16:14 +0100215 def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100216 """Wait until the process exit and return the process return code.
217
218 This method is a coroutine."""
219 if self._returncode is not None:
220 return self._returncode
221
222 waiter = futures.Future(loop=self._loop)
223 self._exit_waiters.append(waiter)
224 return (yield from waiter)
225
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700226 def _try_finish(self):
227 assert not self._finished
228 if self._returncode is None:
229 return
230 if all(p is not None and p.disconnected
231 for p in self._pipes.values()):
232 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100233 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700234
235 def _call_connection_lost(self, exc):
236 try:
237 self._protocol.connection_lost(exc)
238 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100239 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700240 self._proc = None
241 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700242
243
244class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700245
246 def __init__(self, proc, fd):
247 self.proc = proc
248 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800249 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700250 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700251
252 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700253 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700254
Victor Stinneracdb7822014-07-14 18:33:40 +0200255 def __repr__(self):
256 return ('<%s fd=%s pipe=%r>'
257 % (self.__class__.__name__, self.fd, self.pipe))
258
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700259 def connection_lost(self, exc):
260 self.disconnected = True
261 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100262 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700263
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800264 def pause_writing(self):
265 self.proc._protocol.pause_writing()
266
267 def resume_writing(self):
268 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700269
270
271class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
272 protocols.Protocol):
273
274 def data_received(self, data):
275 self.proc._pipe_data_received(self.fd, data)