logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

base_events.py (73451B)


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