base_events.py 76 KB

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