blob: f503f78fdda349b4e56bed1a5a09a44d0dd17a07 [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
5from . import protocols
Guido van Rossum0016e1d2013-10-30 14:56:49 -07006from . import transports
Victor Stinneracdb7822014-07-14 18:33:40 +02007from .log import logger
Guido van Rossum0016e1d2013-10-30 14:56:49 -07008
9
Guido van Rossum0016e1d2013-10-30 14:56:49 -070010class BaseSubprocessTransport(transports.SubprocessTransport):
11
12 def __init__(self, loop, protocol, args, shell,
13 stdin, stdout, stderr, bufsize,
Victor Stinner47cd10d2015-01-30 00:05:19 +010014 waiter=None, extra=None, **kwargs):
Guido van Rossum0016e1d2013-10-30 14:56:49 -070015 super().__init__(extra)
Victor Stinner978a9af2015-01-29 17:50:58 +010016 self._closed = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -070017 self._protocol = protocol
18 self._loop = loop
Victor Stinner47cd10d2015-01-30 00:05:19 +010019 self._proc = None
Victor Stinneracdb7822014-07-14 18:33:40 +020020 self._pid = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010021 self._returncode = None
22 self._exit_waiters = []
23 self._pending_calls = collections.deque()
Guido van Rossum0016e1d2013-10-30 14:56:49 -070024 self._pipes = {}
Victor Stinner47cd10d2015-01-30 00:05:19 +010025 self._finished = False
26
Guido van Rossum0016e1d2013-10-30 14:56:49 -070027 if stdin == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010028 self._pipes[0] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070029 if stdout == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010030 self._pipes[1] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070031 if stderr == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010032 self._pipes[2] = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010033
34 # Create the child process: set the _proc attribute
Victor Stinner6fb1e742015-07-31 17:49:43 +020035 try:
36 self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
37 stderr=stderr, bufsize=bufsize, **kwargs)
38 except:
39 self.close()
40 raise
41
Victor Stinneracdb7822014-07-14 18:33:40 +020042 self._pid = self._proc.pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -070043 self._extra['subprocess'] = self._proc
Victor Stinner47cd10d2015-01-30 00:05:19 +010044
Victor Stinneracdb7822014-07-14 18:33:40 +020045 if self._loop.get_debug():
46 if isinstance(args, (bytes, str)):
47 program = args
48 else:
49 program = args[0]
50 logger.debug('process %r created: pid %s',
51 program, self._pid)
52
Victor Stinner47cd10d2015-01-30 00:05:19 +010053 self._loop.create_task(self._connect_pipes(waiter))
54
Victor Stinneracdb7822014-07-14 18:33:40 +020055 def __repr__(self):
Victor Stinner978a9af2015-01-29 17:50:58 +010056 info = [self.__class__.__name__]
57 if self._closed:
58 info.append('closed')
Victor Stinner7a82afe2015-03-10 16:32:29 +010059 if self._pid is not None:
Christian Heimesd361e992018-05-20 19:57:13 +020060 info.append(f'pid={self._pid}')
Victor Stinneracdb7822014-07-14 18:33:40 +020061 if self._returncode is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -050062 info.append(f'returncode={self._returncode}')
Victor Stinner7a82afe2015-03-10 16:32:29 +010063 elif self._pid is not None:
Victor Stinner4e82fb92015-02-17 22:50:33 +010064 info.append('running')
Victor Stinner7a82afe2015-03-10 16:32:29 +010065 else:
66 info.append('not started')
Victor Stinneracdb7822014-07-14 18:33:40 +020067
68 stdin = self._pipes.get(0)
69 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -050070 info.append(f'stdin={stdin.pipe}')
Victor Stinneracdb7822014-07-14 18:33:40 +020071
72 stdout = self._pipes.get(1)
73 stderr = self._pipes.get(2)
74 if stdout is not None and stderr is stdout:
Yury Selivanov6370f342017-12-10 18:36:12 -050075 info.append(f'stdout=stderr={stdout.pipe}')
Victor Stinneracdb7822014-07-14 18:33:40 +020076 else:
77 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -050078 info.append(f'stdout={stdout.pipe}')
Victor Stinneracdb7822014-07-14 18:33:40 +020079 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -050080 info.append(f'stderr={stderr.pipe}')
Victor Stinneracdb7822014-07-14 18:33:40 +020081
Yury Selivanov6370f342017-12-10 18:36:12 -050082 return '<{}>'.format(' '.join(info))
Guido van Rossum0016e1d2013-10-30 14:56:49 -070083
84 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
85 raise NotImplementedError
86
Yury Selivanova05a6ef2016-09-11 21:11:02 -040087 def set_protocol(self, protocol):
88 self._protocol = protocol
89
90 def get_protocol(self):
91 return self._protocol
92
Yury Selivanov5bb1afb2015-11-16 12:43:21 -050093 def is_closing(self):
94 return self._closed
95
Guido van Rossum0016e1d2013-10-30 14:56:49 -070096 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +010097 if self._closed:
98 return
Victor Stinner978a9af2015-01-29 17:50:58 +010099 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +0100100
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700101 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +0100102 if proto is None:
103 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700104 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100105
Yury Selivanov6370f342017-12-10 18:36:12 -0500106 if (self._proc is not None and
107 # has the child process finished?
108 self._returncode is None and
109 # the child process has finished, but the
110 # transport hasn't been notified yet?
111 self._proc.poll() is None):
112
Victor Stinner47cd10d2015-01-30 00:05:19 +0100113 if self._loop.get_debug():
114 logger.warning('Close running child process: kill %r', self)
115
116 try:
117 self._proc.kill()
118 except ProcessLookupError:
119 pass
120
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100121 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700122
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100123 def __del__(self, _warn=warnings.warn):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900124 if not self._closed:
Victor Stinnerfb2c3462019-01-10 11:24:40 +0100125 _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900126 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100127
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700128 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200129 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700130
131 def get_returncode(self):
132 return self._returncode
133
134 def get_pipe_transport(self, fd):
135 if fd in self._pipes:
136 return self._pipes[fd].pipe
137 else:
138 return None
139
Victor Stinner47cd10d2015-01-30 00:05:19 +0100140 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100141 if self._proc is None:
142 raise ProcessLookupError()
143
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700144 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100145 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700146 self._proc.send_signal(signal)
147
148 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100149 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700150 self._proc.terminate()
151
152 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100153 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700154 self._proc.kill()
155
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200156 async def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100157 try:
158 proc = self._proc
159 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100160
Victor Stinnerf651a602015-01-14 02:10:33 +0100161 if proc.stdin is not None:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200162 _, pipe = await loop.connect_write_pipe(
Victor Stinnerf651a602015-01-14 02:10:33 +0100163 lambda: WriteSubprocessPipeProto(self, 0),
164 proc.stdin)
165 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100166
Victor Stinnerf651a602015-01-14 02:10:33 +0100167 if proc.stdout is not None:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200168 _, pipe = await loop.connect_read_pipe(
Victor Stinnerf651a602015-01-14 02:10:33 +0100169 lambda: ReadSubprocessPipeProto(self, 1),
170 proc.stdout)
171 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100172
Victor Stinnerf651a602015-01-14 02:10:33 +0100173 if proc.stderr is not None:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200174 _, pipe = await loop.connect_read_pipe(
Victor Stinnerf651a602015-01-14 02:10:33 +0100175 lambda: ReadSubprocessPipeProto(self, 2),
176 proc.stderr)
177 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800178
Victor Stinnerf651a602015-01-14 02:10:33 +0100179 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800180
Victor Stinner47cd10d2015-01-30 00:05:19 +0100181 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100182 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100183 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100184 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100185 except Exception as exc:
186 if waiter is not None and not waiter.cancelled():
187 waiter.set_exception(exc)
188 else:
189 if waiter is not None and not waiter.cancelled():
190 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700191
192 def _call(self, cb, *data):
193 if self._pending_calls is not None:
194 self._pending_calls.append((cb, data))
195 else:
196 self._loop.call_soon(cb, *data)
197
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700198 def _pipe_connection_lost(self, fd, exc):
199 self._call(self._protocol.pipe_connection_lost, fd, exc)
200 self._try_finish()
201
202 def _pipe_data_received(self, fd, data):
203 self._call(self._protocol.pipe_data_received, fd, data)
204
205 def _process_exited(self, returncode):
206 assert returncode is not None, returncode
207 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200208 if self._loop.get_debug():
Yury Selivanov6370f342017-12-10 18:36:12 -0500209 logger.info('%r exited with return code %r', self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700210 self._returncode = returncode
Victor Stinnerb0d43ce2016-05-20 13:05:48 +0200211 if self._proc.returncode is None:
212 # asyncio uses a child watcher: copy the status into the Popen
213 # object. On Python 3.6, it is required to avoid a ResourceWarning.
214 self._proc.returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700215 self._call(self._protocol.process_exited)
216 self._try_finish()
217
Victor Stinner47cd10d2015-01-30 00:05:19 +0100218 # wake up futures waiting for wait()
219 for waiter in self._exit_waiters:
220 if not waiter.cancelled():
221 waiter.set_result(returncode)
222 self._exit_waiters = None
223
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200224 async def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100225 """Wait until the process exit and return the process return code.
226
227 This method is a coroutine."""
228 if self._returncode is not None:
229 return self._returncode
230
Yury Selivanov7661db62016-05-16 15:38:39 -0400231 waiter = self._loop.create_future()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100232 self._exit_waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200233 return await waiter
Victor Stinner47cd10d2015-01-30 00:05:19 +0100234
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700235 def _try_finish(self):
236 assert not self._finished
237 if self._returncode is None:
238 return
239 if all(p is not None and p.disconnected
240 for p in self._pipes.values()):
241 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100242 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700243
244 def _call_connection_lost(self, exc):
245 try:
246 self._protocol.connection_lost(exc)
247 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100248 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700249 self._proc = None
250 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700251
252
253class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700254
255 def __init__(self, proc, fd):
256 self.proc = proc
257 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800258 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700259 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700260
261 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700262 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700263
Victor Stinneracdb7822014-07-14 18:33:40 +0200264 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500265 return f'<{self.__class__.__name__} fd={self.fd} pipe={self.pipe!r}>'
Victor Stinneracdb7822014-07-14 18:33:40 +0200266
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700267 def connection_lost(self, exc):
268 self.disconnected = True
269 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100270 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700271
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800272 def pause_writing(self):
273 self.proc._protocol.pause_writing()
274
275 def resume_writing(self):
276 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700277
278
279class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
280 protocols.Protocol):
281
282 def data_received(self, data):
283 self.proc._pipe_data_received(self.fd, data)