base_events.py 68 KB

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