base_subprocess.py 8.73 KB
Newer Older
1 2
import collections
import subprocess
3
import warnings
4

5
from . import compat
6
from . import futures
7 8
from . import protocols
from . import transports
9
from .coroutines import coroutine
10
from .log import logger
11 12 13 14 15 16


class BaseSubprocessTransport(transports.SubprocessTransport):

    def __init__(self, loop, protocol, args, shell,
                 stdin, stdout, stderr, bufsize,
17
                 waiter=None, extra=None, **kwargs):
18
        super().__init__(extra)
19
        self._closed = False
20 21
        self._protocol = protocol
        self._loop = loop
22
        self._proc = None
23
        self._pid = None
24 25 26
        self._returncode = None
        self._exit_waiters = []
        self._pending_calls = collections.deque()
27
        self._pipes = {}
28 29
        self._finished = False

30
        if stdin == subprocess.PIPE:
31
            self._pipes[0] = None
32
        if stdout == subprocess.PIPE:
33
            self._pipes[1] = None
34
        if stderr == subprocess.PIPE:
35
            self._pipes[2] = None
36 37

        # Create the child process: set the _proc attribute
38 39 40 41 42 43 44
        try:
            self._start(args=args, shell=shell, stdin=stdin, stdout=stdout,
                        stderr=stderr, bufsize=bufsize, **kwargs)
        except:
            self.close()
            raise

45
        self._pid = self._proc.pid
46
        self._extra['subprocess'] = self._proc
47

48 49 50 51 52 53 54 55
        if self._loop.get_debug():
            if isinstance(args, (bytes, str)):
                program = args
            else:
                program = args[0]
            logger.debug('process %r created: pid %s',
                         program, self._pid)

56 57
        self._loop.create_task(self._connect_pipes(waiter))

58
    def __repr__(self):
59 60 61
        info = [self.__class__.__name__]
        if self._closed:
            info.append('closed')
62 63
        if self._pid is not None:
            info.append('pid=%s' % self._pid)
64 65
        if self._returncode is not None:
            info.append('returncode=%s' % self._returncode)
66
        elif self._pid is not None:
67
            info.append('running')
68 69
        else:
            info.append('not started')
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85

        stdin = self._pipes.get(0)
        if stdin is not None:
            info.append('stdin=%s' % stdin.pipe)

        stdout = self._pipes.get(1)
        stderr = self._pipes.get(2)
        if stdout is not None and stderr is stdout:
            info.append('stdout=stderr=%s' % stdout.pipe)
        else:
            if stdout is not None:
                info.append('stdout=%s' % stdout.pipe)
            if stderr is not None:
                info.append('stderr=%s' % stderr.pipe)

        return '<%s>' % ' '.join(info)
86 87 88 89

    def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
        raise NotImplementedError

90 91 92
    def is_closing(self):
        return self._closed

93
    def close(self):
94 95
        if self._closed:
            return
96
        self._closed = True
97

98
        for proto in self._pipes.values():
99 100
            if proto is None:
                continue
101
            proto.pipe.close()
102

103 104 105 106 107 108
        if (self._proc is not None
        # the child process finished?
        and self._returncode is None
        # the child process finished but the transport was not notified yet?
        and self._proc.poll() is None
        ):
109 110 111 112 113 114 115 116
            if self._loop.get_debug():
                logger.warning('Close running child process: kill %r', self)

            try:
                self._proc.kill()
            except ProcessLookupError:
                pass

117
            # Don't clear the _proc reference yet: _post_init() may still run
118

119 120 121
    # On Python 3.3 and older, objects with a destructor part of a reference
    # cycle are never destroyed. It's not more the case on Python 3.4 thanks
    # to the PEP 442.
122
    if compat.PY34:
123 124 125 126 127
        def __del__(self):
            if not self._closed:
                warnings.warn("unclosed transport %r" % self, ResourceWarning)
                self.close()

128
    def get_pid(self):
129
        return self._pid
130 131 132 133 134 135 136 137 138 139

    def get_returncode(self):
        return self._returncode

    def get_pipe_transport(self, fd):
        if fd in self._pipes:
            return self._pipes[fd].pipe
        else:
            return None

140 141 142 143
    def _check_proc(self):
        if self._proc is None:
            raise ProcessLookupError()

144
    def send_signal(self, signal):
145
        self._check_proc()
146 147 148
        self._proc.send_signal(signal)

    def terminate(self):
149
        self._check_proc()
150 151 152
        self._proc.terminate()

    def kill(self):
