base_events.py 72 KB

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