unix_events.py 52 KB

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