Debian Codegraph @

lib-python/3/asyncio/base_events.py

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