base_events.py 73 KB

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