base_events.py 72 KB

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