153
        self._check_proc()
154 155
        self._proc.kill()

156
    @coroutine
157
    def _connect_pipes(self, waiter):
158 159 160
        try:
            proc = self._proc
            loop = self._loop
161

162 163 164 165 166
            if proc.stdin is not None:
                _, pipe = yield from loop.connect_write_pipe(
                    lambda: WriteSubprocessPipeProto(self, 0),
                    proc.stdin)
                self._pipes[0] = pipe
167

168 169 170 171 172
            if proc.stdout is not None:
                _, pipe = yield from loop.connect_read_pipe(
                    lambda: ReadSubprocessPipeProto(self, 1),
                    proc.stdout)
                self._pipes[1] = pipe
173

174 175 176 177 178 179 180 181
            if proc.stderr is not None:
                _, pipe = yield from loop.connect_read_pipe(
                    lambda: ReadSubprocessPipeProto(self, 2),
                    proc.stderr)
                self._pipes[2] = pipe

            assert self._pending_calls is not None

182
            loop.call_soon(self._protocol.connection_made, self)
183
            for callback, data in self._pending_calls:
184
                loop.call_soon(callback, *data)
185
            self._pending_calls = None
186 187 188 189 190 191
        except Exception as exc:
            if waiter is not None and not waiter.cancelled():
                waiter.set_exception(exc)
        else:
            if waiter is not None and not waiter.cancelled():
                waiter.set_result(None)
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208

    def _call(self, cb, *data):
        if self._pending_calls is not None:
            self._pending_calls.append((cb, data))
        else:
            self._loop.call_soon(cb, *data)

    def _pipe_connection_lost(self, fd, exc):
        self._call(self._protocol.pipe_connection_lost, fd, exc)
        self._try_finish()

    def _pipe_data_received(self, fd, data):
        self._call(self._protocol.pipe_data_received, fd, data)

    def _process_exited(self, returncode):
        assert returncode is not None, returncode
        assert self._returncode is None, self._returncode
209 210 211
        if self._loop.get_debug():
            logger.info('%r exited with return code %r',
                        self, returncode)
212
        self._returncode = returncode
213 214 215 216
        if self._proc.returncode is None:
            # asyncio uses a child watcher: copy the status into the Popen
            # object. On Python 3.6, it is required to avoid a ResourceWarning.
            self._proc.returncode = returncode
217 218 219
        self._call(self._protocol.process_exited)
        self._try_finish()

220 221 222 223 224 225
        # wake up futures waiting for wait()
        for waiter in self._exit_waiters:
            if not waiter.cancelled():
                waiter.set_result(returncode)
        self._exit_waiters = None

226
    @coroutine
227
    def _wait(self):
228 229 230 231 232 233
        """Wait until the process exit and return the process return code.

        This method is a coroutine."""
        if self._returncode is not None:
            return self._returncode

234
        waiter = self._loop.create_future()
235 236 237
        self._exit_waiters.append(waiter)
        return (yield from waiter)

238 239 240 241 242 243 244
    def _try_finish(self):
        assert not self._finished
        if self._returncode is None:
            return
        if all(p is not None and p.disconnected
               for p in self._pipes.values()):
            self._finished = True
245
            self._call(self._call_connection_lost, None)
246 247 248 249 250

    def _call_connection_lost(self, exc):
        try:
            self._protocol.connection_lost(exc)
        finally:
251
            self._loop = None
252 253 254 255 256 257 258 259 260
            self._proc = None
            self._protocol = None


class WriteSubprocessPipeProto(protocols.BaseProtocol):

    def __init__(self, proc, fd):
        self.proc = proc
        self.fd = fd
261
        self.pipe = None
262 263 264 265 266
        self.disconnected = False

    def connection_made(self, transport):
        self.pipe = transport

267 268 269 270
    def __repr__(self):
        return ('<%s fd=%s pipe=%r>'
                % (self.__class__.__name__, self.fd, self.pipe))

271 272 273
    def connection_lost(self, exc):
        self.disconnected = True
        self.proc._pipe_connection_lost(self.fd, exc)
274
        self.proc = None
275

276 277 278 279 280
    def pause_writing(self):
        self.proc._protocol.pause_writing()

    def resume_writing(self):
        self.proc._protocol.resume_writing()
281 282 283 284 285 286 287


class ReadSubprocessPipeProto(WriteSubprocessPipeProto,
                              protocols.Protocol):

    def data_received(self, data):
        self.proc._pipe_data_received(self.fd, data)