unix_events.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  1. """Selector event loop for Unix with signal handling."""
  2. import errno
  3. import io
  4. import itertools
  5. import os
  6. import selectors
  7. import signal
  8. import socket
  9. import stat
  10. import subprocess
  11. import sys
  12. import threading
  13. import warnings
  14. from . import base_events
  15. from . import base_subprocess
  16. from . import constants
  17. from . import coroutines
  18. from . import events
  19. from . import exceptions
  20. from . import futures
  21. from . import selector_events
  22. from . import tasks
  23. from . import transports
  24. from .log import logger
  25. __all__ = (
  26. 'SelectorEventLoop',
  27. 'AbstractChildWatcher', 'SafeChildWatcher',
  28. 'FastChildWatcher', 'PidfdChildWatcher',
  29. 'MultiLoopChildWatcher', 'ThreadedChildWatcher',
  30. 'DefaultEventLoopPolicy',
  31. )
  32. if sys.platform == 'win32': # pragma: no cover
  33. raise ImportError('Signals are not really supported on Windows')
  34. def _sighandler_noop(signum, frame):
  35. """Dummy signal handler."""
  36. pass
  37. class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
  38. """Unix event loop.
  39. Adds signal handling and UNIX Domain Socket support to SelectorEventLoop.
  40. """
  41. def __init__(self, selector=None):
  42. super().__init__(selector)
  43. self._signal_handlers = {}
  44. def close(self):
  45. super().close()
  46. if not sys.is_finalizing():
  47. for sig in list(self._signal_handlers):
  48. self.remove_signal_handler(sig)
  49. else:
  50. if self._signal_handlers:
  51. warnings.warn(f"Closing the loop {self!r} "
  52. f"on interpreter shutdown "
  53. f"stage, skipping signal handlers removal",
  54. ResourceWarning,
  55. source=self)
  56. self._signal_handlers.clear()
  57. def _process_self_data(self, data):
  58. for signum in data:
  59. if not signum:
  60. # ignore null bytes written by _write_to_self()
  61. continue
  62. self._handle_signal(signum)
  63. def add_signal_handler(self, sig, callback, *args):
  64. """Add a handler for a signal. UNIX only.
  65. Raise ValueError if the signal number is invalid or uncatchable.
  66. Raise RuntimeError if there is a problem setting up the handler.
  67. """
  68. if (coroutines.iscoroutine(callback) or
  69. coroutines.iscoroutinefunction(callback)):
  70. raise TypeError("coroutines cannot be used "
  71. "with add_signal_handler()")
  72. self._check_signal(sig)
  73. self._check_closed()
  74. try:
  75. # set_wakeup_fd() raises ValueError if this is not the
  76. # main thread. By calling it early we ensure that an
  77. # event loop running in another thread cannot add a signal
  78. # handler.
  79. signal.set_wakeup_fd(self._csock.fileno())
  80. except (ValueError, OSError) as exc:
  81. raise RuntimeError(str(exc))
  82. handle = events.Handle(callback, args, self, None)
  83. self._signal_handlers[sig] = handle
  84. try:
  85. # Register a dummy signal handler to ask Python to write the signal
  86. # number in the wakeup file descriptor. _process_self_data() will
  87. # read signal numbers from this file descriptor to handle signals.
  88. signal.signal(sig, _sighandler_noop)
  89. # Set SA_RESTART to limit EINTR occurrences.
  90. signal.siginterrupt(sig, False)
  91. except OSError as exc:
  92. del self._signal_handlers[sig]
  93. if not self._signal_handlers:
  94. try:
  95. signal.set_wakeup_fd(-1)
  96. except (ValueError, OSError) as nexc:
  97. logger.info('set_wakeup_fd(-1) failed: %s', nexc)
  98. if exc.errno == errno.EINVAL:
  99. raise RuntimeError(f'sig {sig} cannot be caught')
  100. else:
  101. raise
  102. def _handle_signal(self, sig):
  103. """Internal helper that is the actual signal handler."""
  104. handle = self._signal_handlers.get(sig)
  105. if handle is None:
  106. return # Assume it's some race condition.
  107. if handle._cancelled:
  108. self.remove_signal_handler(sig) # Remove it properly.
  109. else:
  110. self._add_callback_signalsafe(handle)
  111. def remove_signal_handler(self, sig):
  112. """Remove a handler for a signal. UNIX only.
  113. Return True if a signal handler was removed, False if not.
  114. """
  115. self._check_signal(sig)
  116. try:
  117. del self._signal_handlers[sig]
  118. except KeyError:
  119. return False
  120. if sig == signal.SIGINT:
  121. handler = signal.default_int_handler
  122. else:
  123. handler = signal.SIG_DFL
  124. try:
  125. signal.signal(sig, handler)
  126. except OSError as exc:
  127. if exc.errno == errno.EINVAL:
  128. raise RuntimeError(f'sig {sig} cannot be caught')
  129. else:
  130. raise
  131. if not self._signal_handlers:
  132. try:
  133. signal.set_wakeup_fd(-1)
  134. except (ValueError, OSError) as exc:
  135. logger.info('set_wakeup_fd(-1) failed: %s', exc)
  136. return True
  137. def _check_signal(self, sig):
  138. """Internal helper to validate a signal.
  139. Raise ValueError if the signal number is invalid or uncatchable.
  140. Raise RuntimeError if there is a problem setting up the handler.
  141. """
  142. if not isinstance(sig, int):
  143. raise TypeError(f'sig must be an int, not {sig!r}')
  144. if sig not in signal.valid_signals():
  145. raise ValueError(f'invalid signal number {sig}')
  146. def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
  147. extra=None):
  148. return _UnixReadPipeTransport(self, pipe, protocol, waiter, extra)
  149. def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
  150. extra=None):
  151. return _UnixWritePipeTransport(self, pipe, protocol, waiter, extra)
  152. async def _make_subprocess_transport(self, protocol, args, shell,
  153. stdin, stdout, stderr, bufsize,
  154. extra=None, **kwargs):
  155. with events.get_child_watcher() as watcher:
  156. if not watcher.is_active():
  157. # Check early.
  158. # Raising exception before process creation
  159. # prevents subprocess execution if the watcher
  160. # is not ready to handle it.
  161. raise RuntimeError("asyncio.get_child_watcher() is not activated, "
  162. "subprocess support is not installed.")
  163. waiter = self.create_future()
  164. transp = _UnixSubprocessTransport(self, protocol, args, shell,
  165. stdin, stdout, stderr, bufsize,
  166. waiter=waiter, extra=extra,
  167. **kwargs)
  168. watcher.add_child_handler(transp.get_pid(),
  169. self._child_watcher_callback, transp)
  170. try:
  171. await waiter
  172. except (SystemExit, KeyboardInterrupt):
  173. raise
  174. except BaseException:
  175. transp.close()
  176. await transp._wait()
  177. raise
  178. return transp
  179. def _child_watcher_callback(self, pid, returncode, transp):
  180. self.call_soon_threadsafe(transp._process_exited, returncode)
  181. async def create_unix_connection(
  182. self, protocol_factory, path=None, *,
  183. ssl=None, sock=None,
  184. server_hostname=None,
  185. ssl_handshake_timeout=None):
  186. assert server_hostname is None or isinstance(server_hostname, str)
  187. if ssl:
  188. if server_hostname is None:
  189. raise ValueError(
  190. 'you have to pass server_hostname when using ssl')
  191. else:
  192. if server_hostname is not None:
  193. raise ValueError('server_hostname is only meaningful with ssl')
  194. if ssl_handshake_timeout is not None:
  195. raise ValueError(
  196. 'ssl_handshake_timeout is only meaningful with ssl')
  197. if path is not None:
  198. if sock is not None:
  199. raise ValueError(
  200. 'path and sock can not be specified at the same time')
  201. path = os.fspath(path)
  202. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM, 0)
  203. try:
  204. sock.setblocking(False)
  205. await self.sock_connect(sock, path)
  206. except:
  207. sock.close()
  208. raise
  209. else:
  210. if sock is None:
  211. raise ValueError('no path and sock were specified')
  212. if (sock.family != socket.AF_UNIX or
  213. sock.type != socket.SOCK_STREAM):
  214. raise ValueError(
  215. f'A UNIX Domain Stream Socket was expected, got {sock!r}')
  216. sock.setblocking(False)
  217. transport, protocol = await self._create_connection_transport(
  218. sock, protocol_factory, ssl, server_hostname,
  219. ssl_handshake_timeout=ssl_handshake_timeout)
  220. return transport, protocol
  221. async def create_unix_server(
  222. self, protocol_factory, path=None, *,
  223. sock=None, backlog=100, ssl=None,
  224. ssl_handshake_timeout=None,
  225. start_serving=True):
  226. if isinstance(ssl, bool):
  227. raise TypeError('ssl argument must be an SSLContext or None')
  228. if ssl_handshake_timeout is not None and not ssl:
  229. raise ValueError(
  230. 'ssl_handshake_timeout is only meaningful with ssl')
  231. if path is not None:
  232. if sock is not None:
  233. raise ValueError(
  234. 'path and sock can not be specified at the same time')
  235. path = os.fspath(path)
  236. sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  237. # Check for abstract socket. `str` and `bytes` paths are supported.
  238. if path[0] not in (0, '\x00'):
  239. try:
  240. if stat.S_ISSOCK(os.stat(path).st_mode):
  241. os.remove(path)
  242. except FileNotFoundError:
  243. pass
  244. except OSError as err:
  245. # Directory may have permissions only to create socket.
  246. logger.error('Unable to check or remove stale UNIX socket '
  247. '%r: %r', path, err)
  248. try:
  249. sock.bind(path)
  250. except OSError as exc:
  251. sock.close()
  252. if exc.errno == errno.EADDRINUSE:
  253. # Let's improve the error message by adding
  254. # with what exact address it occurs.
  255. msg = f'Address {path!r} is already in use'
  256. raise OSError(errno.EADDRINUSE, msg) from None
  257. else:
  258. raise
  259. except:
  260. sock.close()
  261. raise
  262. else:
  263. if sock is None:
  264. raise ValueError(
  265. 'path was not specified, and no sock specified')
  266. if (sock.family != socket.AF_UNIX or
  267. sock.type != socket.SOCK_STREAM):
  268. raise ValueError(
  269. f'A UNIX Domain Stream Socket was expected, got {sock!r}')
  270. sock.setblocking(False)
  271. server = base_events.Server(self, [sock], protocol_factory,
  272. ssl, backlog, ssl_handshake_timeout)
  273. if start_serving:
  274. server._start_serving()
  275. # Skip one loop iteration so that all 'loop.add_reader'
  276. # go through.
  277. await tasks.sleep(0)
  278. return server
  279. async def _sock_sendfile_native(self, sock, file, offset, count):
  280. try:
  281. os.sendfile
  282. except AttributeError:
  283. raise exceptions.SendfileNotAvailableError(
  284. "os.sendfile() is not available")
  285. try:
  286. fileno = file.fileno()
  287. except (AttributeError, io.UnsupportedOperation) as err:
  288. raise exceptions.SendfileNotAvailableError("not a regular file")
  289. try:
  290. fsize = os.fstat(fileno).st_size
  291. except OSError:
  292. raise exceptions.SendfileNotAvailableError("not a regular file")
  293. blocksize = count if count else fsize
  294. if not blocksize:
  295. return 0 # empty file
  296. fut = self.create_future()
  297. self._sock_sendfile_native_impl(fut, None, sock, fileno,
  298. offset, count, blocksize, 0)
  299. return await fut
  300. def _sock_sendfile_native_impl(self, fut, registered_fd, sock, fileno,
  301. offset, count, blocksize, total_sent):
  302. fd = sock.fileno()
  303. if registered_fd is not None:
  304. # Remove the callback early. It should be rare that the
  305. # selector says the fd is ready but the call still returns
  306. # EAGAIN, and I am willing to take a hit in that case in
  307. # order to simplify the common case.
  308. self.remove_writer(registered_fd)
  309. if fut.cancelled():
  310. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  311. return
  312. if count:
  313. blocksize = count - total_sent
  314. if blocksize <= 0:
  315. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  316. fut.set_result(total_sent)
  317. return
  318. try:
  319. sent = os.sendfile(fd, fileno, offset, blocksize)
  320. except (BlockingIOError, InterruptedError):
  321. if registered_fd is None:
  322. self._sock_add_cancellation_callback(fut, sock)
  323. self.add_writer(fd, self._sock_sendfile_native_impl, fut,
  324. fd, sock, fileno,
  325. offset, count, blocksize, total_sent)
  326. except OSError as exc:
  327. if (registered_fd is not None and
  328. exc.errno == errno.ENOTCONN and
  329. type(exc) is not ConnectionError):
  330. # If we have an ENOTCONN and this isn't a first call to
  331. # sendfile(), i.e. the connection was closed in the middle
  332. # of the operation, normalize the error to ConnectionError
  333. # to make it consistent across all Posix systems.
  334. new_exc = ConnectionError(
  335. "socket is not connected", errno.ENOTCONN)
  336. new_exc.__cause__ = exc
  337. exc = new_exc
  338. if total_sent == 0:
  339. # We can get here for different reasons, the main
  340. # one being 'file' is not a regular mmap(2)-like
  341. # file, in which case we'll fall back on using
  342. # plain send().
  343. err = exceptions.SendfileNotAvailableError(
  344. "os.sendfile call failed")
  345. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  346. fut.set_exception(err)
  347. else:
  348. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  349. fut.set_exception(exc)
  350. except (SystemExit, KeyboardInterrupt):
  351. raise
  352. except BaseException as exc:
  353. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  354. fut.set_exception(exc)
  355. else:
  356. if sent == 0:
  357. # EOF
  358. self._sock_sendfile_update_filepos(fileno, offset, total_sent)
  359. fut.set_result(total_sent)
  360. else:
  361. offset += sent
  362. total_sent += sent
  363. if registered_fd is None:
  364. self._sock_add_cancellation_callback(fut, sock)
  365. self.add_writer(fd, self._sock_sendfile_native_impl, fut,
  366. fd, sock, fileno,
  367. offset, count, blocksize, total_sent)
  368. def _sock_sendfile_update_filepos(self, fileno, offset, total_sent):
  369. if total_sent > 0:
  370. os.lseek(fileno, offset, os.SEEK_SET)
  371. def _sock_add_cancellation_callback(self, fut, sock):
  372. def cb(fut):
  373. if fut.cancelled():
  374. fd = sock.fileno()
  375. if fd != -1:
  376. self.remove_writer(fd)
  377. fut.add_done_callback(cb)
  378. class _UnixReadPipeTransport(transports.ReadTransport):
  379. max_size = 256 * 1024 # max bytes we read in one event loop iteration
  380. def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
  381. super().__init__(extra)
  382. self._extra['pipe'] = pipe
  383. self._loop = loop
  384. self._pipe = pipe
  385. self._fileno = pipe.fileno()
  386. self._protocol = protocol
  387. self._closing = False
  388. self._paused = False
  389. mode = os.fstat(self._fileno).st_mode
  390. if not (stat.S_ISFIFO(mode) or
  391. stat.S_ISSOCK(mode) or
  392. stat.S_ISCHR(mode)):
  393. self._pipe = None
  394. self._fileno = None
  395. self._protocol = None
  396. raise ValueError("Pipe transport is for pipes/sockets only.")
  397. os.set_blocking(self._fileno, False)
  398. self._loop.call_soon(self._protocol.connection_made, self)
  399. # only start reading when connection_made() has been called
  400. self._loop.call_soon(self._loop._add_reader,
  401. self._fileno, self._read_ready)
  402. if waiter is not None:
  403. # only wake up the waiter when connection_made() has been called
  404. self._loop.call_soon(futures._set_result_unless_cancelled,
  405. waiter, None)
  406. def __repr__(self):
  407. info = [self.__class__.__name__]
  408. if self._pipe is None:
  409. info.append('closed')
  410. elif self._closing:
  411. info.append('closing')
  412. info.append(f'fd={self._fileno}')
  413. selector = getattr(self._loop, '_selector', None)
  414. if self._pipe is not None and selector is not None:
  415. polling = selector_events._test_selector_event(
  416. selector, self._fileno, selectors.EVENT_READ)
  417. if polling:
  418. info.append('polling')
  419. else:
  420. info.append('idle')
  421. elif self._pipe is not None:
  422. info.append('open')
  423. else:
  424. info.append('closed')
  425. return '<{}>'.format(' '.join(info))
  426. def _read_ready(self):
  427. try:
  428. data = os.read(self._fileno, self.max_size)
  429. except (BlockingIOError, InterruptedError):
  430. pass
  431. except OSError as exc:
  432. self._fatal_error(exc, 'Fatal read error on pipe transport')
  433. else:
  434. if data:
  435. self._protocol.data_received(data)
  436. else:
  437. if self._loop.get_debug():
  438. logger.info("%r was closed by peer", self)
  439. self._closing = True
  440. self._loop._remove_reader(self._fileno)
  441. self._loop.call_soon(self._protocol.eof_received)
  442. self._loop.call_soon(self._call_connection_lost, None)
  443. def pause_reading(self):
  444. if self._closing or self._paused:
  445. return
  446. self._paused = True
  447. self._loop._remove_reader(self._fileno)
  448. if self._loop.get_debug():
  449. logger.debug("%r pauses reading", self)
  450. def resume_reading(self):
  451. if self._closing or not self._paused:
  452. return
  453. self._paused = False
  454. self._loop._add_reader(self._fileno, self._read_ready)
  455. if self._loop.get_debug():
  456. logger.debug("%r resumes reading", self)
  457. def set_protocol(self, protocol):
  458. self._protocol = protocol
  459. def get_protocol(self):
  460. return self._protocol
  461. def is_closing(self):
  462. return self._closing
  463. def close(self):
  464. if not self._closing:
  465. self._close(None)
  466. def __del__(self, _warn=warnings.warn):
  467. if self._pipe is not None:
  468. _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
  469. self._pipe.close()
  470. def _fatal_error(self, exc, message='Fatal error on pipe transport'):
  471. # should be called by exception handler only
  472. if (isinstance(exc, OSError) and exc.errno == errno.EIO):
  473. if self._loop.get_debug():
  474. logger.debug("%r: %s", self, message, exc_info=True)
  475. else:
  476. self._loop.call_exception_handler({
  477. 'message': message,
  478. 'exception': exc,
  479. 'transport': self,
  480. 'protocol': self._protocol,
  481. })
  482. self._close(exc)
  483. def _close(self, exc):
  484. self._closing = True
  485. self._loop._remove_reader(self._fileno)
  486. self._loop.call_soon(self._call_connection_lost, exc)
  487. def _call_connection_lost(self, exc):
  488. try:
  489. self._protocol.connection_lost(exc)
  490. finally:
  491. self._pipe.close()
  492. self._pipe = None
  493. self._protocol = None
  494. self._loop = None
  495. class _UnixWritePipeTransport(transports._FlowControlMixin,
  496. transports.WriteTransport):
  497. def __init__(self, loop, pipe, protocol, waiter=None, extra=None):
  498. super().__init__(extra, loop)
  499. self._extra['pipe'] = pipe
  500. self._pipe = pipe
  501. self._fileno = pipe.fileno()
  502. self._protocol = protocol
  503. self._buffer = bytearray()
  504. self._conn_lost = 0
  505. self._closing = False # Set when close() or write_eof() called.
  506. mode = os.fstat(self._fileno).st_mode
  507. is_char = stat.S_ISCHR(mode)
  508. is_fifo = stat.S_ISFIFO(mode)
  509. is_socket = stat.S_ISSOCK(mode)
  510. if not (is_char or is_fifo or is_socket):
  511. self._pipe = None
  512. self._fileno = None
  513. self._protocol = None
  514. raise ValueError("Pipe transport is only for "
  515. "pipes, sockets and character devices")
  516. os.set_blocking(self._fileno, False)
  517. self._loop.call_soon(self._protocol.connection_made, self)
  518. # On AIX, the reader trick (to be notified when the read end of the
  519. # socket is closed) only works for sockets. On other platforms it
  520. # works for pipes and sockets. (Exception: OS X 10.4? Issue #19294.)
  521. if is_socket or (is_fifo and not sys.platform.startswith("aix")):
  522. # only start reading when connection_made() has been called
  523. self._loop.call_soon(self._loop._add_reader,
  524. self._fileno, self._read_ready)
  525. if waiter is not None:
  526. # only wake up the waiter when connection_made() has been called
  527. self._loop.call_soon(futures._set_result_unless_cancelled,
  528. waiter, None)
  529. def __repr__(self):
  530. info = [self.__class__.__name__]
  531. if self._pipe is None:
  532. info.append('closed')
  533. elif self._closing:
  534. info.append('closing')
  535. info.append(f'fd={self._fileno}')
  536. selector = getattr(self._loop, '_selector', None)
  537. if self._pipe is not None and selector is not None:
  538. polling = selector_events._test_selector_event(
  539. selector, self._fileno, selectors.EVENT_WRITE)
  540. if polling:
  541. info.append('polling')
  542. else:
  543. info.append('idle')
  544. bufsize = self.get_write_buffer_size()
  545. info.append(f'bufsize={bufsize}')
  546. elif self._pipe is not None:
  547. info.append('open')
  548. else:
  549. info.append('closed')
  550. return '<{}>'.format(' '.join(info))
  551. def get_write_buffer_size(self):
  552. return len(self._buffer)
  553. def _read_ready(self):
  554. # Pipe was closed by peer.
  555. if self._loop.get_debug():
  556. logger.info("%r was closed by peer", self)
  557. if self._buffer:
  558. self._close(BrokenPipeError())
  559. else:
  560. self._close()
  561. def write(self, data):
  562. assert isinstance(data, (bytes, bytearray, memoryview)), repr(data)
  563. if isinstance(data, bytearray):
  564. data = memoryview(data)
  565. if not data:
  566. return
  567. if self._conn_lost or self._closing:
  568. if self._conn_lost >= constants.LOG_THRESHOLD_FOR_CONNLOST_WRITES:
  569. logger.warning('pipe closed by peer or '
  570. 'os.write(pipe, data) raised exception.')
  571. self._conn_lost += 1
  572. return
  573. if not self._buffer:
  574. # Attempt to send it right away first.
  575. try:
  576. n = os.write(self._fileno, data)
  577. except (BlockingIOError, InterruptedError):
  578. n = 0
  579. except (SystemExit, KeyboardInterrupt):
  580. raise
  581. except BaseException as exc:
  582. self._conn_lost += 1
  583. self._fatal_error(exc, 'Fatal write error on pipe transport')
  584. return
  585. if n == len(data):
  586. return
  587. elif n > 0:
  588. data = memoryview(data)[n:]
  589. self._loop._add_writer(self._fileno, self._write_ready)
  590. self._buffer += data
  591. self._maybe_pause_protocol()
  592. def _write_ready(self):
  593. assert self._buffer, 'Data should not be empty'
  594. try:
  595. n = os.write(self._fileno, self._buffer)
  596. except (BlockingIOError, InterruptedError):
  597. pass
  598. except (SystemExit, KeyboardInterrupt):
  599. raise
  600. except BaseException as exc:
  601. self._buffer.clear()
  602. self._conn_lost += 1
  603. # Remove writer here, _fatal_error() doesn't it
  604. # because _buffer is empty.
  605. self._loop._remove_writer(self._fileno)
  606. self._fatal_error(exc, 'Fatal write error on pipe transport')
  607. else:
  608. if n == len(self._buffer):
  609. self._buffer.clear()
  610. self._loop._remove_writer(self._fileno)
  611. self._maybe_resume_protocol() # May append to buffer.
  612. if self._closing:
  613. self._loop._remove_reader(self._fileno)
  614. self._call_connection_lost(None)
  615. return
  616. elif n > 0:
  617. del self._buffer[:n]
  618. def can_write_eof(self):
  619. return True
  620. def write_eof(self):
  621. if self._closing:
  622. return
  623. assert self._pipe
  624. self._closing = True
  625. if not self._buffer:
  626. self._loop._remove_reader(self._fileno)
  627. self._loop.call_soon(self._call_connection_lost, None)
  628. def set_protocol(self, protocol):
  629. self._protocol = protocol
  630. def get_protocol(self):
  631. return self._protocol
  632. def is_closing(self):
  633. return self._closing
  634. def close(self):
  635. if self._pipe is not None and not self._closing:
  636. # write_eof is all what we needed to close the write pipe
  637. self.write_eof()
  638. def __del__(self, _warn=warnings.warn):
  639. if self._pipe is not None:
  640. _warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
  641. self._pipe.close()
  642. def abort(self):
  643. self._close(None)
  644. def _fatal_error(self, exc, message='Fatal error on pipe transport'):
  645. # should be called by exception handler only
  646. if isinstance(exc, OSError):
  647. if self._loop.get_debug():
  648. logger.debug("%r: %s", self, message, exc_info=True)
  649. else:
  650. self._loop.call_exception_handler({
  651. 'message': message,
  652. 'exception': exc,
  653. 'transport': self,
  654. 'protocol': self._protocol,
  655. })
  656. self._close(exc)
  657. def _close(self, exc=None):
  658. self._closing = True
  659. if self._buffer:
  660. self._loop._remove_writer(self._fileno)
  661. self._buffer.clear()
  662. self._loop._remove_reader(self._fileno)
  663. self._loop.call_soon(self._call_connection_lost, exc)
  664. def _call_connection_lost(self, exc):
  665. try:
  666. self._protocol.connection_lost(exc)
  667. finally:
  668. self._pipe.close()
  669. self._pipe = None
  670. self._protocol = None
  671. self._loop = None
  672. class _UnixSubprocessTransport(base_subprocess.BaseSubprocessTransport):
  673. def _start(self, args, shell, stdin, stdout, stderr, bufsize, **kwargs):
  674. stdin_w = None
  675. if stdin == subprocess.PIPE:
  676. # Use a socket pair for stdin, since not all platforms
  677. # support selecting read events on the write end of a
  678. # socket (which we use in order to detect closing of the
  679. # other end). Notably this is needed on AIX, and works
  680. # just fine on other platforms.
  681. stdin, stdin_w = socket.socketpair()
  682. try:
  683. self._proc = subprocess.Popen(
  684. args, shell=shell, stdin=stdin, stdout=stdout, stderr=stderr,
  685. universal_newlines=False, bufsize=bufsize, **kwargs)
  686. if stdin_w is not None:
  687. stdin.close()
  688. self._proc.stdin = open(stdin_w.detach(), 'wb', buffering=bufsize)
  689. stdin_w = None
  690. finally:
  691. if stdin_w is not None:
  692. stdin.close()
  693. stdin_w.close()
  694. class AbstractChildWatcher:
  695. """Abstract base class for monitoring child processes.
  696. Objects derived from this class monitor a collection of subprocesses and
  697. report their termination or interruption by a signal.
  698. New callbacks are registered with .add_child_handler(). Starting a new
  699. process must be done within a 'with' block to allow the watcher to suspend
  700. its activity until the new process if fully registered (this is needed to
  701. prevent a race condition in some implementations).
  702. Example:
  703. with watcher:
  704. proc = subprocess.Popen("sleep 1")
  705. watcher.add_child_handler(proc.pid, callback)
  706. Notes:
  707. Implementations of this class must be thread-safe.
  708. Since child watcher objects may catch the SIGCHLD signal and call
  709. waitpid(-1), there should be only one active object per process.
  710. """
  711. def add_child_handler(self, pid, callback, *args):
  712. """Register a new child handler.
  713. Arrange for callback(pid, returncode, *args) to be called when
  714. process 'pid' terminates. Specifying another callback for the same
  715. process replaces the previous handler.
  716. Note: callback() must be thread-safe.
  717. """
  718. raise NotImplementedError()
  719. def remove_child_handler(self, pid):
  720. """Removes the handler for process 'pid'.
  721. The function returns True if the handler was successfully removed,
  722. False if there was nothing to remove."""
  723. raise NotImplementedError()
  724. def attach_loop(self, loop):
  725. """Attach the watcher to an event loop.
  726. If the watcher was previously attached to an event loop, then it is
  727. first detached before attaching to the new loop.
  728. Note: loop may be None.
  729. """
  730. raise NotImplementedError()
  731. def close(self):
  732. """Close the watcher.
  733. This must be called to make sure that any underlying resource is freed.
  734. """
  735. raise NotImplementedError()
  736. def is_active(self):
  737. """Return ``True`` if the watcher is active and is used by the event loop.
  738. Return True if the watcher is installed and ready to handle process exit
  739. notifications.
  740. """
  741. raise NotImplementedError()
  742. def __enter__(self):
  743. """Enter the watcher's context and allow starting new processes
  744. This function must return self"""
  745. raise NotImplementedError()
  746. def __exit__(self, a, b, c):
  747. """Exit the watcher's context"""
  748. raise NotImplementedError()
  749. class PidfdChildWatcher(AbstractChildWatcher):
  750. """Child watcher implementation using Linux's pid file descriptors.
  751. This child watcher polls process file descriptors (pidfds) to await child
  752. process termination. In some respects, PidfdChildWatcher is a "Goldilocks"
  753. child watcher implementation. It doesn't require signals or threads, doesn't
  754. interfere with any processes launched outside the event loop, and scales
  755. linearly with the number of subprocesses launched by the event loop. The
  756. main disadvantage is that pidfds are specific to Linux, and only work on
  757. recent (5.3+) kernels.
  758. """
  759. def __init__(self):
  760. self._loop = None
  761. self._callbacks = {}
  762. def __enter__(self):
  763. return self
  764. def __exit__(self, exc_type, exc_value, exc_traceback):
  765. pass
  766. def is_active(self):
  767. return self._loop is not None and self._loop.is_running()
  768. def close(self):
  769. self.attach_loop(None)
  770. def attach_loop(self, loop):
  771. if self._loop is not None and loop is None and self._callbacks:
  772. warnings.warn(
  773. 'A loop is being detached '
  774. 'from a child watcher with pending handlers',
  775. RuntimeWarning)
  776. for pidfd, _, _ in self._callbacks.values():
  777. self._loop._remove_reader(pidfd)
  778. os.close(pidfd)
  779. self._callbacks.clear()
  780. self._loop = loop
  781. def add_child_handler(self, pid, callback, *args):
  782. existing = self._callbacks.get(pid)
  783. if existing is not None:
  784. self._callbacks[pid] = existing[0], callback, args
  785. else:
  786. pidfd = os.pidfd_open(pid)
  787. self._loop._add_reader(pidfd, self._do_wait, pid)
  788. self._callbacks[pid] = pidfd, callback, args
  789. def _do_wait(self, pid):
  790. pidfd, callback, args = self._callbacks.pop(pid)
  791. self._loop._remove_reader(pidfd)
  792. try:
  793. _, status = os.waitpid(pid, 0)
  794. except ChildProcessError:
  795. # The child process is already reaped
  796. # (may happen if waitpid() is called elsewhere).
  797. returncode = 255
  798. logger.warning(
  799. "child process pid %d exit status already read: "
  800. " will report returncode 255",
  801. pid)
  802. else:
  803. returncode = _compute_returncode(status)
  804. os.close(pidfd)
  805. callback(pid, returncode, *args)
  806. def remove_child_handler(self, pid):
  807. try:
  808. pidfd, _, _ = self._callbacks.pop(pid)
  809. except KeyError:
  810. return False
  811. self._loop._remove_reader(pidfd)
  812. os.close(pidfd)
  813. return True
  814. def _compute_returncode(status):
  815. if os.WIFSIGNALED(status):
  816. # The child process died because of a signal.
  817. return -os.WTERMSIG(status)
  818. elif os.WIFEXITED(status):
  819. # The child process exited (e.g sys.exit()).
  820. return os.WEXITSTATUS(status)
  821. else:
  822. # The child exited, but we don't understand its status.
  823. # This shouldn't happen, but if it does, let's just
  824. # return that status; perhaps that helps debug it.
  825. return status
  826. class BaseChildWatcher(AbstractChildWatcher):
  827. def __init__(self):
  828. self._loop = None
  829. self._callbacks = {}
  830. def close(self):
  831. self.attach_loop(None)
  832. def is_active(self):
  833. return self._loop is not None and self._loop.is_running()
  834. def _do_waitpid(self, expected_pid):
  835. raise NotImplementedError()
  836. def _do_waitpid_all(self):
  837. raise NotImplementedError()
  838. def attach_loop(self, loop):
  839. assert loop is None or isinstance(loop, events.AbstractEventLoop)
  840. if self._loop is not None and loop is None and self._callbacks:
  841. warnings.warn(
  842. 'A loop is being detached '
  843. 'from a child watcher with pending handlers',
  844. RuntimeWarning)
  845. if self._loop is not None:
  846. self._loop.remove_signal_handler(signal.SIGCHLD)
  847. self._loop = loop
  848. if loop is not None:
  849. loop.add_signal_handler(signal.SIGCHLD, self._sig_chld)
  850. # Prevent a race condition in case a child terminated
  851. # during the switch.
  852. self._do_waitpid_all()
  853. def _sig_chld(self):
  854. try:
  855. self._do_waitpid_all()
  856. except (SystemExit, KeyboardInterrupt):
  857. raise
  858. except BaseException as exc:
  859. # self._loop should always be available here
  860. # as '_sig_chld' is added as a signal handler
  861. # in 'attach_loop'
  862. self._loop.call_exception_handler({
  863. 'message': 'Unknown exception in SIGCHLD handler',
  864. 'exception': exc,
  865. })
  866. class SafeChildWatcher(BaseChildWatcher):
  867. """'Safe' child watcher implementation.
  868. This implementation avoids disrupting other code spawning processes by
  869. polling explicitly each process in the SIGCHLD handler instead of calling
  870. os.waitpid(-1).
  871. This is a safe solution but it has a significant overhead when handling a
  872. big number of children (O(n) each time SIGCHLD is raised)
  873. """
  874. def close(self):
  875. self._callbacks.clear()
  876. super().close()
  877. def __enter__(self):
  878. return self
  879. def __exit__(self, a, b, c):
  880. pass
  881. def add_child_handler(self, pid, callback, *args):
  882. self._callbacks[pid] = (callback, args)
  883. # Prevent a race condition in case the child is already terminated.
  884. self._do_waitpid(pid)
  885. def remove_child_handler(self, pid):
  886. try:
  887. del self._callbacks[pid]
  888. return True
  889. except KeyError:
  890. return False
  891. def _do_waitpid_all(self):
  892. for pid in list(self._callbacks):
  893. self._do_waitpid(pid)
  894. def _do_waitpid(self, expected_pid):
  895. assert expected_pid > 0
  896. try:
  897. pid, status = os.waitpid(expected_pid, os.WNOHANG)
  898. except ChildProcessError:
  899. # The child process is already reaped
  900. # (may happen if waitpid() is called elsewhere).
  901. pid = expected_pid
  902. returncode = 255
  903. logger.warning(
  904. "Unknown child process pid %d, will report returncode 255",
  905. pid)
  906. else:
  907. if pid == 0:
  908. # The child process is still alive.
  909. return
  910. returncode = _compute_returncode(status)
  911. if self._loop.get_debug():
  912. logger.debug('process %s exited with returncode %s',
  913. expected_pid, returncode)
  914. try:
  915. callback, args = self._callbacks.pop(pid)
  916. except KeyError: # pragma: no cover
  917. # May happen if .remove_child_handler() is called
  918. # after os.waitpid() returns.
  919. if self._loop.get_debug():
  920. logger.warning("Child watcher got an unexpected pid: %r",
  921. pid, exc_info=True)
  922. else:
  923. callback(pid, returncode, *args)
  924. class FastChildWatcher(BaseChildWatcher):
  925. """'Fast' child watcher implementation.
  926. This implementation reaps every terminated processes by calling
  927. os.waitpid(-1) directly, possibly breaking other code spawning processes
  928. and waiting for their termination.
  929. There is no noticeable overhead when handling a big number of children
  930. (O(1) each time a child terminates).
  931. """
  932. def __init__(self):
  933. super().__init__()
  934. self._lock = threading.Lock()
  935. self._zombies = {}
  936. self._forks = 0
  937. def close(self):
  938. self._callbacks.clear()
  939. self._zombies.clear()
  940. super().close()
  941. def __enter__(self):
  942. with self._lock:
  943. self._forks += 1
  944. return self
  945. def __exit__(self, a, b, c):
  946. with self._lock:
  947. self._forks -= 1
  948. if self._forks or not self._zombies:
  949. return
  950. collateral_victims = str(self._zombies)
  951. self._zombies.clear()
  952. logger.warning(
  953. "Caught subprocesses termination from unknown pids: %s",
  954. collateral_victims)
  955. def add_child_handler(self, pid, callback, *args):
  956. assert self._forks, "Must use the context manager"
  957. with self._lock:
  958. try:
  959. returncode = self._zombies.pop(pid)
  960. except KeyError:
  961. # The child is running.
  962. self._callbacks[pid] = callback, args
  963. return
  964. # The child is dead already. We can fire the callback.
  965. callback(pid, returncode, *args)
  966. def remove_child_handler(self, pid):
  967. try:
  968. del self._callbacks[pid]
  969. return True
  970. except KeyError:
  971. return False
  972. def _do_waitpid_all(self):
  973. # Because of signal coalescing, we must keep calling waitpid() as
  974. # long as we're able to reap a child.
  975. while True:
  976. try:
  977. pid, status = os.waitpid(-1, os.WNOHANG)
  978. except ChildProcessError:
  979. # No more child processes exist.
  980. return
  981. else:
  982. if pid == 0:
  983. # A child process is still alive.
  984. return
  985. returncode = _compute_returncode(status)
  986. with self._lock:
  987. try:
  988. callback, args = self._callbacks.pop(pid)
  989. except KeyError:
  990. # unknown child
  991. if self._forks:
  992. # It may not be registered yet.
  993. self._zombies[pid] = returncode
  994. if self._loop.get_debug():
  995. logger.debug('unknown process %s exited '
  996. 'with returncode %s',
  997. pid, returncode)
  998. continue
  999. callback = None
  1000. else:
  1001. if self._loop.get_debug():
  1002. logger.debug('process %s exited with returncode %s',
  1003. pid, returncode)
  1004. if callback is None:
  1005. logger.warning(
  1006. "Caught subprocess termination from unknown pid: "
  1007. "%d -> %d", pid, returncode)
  1008. else:
  1009. callback(pid, returncode, *args)
  1010. class MultiLoopChildWatcher(AbstractChildWatcher):
  1011. """A watcher that doesn't require running loop in the main thread.
  1012. This implementation registers a SIGCHLD signal handler on
  1013. instantiation (which may conflict with other code that
  1014. install own handler for this signal).
  1015. The solution is safe but it has a significant overhead when
  1016. handling a big number of processes (*O(n)* each time a
  1017. SIGCHLD is received).
  1018. """
  1019. # Implementation note:
  1020. # The class keeps compatibility with AbstractChildWatcher ABC
  1021. # To achieve this it has empty attach_loop() method
  1022. # and doesn't accept explicit loop argument
  1023. # for add_child_handler()/remove_child_handler()
  1024. # but retrieves the current loop by get_running_loop()
  1025. def __init__(self):
  1026. self._callbacks = {}
  1027. self._saved_sighandler = None
  1028. def is_active(self):
  1029. return self._saved_sighandler is not None
  1030. def close(self):
  1031. self._callbacks.clear()
  1032. if self._saved_sighandler is None:
  1033. return
  1034. handler = signal.getsignal(signal.SIGCHLD)
  1035. if handler != self._sig_chld:
  1036. logger.warning("SIGCHLD handler was changed by outside code")
  1037. else:
  1038. signal.signal(signal.SIGCHLD, self._saved_sighandler)
  1039. self._saved_sighandler = None
  1040. def __enter__(self):
  1041. return self
  1042. def __exit__(self, exc_type, exc_val, exc_tb):
  1043. pass
  1044. def add_child_handler(self, pid, callback, *args):
  1045. loop = events.get_running_loop()
  1046. self._callbacks[pid] = (loop, callback, args)
  1047. # Prevent a race condition in case the child is already terminated.
  1048. self._do_waitpid(pid)
  1049. def remove_child_handler(self, pid):
  1050. try:
  1051. del self._callbacks[pid]
  1052. return True
  1053. except KeyError:
  1054. return False
  1055. def attach_loop(self, loop):
  1056. # Don't save the loop but initialize itself if called first time
  1057. # The reason to do it here is that attach_loop() is called from
  1058. # unix policy only for the main thread.
  1059. # Main thread is required for subscription on SIGCHLD signal
  1060. if self._saved_sighandler is not None:
  1061. return
  1062. self._saved_sighandler = signal.signal(signal.SIGCHLD, self._sig_chld)
  1063. if self._saved_sighandler is None:
  1064. logger.warning("Previous SIGCHLD handler was set by non-Python code, "
  1065. "restore to default handler on watcher close.")
  1066. self._saved_sighandler = signal.SIG_DFL
  1067. # Set SA_RESTART to limit EINTR occurrences.
  1068. signal.siginterrupt(signal.SIGCHLD, False)
  1069. def _do_waitpid_all(self):
  1070. for pid in list(self._callbacks):
  1071. self._do_waitpid(pid)
  1072. def _do_waitpid(self, expected_pid):
  1073. assert expected_pid > 0
  1074. try:
  1075. pid, status = os.waitpid(expected_pid, os.WNOHANG)
  1076. except ChildProcessError:
  1077. # The child process is already reaped
  1078. # (may happen if waitpid() is called elsewhere).
  1079. pid = expected_pid
  1080. returncode = 255
  1081. logger.warning(
  1082. "Unknown child process pid %d, will report returncode 255",
  1083. pid)
  1084. debug_log = False
  1085. else:
  1086. if pid == 0:
  1087. # The child process is still alive.
  1088. return
  1089. returncode = _compute_returncode(status)
  1090. debug_log = True
  1091. try:
  1092. loop, callback, args = self._callbacks.pop(pid)
  1093. except KeyError: # pragma: no cover
  1094. # May happen if .remove_child_handler() is called
  1095. # after os.waitpid() returns.
  1096. logger.warning("Child watcher got an unexpected pid: %r",
  1097. pid, exc_info=True)
  1098. else:
  1099. if loop.is_closed():
  1100. logger.warning("Loop %r that handles pid %r is closed", loop, pid)
  1101. else:
  1102. if debug_log and loop.get_debug():
  1103. logger.debug('process %s exited with returncode %s',
  1104. expected_pid, returncode)
  1105. loop.call_soon_threadsafe(callback, pid, returncode, *args)
  1106. def _sig_chld(self, signum, frame):
  1107. try:
  1108. self._do_waitpid_all()
  1109. except (SystemExit, KeyboardInterrupt):
  1110. raise
  1111. except BaseException:
  1112. logger.warning('Unknown exception in SIGCHLD handler', exc_info=True)
  1113. class ThreadedChildWatcher(AbstractChildWatcher):
  1114. """Threaded child watcher implementation.
  1115. The watcher uses a thread per process
  1116. for waiting for the process finish.
  1117. It doesn't require subscription on POSIX signal
  1118. but a thread creation is not free.
  1119. The watcher has O(1) complexity, its performance doesn't depend
  1120. on amount of spawn processes.
  1121. """
  1122. def __init__(self):
  1123. self._pid_counter = itertools.count(0)
  1124. self._threads = {}
  1125. def is_active(self):
  1126. return True
  1127. def close(self):
  1128. self._join_threads()
  1129. def _join_threads(self):
  1130. """Internal: Join all non-daemon threads"""
  1131. threads = [thread for thread in list(self._threads.values())
  1132. if thread.is_alive() and not thread.daemon]
  1133. for thread in threads:
  1134. thread.join()
  1135. def __enter__(self):
  1136. return self
  1137. def __exit__(self, exc_type, exc_val, exc_tb):
  1138. pass
  1139. def __del__(self, _warn=warnings.warn):
  1140. threads = [thread for thread in list(self._threads.values())
  1141. if thread.is_alive()]
  1142. if threads:
  1143. _warn(f"{self.__class__} has registered but not finished child processes",
  1144. ResourceWarning,
  1145. source=self)
  1146. def add_child_handler(self, pid, callback, *args):
  1147. loop = events.get_running_loop()
  1148. thread = threading.Thread(target=self._do_waitpid,
  1149. name=f"waitpid-{next(self._pid_counter)}",
  1150. args=(loop, pid, callback, args),
  1151. daemon=True)
  1152. self._threads[pid] = thread
  1153. thread.start()
  1154. def remove_child_handler(self, pid):
  1155. # asyncio never calls remove_child_handler() !!!
  1156. # The method is no-op but is implemented because
  1157. # abstract base classes require it.
  1158. return True
  1159. def attach_loop(self, loop):
  1160. pass
  1161. def _do_waitpid(self, loop, expected_pid, callback, args):
  1162. assert expected_pid > 0
  1163. try:
  1164. pid, status = os.waitpid(expected_pid, 0)
  1165. except ChildProcessError:
  1166. # The child process is already reaped
  1167. # (may happen if waitpid() is called elsewhere).
  1168. pid = expected_pid
  1169. returncode = 255
  1170. logger.warning(
  1171. "Unknown child process pid %d, will report returncode 255",
  1172. pid)
  1173. else:
  1174. returncode = _compute_returncode(status)
  1175. if loop.get_debug():
  1176. logger.debug('process %s exited with returncode %s',
  1177. expected_pid, returncode)
  1178. if loop.is_closed():
  1179. logger.warning("Loop %r that handles pid %r is closed", loop, pid)
  1180. else:
  1181. loop.call_soon_threadsafe(callback, pid, returncode, *args)
  1182. self._threads.pop(expected_pid)
  1183. class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):
  1184. """UNIX event loop policy with a watcher for child processes."""
  1185. _loop_factory = _UnixSelectorEventLoop
  1186. def __init__(self):
  1187. super().__init__()
  1188. self._watcher = None
  1189. def _init_watcher(self):
  1190. with events._lock:
  1191. if self._watcher is None: # pragma: no branch
  1192. self._watcher = ThreadedChildWatcher()
  1193. if threading.current_thread() is threading.main_thread():
  1194. self._watcher.attach_loop(self._local._loop)
  1195. def set_event_loop(self, loop):
  1196. """Set the event loop.
  1197. As a side effect, if a child watcher was set before, then calling
  1198. .set_event_loop() from the main thread will call .attach_loop(loop) on
  1199. the child watcher.
  1200. """
  1201. super().set_event_loop(loop)
  1202. if (self._watcher is not None and
  1203. threading.current_thread() is threading.main_thread()):
  1204. self._watcher.attach_loop(loop)
  1205. def get_child_watcher(self):
  1206. """Get the watcher for child processes.
  1207. If not yet set, a ThreadedChildWatcher object is automatically created.
  1208. """
  1209. if self._watcher is None:
  1210. self._init_watcher()
  1211. return self._watcher
  1212. def set_child_watcher(self, watcher):
  1213. """Set the watcher for child processes."""
  1214. assert watcher is None or isinstance(watcher, AbstractChildWatcher)
  1215. if self._watcher is not None:
  1216. self._watcher.close()
  1217. self._watcher = watcher
  1218. SelectorEventLoop = _UnixSelectorEventLoop
  1219. DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy