unix_events.py 52 KB

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