base_events.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024
  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 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 timeouts
  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. try:
  389. return task
  390. finally:
  391. # gh-128552: prevent a refcycle of
  392. # task.exception().__traceback__->BaseEventLoop.create_task->task
  393. del task
  394. def set_task_factory(self, factory):
  395. """Set a task factory that will be used by loop.create_task().
  396. If factory is None the default task factory will be set.
  397. If factory is a callable, it should have a signature matching
  398. '(loop, coro)', where 'loop' will be a reference to the active
  399. event loop, 'coro' will be a coroutine object. The callable
  400. must return a Future.
  401. """
  402. if factory is not None and not callable(factory):
  403. raise TypeError('task factory must be a callable or None')
  404. self._task_factory = factory
  405. def get_task_factory(self):
  406. """Return a task factory, or None if the default one is in use."""
  407. return self._task_factory
  408. def _make_socket_transport(self, sock, protocol, waiter=None, *,
  409. extra=None, server=None):
  410. """Create socket transport."""
  411. raise NotImplementedError
  412. def _make_ssl_transport(
  413. self, rawsock, protocol, sslcontext, waiter=None,
  414. *, server_side=False, server_hostname=None,
  415. extra=None, server=None,
  416. ssl_handshake_timeout=None,
  417. ssl_shutdown_timeout=None,
  418. call_connection_made=True):
  419. """Create SSL transport."""
  420. raise NotImplementedError
  421. def _make_datagram_transport(self, sock, protocol,
  422. address=None, waiter=None, extra=None):
  423. """Create datagram transport."""
  424. raise NotImplementedError
  425. def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
  426. extra=None):
  427. """Create read pipe transport."""
  428. raise NotImplementedError
  429. def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
  430. extra=None):
  431. """Create write pipe transport."""
  432. raise NotImplementedError
  433. async def _make_subprocess_transport(self, protocol, args, shell,
  434. stdin, stdout, stderr, bufsize,
  435. extra=None, **kwargs):
  436. """Create subprocess transport."""
  437. raise NotImplementedError
  438. def _write_to_self(self):
  439. """Write a byte to self-pipe, to wake up the event loop.
  440. This may be called from a different thread.
  441. The subclass is responsible for implementing the self-pipe.
  442. """
  443. raise NotImplementedError
  444. def _process_events(self, event_list):
  445. """Process selector events."""
  446. raise NotImplementedError
  447. def _check_closed(self):
  448. if self._closed:
  449. raise RuntimeError('Event loop is closed')
  450. def _check_default_executor(self):
  451. if self._executor_shutdown_called:
  452. raise RuntimeError('Executor shutdown has been called')
  453. def _asyncgen_finalizer_hook(self, agen):
  454. self._asyncgens.discard(agen)
  455. if not self.is_closed():
  456. self.call_soon_threadsafe(self.create_task, agen.aclose())
  457. def _asyncgen_firstiter_hook(self, agen):
  458. if self._asyncgens_shutdown_called:
  459. warnings.warn(
  460. f"asynchronous generator {agen!r} was scheduled after "
  461. f"loop.shutdown_asyncgens() call",
  462. ResourceWarning, source=self)
  463. self._asyncgens.add(agen)
  464. async def shutdown_asyncgens(self):
  465. """Shutdown all active asynchronous generators."""
  466. self._asyncgens_shutdown_called = True
  467. if not len(self._asyncgens):
  468. # If Python version is <3.6 or we don't have any asynchronous
  469. # generators alive.
  470. return
  471. closing_agens = list(self._asyncgens)
  472. self._asyncgens.clear()
  473. results = await tasks.gather(
  474. *[ag.aclose() for ag in closing_agens],
  475. return_exceptions=True)
  476. for result, agen in zip(results, closing_agens):
  477. if isinstance(result, Exception):
  478. self.call_exception_handler({
  479. 'message': f'an error occurred during closing of '
  480. f'asynchronous generator {agen!r}',
  481. 'exception': result,
  482. 'asyncgen': agen
  483. })
  484. async def shutdown_default_executor(self, timeout=None):
  485. """Schedule the shutdown of the default executor.
  486. The timeout parameter specifies the amount of time the executor will
  487. be given to finish joining. The default value is None, which means
  488. that the executor will be given an unlimited amount of time.
  489. """
  490. self._executor_shutdown_called = True
  491. if self._default_executor is None:
  492. return
  493. future = self.create_future()
  494. thread = threading.Thread(target=self._do_shutdown, args=(future,))
  495. thread.start()
  496. try:
  497. async with timeouts.timeout(timeout):
  498. await future
  499. except TimeoutError:
  500. warnings.warn("The executor did not finishing joining "
  501. f"its threads within {timeout} seconds.",
  502. RuntimeWarning, stacklevel=2)
  503. self._default_executor.shutdown(wait=False)
  504. else:
  505. thread.join()
  506. def _do_shutdown(self, future):
  507. try:
  508. self._default_executor.shutdown(wait=True)
  509. if not self.is_closed():
  510. self.call_soon_threadsafe(futures._set_result_unless_cancelled,
  511. future, None)
  512. except Exception as ex:
  513. if not self.is_closed() and not future.cancelled():
  514. self.call_soon_threadsafe(future.set_exception, ex)
  515. def _check_running(self):
  516. if self.is_running():
  517. raise RuntimeError('This event loop is already running')
  518. if events._get_running_loop() is not None:
  519. raise RuntimeError(
  520. 'Cannot run the event loop while another loop is running')
  521. def run_forever(self):
  522. """Run until stop() is called."""
  523. self._check_closed()
  524. self._check_running()
  525. self._set_coroutine_origin_tracking(self._debug)
  526. old_agen_hooks = sys.get_asyncgen_hooks()
  527. try:
  528. self._thread_id = threading.get_ident()
  529. sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
  530. finalizer=self._asyncgen_finalizer_hook)
  531. events._set_running_loop(self)
  532. while True:
  533. self._run_once()
  534. if self._stopping:
  535. break
  536. finally:
  537. self._stopping = False
  538. self._thread_id = None
  539. events._set_running_loop(None)
  540. self._set_coroutine_origin_tracking(False)
  541. sys.set_asyncgen_hooks(*old_agen_hooks)
  542. def run_until_complete(self, future):
  543. """Run until the Future is done.
  544. If the argument is a coroutine, it is wrapped in a Task.
  545. WARNING: It would be disastrous to call run_until_complete()
  546. with the same coroutine twice -- it would wrap it in two
  547. different Tasks and that can't be good.
  548. Return the Future's result, or raise its exception.
  549. """
  550. self._check_closed()
  551. self._check_running()
  552. new_task = not futures.isfuture(future)
  553. future = tasks.ensure_future(future, loop=self)
  554. if new_task:
  555. # An exception is raised if the future didn't complete, so there
  556. # is no need to log the "destroy pending task" message
  557. future._log_destroy_pending = False
  558. future.add_done_callback(_run_until_complete_cb)
  559. try:
  560. self.run_forever()
  561. except:
  562. if new_task and future.done() and not future.cancelled():
  563. # The coroutine raised a BaseException. Consume the exception
  564. # to not log a warning, the caller doesn't have access to the
  565. # local task.
  566. future.exception()
  567. raise
  568. finally:
  569. future.remove_done_callback(_run_until_complete_cb)
  570. if not future.done():
  571. raise RuntimeError('Event loop stopped before Future completed.')
  572. return future.result()
  573. def stop(self):
  574. """Stop running the event loop.
  575. Every callback already scheduled will still run. This simply informs
  576. run_forever to stop looping after a complete iteration.
  577. """
  578. self._stopping = True
  579. def close(self):
  580. """Close the event loop.
  581. This clears the queues and shuts down the executor,
  582. but does not wait for the executor to finish.
  583. The event loop must not be running.
  584. """
  585. if self.is_running():
  586. raise RuntimeError("Cannot close a running event loop")
  587. if self._closed:
  588. return
  589. if self._debug:
  590. logger.debug("Close %r", self)
  591. self._closed = True
  592. self._ready.clear()
  593. self._scheduled.clear()
  594. self._executor_shutdown_called = True
  595. executor = self._default_executor
  596. if executor is not None:
  597. self._default_executor = None
  598. executor.shutdown(wait=False)
  599. def is_closed(self):
  600. """Returns True if the event loop was closed."""
  601. return self._closed
  602. def __del__(self, _warn=warnings.warn):
  603. if not self.is_closed():
  604. _warn(f"unclosed event loop {self!r}", ResourceWarning, source=self)
  605. if not self.is_running():
  606. self.close()
  607. def is_running(self):
  608. """Returns True if the event loop is running."""
  609. return (self._thread_id is not None)
  610. def time(self):
  611. """Return the time according to the event loop's clock.
  612. This is a float expressed in seconds since an epoch, but the
  613. epoch, precision, accuracy and drift are unspecified and may
  614. differ per event loop.
  615. """
  616. return time.monotonic()
  617. def call_later(self, delay, callback, *args, context=None):
  618. """Arrange for a callback to be called at a given time.
  619. Return a Handle: an opaque object with a cancel() method that
  620. can be used to cancel the call.
  621. The delay can be an int or float, expressed in seconds. It is
  622. always relative to the current time.
  623. Each callback will be called exactly once. If two callbacks
  624. are scheduled for exactly the same time, it is undefined which
  625. will be called first.
  626. Any positional arguments after the callback will be passed to
  627. the callback when it is called.
  628. """
  629. if delay is None:
  630. raise TypeError('delay must not be None')
  631. timer = self.call_at(self.time() + delay, callback, *args,
  632. context=context)
  633. if timer._source_traceback:
  634. del timer._source_traceback[-1]
  635. return timer
  636. def call_at(self, when, callback, *args, context=None):
  637. """Like call_later(), but uses an absolute time.
  638. Absolute time corresponds to the event loop's time() method.
  639. """
  640. if when is None:
  641. raise TypeError("when cannot be None")
  642. self._check_closed()
  643. if self._debug:
  644. self._check_thread()
  645. self._check_callback(callback, 'call_at')
  646. timer = events.TimerHandle(when, callback, args, self, context)
  647. if timer._source_traceback:
  648. del timer._source_traceback[-1]
  649. heapq.heappush(self._scheduled, timer)
  650. timer._scheduled = True
  651. return timer
  652. def call_soon(self, callback, *args, context=None):
  653. """Arrange for a callback to be called as soon as possible.
  654. This operates as a FIFO queue: callbacks are called in the
  655. order in which they are registered. Each callback will be
  656. called exactly once.
  657. Any positional arguments after the callback will be passed to
  658. the callback when it is called.
  659. """
  660. self._check_closed()
  661. if self._debug:
  662. self._check_thread()
  663. self._check_callback(callback, 'call_soon')
  664. handle = self._call_soon(callback, args, context)
  665. if handle._source_traceback:
  666. del handle._source_traceback[-1]
  667. return handle
  668. def _check_callback(self, callback, method):
  669. if (coroutines.iscoroutine(callback) or
  670. coroutines.iscoroutinefunction(callback)):
  671. raise TypeError(
  672. f"coroutines cannot be used with {method}()")
  673. if not callable(callback):
  674. raise TypeError(
  675. f'a callable object was expected by {method}(), '
  676. f'got {callback!r}')
  677. def _call_soon(self, callback, args, context):
  678. handle = events.Handle(callback, args, self, context)
  679. if handle._source_traceback:
  680. del handle._source_traceback[-1]
  681. self._ready.append(handle)
  682. return handle
  683. def _check_thread(self):
  684. """Check that the current thread is the thread running the event loop.
  685. Non-thread-safe methods of this class make this assumption and will
  686. likely behave incorrectly when the assumption is violated.
  687. Should only be called when (self._debug == True). The caller is
  688. responsible for checking this condition for performance reasons.
  689. """
  690. if self._thread_id is None:
  691. return
  692. thread_id = threading.get_ident()
  693. if thread_id != self._thread_id:
  694. raise RuntimeError(
  695. "Non-thread-safe operation invoked on an event loop other "
  696. "than the current one")
  697. def call_soon_threadsafe(self, callback, *args, context=None):
  698. """Like call_soon(), but thread-safe."""
  699. self._check_closed()
  700. if self._debug:
  701. self._check_callback(callback, 'call_soon_threadsafe')
  702. handle = self._call_soon(callback, args, context)
  703. if handle._source_traceback:
  704. del handle._source_traceback[-1]
  705. self._write_to_self()
  706. return handle
  707. def run_in_executor(self, executor, func, *args):
  708. self._check_closed()
  709. if self._debug:
  710. self._check_callback(func, 'run_in_executor')
  711. if executor is None:
  712. executor = self._default_executor
  713. # Only check when the default executor is being used
  714. self._check_default_executor()
  715. if executor is None:
  716. executor = concurrent.futures.ThreadPoolExecutor(
  717. thread_name_prefix='asyncio'
  718. )
  719. self._default_executor = executor
  720. return futures.wrap_future(
  721. executor.submit(func, *args), loop=self)
  722. def set_default_executor(self, executor):
  723. if not isinstance(executor, concurrent.futures.ThreadPoolExecutor):
  724. raise TypeError('executor must be ThreadPoolExecutor instance')
  725. self._default_executor = executor
  726. def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
  727. msg = [f"{host}:{port!r}"]
  728. if family:
  729. msg.append(f'family={family!r}')
  730. if type:
  731. msg.append(f'type={type!r}')
  732. if proto:
  733. msg.append(f'proto={proto!r}')
  734. if flags:
  735. msg.append(f'flags={flags!r}')
  736. msg = ', '.join(msg)
  737. logger.debug('Get address info %s', msg)
  738. t0 = self.time()
  739. addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
  740. dt = self.time() - t0
  741. msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
  742. if dt >= self.slow_callback_duration:
  743. logger.info(msg)
  744. else:
  745. logger.debug(msg)
  746. return addrinfo
  747. async def getaddrinfo(self, host, port, *,
  748. family=0, type=0, proto=0, flags=0):
  749. if self._debug:
  750. getaddr_func = self._getaddrinfo_debug
  751. else:
  752. getaddr_func = socket.getaddrinfo
  753. return await self.run_in_executor(
  754. None, getaddr_func, host, port, family, type, proto, flags)
  755. async def getnameinfo(self, sockaddr, flags=0):
  756. return await self.run_in_executor(
  757. None, socket.getnameinfo, sockaddr, flags)
  758. async def sock_sendfile(self, sock, file, offset=0, count=None,
  759. *, fallback=True):
  760. if self._debug and sock.gettimeout() != 0:
  761. raise ValueError("the socket must be non-blocking")
  762. _check_ssl_socket(sock)
  763. self._check_sendfile_params(sock, file, offset, count)
  764. try:
  765. return await self._sock_sendfile_native(sock, file,
  766. offset, count)
  767. except exceptions.SendfileNotAvailableError as exc:
  768. if not fallback:
  769. raise
  770. return await self._sock_sendfile_fallback(sock, file,
  771. offset, count)
  772. async def _sock_sendfile_native(self, sock, file, offset, count):
  773. # NB: sendfile syscall is not supported for SSL sockets and
  774. # non-mmap files even if sendfile is supported by OS
  775. raise exceptions.SendfileNotAvailableError(
  776. f"syscall sendfile is not available for socket {sock!r} "
  777. f"and file {file!r} combination")
  778. async def _sock_sendfile_fallback(self, sock, file, offset, count):
  779. if offset:
  780. file.seek(offset)
  781. blocksize = (
  782. min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
  783. if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
  784. )
  785. buf = bytearray(blocksize)
  786. total_sent = 0
  787. try:
  788. while True:
  789. if count:
  790. blocksize = min(count - total_sent, blocksize)
  791. if blocksize <= 0:
  792. break
  793. view = memoryview(buf)[:blocksize]
  794. read = await self.run_in_executor(None, file.readinto, view)
  795. if not read:
  796. break # EOF
  797. await self.sock_sendall(sock, view[:read])
  798. total_sent += read
  799. return total_sent
  800. finally:
  801. if total_sent > 0 and hasattr(file, 'seek'):
  802. file.seek(offset + total_sent)
  803. def _check_sendfile_params(self, sock, file, offset, count):
  804. if 'b' not in getattr(file, 'mode', 'b'):
  805. raise ValueError("file should be opened in binary mode")
  806. if not sock.type == socket.SOCK_STREAM:
  807. raise ValueError("only SOCK_STREAM type sockets are supported")
  808. if count is not None:
  809. if not isinstance(count, int):
  810. raise TypeError(
  811. "count must be a positive integer (got {!r})".format(count))
  812. if count <= 0:
  813. raise ValueError(
  814. "count must be a positive integer (got {!r})".format(count))
  815. if not isinstance(offset, int):
  816. raise TypeError(
  817. "offset must be a non-negative integer (got {!r})".format(
  818. offset))
  819. if offset < 0:
  820. raise ValueError(
  821. "offset must be a non-negative integer (got {!r})".format(
  822. offset))
  823. async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None):
  824. """Create, bind and connect one socket."""
  825. my_exceptions = []
  826. exceptions.append(my_exceptions)
  827. family, type_, proto, _, address = addr_info
  828. sock = None
  829. try:
  830. sock = socket.socket(family=family, type=type_, proto=proto)
  831. sock.setblocking(False)
  832. if local_addr_infos is not None:
  833. for lfamily, _, _, _, laddr in local_addr_infos:
  834. # skip local addresses of different family
  835. if lfamily != family:
  836. continue
  837. try:
  838. sock.bind(laddr)
  839. break
  840. except OSError as exc:
  841. msg = (
  842. f'error while attempting to bind on '
  843. f'address {laddr!r}: {str(exc).lower()}'
  844. )
  845. exc = OSError(exc.errno, msg)
  846. my_exceptions.append(exc)
  847. else: # all bind attempts failed
  848. if my_exceptions:
  849. raise my_exceptions.pop()
  850. else:
  851. raise OSError(f"no matching local address with {family=} found")
  852. await self.sock_connect(sock, address)
  853. return sock
  854. except OSError as exc:
  855. my_exceptions.append(exc)
  856. if sock is not None:
  857. sock.close()
  858. raise
  859. except:
  860. if sock is not None:
  861. sock.close()
  862. raise
  863. finally:
  864. exceptions = my_exceptions = None
  865. async def create_connection(
  866. self, protocol_factory, host=None, port=None,
  867. *, ssl=None, family=0,
  868. proto=0, flags=0, sock=None,
  869. local_addr=None, server_hostname=None,
  870. ssl_handshake_timeout=None,
  871. ssl_shutdown_timeout=None,
  872. happy_eyeballs_delay=None, interleave=None,
  873. all_errors=False):
  874. """Connect to a TCP server.
  875. Create a streaming transport connection to a given internet host and
  876. port: socket family AF_INET or socket.AF_INET6 depending on host (or
  877. family if specified), socket type SOCK_STREAM. protocol_factory must be
  878. a callable returning a protocol instance.
  879. This method is a coroutine which will try to establish the connection
  880. in the background. When successful, the coroutine returns a
  881. (transport, protocol) pair.
  882. """
  883. if server_hostname is not None and not ssl:
  884. raise ValueError('server_hostname is only meaningful with ssl')
  885. if server_hostname is None and ssl:
  886. # Use host as default for server_hostname. It is an error
  887. # if host is empty or not set, e.g. when an
  888. # already-connected socket was passed or when only a port
  889. # is given. To avoid this error, you can pass
  890. # server_hostname='' -- this will bypass the hostname
  891. # check. (This also means that if host is a numeric
  892. # IP/IPv6 address, we will attempt to verify that exact
  893. # address; this will probably fail, but it is possible to
  894. # create a certificate for a specific IP address, so we
  895. # don't judge it here.)
  896. if not host:
  897. raise ValueError('You must set server_hostname '
  898. 'when using ssl without a host')
  899. server_hostname = host
  900. if ssl_handshake_timeout is not None and not ssl:
  901. raise ValueError(
  902. 'ssl_handshake_timeout is only meaningful with ssl')
  903. if ssl_shutdown_timeout is not None and not ssl:
  904. raise ValueError(
  905. 'ssl_shutdown_timeout is only meaningful with ssl')
  906. if sock is not None:
  907. _check_ssl_socket(sock)
  908. if happy_eyeballs_delay is not None and interleave is None:
  909. # If using happy eyeballs, default to interleave addresses by family
  910. interleave = 1
  911. if host is not None or port is not None:
  912. if sock is not None:
  913. raise ValueError(
  914. 'host/port and sock can not be specified at the same time')
  915. infos = await self._ensure_resolved(
  916. (host, port), family=family,
  917. type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
  918. if not infos:
  919. raise OSError('getaddrinfo() returned empty list')
  920. if local_addr is not None:
  921. laddr_infos = await self._ensure_resolved(
  922. local_addr, family=family,
  923. type=socket.SOCK_STREAM, proto=proto,
  924. flags=flags, loop=self)
  925. if not laddr_infos:
  926. raise OSError('getaddrinfo() returned empty list')
  927. else:
  928. laddr_infos = None
  929. if interleave:
  930. infos = _interleave_addrinfos(infos, interleave)
  931. exceptions = []
  932. if happy_eyeballs_delay is None:
  933. # not using happy eyeballs
  934. for addrinfo in infos:
  935. try:
  936. sock = await self._connect_sock(
  937. exceptions, addrinfo, laddr_infos)
  938. break
  939. except OSError:
  940. continue
  941. else: # using happy eyeballs
  942. sock = (await staggered.staggered_race(
  943. (
  944. # can't use functools.partial as it keeps a reference
  945. # to exceptions
  946. lambda addrinfo=addrinfo: self._connect_sock(
  947. exceptions, addrinfo, laddr_infos
  948. )
  949. for addrinfo in infos
  950. ),
  951. happy_eyeballs_delay,
  952. loop=self,
  953. ))[0] # can't use sock, _, _ as it keeks a reference to exceptions
  954. if sock is None:
  955. exceptions = [exc for sub in exceptions for exc in sub]
  956. try:
  957. if all_errors:
  958. raise ExceptionGroup("create_connection failed", exceptions)
  959. if len(exceptions) == 1:
  960. raise exceptions[0]
  961. else:
  962. # If they all have the same str(), raise one.
  963. model = str(exceptions[0])
  964. if all(str(exc) == model for exc in exceptions):
  965. raise exceptions[0]
  966. # Raise a combined exception so the user can see all
  967. # the various error messages.
  968. raise OSError('Multiple exceptions: {}'.format(
  969. ', '.join(str(exc) for exc in exceptions)))
  970. finally:
  971. exceptions = None
  972. else:
  973. if sock is None:
  974. raise ValueError(
  975. 'host and port was not specified and no sock specified')
  976. if sock.type != socket.SOCK_STREAM:
  977. # We allow AF_INET, AF_INET6, AF_UNIX as long as they
  978. # are SOCK_STREAM.
  979. # We support passing AF_UNIX sockets even though we have
  980. # a dedicated API for that: create_unix_connection.
  981. # Disallowing AF_UNIX in this method, breaks backwards
  982. # compatibility.
  983. raise ValueError(
  984. f'A Stream Socket was expected, got {sock!r}')
  985. transport, protocol = await self._create_connection_transport(
  986. sock, protocol_factory, ssl, server_hostname,
  987. ssl_handshake_timeout=ssl_handshake_timeout,
  988. ssl_shutdown_timeout=ssl_shutdown_timeout)
  989. if self._debug:
  990. # Get the socket from the transport because SSL transport closes
  991. # the old socket and creates a new SSL socket
  992. sock = transport.get_extra_info('socket')
  993. logger.debug("%r connected to %s:%r: (%r, %r)",
  994. sock, host, port, transport, protocol)
  995. return transport, protocol
  996. async def _create_connection_transport(
  997. self, sock, protocol_factory, ssl,
  998. server_hostname, server_side=False,
  999. ssl_handshake_timeout=None,
  1000. ssl_shutdown_timeout=None):
  1001. sock.setblocking(False)
  1002. protocol = protocol_factory()
  1003. waiter = self.create_future()
  1004. if ssl:
  1005. sslcontext = None if isinstance(ssl, bool) else ssl
  1006. transport = self._make_ssl_transport(
  1007. sock, protocol, sslcontext, waiter,
  1008. server_side=server_side, server_hostname=server_hostname,
  1009. ssl_handshake_timeout=ssl_handshake_timeout,
  1010. ssl_shutdown_timeout=ssl_shutdown_timeout)
  1011. else:
  1012. transport = self._make_socket_transport(sock, protocol, waiter)
  1013. try:
  1014. await waiter
  1015. except:
  1016. transport.close()
  1017. raise
  1018. return transport, protocol
  1019. async def sendfile(self, transport, file, offset=0, count=None,
  1020. *, fallback=True):
  1021. """Send a file to transport.
  1022. Return the total number of bytes which were sent.
  1023. The method uses high-performance os.sendfile if available.
  1024. file must be a regular file object opened in binary mode.
  1025. offset tells from where to start reading the file. If specified,
  1026. count is the total number of bytes to transmit as opposed to
  1027. sending the file until EOF is reached. File position is updated on
  1028. return or also in case of error in which case file.tell()
  1029. can be used to figure out the number of bytes
  1030. which were sent.
  1031. fallback set to True makes asyncio to manually read and send
  1032. the file when the platform does not support the sendfile syscall
  1033. (e.g. Windows or SSL socket on Unix).
  1034. Raise SendfileNotAvailableError if the system does not support
  1035. sendfile syscall and fallback is False.
  1036. """
  1037. if transport.is_closing():
  1038. raise RuntimeError("Transport is closing")
  1039. mode = getattr(transport, '_sendfile_compatible',
  1040. constants._SendfileMode.UNSUPPORTED)
  1041. if mode is constants._SendfileMode.UNSUPPORTED:
  1042. raise RuntimeError(
  1043. f"sendfile is not supported for transport {transport!r}")
  1044. if mode is constants._SendfileMode.TRY_NATIVE:
  1045. try:
  1046. return await self._sendfile_native(transport, file,
  1047. offset, count)
  1048. except exceptions.SendfileNotAvailableError as exc:
  1049. if not fallback:
  1050. raise
  1051. if not fallback:
  1052. raise RuntimeError(
  1053. f"fallback is disabled and native sendfile is not "
  1054. f"supported for transport {transport!r}")
  1055. return await self._sendfile_fallback(transport, file,
  1056. offset, count)
  1057. async def _sendfile_native(self, transp, file, offset, count):
  1058. raise exceptions.SendfileNotAvailableError(
  1059. "sendfile syscall is not supported")
  1060. async def _sendfile_fallback(self, transp, file, offset, count):
  1061. if offset:
  1062. file.seek(offset)
  1063. blocksize = min(count, 16384) if count else 16384
  1064. buf = bytearray(blocksize)
  1065. total_sent = 0
  1066. proto = _SendfileFallbackProtocol(transp)
  1067. try:
  1068. while True:
  1069. if count:
  1070. blocksize = min(count - total_sent, blocksize)
  1071. if blocksize <= 0:
  1072. return total_sent
  1073. view = memoryview(buf)[:blocksize]
  1074. read = await self.run_in_executor(None, file.readinto, view)
  1075. if not read:
  1076. return total_sent # EOF
  1077. await proto.drain()
  1078. transp.write(view[:read])
  1079. total_sent += read
  1080. finally:
  1081. if total_sent > 0 and hasattr(file, 'seek'):
  1082. file.seek(offset + total_sent)
  1083. await proto.restore()
  1084. async def start_tls(self, transport, protocol, sslcontext, *,
  1085. server_side=False,
  1086. server_hostname=None,
  1087. ssl_handshake_timeout=None,
  1088. ssl_shutdown_timeout=None):
  1089. """Upgrade transport to TLS.
  1090. Return a new transport that *protocol* should start using
  1091. immediately.
  1092. """
  1093. if ssl is None:
  1094. raise RuntimeError('Python ssl module is not available')
  1095. if not isinstance(sslcontext, ssl.SSLContext):
  1096. raise TypeError(
  1097. f'sslcontext is expected to be an instance of ssl.SSLContext, '
  1098. f'got {sslcontext!r}')
  1099. if not getattr(transport, '_start_tls_compatible', False):
  1100. raise TypeError(
  1101. f'transport {transport!r} is not supported by start_tls()')
  1102. waiter = self.create_future()
  1103. ssl_protocol = sslproto.SSLProtocol(
  1104. self, protocol, sslcontext, waiter,
  1105. server_side, server_hostname,
  1106. ssl_handshake_timeout=ssl_handshake_timeout,
  1107. ssl_shutdown_timeout=ssl_shutdown_timeout,
  1108. call_connection_made=False)
  1109. # Pause early so that "ssl_protocol.data_received()" doesn't
  1110. # have a chance to get called before "ssl_protocol.connection_made()".
  1111. transport.pause_reading()
  1112. transport.set_protocol(ssl_protocol)
  1113. conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
  1114. resume_cb = self.call_soon(transport.resume_reading)
  1115. try:
  1116. await waiter
  1117. except BaseException:
  1118. transport.close()
  1119. conmade_cb.cancel()
  1120. resume_cb.cancel()
  1121. raise
  1122. return ssl_protocol._app_transport
  1123. async def create_datagram_endpoint(self, protocol_factory,
  1124. local_addr=None, remote_addr=None, *,
  1125. family=0, proto=0, flags=0,
  1126. reuse_port=None,
  1127. allow_broadcast=None, sock=None):
  1128. """Create datagram connection."""
  1129. if sock is not None:
  1130. if sock.type == socket.SOCK_STREAM:
  1131. raise ValueError(
  1132. f'A datagram socket was expected, got {sock!r}')
  1133. if (local_addr or remote_addr or
  1134. family or proto or flags or
  1135. reuse_port or allow_broadcast):
  1136. # show the problematic kwargs in exception msg
  1137. opts = dict(local_addr=local_addr, remote_addr=remote_addr,
  1138. family=family, proto=proto, flags=flags,
  1139. reuse_port=reuse_port,
  1140. allow_broadcast=allow_broadcast)
  1141. problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
  1142. raise ValueError(
  1143. f'socket modifier keyword arguments can not be used '
  1144. f'when sock is specified. ({problems})')
  1145. sock.setblocking(False)
  1146. r_addr = None
  1147. else:
  1148. if not (local_addr or remote_addr):
  1149. if family == 0:
  1150. raise ValueError('unexpected address family')
  1151. addr_pairs_info = (((family, proto), (None, None)),)
  1152. elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
  1153. for addr in (local_addr, remote_addr):
  1154. if addr is not None and not isinstance(addr, str):
  1155. raise TypeError('string is expected')
  1156. if local_addr and local_addr[0] not in (0, '\x00'):
  1157. try:
  1158. if stat.S_ISSOCK(os.stat(local_addr).st_mode):
  1159. os.remove(local_addr)
  1160. except FileNotFoundError:
  1161. pass
  1162. except OSError as err:
  1163. # Directory may have permissions only to create socket.
  1164. logger.error('Unable to check or remove stale UNIX '
  1165. 'socket %r: %r',
  1166. local_addr, err)
  1167. addr_pairs_info = (((family, proto),
  1168. (local_addr, remote_addr)), )
  1169. else:
  1170. # join address by (family, protocol)
  1171. addr_infos = {} # Using order preserving dict
  1172. for idx, addr in ((0, local_addr), (1, remote_addr)):
  1173. if addr is not None:
  1174. if not (isinstance(addr, tuple) and len(addr) == 2):
  1175. raise TypeError('2-tuple is expected')
  1176. infos = await self._ensure_resolved(
  1177. addr, family=family, type=socket.SOCK_DGRAM,
  1178. proto=proto, flags=flags, loop=self)
  1179. if not infos:
  1180. raise OSError('getaddrinfo() returned empty list')
  1181. for fam, _, pro, _, address in infos:
  1182. key = (fam, pro)
  1183. if key not in addr_infos:
  1184. addr_infos[key] = [None, None]
  1185. addr_infos[key][idx] = address
  1186. # each addr has to have info for each (family, proto) pair
  1187. addr_pairs_info = [
  1188. (key, addr_pair) for key, addr_pair in addr_infos.items()
  1189. if not ((local_addr and addr_pair[0] is None) or
  1190. (remote_addr and addr_pair[1] is None))]
  1191. if not addr_pairs_info:
  1192. raise ValueError('can not get address information')
  1193. exceptions = []
  1194. for ((family, proto),
  1195. (local_address, remote_address)) in addr_pairs_info:
  1196. sock = None
  1197. r_addr = None
  1198. try:
  1199. sock = socket.socket(
  1200. family=family, type=socket.SOCK_DGRAM, proto=proto)
  1201. if reuse_port:
  1202. _set_reuseport(sock)
  1203. if allow_broadcast:
  1204. sock.setsockopt(
  1205. socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  1206. sock.setblocking(False)
  1207. if local_addr:
  1208. sock.bind(local_address)
  1209. if remote_addr:
  1210. if not allow_broadcast:
  1211. await self.sock_connect(sock, remote_address)
  1212. r_addr = remote_address
  1213. except OSError as exc:
  1214. if sock is not None:
  1215. sock.close()
  1216. exceptions.append(exc)
  1217. except:
  1218. if sock is not None:
  1219. sock.close()
  1220. raise
  1221. else:
  1222. break
  1223. else:
  1224. raise exceptions[0]
  1225. protocol = protocol_factory()
  1226. waiter = self.create_future()
  1227. transport = self._make_datagram_transport(
  1228. sock, protocol, r_addr, waiter)
  1229. if self._debug:
  1230. if local_addr:
  1231. logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
  1232. "created: (%r, %r)",
  1233. local_addr, remote_addr, transport, protocol)
  1234. else:
  1235. logger.debug("Datagram endpoint remote_addr=%r created: "
  1236. "(%r, %r)",
  1237. remote_addr, transport, protocol)
  1238. try:
  1239. await waiter
  1240. except:
  1241. transport.close()
  1242. raise
  1243. return transport, protocol
  1244. async def _ensure_resolved(self, address, *,
  1245. family=0, type=socket.SOCK_STREAM,
  1246. proto=0, flags=0, loop):
  1247. host, port = address[:2]
  1248. info = _ipaddr_info(host, port, family, type, proto, *address[2:])
  1249. if info is not None:
  1250. # "host" is already a resolved IP.
  1251. return [info]
  1252. else:
  1253. return await loop.getaddrinfo(host, port, family=family, type=type,
  1254. proto=proto, flags=flags)
  1255. async def _create_server_getaddrinfo(self, host, port, family, flags):
  1256. infos = await self._ensure_resolved((host, port), family=family,
  1257. type=socket.SOCK_STREAM,
  1258. flags=flags, loop=self)
  1259. if not infos:
  1260. raise OSError(f'getaddrinfo({host!r}) returned empty list')
  1261. return infos
  1262. async def create_server(
  1263. self, protocol_factory, host=None, port=None,
  1264. *,
  1265. family=socket.AF_UNSPEC,
  1266. flags=socket.AI_PASSIVE,
  1267. sock=None,
  1268. backlog=100,
  1269. ssl=None,
  1270. reuse_address=None,
  1271. reuse_port=None,
  1272. ssl_handshake_timeout=None,
  1273. ssl_shutdown_timeout=None,
  1274. start_serving=True):
  1275. """Create a TCP server.
  1276. The host parameter can be a string, in that case the TCP server is
  1277. bound to host and port.
  1278. The host parameter can also be a sequence of strings and in that case
  1279. the TCP server is bound to all hosts of the sequence. If a host
  1280. appears multiple times (possibly indirectly e.g. when hostnames
  1281. resolve to the same IP address), the server is only bound once to that
  1282. host.
  1283. Return a Server object which can be used to stop the service.
  1284. This method is a coroutine.
  1285. """
  1286. if isinstance(ssl, bool):
  1287. raise TypeError('ssl argument must be an SSLContext or None')
  1288. if ssl_handshake_timeout is not None and ssl is None:
  1289. raise ValueError(
  1290. 'ssl_handshake_timeout is only meaningful with ssl')
  1291. if ssl_shutdown_timeout is not None and ssl is None:
  1292. raise ValueError(
  1293. 'ssl_shutdown_timeout is only meaningful with ssl')
  1294. if sock is not None:
  1295. _check_ssl_socket(sock)
  1296. if host is not None or port is not None:
  1297. if sock is not None:
  1298. raise ValueError(
  1299. 'host/port and sock can not be specified at the same time')
  1300. if reuse_address is None:
  1301. reuse_address = os.name == "posix" and sys.platform != "cygwin"
  1302. sockets = []
  1303. if host == '':
  1304. hosts = [None]
  1305. elif (isinstance(host, str) or
  1306. not isinstance(host, collections.abc.Iterable)):
  1307. hosts = [host]
  1308. else:
  1309. hosts = host
  1310. fs = [self._create_server_getaddrinfo(host, port, family=family,
  1311. flags=flags)
  1312. for host in hosts]
  1313. infos = await tasks.gather(*fs)
  1314. infos = set(itertools.chain.from_iterable(infos))
  1315. completed = False
  1316. try:
  1317. for res in infos:
  1318. af, socktype, proto, canonname, sa = res
  1319. try:
  1320. sock = socket.socket(af, socktype, proto)
  1321. except socket.error:
  1322. # Assume it's a bad family/type/protocol combination.
  1323. if self._debug:
  1324. logger.warning('create_server() failed to create '
  1325. 'socket.socket(%r, %r, %r)',
  1326. af, socktype, proto, exc_info=True)
  1327. continue
  1328. sockets.append(sock)
  1329. if reuse_address:
  1330. sock.setsockopt(
  1331. socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
  1332. # Since Linux 6.12.9, SO_REUSEPORT is not allowed
  1333. # on other address families than AF_INET/AF_INET6.
  1334. if reuse_port and af in (socket.AF_INET, socket.AF_INET6):
  1335. _set_reuseport(sock)
  1336. # Disable IPv4/IPv6 dual stack support (enabled by
  1337. # default on Linux) which makes a single socket
  1338. # listen on both address families.
  1339. if (_HAS_IPv6 and
  1340. af == socket.AF_INET6 and
  1341. hasattr(socket, 'IPPROTO_IPV6')):
  1342. sock.setsockopt(socket.IPPROTO_IPV6,
  1343. socket.IPV6_V6ONLY,
  1344. True)
  1345. try:
  1346. sock.bind(sa)
  1347. except OSError as err:
  1348. msg = ('error while attempting '
  1349. 'to bind on address %r: %s'
  1350. % (sa, str(err).lower()))
  1351. if err.errno == errno.EADDRNOTAVAIL:
  1352. # Assume the family is not enabled (bpo-30945)
  1353. sockets.pop()
  1354. sock.close()
  1355. if self._debug:
  1356. logger.warning(msg)
  1357. continue
  1358. raise OSError(err.errno, msg) from None
  1359. if not sockets:
  1360. raise OSError('could not bind on any address out of %r'
  1361. % ([info[4] for info in infos],))
  1362. completed = True
  1363. finally:
  1364. if not completed:
  1365. for sock in sockets:
  1366. sock.close()
  1367. else:
  1368. if sock is None:
  1369. raise ValueError('Neither host/port nor sock were specified')
  1370. if sock.type != socket.SOCK_STREAM:
  1371. raise ValueError(f'A Stream Socket was expected, got {sock!r}')
  1372. sockets = [sock]
  1373. for sock in sockets:
  1374. sock.setblocking(False)
  1375. server = Server(self, sockets, protocol_factory,
  1376. ssl, backlog, ssl_handshake_timeout,
  1377. ssl_shutdown_timeout)
  1378. if start_serving:
  1379. server._start_serving()
  1380. # Skip one loop iteration so that all 'loop.add_reader'
  1381. # go through.
  1382. await tasks.sleep(0)
  1383. if self._debug:
  1384. logger.info("%r is serving", server)
  1385. return server
  1386. async def connect_accepted_socket(
  1387. self, protocol_factory, sock,
  1388. *, ssl=None,
  1389. ssl_handshake_timeout=None,
  1390. ssl_shutdown_timeout=None):
  1391. if sock.type != socket.SOCK_STREAM:
  1392. raise ValueError(f'A Stream Socket was expected, got {sock!r}')
  1393. if ssl_handshake_timeout is not None and not ssl:
  1394. raise ValueError(
  1395. 'ssl_handshake_timeout is only meaningful with ssl')
  1396. if ssl_shutdown_timeout is not None and not ssl:
  1397. raise ValueError(
  1398. 'ssl_shutdown_timeout is only meaningful with ssl')
  1399. if sock is not None:
  1400. _check_ssl_socket(sock)
  1401. transport, protocol = await self._create_connection_transport(
  1402. sock, protocol_factory, ssl, '', server_side=True,
  1403. ssl_handshake_timeout=ssl_handshake_timeout,
  1404. ssl_shutdown_timeout=ssl_shutdown_timeout)
  1405. if self._debug:
  1406. # Get the socket from the transport because SSL transport closes
  1407. # the old socket and creates a new SSL socket
  1408. sock = transport.get_extra_info('socket')
  1409. logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
  1410. return transport, protocol
  1411. async def connect_read_pipe(self, protocol_factory, pipe):
  1412. protocol = protocol_factory()
  1413. waiter = self.create_future()
  1414. transport = self._make_read_pipe_transport(pipe, protocol, waiter)
  1415. try:
  1416. await waiter
  1417. except:
  1418. transport.close()
  1419. raise
  1420. if self._debug:
  1421. logger.debug('Read pipe %r connected: (%r, %r)',
  1422. pipe.fileno(), transport, protocol)
  1423. return transport, protocol
  1424. async def connect_write_pipe(self, protocol_factory, pipe):
  1425. protocol = protocol_factory()
  1426. waiter = self.create_future()
  1427. transport = self._make_write_pipe_transport(pipe, protocol, waiter)
  1428. try:
  1429. await waiter
  1430. except:
  1431. transport.close()
  1432. raise
  1433. if self._debug:
  1434. logger.debug('Write pipe %r connected: (%r, %r)',
  1435. pipe.fileno(), transport, protocol)
  1436. return transport, protocol
  1437. def _log_subprocess(self, msg, stdin, stdout, stderr):
  1438. info = [msg]
  1439. if stdin is not None:
  1440. info.append(f'stdin={_format_pipe(stdin)}')
  1441. if stdout is not None and stderr == subprocess.STDOUT:
  1442. info.append(f'stdout=stderr={_format_pipe(stdout)}')
  1443. else:
  1444. if stdout is not None:
  1445. info.append(f'stdout={_format_pipe(stdout)}')
  1446. if stderr is not None:
  1447. info.append(f'stderr={_format_pipe(stderr)}')
  1448. logger.debug(' '.join(info))
  1449. async def subprocess_shell(self, protocol_factory, cmd, *,
  1450. stdin=subprocess.PIPE,
  1451. stdout=subprocess.PIPE,
  1452. stderr=subprocess.PIPE,
  1453. universal_newlines=False,
  1454. shell=True, bufsize=0,
  1455. encoding=None, errors=None, text=None,
  1456. **kwargs):
  1457. if not isinstance(cmd, (bytes, str)):
  1458. raise ValueError("cmd must be a string")
  1459. if universal_newlines:
  1460. raise ValueError("universal_newlines must be False")
  1461. if not shell:
  1462. raise ValueError("shell must be True")
  1463. if bufsize != 0:
  1464. raise ValueError("bufsize must be 0")
  1465. if text:
  1466. raise ValueError("text must be False")
  1467. if encoding is not None:
  1468. raise ValueError("encoding must be None")
  1469. if errors is not None:
  1470. raise ValueError("errors must be None")
  1471. protocol = protocol_factory()
  1472. debug_log = None
  1473. if self._debug:
  1474. # don't log parameters: they may contain sensitive information
  1475. # (password) and may be too long
  1476. debug_log = 'run shell command %r' % cmd
  1477. self._log_subprocess(debug_log, stdin, stdout, stderr)
  1478. transport = await self._make_subprocess_transport(
  1479. protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
  1480. if self._debug and debug_log is not None:
  1481. logger.info('%s: %r', debug_log, transport)
  1482. return transport, protocol
  1483. async def subprocess_exec(self, protocol_factory, program, *args,
  1484. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1485. stderr=subprocess.PIPE, universal_newlines=False,
  1486. shell=False, bufsize=0,
  1487. encoding=None, errors=None, text=None,
  1488. **kwargs):
  1489. if universal_newlines:
  1490. raise ValueError("universal_newlines must be False")
  1491. if shell:
  1492. raise ValueError("shell must be False")
  1493. if bufsize != 0:
  1494. raise ValueError("bufsize must be 0")
  1495. if text:
  1496. raise ValueError("text must be False")
  1497. if encoding is not None:
  1498. raise ValueError("encoding must be None")
  1499. if errors is not None:
  1500. raise ValueError("errors must be None")
  1501. popen_args = (program,) + args
  1502. protocol = protocol_factory()
  1503. debug_log = None
  1504. if self._debug:
  1505. # don't log parameters: they may contain sensitive information
  1506. # (password) and may be too long
  1507. debug_log = f'execute program {program!r}'
  1508. self._log_subprocess(debug_log, stdin, stdout, stderr)
  1509. transport = await self._make_subprocess_transport(
  1510. protocol, popen_args, False, stdin, stdout, stderr,
  1511. bufsize, **kwargs)
  1512. if self._debug and debug_log is not None:
  1513. logger.info('%s: %r', debug_log, transport)
  1514. return transport, protocol
  1515. def get_exception_handler(self):
  1516. """Return an exception handler, or None if the default one is in use.
  1517. """
  1518. return self._exception_handler
  1519. def set_exception_handler(self, handler):
  1520. """Set handler as the new event loop exception handler.
  1521. If handler is None, the default exception handler will
  1522. be set.
  1523. If handler is a callable object, it should have a
  1524. signature matching '(loop, context)', where 'loop'
  1525. will be a reference to the active event loop, 'context'
  1526. will be a dict object (see `call_exception_handler()`
  1527. documentation for details about context).
  1528. """
  1529. if handler is not None and not callable(handler):
  1530. raise TypeError(f'A callable object or None is expected, '
  1531. f'got {handler!r}')
  1532. self._exception_handler = handler
  1533. def default_exception_handler(self, context):
  1534. """Default exception handler.
  1535. This is called when an exception occurs and no exception
  1536. handler is set, and can be called by a custom exception
  1537. handler that wants to defer to the default behavior.
  1538. This default handler logs the error message and other
  1539. context-dependent information. In debug mode, a truncated
  1540. stack trace is also appended showing where the given object
  1541. (e.g. a handle or future or task) was created, if any.
  1542. The context parameter has the same meaning as in
  1543. `call_exception_handler()`.
  1544. """
  1545. message = context.get('message')
  1546. if not message:
  1547. message = 'Unhandled exception in event loop'
  1548. exception = context.get('exception')
  1549. if exception is not None:
  1550. exc_info = (type(exception), exception, exception.__traceback__)
  1551. else:
  1552. exc_info = False
  1553. if ('source_traceback' not in context and
  1554. self._current_handle is not None and
  1555. self._current_handle._source_traceback):
  1556. context['handle_traceback'] = \
  1557. self._current_handle._source_traceback
  1558. log_lines = [message]
  1559. for key in sorted(context):
  1560. if key in {'message', 'exception'}:
  1561. continue
  1562. value = context[key]
  1563. if key == 'source_traceback':
  1564. tb = ''.join(traceback.format_list(value))
  1565. value = 'Object created at (most recent call last):\n'
  1566. value += tb.rstrip()
  1567. elif key == 'handle_traceback':
  1568. tb = ''.join(traceback.format_list(value))
  1569. value = 'Handle created at (most recent call last):\n'
  1570. value += tb.rstrip()
  1571. else:
  1572. value = repr(value)
  1573. log_lines.append(f'{key}: {value}')
  1574. logger.error('\n'.join(log_lines), exc_info=exc_info)
  1575. def call_exception_handler(self, context):
  1576. """Call the current event loop's exception handler.
  1577. The context argument is a dict containing the following keys:
  1578. - 'message': Error message;
  1579. - 'exception' (optional): Exception object;
  1580. - 'future' (optional): Future instance;
  1581. - 'task' (optional): Task instance;
  1582. - 'handle' (optional): Handle instance;
  1583. - 'protocol' (optional): Protocol instance;
  1584. - 'transport' (optional): Transport instance;
  1585. - 'socket' (optional): Socket instance;
  1586. - 'asyncgen' (optional): Asynchronous generator that caused
  1587. the exception.
  1588. New keys maybe introduced in the future.
  1589. Note: do not overload this method in an event loop subclass.
  1590. For custom exception handling, use the
  1591. `set_exception_handler()` method.
  1592. """
  1593. if self._exception_handler is None:
  1594. try:
  1595. self.default_exception_handler(context)
  1596. except (SystemExit, KeyboardInterrupt):
  1597. raise
  1598. except BaseException:
  1599. # Second protection layer for unexpected errors
  1600. # in the default implementation, as well as for subclassed
  1601. # event loops with overloaded "default_exception_handler".
  1602. logger.error('Exception in default exception handler',
  1603. exc_info=True)
  1604. else:
  1605. try:
  1606. ctx = None
  1607. thing = context.get("task")
  1608. if thing is None:
  1609. # Even though Futures don't have a context,
  1610. # Task is a subclass of Future,
  1611. # and sometimes the 'future' key holds a Task.
  1612. thing = context.get("future")
  1613. if thing is None:
  1614. # Handles also have a context.
  1615. thing = context.get("handle")
  1616. if thing is not None and hasattr(thing, "get_context"):
  1617. ctx = thing.get_context()
  1618. if ctx is not None and hasattr(ctx, "run"):
  1619. ctx.run(self._exception_handler, self, context)
  1620. else:
  1621. self._exception_handler(self, context)
  1622. except (SystemExit, KeyboardInterrupt):
  1623. raise
  1624. except BaseException as exc:
  1625. # Exception in the user set custom exception handler.
  1626. try:
  1627. # Let's try default handler.
  1628. self.default_exception_handler({
  1629. 'message': 'Unhandled error in exception handler',
  1630. 'exception': exc,
  1631. 'context': context,
  1632. })
  1633. except (SystemExit, KeyboardInterrupt):
  1634. raise
  1635. except BaseException:
  1636. # Guard 'default_exception_handler' in case it is
  1637. # overloaded.
  1638. logger.error('Exception in default exception handler '
  1639. 'while handling an unexpected error '
  1640. 'in custom exception handler',
  1641. exc_info=True)
  1642. def _add_callback(self, handle):
  1643. """Add a Handle to _ready."""
  1644. if not handle._cancelled:
  1645. self._ready.append(handle)
  1646. def _add_callback_signalsafe(self, handle):
  1647. """Like _add_callback() but called from a signal handler."""
  1648. self._add_callback(handle)
  1649. self._write_to_self()
  1650. def _timer_handle_cancelled(self, handle):
  1651. """Notification that a TimerHandle has been cancelled."""
  1652. if handle._scheduled:
  1653. self._timer_cancelled_count += 1
  1654. def _run_once(self):
  1655. """Run one full iteration of the event loop.
  1656. This calls all currently ready callbacks, polls for I/O,
  1657. schedules the resulting callbacks, and finally schedules
  1658. 'call_later' callbacks.
  1659. """
  1660. sched_count = len(self._scheduled)
  1661. if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
  1662. self._timer_cancelled_count / sched_count >
  1663. _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
  1664. # Remove delayed calls that were cancelled if their number
  1665. # is too high
  1666. new_scheduled = []
  1667. for handle in self._scheduled:
  1668. if handle._cancelled:
  1669. handle._scheduled = False
  1670. else:
  1671. new_scheduled.append(handle)
  1672. heapq.heapify(new_scheduled)
  1673. self._scheduled = new_scheduled
  1674. self._timer_cancelled_count = 0
  1675. else:
  1676. # Remove delayed calls that were cancelled from head of queue.
  1677. while self._scheduled and self._scheduled[0]._cancelled:
  1678. self._timer_cancelled_count -= 1
  1679. handle = heapq.heappop(self._scheduled)
  1680. handle._scheduled = False
  1681. timeout = None
  1682. if self._ready or self._stopping:
  1683. timeout = 0
  1684. elif self._scheduled:
  1685. # Compute the desired timeout.
  1686. when = self._scheduled[0]._when
  1687. timeout = min(max(0, when - self.time()), MAXIMUM_SELECT_TIMEOUT)
  1688. event_list = self._selector.select(timeout)
  1689. self._process_events(event_list)
  1690. # Needed to break cycles when an exception occurs.
  1691. event_list = None
  1692. # Handle 'later' callbacks that are ready.
  1693. end_time = self.time() + self._clock_resolution
  1694. while self._scheduled:
  1695. handle = self._scheduled[0]
  1696. if handle._when >= end_time:
  1697. break
  1698. handle = heapq.heappop(self._scheduled)
  1699. handle._scheduled = False
  1700. self._ready.append(handle)
  1701. # This is the only place where callbacks are actually *called*.
  1702. # All other places just add them to ready.
  1703. # Note: We run all currently scheduled callbacks, but not any
  1704. # callbacks scheduled by callbacks run this time around --
  1705. # they will be run the next time (after another I/O poll).
  1706. # Use an idiom that is thread-safe without using locks.
  1707. ntodo = len(self._ready)
  1708. for i in range(ntodo):
  1709. handle = self._ready.popleft()
  1710. if handle._cancelled:
  1711. continue
  1712. if self._debug:
  1713. try:
  1714. self._current_handle = handle
  1715. t0 = self.time()
  1716. handle._run()
  1717. dt = self.time() - t0
  1718. if dt >= self.slow_callback_duration:
  1719. logger.warning('Executing %s took %.3f seconds',
  1720. _format_handle(handle), dt)
  1721. finally:
  1722. self._current_handle = None
  1723. else:
  1724. handle._run()
  1725. handle = None # Needed to break cycles when an exception occurs.
  1726. def _set_coroutine_origin_tracking(self, enabled):
  1727. if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
  1728. return
  1729. if enabled:
  1730. self._coroutine_origin_tracking_saved_depth = (
  1731. sys.get_coroutine_origin_tracking_depth())
  1732. sys.set_coroutine_origin_tracking_depth(
  1733. constants.DEBUG_STACK_DEPTH)
  1734. else:
  1735. sys.set_coroutine_origin_tracking_depth(
  1736. self._coroutine_origin_tracking_saved_depth)
  1737. self._coroutine_origin_tracking_enabled = enabled
  1738. def get_debug(self):
  1739. return self._debug
  1740. def set_debug(self, enabled):
  1741. self._debug = enabled
  1742. if self.is_running():
  1743. self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)