jpayne@68: import errno jpayne@68: import os jpayne@68: import selectors jpayne@68: import signal jpayne@68: import socket jpayne@68: import struct jpayne@68: import sys jpayne@68: import threading jpayne@68: import warnings jpayne@68: jpayne@68: from . import connection jpayne@68: from . import process jpayne@68: from .context import reduction jpayne@68: from . import resource_tracker jpayne@68: from . import spawn jpayne@68: from . import util jpayne@68: jpayne@68: __all__ = ['ensure_running', 'get_inherited_fds', 'connect_to_new_process', jpayne@68: 'set_forkserver_preload'] jpayne@68: jpayne@68: # jpayne@68: # jpayne@68: # jpayne@68: jpayne@68: MAXFDS_TO_SEND = 256 jpayne@68: SIGNED_STRUCT = struct.Struct('q') # large enough for pid_t jpayne@68: jpayne@68: # jpayne@68: # Forkserver class jpayne@68: # jpayne@68: jpayne@68: class ForkServer(object): jpayne@68: jpayne@68: def __init__(self): jpayne@68: self._forkserver_address = None jpayne@68: self._forkserver_alive_fd = None jpayne@68: self._forkserver_pid = None jpayne@68: self._inherited_fds = None jpayne@68: self._lock = threading.Lock() jpayne@68: self._preload_modules = ['__main__'] jpayne@68: jpayne@68: def _stop(self): jpayne@68: # Method used by unit tests to stop the server jpayne@68: with self._lock: jpayne@68: self._stop_unlocked() jpayne@68: jpayne@68: def _stop_unlocked(self): jpayne@68: if self._forkserver_pid is None: jpayne@68: return jpayne@68: jpayne@68: # close the "alive" file descriptor asks the server to stop jpayne@68: os.close(self._forkserver_alive_fd) jpayne@68: self._forkserver_alive_fd = None jpayne@68: jpayne@68: os.waitpid(self._forkserver_pid, 0) jpayne@68: self._forkserver_pid = None jpayne@68: jpayne@68: os.unlink(self._forkserver_address) jpayne@68: self._forkserver_address = None jpayne@68: jpayne@68: def set_forkserver_preload(self, modules_names): jpayne@68: '''Set list of module names to try to load in forkserver process.''' jpayne@68: if not all(type(mod) is str for mod in self._preload_modules): jpayne@68: raise TypeError('module_names must be a list of strings') jpayne@68: self._preload_modules = modules_names jpayne@68: jpayne@68: def get_inherited_fds(self): jpayne@68: '''Return list of fds inherited from parent process. jpayne@68: jpayne@68: This returns None if the current process was not started by fork jpayne@68: server. jpayne@68: ''' jpayne@68: return self._inherited_fds jpayne@68: jpayne@68: def connect_to_new_process(self, fds): jpayne@68: '''Request forkserver to create a child process. jpayne@68: jpayne@68: Returns a pair of fds (status_r, data_w). The calling process can read jpayne@68: the child process's pid and (eventually) its returncode from status_r. jpayne@68: The calling process should write to data_w the pickled preparation and jpayne@68: process data. jpayne@68: ''' jpayne@68: self.ensure_running() jpayne@68: if len(fds) + 4 >= MAXFDS_TO_SEND: jpayne@68: raise ValueError('too many fds') jpayne@68: with socket.socket(socket.AF_UNIX) as client: jpayne@68: client.connect(self._forkserver_address) jpayne@68: parent_r, child_w = os.pipe() jpayne@68: child_r, parent_w = os.pipe() jpayne@68: allfds = [child_r, child_w, self._forkserver_alive_fd, jpayne@68: resource_tracker.getfd()] jpayne@68: allfds += fds jpayne@68: try: jpayne@68: reduction.sendfds(client, allfds) jpayne@68: return parent_r, parent_w jpayne@68: except: jpayne@68: os.close(parent_r) jpayne@68: os.close(parent_w) jpayne@68: raise jpayne@68: finally: jpayne@68: os.close(child_r) jpayne@68: os.close(child_w) jpayne@68: jpayne@68: def ensure_running(self): jpayne@68: '''Make sure that a fork server is running. jpayne@68: jpayne@68: This can be called from any process. Note that usually a child jpayne@68: process will just reuse the forkserver started by its parent, so jpayne@68: ensure_running() will do nothing. jpayne@68: ''' jpayne@68: with self._lock: jpayne@68: resource_tracker.ensure_running() jpayne@68: if self._forkserver_pid is not None: jpayne@68: # forkserver was launched before, is it still running? jpayne@68: pid, status = os.waitpid(self._forkserver_pid, os.WNOHANG) jpayne@68: if not pid: jpayne@68: # still alive jpayne@68: return jpayne@68: # dead, launch it again jpayne@68: os.close(self._forkserver_alive_fd) jpayne@68: self._forkserver_address = None jpayne@68: self._forkserver_alive_fd = None jpayne@68: self._forkserver_pid = None jpayne@68: jpayne@68: cmd = ('from multiprocessing.forkserver import main; ' + jpayne@68: 'main(%d, %d, %r, **%r)') jpayne@68: jpayne@68: if self._preload_modules: jpayne@68: desired_keys = {'main_path', 'sys_path'} jpayne@68: data = spawn.get_preparation_data('ignore') jpayne@68: data = {x: y for x, y in data.items() if x in desired_keys} jpayne@68: else: jpayne@68: data = {} jpayne@68: jpayne@68: with socket.socket(socket.AF_UNIX) as listener: jpayne@68: address = connection.arbitrary_address('AF_UNIX') jpayne@68: listener.bind(address) jpayne@68: os.chmod(address, 0o600) jpayne@68: listener.listen() jpayne@68: jpayne@68: # all client processes own the write end of the "alive" pipe; jpayne@68: # when they all terminate the read end becomes ready. jpayne@68: alive_r, alive_w = os.pipe() jpayne@68: try: jpayne@68: fds_to_pass = [listener.fileno(), alive_r] jpayne@68: cmd %= (listener.fileno(), alive_r, self._preload_modules, jpayne@68: data) jpayne@68: exe = spawn.get_executable() jpayne@68: args = [exe] + util._args_from_interpreter_flags() jpayne@68: args += ['-c', cmd] jpayne@68: pid = util.spawnv_passfds(exe, args, fds_to_pass) jpayne@68: except: jpayne@68: os.close(alive_w) jpayne@68: raise jpayne@68: finally: jpayne@68: os.close(alive_r) jpayne@68: self._forkserver_address = address jpayne@68: self._forkserver_alive_fd = alive_w jpayne@68: self._forkserver_pid = pid jpayne@68: jpayne@68: # jpayne@68: # jpayne@68: # jpayne@68: jpayne@68: def main(listener_fd, alive_r, preload, main_path=None, sys_path=None): jpayne@68: '''Run forkserver.''' jpayne@68: if preload: jpayne@68: if '__main__' in preload and main_path is not None: jpayne@68: process.current_process()._inheriting = True jpayne@68: try: jpayne@68: spawn.import_main_path(main_path) jpayne@68: finally: jpayne@68: del process.current_process()._inheriting jpayne@68: for modname in preload: jpayne@68: try: jpayne@68: __import__(modname) jpayne@68: except ImportError: jpayne@68: pass jpayne@68: jpayne@68: util._close_stdin() jpayne@68: jpayne@68: sig_r, sig_w = os.pipe() jpayne@68: os.set_blocking(sig_r, False) jpayne@68: os.set_blocking(sig_w, False) jpayne@68: jpayne@68: def sigchld_handler(*_unused): jpayne@68: # Dummy signal handler, doesn't do anything jpayne@68: pass jpayne@68: jpayne@68: handlers = { jpayne@68: # unblocking SIGCHLD allows the wakeup fd to notify our event loop jpayne@68: signal.SIGCHLD: sigchld_handler, jpayne@68: # protect the process from ^C jpayne@68: signal.SIGINT: signal.SIG_IGN, jpayne@68: } jpayne@68: old_handlers = {sig: signal.signal(sig, val) jpayne@68: for (sig, val) in handlers.items()} jpayne@68: jpayne@68: # calling os.write() in the Python signal handler is racy jpayne@68: signal.set_wakeup_fd(sig_w) jpayne@68: jpayne@68: # map child pids to client fds jpayne@68: pid_to_fd = {} jpayne@68: jpayne@68: with socket.socket(socket.AF_UNIX, fileno=listener_fd) as listener, \ jpayne@68: selectors.DefaultSelector() as selector: jpayne@68: _forkserver._forkserver_address = listener.getsockname() jpayne@68: jpayne@68: selector.register(listener, selectors.EVENT_READ) jpayne@68: selector.register(alive_r, selectors.EVENT_READ) jpayne@68: selector.register(sig_r, selectors.EVENT_READ) jpayne@68: jpayne@68: while True: jpayne@68: try: jpayne@68: while True: jpayne@68: rfds = [key.fileobj for (key, events) in selector.select()] jpayne@68: if rfds: jpayne@68: break jpayne@68: jpayne@68: if alive_r in rfds: jpayne@68: # EOF because no more client processes left jpayne@68: assert os.read(alive_r, 1) == b'', "Not at EOF?" jpayne@68: raise SystemExit jpayne@68: jpayne@68: if sig_r in rfds: jpayne@68: # Got SIGCHLD jpayne@68: os.read(sig_r, 65536) # exhaust jpayne@68: while True: jpayne@68: # Scan for child processes jpayne@68: try: jpayne@68: pid, sts = os.waitpid(-1, os.WNOHANG) jpayne@68: except ChildProcessError: jpayne@68: break jpayne@68: if pid == 0: jpayne@68: break jpayne@68: child_w = pid_to_fd.pop(pid, None) jpayne@68: if child_w is not None: jpayne@68: if os.WIFSIGNALED(sts): jpayne@68: returncode = -os.WTERMSIG(sts) jpayne@68: else: jpayne@68: if not os.WIFEXITED(sts): jpayne@68: raise AssertionError( jpayne@68: "Child {0:n} status is {1:n}".format( jpayne@68: pid,sts)) jpayne@68: returncode = os.WEXITSTATUS(sts) jpayne@68: # Send exit code to client process jpayne@68: try: jpayne@68: write_signed(child_w, returncode) jpayne@68: except BrokenPipeError: jpayne@68: # client vanished jpayne@68: pass jpayne@68: os.close(child_w) jpayne@68: else: jpayne@68: # This shouldn't happen really jpayne@68: warnings.warn('forkserver: waitpid returned ' jpayne@68: 'unexpected pid %d' % pid) jpayne@68: jpayne@68: if listener in rfds: jpayne@68: # Incoming fork request jpayne@68: with listener.accept()[0] as s: jpayne@68: # Receive fds from client jpayne@68: fds = reduction.recvfds(s, MAXFDS_TO_SEND + 1) jpayne@68: if len(fds) > MAXFDS_TO_SEND: jpayne@68: raise RuntimeError( jpayne@68: "Too many ({0:n}) fds to send".format( jpayne@68: len(fds))) jpayne@68: child_r, child_w, *fds = fds jpayne@68: s.close() jpayne@68: pid = os.fork() jpayne@68: if pid == 0: jpayne@68: # Child jpayne@68: code = 1 jpayne@68: try: jpayne@68: listener.close() jpayne@68: selector.close() jpayne@68: unused_fds = [alive_r, child_w, sig_r, sig_w] jpayne@68: unused_fds.extend(pid_to_fd.values()) jpayne@68: code = _serve_one(child_r, fds, jpayne@68: unused_fds, jpayne@68: old_handlers) jpayne@68: except Exception: jpayne@68: sys.excepthook(*sys.exc_info()) jpayne@68: sys.stderr.flush() jpayne@68: finally: jpayne@68: os._exit(code) jpayne@68: else: jpayne@68: # Send pid to client process jpayne@68: try: jpayne@68: write_signed(child_w, pid) jpayne@68: except BrokenPipeError: jpayne@68: # client vanished jpayne@68: pass jpayne@68: pid_to_fd[pid] = child_w jpayne@68: os.close(child_r) jpayne@68: for fd in fds: jpayne@68: os.close(fd) jpayne@68: jpayne@68: except OSError as e: jpayne@68: if e.errno != errno.ECONNABORTED: jpayne@68: raise jpayne@68: jpayne@68: jpayne@68: def _serve_one(child_r, fds, unused_fds, handlers): jpayne@68: # close unnecessary stuff and reset signal handlers jpayne@68: signal.set_wakeup_fd(-1) jpayne@68: for sig, val in handlers.items(): jpayne@68: signal.signal(sig, val) jpayne@68: for fd in unused_fds: jpayne@68: os.close(fd) jpayne@68: jpayne@68: (_forkserver._forkserver_alive_fd, jpayne@68: resource_tracker._resource_tracker._fd, jpayne@68: *_forkserver._inherited_fds) = fds jpayne@68: jpayne@68: # Run process object received over pipe jpayne@68: parent_sentinel = os.dup(child_r) jpayne@68: code = spawn._main(child_r, parent_sentinel) jpayne@68: jpayne@68: return code jpayne@68: jpayne@68: jpayne@68: # jpayne@68: # Read and write signed numbers jpayne@68: # jpayne@68: jpayne@68: def read_signed(fd): jpayne@68: data = b'' jpayne@68: length = SIGNED_STRUCT.size jpayne@68: while len(data) < length: jpayne@68: s = os.read(fd, length - len(data)) jpayne@68: if not s: jpayne@68: raise EOFError('unexpected EOF') jpayne@68: data += s jpayne@68: return SIGNED_STRUCT.unpack(data)[0] jpayne@68: jpayne@68: def write_signed(fd, n): jpayne@68: msg = SIGNED_STRUCT.pack(n) jpayne@68: while msg: jpayne@68: nbytes = os.write(fd, msg) jpayne@68: if nbytes == 0: jpayne@68: raise RuntimeError('should not get here') jpayne@68: msg = msg[nbytes:] jpayne@68: jpayne@68: # jpayne@68: # jpayne@68: # jpayne@68: jpayne@68: _forkserver = ForkServer() jpayne@68: ensure_running = _forkserver.ensure_running jpayne@68: get_inherited_fds = _forkserver.get_inherited_fds jpayne@68: connect_to_new_process = _forkserver.connect_to_new_process jpayne@68: set_forkserver_preload = _forkserver.set_forkserver_preload