base_events.py 74 KB

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