blob: 28482b718962bd1a9ac9eae61a7d8963c02e0d48 [file] [log] [blame]
Guido van Rossum0016e1d2013-10-30 14:56:49 -07001import collections
2import subprocess
Victor Stinner978a9af2015-01-29 17:50:58 +01003import warnings
Guido van Rossum0016e1d2013-10-30 14:56:49 -07004
Yury Selivanov2a8911c2015-08-04 15:56:33 -04005from . import compat
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
Victor Stinner6fb1e742015-07-31 17:49:43 +020038 try:
39 self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
40 stderr=stderr, bufsize=bufsize, **kwargs)
41 except:
42 self.close()
43 raise
44
Victor Stinneracdb7822014-07-14 18:33:40 +020045 self._pid = self._proc.pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -070046 self._extra['subprocess'] = self._proc
Victor Stinner47cd10d2015-01-30 00:05:19 +010047
Victor Stinneracdb7822014-07-14 18:33:40 +020048 if self._loop.get_debug():
49 if isinstance(args, (bytes, str)):
50 program = args
51 else:
52 program = args[0]
53 logger.debug('process %r created: pid %s',
54 program, self._pid)
55
Victor Stinner47cd10d2015-01-30 00:05:19 +010056 self._loop.create_task(self._connect_pipes(waiter))
57
Victor Stinneracdb7822014-07-14 18:33:40 +020058 def __repr__(self):
Victor Stinner978a9af2015-01-29 17:50:58 +010059 info = [self.__class__.__name__]
60 if self._closed:
61 info.append('closed')
Victor Stinner7a82afe2015-03-10 16:32:29 +010062 if self._pid is not None:
63 info.append('pid=%s' % self._pid)
Victor Stinneracdb7822014-07-14 18:33:40 +020064 if self._returncode is not None:
65 info.append('returncode=%s' % self._returncode)
Victor Stinner7a82afe2015-03-10 16:32:29 +010066 elif self._pid is not None:
Victor Stinner4e82fb92015-02-17 22:50:33 +010067 info.append('running')
Victor Stinner7a82afe2015-03-10 16:32:29 +010068 else:
69 info.append('not started')
Victor Stinneracdb7822014-07-14 18:33:40 +020070
71 stdin = self._pipes.get(0)
72 if stdin is not None:
73 info.append('stdin=%s' % stdin.pipe)
74
75 stdout = self._pipes.get(1)
76 stderr = self._pipes.get(2)
77 if stdout is not None and stderr is stdout:
78 info.append('stdout=stderr=%s' % stdout.pipe)
79 else:
80 if stdout is not None:
81 info.append('stdout=%s' % stdout.pipe)
82 if stderr is not None:
83 info.append('stderr=%s' % stderr.pipe)
84
85 return '<%s>' % ' '.join(info)
Guido van Rossum0016e1d2013-10-30 14:56:49 -070086
87 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
88 raise NotImplementedError
89
Yury Selivanova05a6ef2016-09-11 21:11:02 -040090 def set_protocol(self, protocol):
91 self._protocol = protocol
92
93 def get_protocol(self):
94 return self._protocol
95
Yury Selivanov5bb1afb2015-11-16 12:43:21 -050096 def is_closing(self):
97 return self._closed
98
Guido van Rossum0016e1d2013-10-30 14:56:49 -070099 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100100 if self._closed:
101 return
Victor Stinner978a9af2015-01-29 17:50:58 +0100102 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +0100103
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700104 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +0100105 if proto is None:
106 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700107 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100108
Victor Stinner8e368122015-02-10 14:49:32 +0100109 if (self._proc is not None
110 # the child process finished?
111 and self._returncode is None
112 # the child process finished but the transport was not notified yet?
113 and self._proc.poll() is None
114 ):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100115 if self._loop.get_debug():
116 logger.warning('Close running child process: kill %r', self)
117
118 try:
119 self._proc.kill()
120 except ProcessLookupError:
121 pass
122
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100123 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700124
Victor Stinner978a9af2015-01-29 17:50:58 +0100125 # On Python 3.3 and older, objects with a destructor part of a reference
126 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
127 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400128 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100129 def __del__(self):
130 if not self._closed:
Victor Stinnere19558a2016-03-23 00:28:08 +0100131 warnings.warn("unclosed transport %r" % self, ResourceWarning,
132 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100133 self.close()
134
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700135 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200136 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700137
138 def get_returncode(self):
139 return self._returncode
140
141 def get_pipe_transport(self, fd):
142 if fd in self._pipes:
143 return self._pipes[fd].pipe
144 else:
145 return None
146
Victor Stinner47cd10d2015-01-30 00:05:19 +0100147 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100148 if self._proc is None:
149 raise ProcessLookupError()
150
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700151 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100152 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700153 self._proc.send_signal(signal)
154
155 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100156 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700157 self._proc.terminate()
158
159 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100160 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700161 self._proc.kill()
162
Victor Stinnerf951d282014-06-29 00:46:45 +0200163 @coroutine
Victor Stinner47cd10d2015-01-30 00:05:19 +0100164 def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100165 try:
166 proc = self._proc
167 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100168
Victor Stinnerf651a602015-01-14 02:10:33 +0100169 if proc.stdin is not None:
170 _, pipe = yield from loop.connect_write_pipe(
171 lambda: WriteSubprocessPipeProto(self, 0),
172 proc.stdin)
173 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100174
Victor Stinnerf651a602015-01-14 02:10:33 +0100175 if proc.stdout is not None:
176 _, pipe = yield from loop.connect_read_pipe(
177 lambda: ReadSubprocessPipeProto(self, 1),
178 proc.stdout)
179 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100180
Victor Stinnerf651a602015-01-14 02:10:33 +0100181 if proc.stderr is not None:
182 _, pipe = yield from loop.connect_read_pipe(
183 lambda: ReadSubprocessPipeProto(self, 2),
184 proc.stderr)
185 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800186
Victor Stinnerf651a602015-01-14 02:10:33 +0100187 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800188
Victor Stinner47cd10d2015-01-30 00:05:19 +0100189 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100190 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100191 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100192 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100193 except Exception as exc:
194 if waiter is not None and not waiter.cancelled():
195 waiter.set_exception(exc)
196 else:
197 if waiter is not None and not waiter.cancelled():
198 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700199
200 def _call(self, cb, *data):
201 if self._pending_calls is not None:
202 self._pending_calls.append((cb, data))
203 else:
204 self._loop.call_soon(cb, *data)
205
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700206 def _pipe_connection_lost(self, fd, exc):
207 self._call(self._protocol.pipe_connection_lost, fd, exc)
208 self._try_finish()
209
210 def _pipe_data_received(self, fd, data):
211 self._call(self._protocol.pipe_data_received, fd, data)
212
213 def _process_exited(self, returncode):
214 assert returncode is not None, returncode
215 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200216 if self._loop.get_debug():
217 logger.info('%r exited with return code %r',
218 self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700219 self._returncode = returncode
Victor Stinnerb0d43ce2016-05-20 13:05:48 +0200220 if self._proc.returncode is None:
221 # asyncio uses a child watcher: copy the status into the Popen
222 # object. On Python 3.6, it is required to avoid a ResourceWarning.
223 self._proc.returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700224 self._call(self._protocol.process_exited)
225 self._try_finish()
226
Victor Stinner47cd10d2015-01-30 00:05:19 +0100227 # wake up futures waiting for wait()
228 for waiter in self._exit_waiters:
229 if not waiter.cancelled():
230 waiter.set_result(returncode)
231 self._exit_waiters = None
232
Victor Stinnerd6dc7bd2015-03-18 11:37:42 +0100233 @coroutine
Victor Stinner1241ecc2015-01-30 00:16:14 +0100234 def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100235 """Wait until the process exit and return the process return code.
236
237 This method is a coroutine."""
238 if self._returncode is not None:
239 return self._returncode
240
Yury Selivanov7661db62016-05-16 15:38:39 -0400241 waiter = self._loop.create_future()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100242 self._exit_waiters.append(waiter)
243 return (yield from waiter)
244
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700245 def _try_finish(self):
246 assert not self._finished
247 if self._returncode is None:
248 return
249 if all(p is not None and p.disconnected
250 for p in self._pipes.values()):
251 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100252 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700253
254 def _call_connection_lost(self, exc):
255 try:
256 self._protocol.connection_lost(exc)
257 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100258 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700259 self._proc = None
260 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700261
262
263class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700264
265 def __init__(self, proc, fd):
266 self.proc = proc
267 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800268 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700269 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700270
271 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700272 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700273
Victor Stinneracdb7822014-07-14 18:33:40 +0200274 def __repr__(self):
275 return ('<%s fd=%s pipe=%r>'
276 % (self.__class__.__name__, self.fd, self.pipe))
277
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700278 def connection_lost(self, exc):
279 self.disconnected = True
280 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100281 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700282
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800283 def pause_writing(self):
284 self.proc._protocol.pause_writing()
285
286 def resume_writing(self):
287 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700288
289
290class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
291 protocols.Protocol):
292
293 def data_received(self, data):
294 self.proc._pipe_data_received(self.fd, data)