blob: 6851cd2b88e30740aa28cc5c52fa08fd65741912 [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
Guido van Rossum0016e1d2013-10-30 14:56:49 -070090 def close(self):
Victor Stinnerf2e43cb2015-01-30 01:20:44 +010091 if self._closed:
92 return
Victor Stinner978a9af2015-01-29 17:50:58 +010093 self._closed = True
Victor Stinner47cd10d2015-01-30 00:05:19 +010094
Guido van Rossum0016e1d2013-10-30 14:56:49 -070095 for proto in self._pipes.values():
Victor Stinner29ad0112015-01-15 00:04:21 +010096 if proto is None:
97 continue
Guido van Rossum0016e1d2013-10-30 14:56:49 -070098 proto.pipe.close()
Victor Stinner47cd10d2015-01-30 00:05:19 +010099
Victor Stinner8e368122015-02-10 14:49:32 +0100100 if (self._proc is not None
101 # the child process finished?
102 and self._returncode is None
103 # the child process finished but the transport was not notified yet?
104 and self._proc.poll() is None
105 ):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100106 if self._loop.get_debug():
107 logger.warning('Close running child process: kill %r', self)
108
109 try:
110 self._proc.kill()
111 except ProcessLookupError:
112 pass
113
Victor Stinnerf2e43cb2015-01-30 01:20:44 +0100114 # Don't clear the _proc reference yet: _post_init() may still run
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700115
Victor Stinner978a9af2015-01-29 17:50:58 +0100116 # On Python 3.3 and older, objects with a destructor part of a reference
117 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
118 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400119 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100120 def __del__(self):
121 if not self._closed:
122 warnings.warn("unclosed transport %r" % self, ResourceWarning)
123 self.close()
124
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700125 def get_pid(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200126 return self._pid
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700127
128 def get_returncode(self):
129 return self._returncode
130
131 def get_pipe_transport(self, fd):
132 if fd in self._pipes:
133 return self._pipes[fd].pipe
134 else:
135 return None
136
Victor Stinner47cd10d2015-01-30 00:05:19 +0100137 def _check_proc(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100138 if self._proc is None:
139 raise ProcessLookupError()
140
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700141 def send_signal(self, signal):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100142 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700143 self._proc.send_signal(signal)
144
145 def terminate(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100146 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700147 self._proc.terminate()
148
149 def kill(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100150 self._check_proc()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700151 self._proc.kill()
152
Victor Stinnerf951d282014-06-29 00:46:45 +0200153 @coroutine
Victor Stinner47cd10d2015-01-30 00:05:19 +0100154 def _connect_pipes(self, waiter):
Victor Stinnerf651a602015-01-14 02:10:33 +0100155 try:
156 proc = self._proc
157 loop = self._loop
Victor Stinner47cd10d2015-01-30 00:05:19 +0100158
Victor Stinnerf651a602015-01-14 02:10:33 +0100159 if proc.stdin is not None:
160 _, pipe = yield from loop.connect_write_pipe(
161 lambda: WriteSubprocessPipeProto(self, 0),
162 proc.stdin)
163 self._pipes[0] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100164
Victor Stinnerf651a602015-01-14 02:10:33 +0100165 if proc.stdout is not None:
166 _, pipe = yield from loop.connect_read_pipe(
167 lambda: ReadSubprocessPipeProto(self, 1),
168 proc.stdout)
169 self._pipes[1] = pipe
Victor Stinner47cd10d2015-01-30 00:05:19 +0100170
Victor Stinnerf651a602015-01-14 02:10:33 +0100171 if proc.stderr is not None:
172 _, pipe = yield from loop.connect_read_pipe(
173 lambda: ReadSubprocessPipeProto(self, 2),
174 proc.stderr)
175 self._pipes[2] = pipe
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800176
Victor Stinnerf651a602015-01-14 02:10:33 +0100177 assert self._pending_calls is not None
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800178
Victor Stinner47cd10d2015-01-30 00:05:19 +0100179 loop.call_soon(self._protocol.connection_made, self)
Victor Stinnerf651a602015-01-14 02:10:33 +0100180 for callback, data in self._pending_calls:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100181 loop.call_soon(callback, *data)
Victor Stinnerf651a602015-01-14 02:10:33 +0100182 self._pending_calls = None
Victor Stinner47cd10d2015-01-30 00:05:19 +0100183 except Exception as exc:
184 if waiter is not None and not waiter.cancelled():
185 waiter.set_exception(exc)
186 else:
187 if waiter is not None and not waiter.cancelled():
188 waiter.set_result(None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700189
190 def _call(self, cb, *data):
191 if self._pending_calls is not None:
192 self._pending_calls.append((cb, data))
193 else:
194 self._loop.call_soon(cb, *data)
195
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700196 def _pipe_connection_lost(self, fd, exc):
197 self._call(self._protocol.pipe_connection_lost, fd, exc)
198 self._try_finish()
199
200 def _pipe_data_received(self, fd, data):
201 self._call(self._protocol.pipe_data_received, fd, data)
202
203 def _process_exited(self, returncode):
204 assert returncode is not None, returncode
205 assert self._returncode is None, self._returncode
Victor Stinneracdb7822014-07-14 18:33:40 +0200206 if self._loop.get_debug():
207 logger.info('%r exited with return code %r',
208 self, returncode)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700209 self._returncode = returncode
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700210 self._call(self._protocol.process_exited)
211 self._try_finish()
212
Victor Stinner47cd10d2015-01-30 00:05:19 +0100213 # wake up futures waiting for wait()
214 for waiter in self._exit_waiters:
215 if not waiter.cancelled():
216 waiter.set_result(returncode)
217 self._exit_waiters = None
218
Victor Stinnerd6dc7bd2015-03-18 11:37:42 +0100219 @coroutine
Victor Stinner1241ecc2015-01-30 00:16:14 +0100220 def _wait(self):
Victor Stinner47cd10d2015-01-30 00:05:19 +0100221 """Wait until the process exit and return the process return code.
222
223 This method is a coroutine."""
224 if self._returncode is not None:
225 return self._returncode
226
227 waiter = futures.Future(loop=self._loop)
228 self._exit_waiters.append(waiter)
229 return (yield from waiter)
230
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700231 def _try_finish(self):
232 assert not self._finished
233 if self._returncode is None:
234 return
235 if all(p is not None and p.disconnected
236 for p in self._pipes.values()):
237 self._finished = True
Victor Stinner1b9763d2014-12-18 23:47:27 +0100238 self._call(self._call_connection_lost, None)
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700239
240 def _call_connection_lost(self, exc):
241 try:
242 self._protocol.connection_lost(exc)
243 finally:
Victor Stinner47cd10d2015-01-30 00:05:19 +0100244 self._loop = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700245 self._proc = None
246 self._protocol = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700247
248
249class WriteSubprocessPipeProto(protocols.BaseProtocol):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700250
251 def __init__(self, proc, fd):
252 self.proc = proc
253 self.fd = fd
Victor Stinneraaabc4f2014-01-29 14:22:56 -0800254 self.pipe = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700255 self.disconnected = False
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700256
257 def connection_made(self, transport):
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700258 self.pipe = transport
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700259
Victor Stinneracdb7822014-07-14 18:33:40 +0200260 def __repr__(self):
261 return ('<%s fd=%s pipe=%r>'
262 % (self.__class__.__name__, self.fd, self.pipe))
263
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700264 def connection_lost(self, exc):
265 self.disconnected = True
266 self.proc._pipe_connection_lost(self.fd, exc)
Victor Stinner587feb12015-01-09 21:34:27 +0100267 self.proc = None
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700268
Guido van Rossum1e9a4462014-01-29 14:28:15 -0800269 def pause_writing(self):
270 self.proc._protocol.pause_writing()
271
272 def resume_writing(self):
273 self.proc._protocol.resume_writing()
Guido van Rossum0016e1d2013-10-30 14:56:49 -0700274
275
276class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
277 protocols.Protocol):
278
279 def data_received(self, data):
280 self.proc._pipe_data_received(self.fd, data)