blob: 23742a169a473056fd0e26163a36df993edc8b80 [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
Guido van Rossum0016e1d2013-10-30 14:56:49 -07006from . import protocols
Guido van Rossum0016e1d2013-10-30 14:56:49 -07007from . import transports
Victor Stinnerf951d282014-06-29 00:46:45 +02008from .coroutines import coroutine
Victor Stinneracdb7822014-07-14 18:33:40 +02009from .log import logger
Guido van Rossum0016e1d2013-10-30 14:56:49 -070010
11
Guido van Rossum0016e1d2013-10-30 14:56:49 -070012class BaseSubprocessTransport(transports.SubprocessTransport):
13
14 def __init__(self, loop, protocol, args, shell,
15 stdin, stdout, stderr, bufsize,
Victor Stinner47cd10d2015-01-30 00:05:19 +010016 waiter=None, extra=None, **kwargs):
Guido van Rossum0016e1d2013-10-30 14:56:49 -070017 super().__init__(extra)
Victor Stinner978a9af2015-01-29 17:50:58 +010018 self._closed = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -070019 self._protocol = protocol
20 self._loop = loop
Victor Stinner47cd10d2015-01-30 00:05:19 +010021 self._proc = None
Victor Stinneracdb7822014-07-14 18:33:40 +020022 self._pid = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010023 self._returncode = None
24 self._exit_waiters = []
25 self._pending_calls = collections.deque()
Guido van Rossum0016e1d2013-10-30 14:56:49 -070026 self._pipes = {}
Victor Stinner47cd10d2015-01-30 00:05:19 +010027 self._finished = False
28
Guido van Rossum0016e1d2013-10-30 14:56:49 -070029 if stdin == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010030 self._pipes[0] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070031 if stdout == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010032 self._pipes[1] = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -070033 if stderr == subprocess.PIPE:
Victor Stinner915bcb02014-02-01 22:49:59 +010034 self._pipes[2] = None
Victor Stinner47cd10d2015-01-30 00:05:19 +010035
36 # Create the child process: set the _proc attribute
Victor Stinner6fb1e742015-07-31 17:49:43 +020037 try:
38 self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
39 stderr=stderr, bufsize=bufsize, **kwargs)
40 except:
41 self.close()
42 raise
43
Victor Stinneracdb7822014-07-14 18:33:40 +020044 self._pid = self._proc.pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -070045 self._extra['subprocess'] = self._proc
Victor Stinner47cd10d2015-01-30 00:05:19 +010046
Victor Stinneracdb7822014-07-14 18:33:40 +020047 if self._loop.get_debug():
48 if isinstance(args, (bytes, str)):
49 program = args
50 else:
51 program = args[0]
52 logger.debug('process %r created: pid %s',
53 program, self._pid)
54
Victor Stinner47cd10d2015-01-30 00:05:19 +010055 self._loop.create_task(self._connect_pipes(waiter))
56
Victor Stinneracdb7822014-07-14 18:33:40 +020057 def __repr__(self):
Victor Stinner978a9af2015-01-29 17:50:58 +010058 info = [self.__class__.__name__]
59 if self._closed:
60 info.append('closed')
Victor Stinner7a82afe2015-03-10 16:32:29 +010061 if self._pid is not None:
62 info.append('pid=%s' % self._pid)
Victor Stinneracdb7822014-07-14 18:33:40 +020063 if self._returncode is not None:
64 info.append('returncode=%s' % self._returncode)
Victor Stinner7a82afe2015-03-10 16:32:29 +010065 elif self._pid is not None:
Victor Stinner4e82fb92015-02-17 22:50:33 +010066 info.append('running')
Victor Stinner7a82afe2015-03-10 16:32:29 +010067 else:
68 info.append('not started')
Victor Stinneracdb7822014-07-14 18:33:40 +020069
70 stdin = self._pipes.get(0)
71 if stdin is not None:
72 info.append('stdin=%s' % stdin.pipe)
73
74 stdout = self._pipes.get(1)
75 stderr = self._pipes.get(2)
76 if stdout is not None and stderr is stdout:
77 info.append('stdout=stderr=%s' % stdout.pipe)
78 else:
79 if stdout is not None:
80 info.append('stdout=%s' % stdout.pipe)
81 if stderr is not None:
82 info.append('stderr=%s' % stderr.pipe)
83
84 return '<%s>' % ' '.join(info)
Guido van Rossum0016e1d2013-10-30 14:56:49 -070085
86 def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
87 raise NotImplementedError
88
Yury Selivanova05a6ef2016-09-11 21:11:02 -040089 def set_protocol(self, protocol):
90 self._protocol = protocol
91
92 def get_protocol(self):
93 return self._protocol
94
Yury Selivanov5bb1afb2015-11-16 12:43:21 -050095 def is_closing(self):
96 return self._closed
97
Guido van Rossum0016e1d2013-10-30 14:56:49 -070098 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +010099 if self._closed:
100 return
Victor Stinner978a9af2015-01-29 17:50:58 +0100101 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +0100102
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700103 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +0100104 if proto is None:
105 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700106 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100107
Victor Stinner8e368122015-02-10 14:49:32 +0100108 if (self._proc is not None
109 # the child process finished?
110 and self._returncode is None
111 # the child process finished but the transport was not notified yet?
112 and self._proc.poll() is None
113 ):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100114 if self._loop.get_debug():
115 logger.warning('Close running child process: kill %r', self)
116
117 try:
118 self._proc.kill()
119 except ProcessLookupError:
120 pass
121
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100122 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700123
Victor Stinner978a9af2015-01-29 17:50:58 +0100124 # On Python 3.3 and older, objects with a destructor part of a reference
125 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
126 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400127 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100128 def __del__(self):
129 if not self._closed:
130 warnings.warn("unclosed transport %r" % self, ResourceWarning)
131 self.close()
132
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700133 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200134 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700135
136 def get_returncode(self):
137 return self._returncode
138
139 def get_pipe_transport(self, fd):
140 if fd in self._pipes:
141 return self._pipes[fd].pipe
142 else:
143 return None
144
Victor Stinner47cd10d2015-01-30 00:05:19 +0100145 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100146 if self._proc is None:
147 raise ProcessLookupError()
148
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700149 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100150 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700151 self._proc.send_signal(signal)
152
153 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100154 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700155 self._proc.terminate()
156
157 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100158 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700159 self._proc.kill()
160
Victor Stinnerf951d282014-06-29 00:46:45 +0200161 @coroutine
Victor Stinner47cd10d2015-01-30 00:05:19 +0100162 def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100163 try:
164 proc = self._proc
165 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100166
Victor Stinnerf651a602015-01-14 02:10:33 +0100167 if proc.stdin is not None:
168 _, pipe = yield from loop.connect_write_pipe(
169 lambda: WriteSubprocessPipeProto(self, 0),
170 proc.stdin)
171 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100172
Victor Stinnerf651a602015-01-14 02:10:33 +0100173 if proc.stdout is not None:
174 _, pipe = yield from loop.connect_read_pipe(
175 lambda: ReadSubprocessPipeProto(self, 1),
176 proc.stdout)
177 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100178
Victor Stinnerf651a602015-01-14 02:10:33 +0100179 if proc.stderr is not None:
180 _, pipe = yield from loop.connect_read_pipe(
181 lambda: ReadSubprocessPipeProto(self, 2),
182 proc.stderr)
183 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800184
Victor Stinnerf651a602015-01-14 02:10:33 +0100185 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800186
Victor Stinner47cd10d2015-01-30 00:05:19 +0100187 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100188 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100189 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100190 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100191 except Exception as exc:
192 if waiter is not None and not waiter.cancelled():
193 waiter.set_exception(exc)
194 else:
195 if waiter is not None and not waiter.cancelled():
196 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700197
198 def _call(self, cb, *data):
199 if self._pending_calls is not None:
200 self._pending_calls.append((cb, data))
201 else:
202 self._loop.call_soon(cb, *data)
203
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700204 def _pipe_connection_lost(self, fd, exc):
205 self._call(self._protocol.pipe_connection_lost, fd, exc)
206 self._try_finish()
207
208 def _pipe_data_received(self, fd, data):
209 self._call(self._protocol.pipe_data_received, fd, data)
210
211 def _process_exited(self, returncode):
212 assert returncode is not None, returncode
213 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200214 if self._loop.get_debug():
215 logger.info('%r exited with return code %r',
216 self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700217 self._returncode = returncode
Victor Stinnerb0d43ce2016-05-20 13:05:48 +0200218 if self._proc.returncode is None:
219 # asyncio uses a child watcher: copy the status into the Popen
220 # object. On Python 3.6, it is required to avoid a ResourceWarning.
221 self._proc.returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700222 self._call(self._protocol.process_exited)
223 self._try_finish()
224
Victor Stinner47cd10d2015-01-30 00:05:19 +0100225 # wake up futures waiting for wait()
226 for waiter in self._exit_waiters:
227 if not waiter.cancelled():
228 waiter.set_result(returncode)
229 self._exit_waiters = None
230
Victor Stinnerd6dc7bd2015-03-18 11:37:42 +0100231 @coroutine
Victor Stinner1241ecc2015-01-30 00:16:14 +0100232 def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100233 """Wait until the process exit and return the process return code.
234
235 This method is a coroutine."""
236 if self._returncode is not None:
237 return self._returncode
238
Yury Selivanov7661db62016-05-16 15:38:39 -0400239 waiter = self._loop.create_future()
Victor Stinner47cd10d2015-01-30 00:05:19 +0100240 self._exit_waiters.append(waiter)
241 return (yield from waiter)
242
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700243 def _try_finish(self):
244 assert not self._finished
245 if self._returncode is None:
246 return
247 if all(p is not None and p.disconnected
248 for p in self._pipes.values()):
249 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100250 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700251
252 def _call_connection_lost(self, exc):
253 try:
254 self._protocol.connection_lost(exc)
255 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100256 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700257 self._proc = None
258 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700259
260
261class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700262
263 def __init__(self, proc, fd):
264 self.proc = proc
265 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800266 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700267 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700268
269 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700270 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700271
Victor Stinneracdb7822014-07-14 18:33:40 +0200272 def __repr__(self):
273 return ('<%s fd=%s pipe=%r>'
274 % (self.__class__.__name__, self.fd, self.pipe))
275
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700276 def connection_lost(self, exc):
277 self.disconnected = True
278 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100279 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700280
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800281 def pause_writing(self):
282 self.proc._protocol.pause_writing()
283
284 def resume_writing(self):
285 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700286
287
288class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
289 protocols.Protocol):
290
291 def data_received(self, data):
292 self.proc._pipe_data_received(self.fd, data)