base_events.py 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010
  1. """Base implementation of event loop.
  2. The event loop can be broken up into a multiplexer (the part
  3. responsible for notifying us of I/O events) and the event loop proper,
  4. which wraps a multiplexer with functionality for scheduling callbacks,
  5. immediately or at a given time in the future.
  6. Whenever a public API takes a callback, subsequent positional
  7. arguments will be passed to the callback if/when it is called. This
  8. avoids the proliferation of trivial lambdas implementing closures.
  9. Keyword arguments for the callback are not supported; this is a
  10. conscious design decision, leaving the door open for keyword arguments
  11. to modify the meaning of the API call itself.
  12. """
  13. import collections
  14. import collections.abc
  15. import concurrent.futures
  16. import errno
  17. import functools
  18. import heapq
  19. import itertools
  20. import os
  21. import socket
  22. import stat
  23. import subprocess
  24. import threading
  25. import time
  26. import traceback
  27. import sys
  28. import warnings
  29. import weakref
  30. try:
  31. import ssl
  32. except ImportError: # pragma: no cover
  33. ssl = None
  34. from . import constants
  35. from . import coroutines
  36. from . import events
  37. from . import exceptions
  38. from . import futures
  39. from . import protocols
  40. from . import sslproto
  41. from . import staggered
  42. from . import tasks
  43. from . import transports
  44. from . import trsock
  45. from .log import logger
  46. __all__ = 'BaseEventLoop','Server',
  47. # Minimum number of _scheduled timer handles before cleanup of
  48. # cancelled handles is performed.
  49. _MIN_SCHEDULED_TIMER_HANDLES = 100
  50. # Minimum fraction of _scheduled timer handles that are cancelled
  51. # before cleanup of cancelled handles is performed.
  52. _MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
  53. _HAS_IPv6 = hasattr(socket, 'AF_INET6')
  54. # Maximum timeout passed to select to avoid OS limitations
  55. MAXIMUM_SELECT_TIMEOUT = 24 * 3600
  56. def _format_handle(handle):
  57. cb = handle._callback
  58. if isinstance(getattr(cb, '__self__', None), tasks.Task):
  59. # format the task
  60. return repr(cb.__self__)
  61. else:
  62. return str(handle)
  63. def _format_pipe(fd):
  64. if fd == subprocess.PIPE:
  65. return '<pipe>'
  66. elif fd == subprocess.STDOUT:
  67. return '<stdout>'
  68. else:
  69. return repr(fd)
  70. def _set_reuseport(sock):
  71. if not hasattr(socket, 'SO_REUSEPORT'):
  72. raise ValueError('reuse_port not supported by socket module')
  73. else:
  74. try:
  75. sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  76. except OSError:
  77. raise ValueError('reuse_port not supported by socket module, '
  78. 'SO_REUSEPORT defined but not implemented.')
  79. def _ipaddr_info(host, port, family, type, proto, flowinfo=0, scopeid=0):
  80. # Try to skip getaddrinfo if "host" is already an IP. Users might have
  81. # handled name resolution in their own code and pass in resolved IPs.
  82. if not hasattr(socket, 'inet_pton'):
  83. return
  84. if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
  85. host is None:
  86. return None
  87. if type == socket.SOCK_STREAM:
  88. proto = socket.IPPROTO_TCP
  89. elif type == socket.SOCK_DGRAM:
  90. proto = socket.IPPROTO_UDP
  91. else:
  92. return None
  93. if port is None:
  94. port = 0
  95. elif isinstance(port, bytes) and port == b'':
  96. port = 0
  97. elif isinstance(port, str) and port == '':
  98. port = 0
  99. else:
  100. # If port's a service name like "http", don't skip getaddrinfo.
  101. try:
  102. port = int(port)
  103. except (TypeError, ValueError):
  104. return None
  105. if family == socket.AF_UNSPEC:
  106. afs = [socket.AF_INET]
  107. if _HAS_IPv6:
  108. afs.append(socket.AF_INET6)
  109. else:
  110. afs = [family]
  111. if isinstance(host, bytes):
  112. host = host.decode('idna')
  113. if '%' in host:
  114. # Linux's inet_pton doesn't accept an IPv6 zone index after host,
  115. # like '::1%lo0'.
  116. return None
  117. for af in afs:
  118. try:
  119. socket.inet_pton(af, host)
  120. # The host has already been resolved.
  121. if _HAS_IPv6 and af == socket.AF_INET6:
  122. return af, type, proto, '', (host, port, flowinfo, scopeid)
  123. else:
  124. return af, type, proto, '', (host, port)
  125. except OSError:
  126. pass
  127. # "host" is not an IP address.
  128. return None
  129. def _interleave_addrinfos(addrinfos, first_address_family_count=1):
  130. """Interleave list of addrinfo tuples by family."""
  131. # Group addresses by family
  132. addrinfos_by_family = collections.OrderedDict()
  133. for addr in addrinfos:
  134. family = addr[0]
  135. if family not in addrinfos_by_family:
  136. addrinfos_by_family[family] = []
  137. addrinfos_by_family[family].append(addr)
  138. addrinfos_lists = list(addrinfos_by_family.values())
  139. reordered = []
  140. if first_address_family_count > 1:
  141. reordered.extend(addrinfos_lists[0][:first_address_family_count - 1])
  142. del addrinfos_lists[0][:first_address_family_count - 1]
  143. reordered.extend(
  144. a for a in itertools.chain.from_iterable(
  145. itertools.zip_longest(*addrinfos_lists)
  146. ) if a is not None)
  147. return reordered
  148. def _run_until_complete_cb(fut):
  149. if not fut.cancelled():
  150. exc = fut.exception()
  151. if isinstance(exc, (SystemExit, KeyboardInterrupt)):
  152. # Issue #22429: run_forever() already finished, no need to
  153. # stop it.
  154. return
  155. futures._get_loop(fut).stop()
  156. if hasattr(socket, 'TCP_NODELAY'):
  157. def _set_nodelay(sock):
  158. if (sock.family in {socket.AF_INET, socket.AF_INET6} and
  159. sock.type == socket.SOCK_STREAM and
  160. sock.proto == socket.IPPROTO_TCP):
  161. sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  162. else:
  163. def _set_nodelay(sock):
  164. pass
  165. def _check_ssl_socket(sock):
  166. if ssl is not None and isinstance(sock, ssl.SSLSocket):
  167. raise TypeError("Socket cannot be of type SSLSocket")
  168. class _SendfileFallbackProtocol(protocols.Protocol):
  169. def __init__(self, transp):
  170. if not isinstance(transp, transports._FlowControlMixin):
  171. raise TypeError("transport should be _FlowControlMixin instance")
  172. self._transport = transp
  173. self._proto = transp.get_protocol()
  174. self._should_resume_reading = transp.is_reading()
  175. self._should_resume_writing = transp._protocol_paused
  176. transp.pause_reading()
  177. transp.set_protocol(self)
  178. if self._should_resume_writing:
  179. self._write_ready_fut = self._transport._loop.create_future()
  180. else:
  181. self._write_ready_fut = None
  182. async def drain(self):
  183. if self._transport.is_closing():
  184. raise ConnectionError("Connection closed by peer")
  185. fut = self._write_ready_fut
  186. if fut is None:
  187. return
  188. await fut
  189. def connection_made(self, transport):
  190. raise RuntimeError("Invalid state: "
  191. "connection should have been established already.")
  192. def connection_lost(self, exc):
  193. if self._write_ready_fut is not None:
  194. # Never happens if peer disconnects after sending the whole content
  195. # Thus disconnection is always an exception from user perspective
  196. if exc is None:
  197. self._write_ready_fut.set_exception(
  198. ConnectionError("Connection is closed by peer"))
  199. else:
  200. self._write_ready_fut.set_exception(exc)
  201. self._proto.connection_lost(exc)
  202. def pause_writing(self):
  203. if self._write_ready_fut is not None:
  204. return
  205. self._write_ready_fut = self._transport._loop.create_future()
  206. def resume_writing(self):
  207. if self._write_ready_fut is None:
  208. return
  209. self._write_ready_fut.set_result(False)
  210. self._write_ready_fut = None
  211. def data_received(self, data):
  212. raise RuntimeError("Invalid state: reading should be paused")
  213. def eof_received(self):
  214. raise RuntimeError("Invalid state: reading should be paused")
  215. async def restore(self):
  216. self._transport.set_protocol(self._proto)
  217. if self._should_resume_reading:
  218. self._transport.resume_reading()
  219. if self._write_ready_fut is not None:
  220. # Cancel the future.
  221. # Basically it has no effect because protocol is switched back,
  222. # no code should wait for it anymore.
  223. self._write_ready_fut.cancel()
  224. if self._should_resume_writing:
  225. self._proto.resume_writing()
  226. class Server(events.AbstractServer):
  227. def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
  228. ssl_handshake_timeout, ssl_shutdown_timeout=None):
  229. self._loop = loop
  230. self._sockets = sockets
  231. self._active_count = 0
  232. self._waiters = []
  233. self._protocol_factory = protocol_factory
  234. self._backlog = backlog
  235. self._ssl_context = ssl_context
  236. self._ssl_handshake_timeout = ssl_handshake_timeout
  237. self._ssl_shutdown_timeout = ssl_shutdown_timeout
  238. self._serving = False
  239. self._serving_forever_fut = None
  240. def __repr__(self):
  241. return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
  242. def _attach(self):
  243. assert self._sockets is not None
  244. self._active_count += 1
  245. def _detach(self):
  246. assert self._active_count > 0
  247. self._active_count -= 1
  248. if self._active_count == 0 and self._sockets is None:
  249. self._wakeup()
  250. def _wakeup(self):
  251. waiters = self._waiters
  252. self._waiters = None
  253. for waiter in waiters:
  254. if not waiter.done():
  255. waiter.set_result(None)
  256. def _start_serving(self):
  257. if self._serving:
  258. return
  259. self._serving = True
  260. for sock in self._sockets:
  261. sock.listen(self._backlog)
  262. self._loop._start_serving(
  263. self._protocol_factory, sock, self._ssl_context,
  264. self, self._backlog, self._ssl_handshake_timeout,
  265. self._ssl_shutdown_timeout)
  266. def get_loop(self):
  267. return self._loop
  268. def is_serving(self):
  269. return self._serving
  270. @property
  271. def sockets(self):
  272. if self._sockets is None:
  273. return ()
  274. return tuple(trsock.TransportSocket(s) for s in self._sockets)
  275. def close(self):
  276. sockets = self._sockets
  277. if sockets is None:
  278. return
  279. self._sockets = None
  280. for sock in sockets:
  281. self._loop._stop_serving(sock)
  282. self._serving = False
  283. if (self._serving_forever_fut is not None and
  284. not self._serving_forever_fut.done()):
  285. self._serving_forever_fut.cancel()
  286. self._serving_forever_fut = None
  287. if self._active_count == 0:
  288. self._wakeup()
  289. async def start_serving(self):
  290. self._start_serving()
  291. # Skip one loop iteration so that all 'loop.add_reader'
  292. # go through.
  293. await tasks.sleep(0)
  294. async def serve_forever(self):
  295. if self._serving_forever_fut is not None:
  296. raise RuntimeError(
  297. f'server {self!r} is already being awaited on serve_forever()')
  298. if self._sockets is None:
  299. raise RuntimeError(f'server {self!r} is closed')
  300. self._start_serving()
  301. self._serving_forever_fut = self._loop.create_future()
  302. try:
  303. await self._serving_forever_fut
  304. except exceptions.CancelledError:
  305. try:
  306. self.close()
  307. await self.wait_closed()
  308. finally:
  309. raise
  310. finally:
  311. self._serving_forever_fut = None
  312. async def wait_closed(self):
  313. """Wait until server is closed and all connections are dropped.
  314. - If the server is not closed, wait.
  315. - If it is closed, but there are still active connections, wait.
  316. Anyone waiting here will be unblocked once both conditions
  317. (server is closed and all connections have been dropped)
  318. have become true, in either order.
  319. Historical note: In 3.11 and before, this was broken, returning
  320. immediately if the server was already closed, even if there
  321. were still active connections. An attempted fix in 3.12.0 was
  322. still broken, returning immediately if the server was still
  323. open and there were no active connections. Hopefully in 3.12.1
  324. we have it right.
  325. """
  326. # Waiters are unblocked by self._wakeup(), which is called
  327. # from two places: self.close() and self._detach(), but only
  328. # when both conditions have become true. To signal that this
  329. # has happened, self._wakeup() sets self._waiters to None.
  330. if self._waiters is None:
  331. return
  332. waiter = self._loop.create_future()
  333. self._waiters.append(waiter)
  334. await waiter
  335. class BaseEventLoop(events.AbstractEventLoop):
  336. def __init__(self):
  337. self._timer_cancelled_count = 0
  338. self._closed = False
  339. self._stopping = False
  340. self._ready = collections.deque()
  341. self._scheduled = []
  342. self._default_executor = None
  343. self._internal_fds = 0
  344. # Identifier of the thread running the event loop, or None if the
  345. # event loop is not running
  346. self._thread_id = None
  347. self._clock_resolution = time.get_clock_info('monotonic').resolution
  348. self._exception_handler = None
  349. self.set_debug(coroutines._is_debug_mode())
  350. # In debug mode, if the execution of a callback or a step of a task
  351. # exceed this duration in seconds, the slow callback/task is logged.
  352. self.slow_callback_duration = 0.1
  353. self._current_handle = None
  354. self._task_factory = None
  355. self._coroutine_origin_tracking_enabled = False
  356. self._coroutine_origin_tracking_saved_depth = None
  357. # A weak set of all asynchronous generators that are
  358. # being iterated by the loop.
  359. self._asyncgens = weakref.WeakSet()
  360. # Set to True when `loop.shutdown_asyncgens` is called.
  361. self._asyncgens_shutdown_called = False
  362. # Set to True when `loop.shutdown_default_executor` is called.
  363. self._executor_shutdown_called = False
  364. def __repr__(self):
  365. return (
  366. f'<{self.__class__.__name__} running={self.is_running()} '
  367. f'closed={self.is_closed()} debug={self.get_debug()}>'
  368. )
  369. def create_future(self):
  370. """Create a Future object attached to the loop."""
  371. return futures.Future(loop=self)
  372. def create_task(self, coro, *, name=None, context=None):
  373. """Schedule a coroutine object.
  374. Return a task object.
  375. """
  376. self._check_closed()
  377. if self._task_factory is None:
  378. task = tasks.Task(coro, loop=self, name=name, context=context)
  379. if task._source_traceback:
  380. del task._source_traceback[-1]
  381. else:
  382. if context is None:
  383. # Use legacy API if context is not needed
  384. task = self._task_factory(self, coro)
  385. else:
  386. task = self._task_factory(self, coro, context=context)
  387. tasks._set_task_name(task, name)
  388. return task
  389. def set_task_factory(self, factory):
  390. """Set a task factory that will be used by loop.create_task().
  391. If factory is None the default task factory will be set.
  392. If factory is a callable, it should have a signature matching
  393. '(loop, coro)', where 'loop' will be a reference to the active
  394. event loop, 'coro' will be a coroutine object. The callable
  395. must return a Future.
  396. """
  397. if factory is not None and not callable(factory):
  398. raise TypeError('task factory must be a callable or None')
  399. self._task_factory = factory
  400. def get_task_factory(self):
  401. """Return a task factory, or None if the default one is in use."""
  402. return self._task_factory
  403. def _make_socket_transport(self, sock, protocol, waiter=None, *,
  404. extra=None, server=None):
  405. """Create socket transport."""
  406. raise NotImplementedError
  407. def _make_ssl_transport(
  408. self, rawsock, protocol, sslcontext, waiter=None,
  409. *, server_side=False, server_hostname=None,
  410. extra=None, server=None,
  411. ssl_handshake_timeout=None,
  412. ssl_shutdown_timeout=None,
  413. call_connection_made=True):
  414. """Create SSL transport."""
  415. raise NotImplementedError
  416. def _make_datagram_transport(self, sock, protocol,
  417. address=None, waiter=None, extra=None):
  418. """Create datagram transport."""
  419. raise NotImplementedError
  420. def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
  421. extra=None):
  422. """Create read pipe transport."""
  423. raise NotImplementedError
  424. def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
  425. extra=None):
  426. """Create write pipe transport."""
  427. raise NotImplementedError
  428. async def _make_subprocess_transport(self, protocol, args, shell,
  429. stdin, stdout, stderr, bufsize,
  430. extra=None, **kwargs):
  431. """Create subprocess transport."""
  432. raise NotImplementedError
  433. def _write_to_self(self):
  434. """Write a byte to self-pipe, to wake up the event loop.
  435. This may be called from a different thread.
  436. The subclass is responsible for implementing the self-pipe.
  437. """
  438. raise NotImplementedError
  439. def _process_events(self, event_list):
  440. """Process selector events."""
  441. raise NotImplementedError
  442. def _check_closed(self):
  443. if self._closed:
  444. raise RuntimeError('Event loop is closed')
  445. def _check_default_executor(self):
  446. if self._executor_shutdown_called:
  447. raise RuntimeError('Executor shutdown has been called')
  448. def _asyncgen_finalizer_hook(self, agen):
  449. self._asyncgens.discard(agen)
  450. if not self.is_closed():
  451. self.call_soon_threadsafe(self.create_task, agen.aclose())
  452. def _asyncgen_firstiter_hook(self, agen):
  453. if self._asyncgens_shutdown_called:
  454. warnings.warn(
  455. f"asynchronous generator {agen!r} was scheduled after "
  456. f"loop.shutdown_asyncgens() call",
  457. ResourceWarning, source=self)
  458. self._asyncgens.add(agen)
  459. async def shutdown_asyncgens(self):
  460. """Shutdown all active asynchronous generators."""
  461. self._asyncgens_shutdown_called = True
  462. if not len(self._asyncgens):
  463. # If Python version is <3.6 or we don't have any asynchronous
  464. # generators alive.
  465. return
  466. closing_agens = list(self._asyncgens)
  467. self._asyncgens.clear()
  468. results = await tasks.gather(
  469. *[ag.aclose() for ag in closing_agens],
  470. return_exceptions=True)
  471. for result, agen in zip(results, closing_agens):
  472. if isinstance(result, Exception):
  473. self.call_exception_handler({
  474. 'message': f'an error occurred during closing of '
  475. f'asynchronous generator {agen!r}',
  476. 'exception': result,
  477. 'asyncgen': agen
  478. })
  479. async def shutdown_default_executor(self, timeout=None):
  480. """Schedule the shutdown of the default executor.
  481. The timeout parameter specifies the amount of time the executor will
  482. be given to finish joining. The default value is None, which means
  483. that the executor will be given an unlimited amount of time.
  484. """
  485. self._executor_shutdown_called = True
  486. if self._default_executor is None:
  487. return
  488. future = self.create_future()
  489. thread = threading.Thread(target=self._do_shutdown, args=(future,))
  490. thread.start()
  491. try:
  492. await future
  493. finally:
  494. thread.join(timeout)
  495. if thread.is_alive():
  496. warnings.warn("The executor did not finishing joining "
  497. f"its threads within {timeout} seconds.",
  498. RuntimeWarning, stacklevel=2)
  499. self._default_executor.shutdown(wait=False)
  500. def _do_shutdown(self, future):
  501. try:
  502. self._default_executor.shutdown(wait=True)
  503. if not self.is_closed():
  504. self.call_soon_threadsafe(future.set_result, None)
  505. except Exception as ex:
  506. if not self.is_closed():
  507. self.call_soon_threadsafe(future.set_exception, ex)
  508. def _check_running(self):
  509. if self.is_running():
  510. raise RuntimeError('This event loop is already running')
  511. if events._get_running_loop() is not None:
  512. raise RuntimeError(
  513. 'Cannot run the event loop while another loop is running')
  514. def run_forever(self):
  515. """Run until stop() is called."""
  516. self._check_closed()
  517. self._check_running()
  518. self._set_coroutine_origin_tracking(self._debug)
  519. old_agen_hooks = sys.get_asyncgen_hooks()
  520. try:
  521. self._thread_id = threading.get_ident()
  522. sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
  523. finalizer=self._asyncgen_finalizer_hook)
  524. events._set_running_loop(self)
  525. while True:
  526. self._run_once()
  527. if self._stopping:
  528. break
  529. finally:
  530. self._stopping = False
  531. self._thread_id = None
  532. events._set_running_loop(None)
  533. self._set_coroutine_origin_tracking(False)
  534. sys.set_asyncgen_hooks(*old_agen_hooks)
  535. def run_until_complete(self, future):
  536. """Run until the Future is done.
  537. If the argument is a coroutine, it is wrapped in a Task.
  538. WARNING: It would be disastrous to call run_until_complete()
  539. with the same coroutine twice -- it would wrap it in two
  540. different Tasks and that can't be good.
  541. Return the Future's result, or raise its exception.
  542. """
  543. self._check_closed()
  544. self._check_running()
  545. new_task = not futures.isfuture(future)
  546. future = tasks.ensure_future(future, loop=self)
  547. if new_task:
  548. # An exception is raised if the future didn't complete, so there
  549. # is no need to log the "destroy pending task" message
  550. future._log_destroy_pending = False
  551. future.add_done_callback(_run_until_complete_cb)
  552. try:
  553. self.run_forever()
  554. except:
  555. if new_task and future.done() and not future.cancelled():
  556. # The coroutine raised a BaseException. Consume the exception
  557. # to not log a warning, the caller doesn't have access to the
  558. # local task.
  559. future.exception()
  560. raise
  561. finally:
  562. future.remove_done_callback(_run_until_complete_cb)
  563. if not future.done():
  564. raise RuntimeError('Event loop stopped before Future completed.')
  565. return future.result()
  566. def stop(self):
  567. """Stop running the event loop.
  568. Every callback already scheduled will still run. This simply informs
  569. run_forever to stop looping after a complete iteration.
  570. """
  571. self._stopping = True
  572. def close(self):
  573. """Close the event loop.
  574. This clears the queues and shuts down the executor,
  575. but does not wait for the executor to finish.
  576. The event loop must not be running.
  577. """
  578. if self.is_running():
  579. raise RuntimeError("Cannot close a running event loop")
  580. if self._closed:
  581. return
  582. if self._debug:
  583. logger.debug("Close %r", self)
  584. self._closed = True
  585. self._ready.clear()
  586. self._scheduled.clear()
  587. self._executor_shutdown_called = True
  588. executor = self._default_executor
  589. if executor is not None:
  590. self._default_executor = None
  591. executor.shutdown(wait=False)
  592. def is_closed(self):
  593. """Returns True if the event loop was closed."""
  594. return self._closed
  595. def __del__(self, _warn=warnings.warn):
  596. if not self.is_closed():
  597. _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
  598. if not self.is_running():
  599. self.close()
  600. def is_running(self):
  601. """Returns True if the event loop is running."""
  602. return (self._thread_id is not None)
  603. def time(self):
  604. """Return the time according to the event loop's clock.
  605. This is a float expressed in seconds since an epoch, but the
  606. epoch, precision, accuracy and drift are unspecified and may
  607. differ per event loop.
  608. """
  609. return time.monotonic()
  610. def call_later(self, delay, callback, *args, context=None):
  611. """Arrange for a callback to be called at a given time.
  612. Return a Handle: an opaque object with a cancel() method that
  613. can be used to cancel the call.
  614. The delay can be an int or float, expressed in seconds. It is
  615. always relative to the current time.
  616. Each callback will be called exactly once. If two callbacks
  617. are scheduled for exactly the same time, it is undefined which
  618. will be called first.
  619. Any positional arguments after the callback will be passed to
  620. the callback when it is called.
  621. """
  622. if delay is None:
  623. raise TypeError('delay must not be None')
  624. timer = self.call_at(self.time() + delay, callback, *args,
  625. context=context)
  626. if timer._source_traceback:
  627. del timer._source_traceback[-1]
  628. return timer
  629. def call_at(self, when, callback, *args, context=None):
  630. """Like call_later(), but uses an absolute time.
  631. Absolute time corresponds to the event loop's time() method.
  632. """
  633. if when is None:
  634. raise TypeError("when cannot be None")
  635. self._check_closed()
  636. if self._debug:
  637. self._check_thread()
  638. self._check_callback(callback, 'call_at')
  639. timer = events.TimerHandle(when, callback, args, self, context)
  640. if timer._source_traceback:
  641. del timer._source_traceback[-1]
  642. heapq.heappush(self._scheduled, timer)
  643. timer._scheduled = True
  644. return timer
  645. def call_soon(self, callback, *args, context=None):
  646. """Arrange for a callback to be called as soon as possible.
  647. This operates as a FIFO queue: callbacks are called in the
  648. order in which they are registered. Each callback will be
  649. called exactly once.
  650. Any positional arguments after the callback will be passed to
  651. the callback when it is called.
  652. """
  653. self._check_closed()
  654. if self._debug:
  655. self._check_thread()
  656. self._check_callback(callback, 'call_soon')
  657. handle = self._call_soon(callback, args, context)
  658. if handle._source_traceback:
  659. del handle._source_traceback[-1]
  660. return handle
  661. def _check_callback(self, callback, method):
  662. if (coroutines.iscoroutine(callback) or
  663. coroutines.iscoroutinefunction(callback)):
  664. raise TypeError(
  665. f"coroutines cannot be used with {method}()")
  666. if not callable(callback):
  667. raise TypeError(
  668. f'a callable object was expected by {method}(), '
  669. f'got {callback!r}')
  670. def _call_soon(self, callback, args, context):
  671. handle = events.Handle(callback, args, self, context)
  672. if handle._source_traceback:
  673. del handle._source_traceback[-1]
  674. self._ready.append(handle)
  675. return handle
  676. def _check_thread(self):
  677. """Check that the current thread is the thread running the event loop.
  678. Non-thread-safe methods of this class make this assumption and will
  679. likely behave incorrectly when the assumption is violated.
  680. Should only be called when (self._debug == True). The caller is
  681. responsible for checking this condition for performance reasons.
  682. """
  683. if self._thread_id is None:
  684. return
  685. thread_id = threading.get_ident()
  686. if thread_id != self._thread_id:
  687. raise RuntimeError(
  688. "Non-thread-safe operation invoked on an event loop other "
  689. "than the current one")
  690. def call_soon_threadsafe(self, callback, *args, context=None):
  691. """Like call_soon(), but thread-safe."""
  692. self._check_closed()
  693. if self._debug:
  694. self._check_callback(callback, 'call_soon_threadsafe')
  695. handle = self._call_soon(callback, args, context)
  696. if handle._source_traceback:
  697. del handle._source_traceback[-1]
  698. self._write_to_self()
  699. return handle
  700. def run_in_executor(self, executor, func, *args):
  701. self._check_closed()
  702. if self._debug:
  703. self._check_callback(func, 'run_in_executor')
  704. if executor is None:
  705. executor = self._default_executor
  706. # Only check when the default executor is being used
  707. self._check_default_executor()
  708. if executor is None:
  709. executor = concurrent.futures.ThreadPoolExecutor(
  710. thread_name_prefix='asyncio'
  711. )
  712. self._default_executor = executor
  713. return futures.wrap_future(
  714. executor.submit(func, *args), loop=self)
  715. def set_default_executor(self, executor):
  716. if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
  717. raise TypeError('executor must be ThreadPoolExecutor instance')
  718. self._default_executor = executor
  719. def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
  720. msg = [f"{host}:{port!r}"]
  721. if family:
  722. msg.append(f'family={family!r}')
  723. if type:
  724. msg.append(f'type={type!r}')
  725. if proto:
  726. msg.append(f'proto={proto!r}')
  727. if flags:
  728. msg.append(f'flags={flags!r}')
  729. msg = ', '.join(msg)
  730. logger.debug('Get address info %s', msg)
  731. t0 = self.time()
  732. addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
  733. dt = self.time() - t0
  734. msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
  735. if dt >= self.slow_callback_duration:
  736. logger.info(msg)
  737. else:
  738. logger.debug(msg)
  739. return addrinfo
  740. async def getaddrinfo(self, host, port, *,
  741. family=0, type=0, proto=0, flags=0):
  742. if self._debug:
  743. getaddr_func = self._getaddrinfo_debug
  744. else:
  745. getaddr_func = socket.getaddrinfo
  746. return await self.run_in_executor(
  747. None, getaddr_func, host, port, family, type, proto, flags)
  748. async def getnameinfo(self, sockaddr, flags=0):
  749. return await self.run_in_executor(
  750. None, socket.getnameinfo, sockaddr, flags)
  751. async def sock_sendfile(self, sock, file, offset=0, count=None,
  752. *, fallback=True):
  753. if self._debug and sock.gettimeout() != 0:
  754. raise ValueError("the socket must be non-blocking")
  755. _check_ssl_socket(sock)
  756. self._check_sendfile_params(sock, file, offset, count)
  757. try:
  758. return await self._sock_sendfile_native(sock, file,
  759. offset, count)
  760. except exceptions.SendfileNotAvailableError as exc:
  761. if not fallback:
  762. raise
  763. return await self._sock_sendfile_fallback(sock, file,
  764. offset, count)
  765. async def _sock_sendfile_native(self, sock, file, offset, count):
  766. # NB: sendfile syscall is not supported for SSL sockets and
  767. # non-mmap files even if sendfile is supported by OS
  768. raise exceptions.SendfileNotAvailableError(
  769. f"syscall sendfile is not available for socket {sock!r} "
  770. f"and file {file!r} combination")
  771. async def _sock_sendfile_fallback(self, sock, file, offset, count):
  772. if offset:
  773. file.seek(offset)
  774. blocksize = (
  775. min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
  776. if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
  777. )
  778. buf = bytearray(blocksize)
  779. total_sent = 0
  780. try:
  781. while True:
  782. if count:
  783. blocksize = min(count - total_sent, blocksize)
  784. if blocksize <= 0:
  785. break
  786. view = memoryview(buf)[:blocksize]
  787. read = await self.run_in_executor(None, file.readinto, view)
  788. if not read:
  789. break # EOF
  790. await self.sock_sendall(sock, view[:read])
  791. total_sent += read
  792. return total_sent
  793. finally:
  794. if total_sent > 0 and hasattr(file, 'seek'):
  795. file.seek(offset + total_sent)
  796. def _check_sendfile_params(self, sock, file, offset, count):
  797. if 'b' not in getattr(file, 'mode', 'b'):
  798. raise ValueError("file should be opened in binary mode")
  799. if not sock.type == socket.SOCK_STREAM:
  800. raise ValueError("only SOCK_STREAM type sockets are supported")
  801. if count is not None:
  802. if not isinstance(count, int):
  803. raise TypeError(
  804. "count must be a positive integer (got {!r})".format(count))
  805. if count <= 0:
  806. raise ValueError(
  807. "count must be a positive integer (got {!r})".format(count))
  808. if not isinstance(offset, int):
  809. raise TypeError(
  810. "offset must be a non-negative integer (got {!r})".format(
  811. offset))
  812. if offset < 0:
  813. raise ValueError(
  814. "offset must be a non-negative integer (got {!r})".format(
  815. offset))
  816. async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
  817. """Create, bind and connect one socket."""
  818. my_exceptions = []
  819. exceptions.append(my_exceptions)
  820. family, type_, proto, _, address = addr_info
  821. sock = None
  822. try:
  823. sock = socket.socket(family=family, type=type_, proto=proto)
  824. sock.setblocking(False)
  825. if local_addr_infos is not None:
  826. for lfamily, _, _, _, laddr in local_addr_infos:
  827. # skip local addresses of different family
  828. if lfamily != family:
  829. continue
  830. try:
  831. sock.bind(laddr)
  832. break
  833. except OSError as exc:
  834. msg = (
  835. f'error while attempting to bind on '
  836. f'address {laddr!r}: '
  837. f'{exc.strerror.lower()}'
  838. )
  839. exc = OSError(exc.errno, msg)
  840. my_exceptions.append(exc)
  841. else: # all bind attempts failed
  842. if my_exceptions:
  843. raise my_exceptions.pop()
  844. else:
  845. raise OSError(f"no matching local address with {family=} found")
  846. await self.sock_connect(sock, address)
  847. return sock
  848. except OSError as exc:
  849. my_exceptions.append(exc)
  850. if sock is not None:
  851. sock.close()
  852. raise
  853. except:
  854. if sock is not None:
  855. sock.close()
  856. raise
  857. finally:
  858. exceptions = my_exceptions = None
  859. async def create_connection(
  860. self, protocol_factory, host=None, port=None,
  861. *, ssl=None, family=0,
  862. proto=0, flags=0, sock=None,
  863. local_addr=None, server_hostname=None,
  864. ssl_handshake_timeout=None,
  865. ssl_shutdown_timeout=None,
  866. happy_eyeballs_delay=None, interleave=None,
  867. all_errors=False):
  868. """Connect to a TCP server.
  869. Create a streaming transport connection to a given internet host and
  870. port: socket family AF_INET or socket.AF_INET6 depending on host (or
  871. family if specified), socket type SOCK_STREAM. protocol_factory must be
  872. a callable returning a protocol instance.
  873. This method is a coroutine which will try to establish the connection
  874. in the background. When successful, the coroutine returns a
  875. (transport, protocol) pair.
  876. """
  877. if server_hostname is not None and not ssl:
  878. raise ValueError('server_hostname is only meaningful with ssl')
  879. if server_hostname is None and ssl:
  880. # Use host as default for server_hostname. It is an error
  881. # if host is empty or not set, e.g. when an
  882. # already-connected socket was passed or when only a port
  883. # is given. To avoid this error, you can pass
  884. # server_hostname='' -- this will bypass the hostname
  885. # check. (This also means that if host is a numeric
  886. # IP/IPv6 address, we will attempt to verify that exact
  887. # address; this will probably fail, but it is possible to
  888. # create a certificate for a specific IP address, so we
  889. # don't judge it here.)
  890. if not host:
  891. raise ValueError('You must set server_hostname '
  892. 'when using ssl without a host')
  893. server_hostname = host
  894. if ssl_handshake_timeout is not None and not ssl:
  895. raise ValueError(
  896. 'ssl_handshake_timeout is only meaningful with ssl')
  897. if ssl_shutdown_timeout is not None and not ssl:
  898. raise ValueError(
  899. 'ssl_shutdown_timeout is only meaningful with ssl')
  900. if sock is not None:
  901. _check_ssl_socket(sock)
  902. if happy_eyeballs_delay is not None and interleave is None:
  903. # If using happy eyeballs, default to interleave addresses by family
  904. interleave = 1
  905. if host is not None or port is not None:
  906. if sock is not None:
  907. raise ValueError(
  908. 'host/port and sock can not be specified at the same time')
  909. infos = await self._ensure_resolved(
  910. (host, port), family=family,
  911. type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
  912. if not infos:
  913. raise OSError('getaddrinfo() returned empty list')
  914. if local_addr is not None:
  915. laddr_infos = await self._ensure_resolved(
  916. local_addr, family=family,
  917. type=socket.SOCK_STREAM, proto=proto,
  918. flags=flags, loop=self)
  919. if not laddr_infos:
  920. raise OSError('getaddrinfo() returned empty list')
  921. else:
  922. laddr_infos = None
  923. if interleave:
  924. infos = _interleave_addrinfos(infos, interleave)
  925. exceptions = []
  926. if happy_eyeballs_delay is None:
  927. # not using happy eyeballs
  928. for addrinfo in infos:
  929. try:
  930. sock = await self._connect_sock(
  931. exceptions, addrinfo, laddr_infos)
  932. break
  933. except OSError:
  934. continue
  935. else: # using happy eyeballs
  936. sock, _, _ = await staggered.staggered_race(
  937. (functools.partial(self._connect_sock,
  938. exceptions, addrinfo, laddr_infos)
  939. for addrinfo in infos),
  940. happy_eyeballs_delay, loop=self)
  941. if sock is None:
  942. exceptions = [exc for sub in exceptions for exc in sub]
  943. try:
  944. if all_errors:
  945. raise ExceptionGroup("create_connection failed", exceptions)
  946. if len(exceptions) == 1:
  947. raise exceptions[0]
  948. else:
  949. # If they all have the same str(), raise one.
  950. model = str(exceptions[0])
  951. if all(str(exc) == model for exc in exceptions):
  952. raise exceptions[0]
  953. # Raise a combined exception so the user can see all
  954. # the various error messages.
  955. raise OSError('Multiple exceptions: {}'.format(
  956. ', '.join(str(exc) for exc in exceptions)))
  957. finally:
  958. exceptions = None
  959. else:
  960. if sock is None:
  961. raise ValueError(
  962. 'host and port was not specified and no sock specified')
  963. if sock.type != socket.SOCK_STREAM:
  964. # We allow AF_INET, AF_INET6, AF_UNIX as long as they
  965. # are SOCK_STREAM.
  966. # We support passing AF_UNIX sockets even though we have
  967. # a dedicated API for that: create_unix_connection.
  968. # Disallowing AF_UNIX in this method, breaks backwards
  969. # compatibility.
  970. raise ValueError(
  971. f'A Stream Socket was expected, got {sock!r}')
  972. transport, protocol = await self._create_connection_transport(
  973. sock, protocol_factory, ssl, server_hostname,
  974. ssl_handshake_timeout=ssl_handshake_timeout,
  975. ssl_shutdown_timeout=ssl_shutdown_timeout)
  976. if self._debug:
  977. # Get the socket from the transport because SSL transport closes
  978. # the old socket and creates a new SSL socket
  979. sock = transport.get_extra_info('socket')
  980. logger.debug("%r connected to %s:%r: (%r, %r)",
  981. sock, host, port, transport, protocol)
  982. return transport, protocol
  983. async def _create_connection_transport(
  984. self, sock, protocol_factory, ssl,
  985. server_hostname, server_side=False,
  986. ssl_handshake_timeout=None,
  987. ssl_shutdown_timeout=None):
  988. sock.setblocking(False)
  989. protocol = protocol_factory()
  990. waiter = self.create_future()
  991. if ssl:
  992. sslcontext = None if isinstance(ssl, bool) else ssl
  993. transport = self._make_ssl_transport(
  994. sock, protocol, sslcontext, waiter,
  995. server_side=server_side, server_hostname=server_hostname,
  996. ssl_handshake_timeout=ssl_handshake_timeout,
  997. ssl_shutdown_timeout=ssl_shutdown_timeout)
  998. else:
  999. transport = self._make_socket_transport(sock, protocol, waiter)
  1000. try:
  1001. await waiter
  1002. except:
  1003. transport.close()
  1004. raise
  1005. return transport, protocol
  1006. async def sendfile(self, transport, file, offset=0, count=None,
  1007. *, fallback=True):
  1008. """Send a file to transport.
  1009. Return the total number of bytes which were sent.
  1010. The method uses high-performance os.sendfile if available.
  1011. file must be a regular file object opened in binary mode.
  1012. offset tells from where to start reading the file. If specified,
  1013. count is the total number of bytes to transmit as opposed to
  1014. sending the file until EOF is reached. File position is updated on
  1015. return or also in case of error in which case file.tell()
  1016. can be used to figure out the number of bytes
  1017. which were sent.
  1018. fallback set to True makes asyncio to manually read and send
  1019. the file when the platform does not support the sendfile syscall
  1020. (e.g. Windows or SSL socket on Unix).
  1021. Raise SendfileNotAvailableError if the system does not support
  1022. sendfile syscall and fallback is False.
  1023. """
  1024. if transport.is_closing():
  1025. raise RuntimeError("Transport is closing")
  1026. mode = getattr(transport, '_sendfile_compatible',
  1027. constants._SendfileMode.UNSUPPORTED)
  1028. if mode is constants._SendfileMode.UNSUPPORTED:
  1029. raise RuntimeError(
  1030. f"sendfile is not supported for transport {transport!r}")
  1031. if mode is constants._SendfileMode.TRY_NATIVE:
  1032. try:
  1033. return await self._sendfile_native(transport, file,
  1034. offset, count)
  1035. except exceptions.SendfileNotAvailableError as exc:
  1036. if not fallback:
  1037. raise
  1038. if not fallback:
  1039. raise RuntimeError(
  1040. f"fallback is disabled and native sendfile is not "
  1041. f"supported for transport {transport!r}")
  1042. return await self._sendfile_fallback(transport, file,
  1043. offset, count)
  1044. async def _sendfile_native(self, transp, file, offset, count):
  1045. raise exceptions.SendfileNotAvailableError(
  1046. "sendfile syscall is not supported")
  1047. async def _sendfile_fallback(self, transp, file, offset, count):
  1048. if offset:
  1049. file.seek(offset)
  1050. blocksize = min(count, 16384) if count else 16384
  1051. buf = bytearray(blocksize)
  1052. total_sent = 0
  1053. proto = _SendfileFallbackProtocol(transp)
  1054. try:
  1055. while True:
  1056. if count:
  1057. blocksize = min(count - total_sent, blocksize)
  1058. if blocksize <= 0:
  1059. return total_sent
  1060. view = memoryview(buf)[:blocksize]
  1061. read = await self.run_in_executor(None, file.readinto, view)
  1062. if not read:
  1063. return total_sent # EOF
  1064. await proto.drain()
  1065. transp.write(view[:read])
  1066. total_sent += read
  1067. finally:
  1068. if total_sent > 0 and hasattr(file, 'seek'):
  1069. file.seek(offset + total_sent)
  1070. await proto.restore()
  1071. async def start_tls(self, transport, protocol, sslcontext, *,
  1072. server_side=False,
  1073. server_hostname=None,
  1074. ssl_handshake_timeout=None,
  1075. ssl_shutdown_timeout=None):
  1076. """Upgrade transport to TLS.
  1077. Return a new transport that *protocol* should start using
  1078. immediately.
  1079. """
  1080. if ssl is None:
  1081. raise RuntimeError('Python ssl module is not available')
  1082. if not isinstance(sslcontext, ssl.SSLContext):
  1083. raise TypeError(
  1084. f'sslcontext is expected to be an instance of ssl.SSLContext, '
  1085. f'got {sslcontext!r}')
  1086. if not getattr(transport, '_start_tls_compatible', False):
  1087. raise TypeError(
  1088. f'transport {transport!r} is not supported by start_tls()')
  1089. waiter = self.create_future()
  1090. ssl_protocol = sslproto.SSLProtocol(
  1091. self, protocol, sslcontext, waiter,
  1092. server_side, server_hostname,
  1093. ssl_handshake_timeout=ssl_handshake_timeout,
  1094. ssl_shutdown_timeout=ssl_shutdown_timeout,
  1095. call_connection_made=False)
  1096. # Pause early so that "ssl_protocol.data_received()" doesn't
  1097. # have a chance to get called before "ssl_protocol.connection_made()".
  1098. transport.pause_reading()
  1099. transport.set_protocol(ssl_protocol)
  1100. conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
  1101. resume_cb = self.call_soon(transport.resume_reading)
  1102. try:
  1103. await waiter
  1104. except BaseException:
  1105. transport.close()
  1106. conmade_cb.cancel()
  1107. resume_cb.cancel()
  1108. raise
  1109. return ssl_protocol._app_transport
  1110. async def create_datagram_endpoint(self, protocol_factory,
  1111. local_addr=None, remote_addr=None, *,
  1112. family=0, proto=0, flags=0,
  1113. reuse_port=None,
  1114. allow_broadcast=None, sock=None):
  1115. """Create datagram connection."""
  1116. if sock is not None:
  1117. if sock.type == socket.SOCK_STREAM:
  1118. raise ValueError(
  1119. f'A datagram socket was expected, got {sock!r}')
  1120. if (local_addr or remote_addr or
  1121. family or proto or flags or
  1122. reuse_port or allow_broadcast):
  1123. # show the problematic kwargs in exception msg
  1124. opts = dict(local_addr=local_addr, remote_addr=remote_addr,
  1125. family=family, proto=proto, flags=flags,
  1126. reuse_port=reuse_port,
  1127. allow_broadcast=allow_broadcast)
  1128. problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
  1129. raise ValueError(
  1130. f'socket modifier keyword arguments can not be used '
  1131. f'when sock is specified. ({problems})')
  1132. sock.setblocking(False)
  1133. r_addr = None
  1134. else:
  1135. if not (local_addr or remote_addr):
  1136. if family == 0:
  1137. raise ValueError('unexpected address family')
  1138. addr_pairs_info = (((family, proto), (None, None)),)
  1139. elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
  1140. for addr in (local_addr, remote_addr):
  1141. if addr is not None and not isinstance(addr, str):
  1142. raise TypeError('string is expected')
  1143. if local_addr and local_addr[0] not in (0, '\x00'):
  1144. try:
  1145. if stat.S_ISSOCK(os.stat(local_addr).st_mode):
  1146. os.remove(local_addr)
  1147. except FileNotFoundError:
  1148. pass
  1149. except OSError as err:
  1150. # Directory may have permissions only to create socket.
  1151. logger.error('Unable to check or remove stale UNIX '
  1152. 'socket %r: %r',
  1153. local_addr, err)
  1154. addr_pairs_info = (((family, proto),
  1155. (local_addr, remote_addr)), )
  1156. else:
  1157. # join address by (family, protocol)
  1158. addr_infos = {} # Using order preserving dict
  1159. for idx, addr in ((0, local_addr), (1, remote_addr)):
  1160. if addr is not None:
  1161. if not (isinstance(addr, tuple) and len(addr) == 2):
  1162. raise TypeError('2-tuple is expected')
  1163. infos = await self._ensure_resolved(
  1164. addr, family=family, type=socket.SOCK_DGRAM,
  1165. proto=proto, flags=flags, loop=self)
  1166. if not infos:
  1167. raise OSError('getaddrinfo() returned empty list')
  1168. for fam, _, pro, _, address in infos:
  1169. key = (fam, pro)
  1170. if key not in addr_infos:
  1171. addr_infos[key] = [None, None]
  1172. addr_infos[key][idx] = address
  1173. # each addr has to have info for each (family, proto) pair
  1174. addr_pairs_info = [
  1175. (key, addr_pair) for key, addr_pair in addr_infos.items()
  1176. if not ((local_addr and addr_pair[0] is None) or
  1177. (remote_addr and addr_pair[1] is None))]
  1178. if not addr_pairs_info:
  1179. raise ValueError('can not get address information')
  1180. exceptions = []
  1181. for ((family, proto),
  1182. (local_address, remote_address)) in addr_pairs_info:
  1183. sock = None
  1184. r_addr = None
  1185. try:
  1186. sock = socket.socket(
  1187. family=family, type=socket.SOCK_DGRAM, proto=proto)
  1188. if reuse_port:
  1189. _set_reuseport(sock)
  1190. if allow_broadcast:
  1191. sock.setsockopt(
  1192. socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  1193. sock.setblocking(False)
  1194. if local_addr:
  1195. sock.bind(local_address)
  1196. if remote_addr:
  1197. if not allow_broadcast:
  1198. await self.sock_connect(sock, remote_address)
  1199. r_addr = remote_address
  1200. except OSError as exc:
  1201. if sock is not None:
  1202. sock.close()
  1203. exceptions.append(exc)
  1204. except:
  1205. if sock is not None:
  1206. sock.close()
  1207. raise
  1208. else:
  1209. break
  1210. else:
  1211. raise exceptions[0]
  1212. protocol = protocol_factory()
  1213. waiter = self.create_future()
  1214. transport = self._make_datagram_transport(
  1215. sock, protocol, r_addr, waiter)
  1216. if self._debug:
  1217. if local_addr:
  1218. logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
  1219. "created: (%r, %r)",
  1220. local_addr, remote_addr, transport, protocol)
  1221. else:
  1222. logger.debug("Datagram endpoint remote_addr=%r created: "
  1223. "(%r, %r)",
  1224. remote_addr, transport, protocol)
  1225. try:
  1226. await waiter
  1227. except:
  1228. transport.close()
  1229. raise
  1230. return transport, protocol
  1231. async def _ensure_resolved(self, address, *,
  1232. family=0, type=socket.SOCK_STREAM,
  1233. proto=0, flags=0, loop):
  1234. host, port = address[:2]
  1235. info = _ipaddr_info(host, port, family, type, proto, *address[2:])
  1236. if info is not None:
  1237. # "host" is already a resolved IP.
  1238. return [info]
  1239. else:
  1240. return await loop.getaddrinfo(host, port, family=family, type=type,
  1241. proto=proto, flags=flags)
  1242. async def _create_server_getaddrinfo(self, host, port, family, flags):
  1243. infos = await self._ensure_resolved((host, port), family=family,
  1244. type=socket.SOCK_STREAM,
  1245. flags=flags, loop=self)
  1246. if not infos:
  1247. raise OSError(f'getaddrinfo({host!r}) returned empty list')
  1248. return infos
  1249. async def create_server(
  1250. self, protocol_factory, host=None, port=None,
  1251. *,
  1252. family=socket.AF_UNSPEC,
  1253. flags=socket.AI_PASSIVE,
  1254. sock=None,
  1255. backlog=100,
  1256. ssl=None,
  1257. reuse_address=None,
  1258. reuse_port=None,
  1259. ssl_handshake_timeout=None,
  1260. ssl_shutdown_timeout=None,
  1261. start_serving=True):
  1262. """Create a TCP server.
  1263. The host parameter can be a string, in that case the TCP server is
  1264. bound to host and port.
  1265. The host parameter can also be a sequence of strings and in that case
  1266. the TCP server is bound to all hosts of the sequence. If a host
  1267. appears multiple times (possibly indirectly e.g. when hostnames
  1268. resolve to the same IP address), the server is only bound once to that
  1269. host.
  1270. Return a Server object which can be used to stop the service.
  1271. This method is a coroutine.
  1272. """
  1273. if isinstance(ssl, bool):
  1274. raise TypeError('ssl argument must be an SSLContext or None')
  1275. if ssl_handshake_timeout is not None and ssl is None:
  1276. raise ValueError(
  1277. 'ssl_handshake_timeout is only meaningful with ssl')
  1278. if ssl_shutdown_timeout is not None and ssl is None:
  1279. raise ValueError(
  1280. 'ssl_shutdown_timeout is only meaningful with ssl')
  1281. if sock is not None:
  1282. _check_ssl_socket(sock)
  1283. if host is not None or port is not None:
  1284. if sock is not None:
  1285. raise ValueError(
  1286. 'host/port and sock can not be specified at the same time')
  1287. if reuse_address is None:
  1288. reuse_address = os.name == "posix" and sys.platform != "cygwin"
  1289. sockets = []
  1290. if host == '':
  1291. hosts = [None]
  1292. elif (isinstance(host, str) or
  1293. not isinstance(host, collections.abc.Iterable)):
  1294. hosts = [host]
  1295. else:
  1296. hosts = host
  1297. fs = [self._create_server_getaddrinfo(host, port, family=family,
  1298. flags=flags)
  1299. for host in hosts]
  1300. infos = await tasks.gather(*fs)
  1301. infos = set(itertools.chain.from_iterable(infos))
  1302. completed = False
  1303. try:
  1304. for res in infos:
  1305. af, socktype, proto, canonname, sa = res
  1306. try:
  1307. sock = socket.socket(af, socktype, proto)
  1308. except socket.error:
  1309. # Assume it's a bad family/type/protocol combination.
  1310. if self._debug:
  1311. logger.warning('create_server() failed to create '
  1312. 'socket.socket(%r, %r, %r)',
  1313. af, socktype, proto, exc_info=True)
  1314. continue
  1315. sockets.append(sock)
  1316. if reuse_address:
  1317. sock.setsockopt(
  1318. socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
  1319. if reuse_port:
  1320. _set_reuseport(sock)
  1321. # Disable IPv4/IPv6 dual stack support (enabled by
  1322. # default on Linux) which makes a single socket
  1323. # listen on both address families.
  1324. if (_HAS_IPv6 and
  1325. af == socket.AF_INET6 and
  1326. hasattr(socket, 'IPPROTO_IPV6')):
  1327. sock.setsockopt(socket.IPPROTO_IPV6,
  1328. socket.IPV6_V6ONLY,
  1329. True)
  1330. try:
  1331. sock.bind(sa)
  1332. except OSError as err:
  1333. msg = ('error while attempting '
  1334. 'to bind on address %r: %s'
  1335. % (sa, err.strerror.lower()))
  1336. if err.errno == errno.EADDRNOTAVAIL:
  1337. # Assume the family is not enabled (bpo-30945)
  1338. sockets.pop()
  1339. sock.close()
  1340. if self._debug:
  1341. logger.warning(msg)
  1342. continue
  1343. raise OSError(err.errno, msg) from None
  1344. if not sockets:
  1345. raise OSError('could not bind on any address out of %r'
  1346. % ([info[4] for info in infos],))
  1347. completed = True
  1348. finally:
  1349. if not completed:
  1350. for sock in sockets:
  1351. sock.close()
  1352. else:
  1353. if sock is None:
  1354. raise ValueError('Neither host/port nor sock were specified')
  1355. if sock.type != socket.SOCK_STREAM:
  1356. raise ValueError(f'A Stream Socket was expected, got {sock!r}')
  1357. sockets = [sock]
  1358. for sock in sockets:
  1359. sock.setblocking(False)
  1360. server = Server(self, sockets, protocol_factory,
  1361. ssl, backlog, ssl_handshake_timeout,
  1362. ssl_shutdown_timeout)
  1363. if start_serving:
  1364. server._start_serving()
  1365. # Skip one loop iteration so that all 'loop.add_reader'
  1366. # go through.
  1367. await tasks.sleep(0)
  1368. if self._debug:
  1369. logger.info("%r is serving", server)
  1370. return server
  1371. async def connect_accepted_socket(
  1372. self, protocol_factory, sock,
  1373. *, ssl=None,
  1374. ssl_handshake_timeout=None,
  1375. ssl_shutdown_timeout=None):
  1376. if sock.type != socket.SOCK_STREAM:
  1377. raise ValueError(f'A Stream Socket was expected, got {sock!r}')
  1378. if ssl_handshake_timeout is not None and not ssl:
  1379. raise ValueError(
  1380. 'ssl_handshake_timeout is only meaningful with ssl')
  1381. if ssl_shutdown_timeout is not None and not ssl:
  1382. raise ValueError(
  1383. 'ssl_shutdown_timeout is only meaningful with ssl')
  1384. if sock is not None:
  1385. _check_ssl_socket(sock)
  1386. transport, protocol = await self._create_connection_transport(
  1387. sock, protocol_factory, ssl, '', server_side=True,
  1388. ssl_handshake_timeout=ssl_handshake_timeout,
  1389. ssl_shutdown_timeout=ssl_shutdown_timeout)
  1390. if self._debug:
  1391. # Get the socket from the transport because SSL transport closes
  1392. # the old socket and creates a new SSL socket
  1393. sock = transport.get_extra_info('socket')
  1394. logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
  1395. return transport, protocol
  1396. async def connect_read_pipe(self, protocol_factory, pipe):
  1397. protocol = protocol_factory()
  1398. waiter = self.create_future()
  1399. transport = self._make_read_pipe_transport(pipe, protocol, waiter)
  1400. try:
  1401. await waiter
  1402. except:
  1403. transport.close()
  1404. raise
  1405. if self._debug:
  1406. logger.debug('Read pipe %r connected: (%r, %r)',
  1407. pipe.fileno(), transport, protocol)
  1408. return transport, protocol
  1409. async def connect_write_pipe(self, protocol_factory, pipe):
  1410. protocol = protocol_factory()
  1411. waiter = self.create_future()
  1412. transport = self._make_write_pipe_transport(pipe, protocol, waiter)
  1413. try:
  1414. await waiter
  1415. except:
  1416. transport.close()
  1417. raise
  1418. if self._debug:
  1419. logger.debug('Write pipe %r connected: (%r, %r)',
  1420. pipe.fileno(), transport, protocol)
  1421. return transport, protocol
  1422. def _log_subprocess(self, msg, stdin, stdout, stderr):
  1423. info = [msg]
  1424. if stdin is not None:
  1425. info.append(f'stdin={_format_pipe(stdin)}')
  1426. if stdout is not None and stderr == subprocess.STDOUT:
  1427. info.append(f'stdout=stderr={_format_pipe(stdout)}')
  1428. else:
  1429. if stdout is not None:
  1430. info.append(f'stdout={_format_pipe(stdout)}')
  1431. if stderr is not None:
  1432. info.append(f'stderr={_format_pipe(stderr)}')
  1433. logger.debug(' '.join(info))
  1434. async def subprocess_shell(self, protocol_factory, cmd, *,
  1435. stdin=subprocess.PIPE,
  1436. stdout=subprocess.PIPE,
  1437. stderr=subprocess.PIPE,
  1438. universal_newlines=False,
  1439. shell=True, bufsize=0,
  1440. encoding=None, errors=None, text=None,
  1441. **kwargs):
  1442. if not isinstance(cmd, (bytes, str)):
  1443. raise ValueError("cmd must be a string")
  1444. if universal_newlines:
  1445. raise ValueError("universal_newlines must be False")
  1446. if not shell:
  1447. raise ValueError("shell must be True")
  1448. if bufsize != 0:
  1449. raise ValueError("bufsize must be 0")
  1450. if text:
  1451. raise ValueError("text must be False")
  1452. if encoding is not None:
  1453. raise ValueError("encoding must be None")
  1454. if errors is not None:
  1455. raise ValueError("errors must be None")
  1456. protocol = protocol_factory()
  1457. debug_log = None
  1458. if self._debug:
  1459. # don't log parameters: they may contain sensitive information
  1460. # (password) and may be too long
  1461. debug_log = 'run shell command %r' % cmd
  1462. self._log_subprocess(debug_log, stdin, stdout, stderr)
  1463. transport = await self._make_subprocess_transport(
  1464. protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
  1465. if self._debug and debug_log is not None:
  1466. logger.info('%s: %r', debug_log, transport)
  1467. return transport, protocol
  1468. async def subprocess_exec(self, protocol_factory, program, *args,
  1469. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1470. stderr=subprocess.PIPE, universal_newlines=False,
  1471. shell=False, bufsize=0,
  1472. encoding=None, errors=None, text=None,
  1473. **kwargs):
  1474. if universal_newlines:
  1475. raise ValueError("universal_newlines must be False")
  1476. if shell:
  1477. raise ValueError("shell must be False")
  1478. if bufsize != 0:
  1479. raise ValueError("bufsize must be 0")
  1480. if text:
  1481. raise ValueError("text must be False")
  1482. if encoding is not None:
  1483. raise ValueError("encoding must be None")
  1484. if errors is not None:
  1485. raise ValueError("errors must be None")
  1486. popen_args = (program,) + args
  1487. protocol = protocol_factory()
  1488. debug_log = None
  1489. if self._debug:
  1490. # don't log parameters: they may contain sensitive information
  1491. # (password) and may be too long
  1492. debug_log = f'execute program {program!r}'
  1493. self._log_subprocess(debug_log, stdin, stdout, stderr)
  1494. transport = await self._make_subprocess_transport(
  1495. protocol, popen_args, False, stdin, stdout, stderr,
  1496. bufsize, **kwargs)
  1497. if self._debug and debug_log is not None:
  1498. logger.info('%s: %r', debug_log, transport)
  1499. return transport, protocol
  1500. def get_exception_handler(self):
  1501. """Return an exception handler, or None if the default one is in use.
  1502. """
  1503. return self._exception_handler
  1504. def set_exception_handler(self, handler):
  1505. """Set handler as the new event loop exception handler.
  1506. If handler is None, the default exception handler will
  1507. be set.
  1508. If handler is a callable object, it should have a
  1509. signature matching '(loop, context)', where 'loop'
  1510. will be a reference to the active event loop, 'context'
  1511. will be a dict object (see `call_exception_handler()`
  1512. documentation for details about context).
  1513. """
  1514. if handler is not None and not callable(handler):
  1515. raise TypeError(f'A callable object or None is expected, '
  1516. f'got {handler!r}')
  1517. self._exception_handler = handler
  1518. def default_exception_handler(self, context):
  1519. """Default exception handler.
  1520. This is called when an exception occurs and no exception
  1521. handler is set, and can be called by a custom exception
  1522. handler that wants to defer to the default behavior.
  1523. This default handler logs the error message and other
  1524. context-dependent information. In debug mode, a truncated
  1525. stack trace is also appended showing where the given object
  1526. (e.g. a handle or future or task) was created, if any.
  1527. The context parameter has the same meaning as in
  1528. `call_exception_handler()`.
  1529. """
  1530. message = context.get('message')
  1531. if not message:
  1532. message = 'Unhandled exception in event loop'
  1533. exception = context.get('exception')
  1534. if exception is not None:
  1535. exc_info = (type(exception), exception, exception.__traceback__)
  1536. else:
  1537. exc_info = False
  1538. if ('source_traceback' not in context and
  1539. self._current_handle is not None and
  1540. self._current_handle._source_traceback):
  1541. context['handle_traceback'] = \
  1542. self._current_handle._source_traceback
  1543. log_lines = [message]
  1544. for key in sorted(context):
  1545. if key in {'message', 'exception'}:
  1546. continue
  1547. value = context[key]
  1548. if key == 'source_traceback':
  1549. tb = ''.join(traceback.format_list(value))
  1550. value = 'Object created at (most recent call last):\n'
  1551. value += tb.rstrip()
  1552. elif key == 'handle_traceback':
  1553. tb = ''.join(traceback.format_list(value))
  1554. value = 'Handle created at (most recent call last):\n'
  1555. value += tb.rstrip()
  1556. else:
  1557. value = repr(value)
  1558. log_lines.append(f'{key}: {value}')
  1559. logger.error('\n'.join(log_lines), exc_info=exc_info)
  1560. def call_exception_handler(self, context):
  1561. """Call the current event loop's exception handler.
  1562. The context argument is a dict containing the following keys:
  1563. - 'message': Error message;
  1564. - 'exception' (optional): Exception object;
  1565. - 'future' (optional): Future instance;
  1566. - 'task' (optional): Task instance;
  1567. - 'handle' (optional): Handle instance;
  1568. - 'protocol' (optional): Protocol instance;
  1569. - 'transport' (optional): Transport instance;
  1570. - 'socket' (optional): Socket instance;
  1571. - 'asyncgen' (optional): Asynchronous generator that caused
  1572. the exception.
  1573. New keys maybe introduced in the future.
  1574. Note: do not overload this method in an event loop subclass.
  1575. For custom exception handling, use the
  1576. `set_exception_handler()` method.
  1577. """
  1578. if self._exception_handler is None:
  1579. try:
  1580. self.default_exception_handler(context)
  1581. except (SystemExit, KeyboardInterrupt):
  1582. raise
  1583. except BaseException:
  1584. # Second protection layer for unexpected errors
  1585. # in the default implementation, as well as for subclassed
  1586. # event loops with overloaded "default_exception_handler".
  1587. logger.error('Exception in default exception handler',
  1588. exc_info=True)
  1589. else:
  1590. try:
  1591. ctx = None
  1592. thing = context.get("task")
  1593. if thing is None:
  1594. # Even though Futures don't have a context,
  1595. # Task is a subclass of Future,
  1596. # and sometimes the 'future' key holds a Task.
  1597. thing = context.get("future")
  1598. if thing is None:
  1599. # Handles also have a context.
  1600. thing = context.get("handle")
  1601. if thing is not None and hasattr(thing, "get_context"):
  1602. ctx = thing.get_context()
  1603. if ctx is not None and hasattr(ctx, "run"):
  1604. ctx.run(self._exception_handler, self, context)
  1605. else:
  1606. self._exception_handler(self, context)
  1607. except (SystemExit, KeyboardInterrupt):
  1608. raise
  1609. except BaseException as exc:
  1610. # Exception in the user set custom exception handler.
  1611. try:
  1612. # Let's try default handler.
  1613. self.default_exception_handler({
  1614. 'message': 'Unhandled error in exception handler',
  1615. 'exception': exc,
  1616. 'context': context,
  1617. })
  1618. except (SystemExit, KeyboardInterrupt):
  1619. raise
  1620. except BaseException:
  1621. # Guard 'default_exception_handler' in case it is
  1622. # overloaded.
  1623. logger.error('Exception in default exception handler '
  1624. 'while handling an unexpected error '
  1625. 'in custom exception handler',
  1626. exc_info=True)
  1627. def _add_callback(self, handle):
  1628. """Add a Handle to _ready."""
  1629. if not handle._cancelled:
  1630. self._ready.append(handle)
  1631. def _add_callback_signalsafe(self, handle):
  1632. """Like _add_callback() but called from a signal handler."""
  1633. self._add_callback(handle)
  1634. self._write_to_self()
  1635. def _timer_handle_cancelled(self, handle):
  1636. """Notification that a TimerHandle has been cancelled."""
  1637. if handle._scheduled:
  1638. self._timer_cancelled_count += 1
  1639. def _run_once(self):
  1640. """Run one full iteration of the event loop.
  1641. This calls all currently ready callbacks, polls for I/O,
  1642. schedules the resulting callbacks, and finally schedules
  1643. 'call_later' callbacks.
  1644. """
  1645. sched_count = len(self._scheduled)
  1646. if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
  1647. self._timer_cancelled_count / sched_count >
  1648. _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
  1649. # Remove delayed calls that were cancelled if their number
  1650. # is too high
  1651. new_scheduled = []
  1652. for handle in self._scheduled:
  1653. if handle._cancelled:
  1654. handle._scheduled = False
  1655. else:
  1656. new_scheduled.append(handle)
  1657. heapq.heapify(new_scheduled)
  1658. self._scheduled = new_scheduled
  1659. self._timer_cancelled_count = 0
  1660. else:
  1661. # Remove delayed calls that were cancelled from head of queue.
  1662. while self._scheduled and self._scheduled[0]._cancelled:
  1663. self._timer_cancelled_count -= 1
  1664. handle = heapq.heappop(self._scheduled)
  1665. handle._scheduled = False
  1666. timeout = None
  1667. if self._ready or self._stopping:
  1668. timeout = 0
  1669. elif self._scheduled:
  1670. # Compute the desired timeout.
  1671. when = self._scheduled[0]._when
  1672. timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
  1673. event_list = self._selector.select(timeout)
  1674. self._process_events(event_list)
  1675. # Needed to break cycles when an exception occurs.
  1676. event_list = None
  1677. # Handle 'later' callbacks that are ready.
  1678. end_time = self.time() + self._clock_resolution
  1679. while self._scheduled:
  1680. handle = self._scheduled[0]
  1681. if handle._when >= end_time:
  1682. break
  1683. handle = heapq.heappop(self._scheduled)
  1684. handle._scheduled = False
  1685. self._ready.append(handle)
  1686. # This is the only place where callbacks are actually *called*.
  1687. # All other places just add them to ready.
  1688. # Note: We run all currently scheduled callbacks, but not any
  1689. # callbacks scheduled by callbacks run this time around --
  1690. # they will be run the next time (after another I/O poll).
  1691. # Use an idiom that is thread-safe without using locks.
  1692. ntodo = len(self._ready)
  1693. for i in range(ntodo):
  1694. handle = self._ready.popleft()
  1695. if handle._cancelled:
  1696. continue
  1697. if self._debug:
  1698. try:
  1699. self._current_handle = handle
  1700. t0 = self.time()
  1701. handle._run()
  1702. dt = self.time() - t0
  1703. if dt >= self.slow_callback_duration:
  1704. logger.warning('Executing %s took %.3f seconds',
  1705. _format_handle(handle), dt)
  1706. finally:
  1707. self._current_handle = None
  1708. else:
  1709. handle._run()
  1710. handle = None # Needed to break cycles when an exception occurs.
  1711. def _set_coroutine_origin_tracking(self, enabled):
  1712. if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
  1713. return
  1714. if enabled:
  1715. self._coroutine_origin_tracking_saved_depth = (
  1716. sys.get_coroutine_origin_tracking_depth())
  1717. sys.set_coroutine_origin_tracking_depth(
  1718. constants.DEBUG_STACK_DEPTH)
  1719. else:
  1720. sys.set_coroutine_origin_tracking_depth(
  1721. self._coroutine_origin_tracking_saved_depth)
  1722. self._coroutine_origin_tracking_enabled = enabled
  1723. def get_debug(self):
  1724. return self._debug
  1725. def set_debug(self, enabled):
  1726. self._debug = enabled
  1727. if self.is_running():
  1728. self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)