blob: 68a1ebe623b87192c4da9ef95e8847c26b51df3e [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Base implementation of event loop.
2
3The event loop can be broken up into a multiplexer (the part
Victor Stinneracdb7822014-07-14 18:33:40 +02004responsible for notifying us of I/O events) and the event loop proper,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07005which wraps a multiplexer with functionality for scheduling callbacks,
6immediately or at a given time in the future.
7
8Whenever a public API takes a callback, subsequent positional
9arguments will be passed to the callback if/when it is called. This
10avoids the proliferation of trivial lambdas implementing closures.
11Keyword arguments for the callback are not supported; this is a
12conscious design decision, leaving the door open for keyword arguments
13to modify the meaning of the API call itself.
14"""
15
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import collections
Serhiy Storchaka2e576f52017-04-24 09:05:00 +030017import collections.abc
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import concurrent.futures
19import heapq
Victor Stinner5e4a7d82015-09-21 18:33:43 +020020import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070021import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020022import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023import socket
24import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010025import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020027import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070028import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010029import warnings
Yury Selivanoveb636452016-09-08 22:01:51 -070030import weakref
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanovf111b3d2017-12-30 00:35:36 -050032try:
33 import ssl
34except ImportError: # pragma: no cover
35 ssl = None
36
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037from . import constants
Victor Stinnerf951d282014-06-29 00:46:45 +020038from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039from . import events
40from . import futures
Andrew Svetlov7c684072018-01-27 21:22:47 +020041from . import protocols
Yury Selivanovf111b3d2017-12-30 00:35:36 -050042from . import sslproto
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070043from . import tasks
Andrew Svetlov7c684072018-01-27 21:22:47 +020044from . import transports
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070045from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046
47
Yury Selivanov6370f342017-12-10 18:36:12 -050048__all__ = 'BaseEventLoop',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049
50
Yury Selivanov592ada92014-09-25 12:07:56 -040051# Minimum number of _scheduled timer handles before cleanup of
52# cancelled handles is performed.
53_MIN_SCHEDULED_TIMER_HANDLES = 100
54
55# Minimum fraction of _scheduled timer handles that are cancelled
56# before cleanup of cancelled handles is performed.
57_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070058
Victor Stinnerc94a93a2016-04-01 21:43:39 +020059# Exceptions which must not call the exception handler in fatal error
60# methods (_fatal_error())
61_FATAL_ERROR_IGNORE = (BrokenPipeError,
62 ConnectionResetError, ConnectionAbortedError)
63
64
Victor Stinner0e6f52a2014-06-20 17:34:15 +020065def _format_handle(handle):
66 cb = handle._callback
Yury Selivanova0c1ba62016-10-28 12:52:37 -040067 if isinstance(getattr(cb, '__self__', None), tasks.Task):
Victor Stinner0e6f52a2014-06-20 17:34:15 +020068 # format the task
69 return repr(cb.__self__)
70 else:
71 return str(handle)
72
73
Victor Stinneracdb7822014-07-14 18:33:40 +020074def _format_pipe(fd):
75 if fd == subprocess.PIPE:
76 return '<pipe>'
77 elif fd == subprocess.STDOUT:
78 return '<stdout>'
79 else:
80 return repr(fd)
81
82
Yury Selivanov5587d7c2016-09-15 15:45:07 -040083def _set_reuseport(sock):
84 if not hasattr(socket, 'SO_REUSEPORT'):
85 raise ValueError('reuse_port not supported by socket module')
86 else:
87 try:
88 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
89 except OSError:
90 raise ValueError('reuse_port not supported by socket module, '
91 'SO_REUSEPORT defined but not implemented.')
92
93
Yury Selivanovd5c2a622015-12-16 19:31:17 -050094def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040095 # Try to skip getaddrinfo if "host" is already an IP. Users might have
96 # handled name resolution in their own code and pass in resolved IPs.
97 if not hasattr(socket, 'inet_pton'):
98 return
99
100 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
101 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500102 return None
103
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500104 if type == socket.SOCK_STREAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500105 proto = socket.IPPROTO_TCP
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500106 elif type == socket.SOCK_DGRAM:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500107 proto = socket.IPPROTO_UDP
108 else:
109 return None
110
Yury Selivanova7146162016-06-02 16:51:07 -0400111 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400112 port = 0
Guido van Rossume3c65a72016-09-30 08:17:15 -0700113 elif isinstance(port, bytes) and port == b'':
114 port = 0
115 elif isinstance(port, str) and port == '':
116 port = 0
117 else:
118 # If port's a service name like "http", don't skip getaddrinfo.
119 try:
120 port = int(port)
121 except (TypeError, ValueError):
122 return None
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400123
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400124 if family == socket.AF_UNSPEC:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500125 afs = [socket.AF_INET]
126 if hasattr(socket, 'AF_INET6'):
127 afs.append(socket.AF_INET6)
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400128 else:
129 afs = [family]
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500130
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400131 if isinstance(host, bytes):
132 host = host.decode('idna')
133 if '%' in host:
134 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
135 # like '::1%lo0'.
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500136 return None
137
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400138 for af in afs:
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500139 try:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400140 socket.inet_pton(af, host)
141 # The host has already been resolved.
142 return af, type, proto, '', (host, port)
143 except OSError:
144 pass
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400146 # "host" is not an IP address.
147 return None
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148
149
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100150def _run_until_complete_cb(fut):
Yury Selivanov36c2c042017-12-19 07:19:53 -0500151 if not fut.cancelled():
152 exc = fut.exception()
153 if isinstance(exc, BaseException) and not isinstance(exc, Exception):
154 # Issue #22429: run_forever() already finished, no need to
155 # stop it.
156 return
Yury Selivanovca9b36c2017-12-23 15:04:15 -0500157 futures._get_loop(fut).stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100158
159
Andrew Svetlov7c684072018-01-27 21:22:47 +0200160class _SendfileFallbackProtocol(protocols.Protocol):
161 def __init__(self, transp):
162 if not isinstance(transp, transports._FlowControlMixin):
163 raise TypeError("transport should be _FlowControlMixin instance")
164 self._transport = transp
165 self._proto = transp.get_protocol()
166 self._should_resume_reading = transp.is_reading()
167 self._should_resume_writing = transp._protocol_paused
168 transp.pause_reading()
169 transp.set_protocol(self)
170 if self._should_resume_writing:
171 self._write_ready_fut = self._transport._loop.create_future()
172 else:
173 self._write_ready_fut = None
174
175 async def drain(self):
176 if self._transport.is_closing():
177 raise ConnectionError("Connection closed by peer")
178 fut = self._write_ready_fut
179 if fut is None:
180 return
181 await fut
182
183 def connection_made(self, transport):
184 raise RuntimeError("Invalid state: "
185 "connection should have been established already.")
186
187 def connection_lost(self, exc):
188 if self._write_ready_fut is not None:
189 # Never happens if peer disconnects after sending the whole content
190 # Thus disconnection is always an exception from user perspective
191 if exc is None:
192 self._write_ready_fut.set_exception(
193 ConnectionError("Connection is closed by peer"))
194 else:
195 self._write_ready_fut.set_exception(exc)
196 self._proto.connection_lost(exc)
197
198 def pause_writing(self):
199 if self._write_ready_fut is not None:
200 return
201 self._write_ready_fut = self._transport._loop.create_future()
202
203 def resume_writing(self):
204 if self._write_ready_fut is None:
205 return
206 self._write_ready_fut.set_result(False)
207 self._write_ready_fut = None
208
209 def data_received(self, data):
210 raise RuntimeError("Invalid state: reading should be paused")
211
212 def eof_received(self):
213 raise RuntimeError("Invalid state: reading should be paused")
214
215 async def restore(self):
216 self._transport.set_protocol(self._proto)
217 if self._should_resume_reading:
218 self._transport.resume_reading()
219 if self._write_ready_fut is not None:
220 # Cancel the future.
221 # Basically it has no effect because protocol is switched back,
222 # no code should wait for it anymore.
223 self._write_ready_fut.cancel()
224 if self._should_resume_writing:
225 self._proto.resume_writing()
226
227
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700228class Server(events.AbstractServer):
229
Yury Selivanovc9070d02018-01-25 18:08:09 -0500230 def __init__(self, loop, sockets, protocol_factory, ssl_context, backlog,
231 ssl_handshake_timeout):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200232 self._loop = loop
Yury Selivanovc9070d02018-01-25 18:08:09 -0500233 self._sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200234 self._active_count = 0
235 self._waiters = []
Yury Selivanovc9070d02018-01-25 18:08:09 -0500236 self._protocol_factory = protocol_factory
237 self._backlog = backlog
238 self._ssl_context = ssl_context
239 self._ssl_handshake_timeout = ssl_handshake_timeout
240 self._serving = False
241 self._serving_forever_fut = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700242
Victor Stinnere912e652014-07-12 03:11:53 +0200243 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500244 return f'<{self.__class__.__name__} sockets={self.sockets!r}>'
Victor Stinnere912e652014-07-12 03:11:53 +0200245
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200246 def _attach(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500247 assert self._sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200248 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700249
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200250 def _detach(self):
251 assert self._active_count > 0
252 self._active_count -= 1
Yury Selivanovc9070d02018-01-25 18:08:09 -0500253 if self._active_count == 0 and self._sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700254 self._wakeup()
255
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200257 waiters = self._waiters
258 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700259 for waiter in waiters:
260 if not waiter.done():
261 waiter.set_result(waiter)
262
Yury Selivanovc9070d02018-01-25 18:08:09 -0500263 def _start_serving(self):
264 if self._serving:
265 return
266 self._serving = True
267 for sock in self._sockets:
268 sock.listen(self._backlog)
269 self._loop._start_serving(
270 self._protocol_factory, sock, self._ssl_context,
271 self, self._backlog, self._ssl_handshake_timeout)
272
273 def get_loop(self):
274 return self._loop
275
276 def is_serving(self):
277 return self._serving
278
279 @property
280 def sockets(self):
281 if self._sockets is None:
282 return []
283 return list(self._sockets)
284
285 def close(self):
286 sockets = self._sockets
287 if sockets is None:
288 return
289 self._sockets = None
290
291 for sock in sockets:
292 self._loop._stop_serving(sock)
293
294 self._serving = False
295
296 if (self._serving_forever_fut is not None and
297 not self._serving_forever_fut.done()):
298 self._serving_forever_fut.cancel()
299 self._serving_forever_fut = None
300
301 if self._active_count == 0:
302 self._wakeup()
303
304 async def start_serving(self):
305 self._start_serving()
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -0700306 # Skip one loop iteration so that all 'loop.add_reader'
307 # go through.
308 await tasks.sleep(0, loop=self._loop)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500309
310 async def serve_forever(self):
311 if self._serving_forever_fut is not None:
312 raise RuntimeError(
313 f'server {self!r} is already being awaited on serve_forever()')
314 if self._sockets is None:
315 raise RuntimeError(f'server {self!r} is closed')
316
317 self._start_serving()
318 self._serving_forever_fut = self._loop.create_future()
319
320 try:
321 await self._serving_forever_fut
322 except futures.CancelledError:
323 try:
324 self.close()
325 await self.wait_closed()
326 finally:
327 raise
328 finally:
329 self._serving_forever_fut = None
330
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200331 async def wait_closed(self):
Yury Selivanovc9070d02018-01-25 18:08:09 -0500332 if self._sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700333 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400334 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200335 self._waiters.append(waiter)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200336 await waiter
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700337
338
339class BaseEventLoop(events.AbstractEventLoop):
340
341 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400342 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200343 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800344 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700345 self._ready = collections.deque()
346 self._scheduled = []
347 self._default_executor = None
348 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100349 # Identifier of the thread running the event loop, or None if the
350 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100351 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100352 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500353 self._exception_handler = None
Victor Stinner44862df2017-11-20 07:14:07 -0800354 self.set_debug(coroutines._is_debug_mode())
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200355 # In debug mode, if the execution of a callback or a step of a task
356 # exceed this duration in seconds, the slow callback/task is logged.
357 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100358 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400359 self._task_factory = None
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800360 self._coroutine_origin_tracking_enabled = False
361 self._coroutine_origin_tracking_saved_depth = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700362
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500363 # A weak set of all asynchronous generators that are
364 # being iterated by the loop.
365 self._asyncgens = weakref.WeakSet()
Yury Selivanoveb636452016-09-08 22:01:51 -0700366 # Set to True when `loop.shutdown_asyncgens` is called.
367 self._asyncgens_shutdown_called = False
368
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200369 def __repr__(self):
Yury Selivanov6370f342017-12-10 18:36:12 -0500370 return (
371 f'<{self.__class__.__name__} running={self.is_running()} '
372 f'closed={self.is_closed()} debug={self.get_debug()}>'
373 )
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200374
Yury Selivanov7661db62016-05-16 15:38:39 -0400375 def create_future(self):
376 """Create a Future object attached to the loop."""
377 return futures.Future(loop=self)
378
Victor Stinner896a25a2014-07-08 11:29:25 +0200379 def create_task(self, coro):
380 """Schedule a coroutine object.
381
Victor Stinneracdb7822014-07-14 18:33:40 +0200382 Return a task object.
383 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100384 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400385 if self._task_factory is None:
386 task = tasks.Task(coro, loop=self)
387 if task._source_traceback:
388 del task._source_traceback[-1]
389 else:
390 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200391 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200392
Yury Selivanov740169c2015-05-11 14:23:38 -0400393 def set_task_factory(self, factory):
394 """Set a task factory that will be used by loop.create_task().
395
396 If factory is None the default task factory will be set.
397
398 If factory is a callable, it should have a signature matching
399 '(loop, coro)', where 'loop' will be a reference to the active
400 event loop, 'coro' will be a coroutine object. The callable
401 must return a Future.
402 """
403 if factory is not None and not callable(factory):
404 raise TypeError('task factory must be a callable or None')
405 self._task_factory = factory
406
407 def get_task_factory(self):
408 """Return a task factory, or None if the default one is in use."""
409 return self._task_factory
410
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700411 def _make_socket_transport(self, sock, protocol, waiter=None, *,
412 extra=None, server=None):
413 """Create socket transport."""
414 raise NotImplementedError
415
Neil Aspinallf7686c12017-12-19 19:45:42 +0000416 def _make_ssl_transport(
417 self, rawsock, protocol, sslcontext, waiter=None,
418 *, server_side=False, server_hostname=None,
419 extra=None, server=None,
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500420 ssl_handshake_timeout=None,
421 call_connection_made=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700422 """Create SSL transport."""
423 raise NotImplementedError
424
425 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200426 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700427 """Create datagram transport."""
428 raise NotImplementedError
429
430 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
431 extra=None):
432 """Create read pipe transport."""
433 raise NotImplementedError
434
435 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
436 extra=None):
437 """Create write pipe transport."""
438 raise NotImplementedError
439
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200440 async def _make_subprocess_transport(self, protocol, args, shell,
441 stdin, stdout, stderr, bufsize,
442 extra=None, **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700443 """Create subprocess transport."""
444 raise NotImplementedError
445
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700446 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200447 """Write a byte to self-pipe, to wake up the event loop.
448
449 This may be called from a different thread.
450
451 The subclass is responsible for implementing the self-pipe.
452 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700453 raise NotImplementedError
454
455 def _process_events(self, event_list):
456 """Process selector events."""
457 raise NotImplementedError
458
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200459 def _check_closed(self):
460 if self._closed:
461 raise RuntimeError('Event loop is closed')
462
Yury Selivanoveb636452016-09-08 22:01:51 -0700463 def _asyncgen_finalizer_hook(self, agen):
464 self._asyncgens.discard(agen)
465 if not self.is_closed():
466 self.create_task(agen.aclose())
Yury Selivanoved054062016-10-21 17:13:40 -0400467 # Wake up the loop if the finalizer was called from
468 # a different thread.
469 self._write_to_self()
Yury Selivanoveb636452016-09-08 22:01:51 -0700470
471 def _asyncgen_firstiter_hook(self, agen):
472 if self._asyncgens_shutdown_called:
473 warnings.warn(
Yury Selivanov6370f342017-12-10 18:36:12 -0500474 f"asynchronous generator {agen!r} was scheduled after "
475 f"loop.shutdown_asyncgens() call",
Yury Selivanoveb636452016-09-08 22:01:51 -0700476 ResourceWarning, source=self)
477
478 self._asyncgens.add(agen)
479
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200480 async def shutdown_asyncgens(self):
Yury Selivanoveb636452016-09-08 22:01:51 -0700481 """Shutdown all active asynchronous generators."""
482 self._asyncgens_shutdown_called = True
483
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500484 if not len(self._asyncgens):
Yury Selivanov0a91d482016-09-15 13:24:03 -0400485 # If Python version is <3.6 or we don't have any asynchronous
486 # generators alive.
Yury Selivanoveb636452016-09-08 22:01:51 -0700487 return
488
489 closing_agens = list(self._asyncgens)
490 self._asyncgens.clear()
491
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200492 results = await tasks.gather(
Yury Selivanoveb636452016-09-08 22:01:51 -0700493 *[ag.aclose() for ag in closing_agens],
494 return_exceptions=True,
495 loop=self)
496
Yury Selivanoveb636452016-09-08 22:01:51 -0700497 for result, agen in zip(results, closing_agens):
498 if isinstance(result, Exception):
499 self.call_exception_handler({
Yury Selivanov6370f342017-12-10 18:36:12 -0500500 'message': f'an error occurred during closing of '
501 f'asynchronous generator {agen!r}',
Yury Selivanoveb636452016-09-08 22:01:51 -0700502 'exception': result,
503 'asyncgen': agen
504 })
505
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506 def run_forever(self):
507 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200508 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100509 if self.is_running():
Yury Selivanov600a3492016-11-04 14:29:28 -0400510 raise RuntimeError('This event loop is already running')
511 if events._get_running_loop() is not None:
512 raise RuntimeError(
513 'Cannot run the event loop while another loop is running')
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800514 self._set_coroutine_origin_tracking(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100515 self._thread_id = threading.get_ident()
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500516
517 old_agen_hooks = sys.get_asyncgen_hooks()
518 sys.set_asyncgen_hooks(firstiter=self._asyncgen_firstiter_hook,
519 finalizer=self._asyncgen_finalizer_hook)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700520 try:
Yury Selivanov600a3492016-11-04 14:29:28 -0400521 events._set_running_loop(self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700522 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800523 self._run_once()
524 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 break
526 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800527 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100528 self._thread_id = None
Yury Selivanov600a3492016-11-04 14:29:28 -0400529 events._set_running_loop(None)
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800530 self._set_coroutine_origin_tracking(False)
Yury Selivanova4afcdf2018-01-21 14:56:59 -0500531 sys.set_asyncgen_hooks(*old_agen_hooks)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700532
533 def run_until_complete(self, future):
534 """Run until the Future is done.
535
536 If the argument is a coroutine, it is wrapped in a Task.
537
Victor Stinneracdb7822014-07-14 18:33:40 +0200538 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700539 with the same coroutine twice -- it would wrap it in two
540 different Tasks and that can't be good.
541
542 Return the Future's result, or raise its exception.
543 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200544 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200545
Guido van Rossum7b3b3dc2016-09-09 14:26:31 -0700546 new_task = not futures.isfuture(future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400547 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200548 if new_task:
549 # An exception is raised if the future didn't complete, so there
550 # is no need to log the "destroy pending task" message
551 future._log_destroy_pending = False
552
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100553 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200554 try:
555 self.run_forever()
556 except:
557 if new_task and future.done() and not future.cancelled():
558 # The coroutine raised a BaseException. Consume the exception
559 # to not log a warning, the caller doesn't have access to the
560 # local task.
561 future.exception()
562 raise
jimmylai21b3e042017-05-22 22:32:46 -0700563 finally:
564 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700565 if not future.done():
566 raise RuntimeError('Event loop stopped before Future completed.')
567
568 return future.result()
569
570 def stop(self):
571 """Stop running the event loop.
572
Guido van Rossum41f69f42015-11-19 13:28:47 -0800573 Every callback already scheduled will still run. This simply informs
574 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700575 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800576 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700577
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200578 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700579 """Close the event loop.
580
581 This clears the queues and shuts down the executor,
582 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200583
584 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700585 """
Victor Stinner956de692014-12-26 21:07:52 +0100586 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200587 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200588 if self._closed:
589 return
Victor Stinnere912e652014-07-12 03:11:53 +0200590 if self._debug:
591 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400592 self._closed = True
593 self._ready.clear()
594 self._scheduled.clear()
595 executor = self._default_executor
596 if executor is not None:
597 self._default_executor = None
598 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200599
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200600 def is_closed(self):
601 """Returns True if the event loop was closed."""
602 return self._closed
603
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900604 def __del__(self):
605 if not self.is_closed():
Yury Selivanov6370f342017-12-10 18:36:12 -0500606 warnings.warn(f"unclosed event loop {self!r}", ResourceWarning,
INADA Naoki3e2ad8e2017-04-25 10:57:18 +0900607 source=self)
608 if not self.is_running():
609 self.close()
Victor Stinner978a9af2015-01-29 17:50:58 +0100610
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700611 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200612 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100613 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700614
615 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200616 """Return the time according to the event loop's clock.
617
618 This is a float expressed in seconds since an epoch, but the
619 epoch, precision, accuracy and drift are unspecified and may
620 differ per event loop.
621 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622 return time.monotonic()
623
Yury Selivanovf23746a2018-01-22 19:11:18 -0500624 def call_later(self, delay, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625 """Arrange for a callback to be called at a given time.
626
627 Return a Handle: an opaque object with a cancel() method that
628 can be used to cancel the call.
629
630 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200631 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700632
633 Each callback will be called exactly once. If two callbacks
634 are scheduled for exactly the same time, it undefined which
635 will be called first.
636
637 Any positional arguments after the callback will be passed to
638 the callback when it is called.
639 """
Yury Selivanovf23746a2018-01-22 19:11:18 -0500640 timer = self.call_at(self.time() + delay, callback, *args,
641 context=context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200642 if timer._source_traceback:
643 del timer._source_traceback[-1]
644 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700645
Yury Selivanovf23746a2018-01-22 19:11:18 -0500646 def call_at(self, when, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200647 """Like call_later(), but uses an absolute time.
648
649 Absolute time corresponds to the event loop's time() method.
650 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100651 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100652 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100653 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700654 self._check_callback(callback, 'call_at')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500655 timer = events.TimerHandle(when, callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200656 if timer._source_traceback:
657 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700658 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400659 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700660 return timer
661
Yury Selivanovf23746a2018-01-22 19:11:18 -0500662 def call_soon(self, callback, *args, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700663 """Arrange for a callback to be called as soon as possible.
664
Victor Stinneracdb7822014-07-14 18:33:40 +0200665 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700666 order in which they are registered. Each callback will be
667 called exactly once.
668
669 Any positional arguments after the callback will be passed to
670 the callback when it is called.
671 """
Yury Selivanov491a9122016-11-03 15:09:24 -0700672 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100673 if self._debug:
674 self._check_thread()
Yury Selivanov491a9122016-11-03 15:09:24 -0700675 self._check_callback(callback, 'call_soon')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500676 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200677 if handle._source_traceback:
678 del handle._source_traceback[-1]
679 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100680
Yury Selivanov491a9122016-11-03 15:09:24 -0700681 def _check_callback(self, callback, method):
682 if (coroutines.iscoroutine(callback) or
683 coroutines.iscoroutinefunction(callback)):
684 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500685 f"coroutines cannot be used with {method}()")
Yury Selivanov491a9122016-11-03 15:09:24 -0700686 if not callable(callback):
687 raise TypeError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500688 f'a callable object was expected by {method}(), '
689 f'got {callback!r}')
Yury Selivanov491a9122016-11-03 15:09:24 -0700690
Yury Selivanovf23746a2018-01-22 19:11:18 -0500691 def _call_soon(self, callback, args, context):
692 handle = events.Handle(callback, args, self, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200693 if handle._source_traceback:
694 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700695 self._ready.append(handle)
696 return handle
697
Victor Stinner956de692014-12-26 21:07:52 +0100698 def _check_thread(self):
699 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100700
Victor Stinneracdb7822014-07-14 18:33:40 +0200701 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100702 likely behave incorrectly when the assumption is violated.
703
Victor Stinneracdb7822014-07-14 18:33:40 +0200704 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100705 responsible for checking this condition for performance reasons.
706 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100707 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200708 return
Victor Stinner956de692014-12-26 21:07:52 +0100709 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100710 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100711 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200712 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100713 "than the current one")
714
Yury Selivanovf23746a2018-01-22 19:11:18 -0500715 def call_soon_threadsafe(self, callback, *args, context=None):
Victor Stinneracdb7822014-07-14 18:33:40 +0200716 """Like call_soon(), but thread-safe."""
Yury Selivanov491a9122016-11-03 15:09:24 -0700717 self._check_closed()
718 if self._debug:
719 self._check_callback(callback, 'call_soon_threadsafe')
Yury Selivanovf23746a2018-01-22 19:11:18 -0500720 handle = self._call_soon(callback, args, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200721 if handle._source_traceback:
722 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700723 self._write_to_self()
724 return handle
725
Yury Selivanovbec23722018-01-28 14:09:40 -0500726 def run_in_executor(self, executor, func, *args):
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100727 self._check_closed()
Yury Selivanov491a9122016-11-03 15:09:24 -0700728 if self._debug:
729 self._check_callback(func, 'run_in_executor')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700730 if executor is None:
731 executor = self._default_executor
732 if executor is None:
Yury Selivanove8a60452016-10-21 17:40:42 -0400733 executor = concurrent.futures.ThreadPoolExecutor()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 self._default_executor = executor
Yury Selivanovbec23722018-01-28 14:09:40 -0500735 return futures.wrap_future(
Yury Selivanov19a44f62017-12-14 20:53:26 -0500736 executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700737
738 def set_default_executor(self, executor):
739 self._default_executor = executor
740
Victor Stinnere912e652014-07-12 03:11:53 +0200741 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
Yury Selivanov6370f342017-12-10 18:36:12 -0500742 msg = [f"{host}:{port!r}"]
Victor Stinnere912e652014-07-12 03:11:53 +0200743 if family:
Yury Selivanov19d0d542017-12-10 19:52:53 -0500744 msg.append(f'family={family!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200745 if type:
Yury Selivanov6370f342017-12-10 18:36:12 -0500746 msg.append(f'type={type!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200747 if proto:
Yury Selivanov6370f342017-12-10 18:36:12 -0500748 msg.append(f'proto={proto!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200749 if flags:
Yury Selivanov6370f342017-12-10 18:36:12 -0500750 msg.append(f'flags={flags!r}')
Victor Stinnere912e652014-07-12 03:11:53 +0200751 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200752 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200753
754 t0 = self.time()
755 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
756 dt = self.time() - t0
757
Yury Selivanov6370f342017-12-10 18:36:12 -0500758 msg = f'Getting address info {msg} took {dt * 1e3:.3f}ms: {addrinfo!r}'
Victor Stinnere912e652014-07-12 03:11:53 +0200759 if dt >= self.slow_callback_duration:
760 logger.info(msg)
761 else:
762 logger.debug(msg)
763 return addrinfo
764
Yury Selivanov19a44f62017-12-14 20:53:26 -0500765 async def getaddrinfo(self, host, port, *,
766 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400767 if self._debug:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500768 getaddr_func = self._getaddrinfo_debug
Victor Stinnere912e652014-07-12 03:11:53 +0200769 else:
Yury Selivanov19a44f62017-12-14 20:53:26 -0500770 getaddr_func = socket.getaddrinfo
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700771
Yury Selivanov19a44f62017-12-14 20:53:26 -0500772 return await self.run_in_executor(
773 None, getaddr_func, host, port, family, type, proto, flags)
774
775 async def getnameinfo(self, sockaddr, flags=0):
776 return await self.run_in_executor(
777 None, socket.getnameinfo, sockaddr, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700778
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200779 async def sock_sendfile(self, sock, file, offset=0, count=None,
780 *, fallback=True):
781 if self._debug and sock.gettimeout() != 0:
782 raise ValueError("the socket must be non-blocking")
783 self._check_sendfile_params(sock, file, offset, count)
784 try:
785 return await self._sock_sendfile_native(sock, file,
786 offset, count)
Andrew Svetlov7464e872018-01-19 20:04:29 +0200787 except events.SendfileNotAvailableError as exc:
788 if not fallback:
789 raise
790 return await self._sock_sendfile_fallback(sock, file,
791 offset, count)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200792
793 async def _sock_sendfile_native(self, sock, file, offset, count):
794 # NB: sendfile syscall is not supported for SSL sockets and
795 # non-mmap files even if sendfile is supported by OS
Andrew Svetlov7464e872018-01-19 20:04:29 +0200796 raise events.SendfileNotAvailableError(
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200797 f"syscall sendfile is not available for socket {sock!r} "
798 "and file {file!r} combination")
799
800 async def _sock_sendfile_fallback(self, sock, file, offset, count):
801 if offset:
802 file.seek(offset)
Miss Islington (bot)420092e2018-05-28 18:42:45 -0700803 blocksize = (
804 min(count, constants.SENDFILE_FALLBACK_READBUFFER_SIZE)
805 if count else constants.SENDFILE_FALLBACK_READBUFFER_SIZE
806 )
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200807 buf = bytearray(blocksize)
808 total_sent = 0
809 try:
810 while True:
811 if count:
812 blocksize = min(count - total_sent, blocksize)
813 if blocksize <= 0:
814 break
815 view = memoryview(buf)[:blocksize]
Miss Islington (bot)420092e2018-05-28 18:42:45 -0700816 read = await self.run_in_executor(None, file.readinto, view)
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200817 if not read:
818 break # EOF
819 await self.sock_sendall(sock, view)
820 total_sent += read
821 return total_sent
822 finally:
823 if total_sent > 0 and hasattr(file, 'seek'):
824 file.seek(offset + total_sent)
825
826 def _check_sendfile_params(self, sock, file, offset, count):
827 if 'b' not in getattr(file, 'mode', 'b'):
828 raise ValueError("file should be opened in binary mode")
829 if not sock.type == socket.SOCK_STREAM:
830 raise ValueError("only SOCK_STREAM type sockets are supported")
831 if count is not None:
832 if not isinstance(count, int):
833 raise TypeError(
834 "count must be a positive integer (got {!r})".format(count))
835 if count <= 0:
836 raise ValueError(
837 "count must be a positive integer (got {!r})".format(count))
838 if not isinstance(offset, int):
839 raise TypeError(
840 "offset must be a non-negative integer (got {!r})".format(
841 offset))
842 if offset < 0:
843 raise ValueError(
844 "offset must be a non-negative integer (got {!r})".format(
845 offset))
846
Neil Aspinallf7686c12017-12-19 19:45:42 +0000847 async def create_connection(
848 self, protocol_factory, host=None, port=None,
849 *, ssl=None, family=0,
850 proto=0, flags=0, sock=None,
851 local_addr=None, server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200852 ssl_handshake_timeout=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200853 """Connect to a TCP server.
854
855 Create a streaming transport connection to a given Internet host and
856 port: socket family AF_INET or socket.AF_INET6 depending on host (or
857 family if specified), socket type SOCK_STREAM. protocol_factory must be
858 a callable returning a protocol instance.
859
860 This method is a coroutine which will try to establish the connection
861 in the background. When successful, the coroutine returns a
862 (transport, protocol) pair.
863 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700864 if server_hostname is not None and not ssl:
865 raise ValueError('server_hostname is only meaningful with ssl')
866
867 if server_hostname is None and ssl:
868 # Use host as default for server_hostname. It is an error
869 # if host is empty or not set, e.g. when an
870 # already-connected socket was passed or when only a port
871 # is given. To avoid this error, you can pass
872 # server_hostname='' -- this will bypass the hostname
873 # check. (This also means that if host is a numeric
874 # IP/IPv6 address, we will attempt to verify that exact
875 # address; this will probably fail, but it is possible to
876 # create a certificate for a specific IP address, so we
877 # don't judge it here.)
878 if not host:
879 raise ValueError('You must set server_hostname '
880 'when using ssl without a host')
881 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700882
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200883 if ssl_handshake_timeout is not None and not ssl:
884 raise ValueError(
885 'ssl_handshake_timeout is only meaningful with ssl')
886
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700887 if host is not None or port is not None:
888 if sock is not None:
889 raise ValueError(
890 'host/port and sock can not be specified at the same time')
891
Yury Selivanov19a44f62017-12-14 20:53:26 -0500892 infos = await self._ensure_resolved(
893 (host, port), family=family,
894 type=socket.SOCK_STREAM, proto=proto, flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700895 if not infos:
896 raise OSError('getaddrinfo() returned empty list')
Yury Selivanov19a44f62017-12-14 20:53:26 -0500897
898 if local_addr is not None:
899 laddr_infos = await self._ensure_resolved(
900 local_addr, family=family,
901 type=socket.SOCK_STREAM, proto=proto,
902 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700903 if not laddr_infos:
904 raise OSError('getaddrinfo() returned empty list')
905
906 exceptions = []
907 for family, type, proto, cname, address in infos:
908 try:
909 sock = socket.socket(family=family, type=type, proto=proto)
910 sock.setblocking(False)
Yury Selivanov19a44f62017-12-14 20:53:26 -0500911 if local_addr is not None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700912 for _, _, _, _, laddr in laddr_infos:
913 try:
914 sock.bind(laddr)
915 break
916 except OSError as exc:
Yury Selivanov6370f342017-12-10 18:36:12 -0500917 msg = (
918 f'error while attempting to bind on '
919 f'address {laddr!r}: '
920 f'{exc.strerror.lower()}'
921 )
922 exc = OSError(exc.errno, msg)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700923 exceptions.append(exc)
924 else:
925 sock.close()
926 sock = None
927 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200928 if self._debug:
929 logger.debug("connect %r to %r", sock, address)
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200930 await self.sock_connect(sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700931 except OSError as exc:
932 if sock is not None:
933 sock.close()
934 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200935 except:
936 if sock is not None:
937 sock.close()
938 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700939 else:
940 break
941 else:
942 if len(exceptions) == 1:
943 raise exceptions[0]
944 else:
945 # If they all have the same str(), raise one.
946 model = str(exceptions[0])
947 if all(str(exc) == model for exc in exceptions):
948 raise exceptions[0]
949 # Raise a combined exception so the user can see all
950 # the various error messages.
951 raise OSError('Multiple exceptions: {}'.format(
952 ', '.join(str(exc) for exc in exceptions)))
953
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500954 else:
955 if sock is None:
956 raise ValueError(
957 'host and port was not specified and no sock specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -0500958 if sock.type != socket.SOCK_STREAM:
Yury Selivanovdab05842016-11-21 17:47:27 -0500959 # We allow AF_INET, AF_INET6, AF_UNIX as long as they
960 # are SOCK_STREAM.
961 # We support passing AF_UNIX sockets even though we have
962 # a dedicated API for that: create_unix_connection.
963 # Disallowing AF_UNIX in this method, breaks backwards
964 # compatibility.
Yury Selivanova1a8b7d2016-11-09 15:47:00 -0500965 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -0500966 f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700967
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200968 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +0000969 sock, protocol_factory, ssl, server_hostname,
970 ssl_handshake_timeout=ssl_handshake_timeout)
Victor Stinnere912e652014-07-12 03:11:53 +0200971 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200972 # Get the socket from the transport because SSL transport closes
973 # the old socket and creates a new SSL socket
974 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200975 logger.debug("%r connected to %s:%r: (%r, %r)",
976 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500977 return transport, protocol
978
Neil Aspinallf7686c12017-12-19 19:45:42 +0000979 async def _create_connection_transport(
980 self, sock, protocol_factory, ssl,
981 server_hostname, server_side=False,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200982 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400983
984 sock.setblocking(False)
985
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700986 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400987 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700988 if ssl:
989 sslcontext = None if isinstance(ssl, bool) else ssl
990 transport = self._make_ssl_transport(
991 sock, protocol, sslcontext, waiter,
Neil Aspinallf7686c12017-12-19 19:45:42 +0000992 server_side=server_side, server_hostname=server_hostname,
993 ssl_handshake_timeout=ssl_handshake_timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700994 else:
995 transport = self._make_socket_transport(sock, protocol, waiter)
996
Victor Stinner29ad0112015-01-15 00:04:21 +0100997 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200998 await waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100999 except:
Victor Stinner29ad0112015-01-15 00:04:21 +01001000 transport.close()
1001 raise
1002
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001003 return transport, protocol
1004
Andrew Svetlov7c684072018-01-27 21:22:47 +02001005 async def sendfile(self, transport, file, offset=0, count=None,
1006 *, fallback=True):
1007 """Send a file to transport.
1008
1009 Return the total number of bytes which were sent.
1010
1011 The method uses high-performance os.sendfile if available.
1012
1013 file must be a regular file object opened in binary mode.
1014
1015 offset tells from where to start reading the file. If specified,
1016 count is the total number of bytes to transmit as opposed to
1017 sending the file until EOF is reached. File position is updated on
1018 return or also in case of error in which case file.tell()
1019 can be used to figure out the number of bytes
1020 which were sent.
1021
1022 fallback set to True makes asyncio to manually read and send
1023 the file when the platform does not support the sendfile syscall
1024 (e.g. Windows or SSL socket on Unix).
1025
1026 Raise SendfileNotAvailableError if the system does not support
1027 sendfile syscall and fallback is False.
1028 """
1029 if transport.is_closing():
1030 raise RuntimeError("Transport is closing")
1031 mode = getattr(transport, '_sendfile_compatible',
1032 constants._SendfileMode.UNSUPPORTED)
1033 if mode is constants._SendfileMode.UNSUPPORTED:
1034 raise RuntimeError(
1035 f"sendfile is not supported for transport {transport!r}")
1036 if mode is constants._SendfileMode.TRY_NATIVE:
1037 try:
1038 return await self._sendfile_native(transport, file,
1039 offset, count)
1040 except events.SendfileNotAvailableError as exc:
1041 if not fallback:
1042 raise
Yury Selivanovb1a6ac42018-01-27 15:52:52 -05001043
1044 if not fallback:
1045 raise RuntimeError(
1046 f"fallback is disabled and native sendfile is not "
1047 f"supported for transport {transport!r}")
1048
Andrew Svetlov7c684072018-01-27 21:22:47 +02001049 return await self._sendfile_fallback(transport, file,
1050 offset, count)
1051
1052 async def _sendfile_native(self, transp, file, offset, count):
1053 raise events.SendfileNotAvailableError(
1054 "sendfile syscall is not supported")
1055
1056 async def _sendfile_fallback(self, transp, file, offset, count):
1057 if offset:
1058 file.seek(offset)
1059 blocksize = min(count, 16384) if count else 16384
1060 buf = bytearray(blocksize)
1061 total_sent = 0
1062 proto = _SendfileFallbackProtocol(transp)
1063 try:
1064 while True:
1065 if count:
1066 blocksize = min(count - total_sent, blocksize)
1067 if blocksize <= 0:
1068 return total_sent
1069 view = memoryview(buf)[:blocksize]
1070 read = file.readinto(view)
1071 if not read:
1072 return total_sent # EOF
1073 await proto.drain()
1074 transp.write(view)
1075 total_sent += read
1076 finally:
1077 if total_sent > 0 and hasattr(file, 'seek'):
1078 file.seek(offset + total_sent)
1079 await proto.restore()
1080
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001081 async def start_tls(self, transport, protocol, sslcontext, *,
1082 server_side=False,
1083 server_hostname=None,
1084 ssl_handshake_timeout=None):
1085 """Upgrade transport to TLS.
1086
1087 Return a new transport that *protocol* should start using
1088 immediately.
1089 """
1090 if ssl is None:
1091 raise RuntimeError('Python ssl module is not available')
1092
1093 if not isinstance(sslcontext, ssl.SSLContext):
1094 raise TypeError(
1095 f'sslcontext is expected to be an instance of ssl.SSLContext, '
1096 f'got {sslcontext!r}')
1097
1098 if not getattr(transport, '_start_tls_compatible', False):
1099 raise TypeError(
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001100 f'transport {transport!r} is not supported by start_tls()')
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001101
1102 waiter = self.create_future()
1103 ssl_protocol = sslproto.SSLProtocol(
1104 self, protocol, sslcontext, waiter,
1105 server_side, server_hostname,
1106 ssl_handshake_timeout=ssl_handshake_timeout,
1107 call_connection_made=False)
1108
Miss Islington (bot)eca08592018-05-28 22:59:03 -07001109 # Pause early so that "ssl_protocol.data_received()" doesn't
1110 # have a chance to get called before "ssl_protocol.connection_made()".
1111 transport.pause_reading()
1112
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001113 transport.set_protocol(ssl_protocol)
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001114 conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
1115 resume_cb = self.call_soon(transport.resume_reading)
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001116
Miss Islington (bot)87936d02018-06-04 09:05:46 -07001117 try:
1118 await waiter
1119 except Exception:
1120 transport.close()
Miss Islington (bot)79c7e572018-06-05 07:18:20 -07001121 conmade_cb.cancel()
1122 resume_cb.cancel()
Miss Islington (bot)87936d02018-06-04 09:05:46 -07001123 raise
1124
Yury Selivanovf111b3d2017-12-30 00:35:36 -05001125 return ssl_protocol._app_transport
1126
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001127 async def create_datagram_endpoint(self, protocol_factory,
1128 local_addr=None, remote_addr=None, *,
1129 family=0, proto=0, flags=0,
1130 reuse_address=None, reuse_port=None,
1131 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001132 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001133 if sock is not None:
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001134 if sock.type != socket.SOCK_DGRAM:
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001135 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001136 f'A UDP Socket was expected, got {sock!r}')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001137 if (local_addr or remote_addr or
1138 family or proto or flags or
1139 reuse_address or reuse_port or allow_broadcast):
1140 # show the problematic kwargs in exception msg
1141 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
1142 family=family, proto=proto, flags=flags,
1143 reuse_address=reuse_address, reuse_port=reuse_port,
1144 allow_broadcast=allow_broadcast)
Yury Selivanov6370f342017-12-10 18:36:12 -05001145 problems = ', '.join(f'{k}={v}' for k, v in opts.items() if v)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001146 raise ValueError(
Yury Selivanov6370f342017-12-10 18:36:12 -05001147 f'socket modifier keyword arguments can not be used '
1148 f'when sock is specified. ({problems})')
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001149 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001150 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001151 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001152 if not (local_addr or remote_addr):
1153 if family == 0:
1154 raise ValueError('unexpected address family')
1155 addr_pairs_info = (((family, proto), (None, None)),)
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001156 elif hasattr(socket, 'AF_UNIX') and family == socket.AF_UNIX:
1157 for addr in (local_addr, remote_addr):
Victor Stinner28e61652017-11-28 00:34:08 +01001158 if addr is not None and not isinstance(addr, str):
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +01001159 raise TypeError('string is expected')
1160 addr_pairs_info = (((family, proto),
1161 (local_addr, remote_addr)), )
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001162 else:
1163 # join address by (family, protocol)
1164 addr_infos = collections.OrderedDict()
1165 for idx, addr in ((0, local_addr), (1, remote_addr)):
1166 if addr is not None:
1167 assert isinstance(addr, tuple) and len(addr) == 2, (
1168 '2-tuple is expected')
1169
Yury Selivanov19a44f62017-12-14 20:53:26 -05001170 infos = await self._ensure_resolved(
Yury Selivanovf1c6fa92016-06-08 12:33:31 -04001171 addr, family=family, type=socket.SOCK_DGRAM,
1172 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001173 if not infos:
1174 raise OSError('getaddrinfo() returned empty list')
1175
1176 for fam, _, pro, _, address in infos:
1177 key = (fam, pro)
1178 if key not in addr_infos:
1179 addr_infos[key] = [None, None]
1180 addr_infos[key][idx] = address
1181
1182 # each addr has to have info for each (family, proto) pair
1183 addr_pairs_info = [
1184 (key, addr_pair) for key, addr_pair in addr_infos.items()
1185 if not ((local_addr and addr_pair[0] is None) or
1186 (remote_addr and addr_pair[1] is None))]
1187
1188 if not addr_pairs_info:
1189 raise ValueError('can not get address information')
1190
1191 exceptions = []
1192
1193 if reuse_address is None:
1194 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1195
1196 for ((family, proto),
1197 (local_address, remote_address)) in addr_pairs_info:
1198 sock = None
1199 r_addr = None
1200 try:
1201 sock = socket.socket(
1202 family=family, type=socket.SOCK_DGRAM, proto=proto)
1203 if reuse_address:
1204 sock.setsockopt(
1205 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1206 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001207 _set_reuseport(sock)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001208 if allow_broadcast:
1209 sock.setsockopt(
1210 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
1211 sock.setblocking(False)
1212
1213 if local_addr:
1214 sock.bind(local_address)
1215 if remote_addr:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001216 await self.sock_connect(sock, remote_address)
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001217 r_addr = remote_address
1218 except OSError as exc:
1219 if sock is not None:
1220 sock.close()
1221 exceptions.append(exc)
1222 except:
1223 if sock is not None:
1224 sock.close()
1225 raise
1226 else:
1227 break
1228 else:
1229 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001230
1231 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001232 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001233 transport = self._make_datagram_transport(
1234 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +02001235 if self._debug:
1236 if local_addr:
1237 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
1238 "created: (%r, %r)",
1239 local_addr, remote_addr, transport, protocol)
1240 else:
1241 logger.debug("Datagram endpoint remote_addr=%r created: "
1242 "(%r, %r)",
1243 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +01001244
1245 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001246 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001247 except:
1248 transport.close()
1249 raise
1250
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001251 return transport, protocol
1252
Yury Selivanov19a44f62017-12-14 20:53:26 -05001253 async def _ensure_resolved(self, address, *,
1254 family=0, type=socket.SOCK_STREAM,
1255 proto=0, flags=0, loop):
1256 host, port = address[:2]
1257 info = _ipaddr_info(host, port, family, type, proto)
1258 if info is not None:
1259 # "host" is already a resolved IP.
1260 return [info]
1261 else:
1262 return await loop.getaddrinfo(host, port, family=family, type=type,
1263 proto=proto, flags=flags)
1264
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001265 async def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanov19a44f62017-12-14 20:53:26 -05001266 infos = await self._ensure_resolved((host, port), family=family,
1267 type=socket.SOCK_STREAM,
1268 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001269 if not infos:
Yury Selivanov6370f342017-12-10 18:36:12 -05001270 raise OSError(f'getaddrinfo({host!r}) returned empty list')
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001271 return infos
1272
Neil Aspinallf7686c12017-12-19 19:45:42 +00001273 async def create_server(
1274 self, protocol_factory, host=None, port=None,
1275 *,
1276 family=socket.AF_UNSPEC,
1277 flags=socket.AI_PASSIVE,
1278 sock=None,
1279 backlog=100,
1280 ssl=None,
1281 reuse_address=None,
1282 reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -05001283 ssl_handshake_timeout=None,
1284 start_serving=True):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001285 """Create a TCP server.
1286
Yury Selivanov6370f342017-12-10 18:36:12 -05001287 The host parameter can be a string, in that case the TCP server is
1288 bound to host and port.
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001289
1290 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -05001291 the TCP server is bound to all hosts of the sequence. If a host
1292 appears multiple times (possibly indirectly e.g. when hostnames
1293 resolve to the same IP address), the server is only bound once to that
1294 host.
Victor Stinnerd1432092014-06-19 17:11:49 +02001295
Victor Stinneracdb7822014-07-14 18:33:40 +02001296 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +02001297
1298 This method is a coroutine.
1299 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -07001300 if isinstance(ssl, bool):
1301 raise TypeError('ssl argument must be an SSLContext or None')
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001302
1303 if ssl_handshake_timeout is not None and ssl is None:
1304 raise ValueError(
1305 'ssl_handshake_timeout is only meaningful with ssl')
1306
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001307 if host is not None or port is not None:
1308 if sock is not None:
1309 raise ValueError(
1310 'host/port and sock can not be specified at the same time')
1311
1312 AF_INET6 = getattr(socket, 'AF_INET6', 0)
1313 if reuse_address is None:
1314 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
1315 sockets = []
1316 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001317 hosts = [None]
1318 elif (isinstance(host, str) or
Serhiy Storchaka2e576f52017-04-24 09:05:00 +03001319 not isinstance(host, collections.abc.Iterable)):
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001320 hosts = [host]
1321 else:
1322 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001323
Victor Stinner5e4a7d82015-09-21 18:33:43 +02001324 fs = [self._create_server_getaddrinfo(host, port, family=family,
1325 flags=flags)
1326 for host in hosts]
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001327 infos = await tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -05001328 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001329
1330 completed = False
1331 try:
1332 for res in infos:
1333 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -07001334 try:
1335 sock = socket.socket(af, socktype, proto)
1336 except socket.error:
1337 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +02001338 if self._debug:
1339 logger.warning('create_server() failed to create '
1340 'socket.socket(%r, %r, %r)',
1341 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -07001342 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001343 sockets.append(sock)
1344 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -07001345 sock.setsockopt(
1346 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
1347 if reuse_port:
Yury Selivanov5587d7c2016-09-15 15:45:07 -04001348 _set_reuseport(sock)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001349 # Disable IPv4/IPv6 dual stack support (enabled by
1350 # default on Linux) which makes a single socket
1351 # listen on both address families.
1352 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
1353 sock.setsockopt(socket.IPPROTO_IPV6,
1354 socket.IPV6_V6ONLY,
1355 True)
1356 try:
1357 sock.bind(sa)
1358 except OSError as err:
1359 raise OSError(err.errno, 'error while attempting '
1360 'to bind on address %r: %s'
Serhiy Storchaka5affd232017-04-05 09:37:24 +03001361 % (sa, err.strerror.lower())) from None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001362 completed = True
1363 finally:
1364 if not completed:
1365 for sock in sockets:
1366 sock.close()
1367 else:
1368 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +02001369 raise ValueError('Neither host/port nor sock were specified')
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001370 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001371 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001372 sockets = [sock]
1373
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001374 for sock in sockets:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001375 sock.setblocking(False)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001376
1377 server = Server(self, sockets, protocol_factory,
1378 ssl, backlog, ssl_handshake_timeout)
1379 if start_serving:
1380 server._start_serving()
Miss Islington (bot)bc3a0022018-05-28 11:50:45 -07001381 # Skip one loop iteration so that all 'loop.add_reader'
1382 # go through.
1383 await tasks.sleep(0, loop=self)
Yury Selivanovc9070d02018-01-25 18:08:09 -05001384
Victor Stinnere912e652014-07-12 03:11:53 +02001385 if self._debug:
1386 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001387 return server
1388
Neil Aspinallf7686c12017-12-19 19:45:42 +00001389 async def connect_accepted_socket(
1390 self, protocol_factory, sock,
1391 *, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001392 ssl_handshake_timeout=None):
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001393 """Handle an accepted connection.
1394
1395 This is used by servers that accept connections outside of
1396 asyncio but that use asyncio to handle connections.
1397
1398 This method is a coroutine. When completed, the coroutine
1399 returns a (transport, protocol) pair.
1400 """
Yury Selivanova7bd64c2017-12-19 06:44:37 -05001401 if sock.type != socket.SOCK_STREAM:
Yury Selivanov6370f342017-12-10 18:36:12 -05001402 raise ValueError(f'A Stream Socket was expected, got {sock!r}')
Yury Selivanova1a8b7d2016-11-09 15:47:00 -05001403
Andrew Svetlov51eb1c62017-12-20 20:24:43 +02001404 if ssl_handshake_timeout is not None and not ssl:
1405 raise ValueError(
1406 'ssl_handshake_timeout is only meaningful with ssl')
1407
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001408 transport, protocol = await self._create_connection_transport(
Neil Aspinallf7686c12017-12-19 19:45:42 +00001409 sock, protocol_factory, ssl, '', server_side=True,
1410 ssl_handshake_timeout=ssl_handshake_timeout)
Yury Selivanov252e9ed2016-07-12 18:23:10 -04001411 if self._debug:
1412 # Get the socket from the transport because SSL transport closes
1413 # the old socket and creates a new SSL socket
1414 sock = transport.get_extra_info('socket')
1415 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1416 return transport, protocol
1417
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001418 async def connect_read_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001419 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001420 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001421 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001422
1423 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001424 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001425 except:
1426 transport.close()
1427 raise
1428
Victor Stinneracdb7822014-07-14 18:33:40 +02001429 if self._debug:
1430 logger.debug('Read pipe %r connected: (%r, %r)',
1431 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001432 return transport, protocol
1433
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001434 async def connect_write_pipe(self, protocol_factory, pipe):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001435 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001436 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001437 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001438
1439 try:
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001440 await waiter
Victor Stinner2596dd02015-01-26 11:02:18 +01001441 except:
1442 transport.close()
1443 raise
1444
Victor Stinneracdb7822014-07-14 18:33:40 +02001445 if self._debug:
1446 logger.debug('Write pipe %r connected: (%r, %r)',
1447 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001448 return transport, protocol
1449
Victor Stinneracdb7822014-07-14 18:33:40 +02001450 def _log_subprocess(self, msg, stdin, stdout, stderr):
1451 info = [msg]
1452 if stdin is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001453 info.append(f'stdin={_format_pipe(stdin)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001454 if stdout is not None and stderr == subprocess.STDOUT:
Yury Selivanov6370f342017-12-10 18:36:12 -05001455 info.append(f'stdout=stderr={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001456 else:
1457 if stdout is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001458 info.append(f'stdout={_format_pipe(stdout)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001459 if stderr is not None:
Yury Selivanov6370f342017-12-10 18:36:12 -05001460 info.append(f'stderr={_format_pipe(stderr)}')
Victor Stinneracdb7822014-07-14 18:33:40 +02001461 logger.debug(' '.join(info))
1462
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001463 async def subprocess_shell(self, protocol_factory, cmd, *,
1464 stdin=subprocess.PIPE,
1465 stdout=subprocess.PIPE,
1466 stderr=subprocess.PIPE,
1467 universal_newlines=False,
1468 shell=True, bufsize=0,
1469 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001470 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001471 raise ValueError("cmd must be a string")
1472 if universal_newlines:
1473 raise ValueError("universal_newlines must be False")
1474 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001475 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001476 if bufsize != 0:
1477 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001478 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001479 if self._debug:
1480 # don't log parameters: they may contain sensitive information
1481 # (password) and may be too long
1482 debug_log = 'run shell command %r' % cmd
1483 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001484 transport = await self._make_subprocess_transport(
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001485 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001486 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001487 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001488 return transport, protocol
1489
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001490 async def subprocess_exec(self, protocol_factory, program, *args,
1491 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1492 stderr=subprocess.PIPE, universal_newlines=False,
1493 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001494 if universal_newlines:
1495 raise ValueError("universal_newlines must be False")
1496 if shell:
1497 raise ValueError("shell must be False")
1498 if bufsize != 0:
1499 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001500 popen_args = (program,) + args
1501 for arg in popen_args:
1502 if not isinstance(arg, (str, bytes)):
Yury Selivanov6370f342017-12-10 18:36:12 -05001503 raise TypeError(
1504 f"program arguments must be a bytes or text string, "
1505 f"not {type(arg).__name__}")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001506 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001507 if self._debug:
1508 # don't log parameters: they may contain sensitive information
1509 # (password) and may be too long
Yury Selivanov6370f342017-12-10 18:36:12 -05001510 debug_log = f'execute program {program!r}'
Victor Stinneracdb7822014-07-14 18:33:40 +02001511 self._log_subprocess(debug_log, stdin, stdout, stderr)
Andrew Svetlov5f841b52017-12-09 00:23:48 +02001512 transport = await self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001513 protocol, popen_args, False, stdin, stdout, stderr,
1514 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001515 if self._debug:
Vinay Sajipdd917f82016-08-31 08:22:29 +01001516 logger.info('%s: %r', debug_log, transport)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001517 return transport, protocol
1518
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001519 def get_exception_handler(self):
1520 """Return an exception handler, or None if the default one is in use.
1521 """
1522 return self._exception_handler
1523
Yury Selivanov569efa22014-02-18 18:02:19 -05001524 def set_exception_handler(self, handler):
1525 """Set handler as the new event loop exception handler.
1526
1527 If handler is None, the default exception handler will
1528 be set.
1529
1530 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001531 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001532 will be a reference to the active event loop, 'context'
1533 will be a dict object (see `call_exception_handler()`
1534 documentation for details about context).
1535 """
1536 if handler is not None and not callable(handler):
Yury Selivanov6370f342017-12-10 18:36:12 -05001537 raise TypeError(f'A callable object or None is expected, '
1538 f'got {handler!r}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001539 self._exception_handler = handler
1540
1541 def default_exception_handler(self, context):
1542 """Default exception handler.
1543
1544 This is called when an exception occurs and no exception
1545 handler is set, and can be called by a custom exception
1546 handler that wants to defer to the default behavior.
1547
Antoine Pitrou921e9432017-11-07 17:23:29 +01001548 This default handler logs the error message and other
1549 context-dependent information. In debug mode, a truncated
1550 stack trace is also appended showing where the given object
1551 (e.g. a handle or future or task) was created, if any.
1552
Victor Stinneracdb7822014-07-14 18:33:40 +02001553 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001554 `call_exception_handler()`.
1555 """
1556 message = context.get('message')
1557 if not message:
1558 message = 'Unhandled exception in event loop'
1559
1560 exception = context.get('exception')
1561 if exception is not None:
1562 exc_info = (type(exception), exception, exception.__traceback__)
1563 else:
1564 exc_info = False
1565
Yury Selivanov6370f342017-12-10 18:36:12 -05001566 if ('source_traceback' not in context and
1567 self._current_handle is not None and
1568 self._current_handle._source_traceback):
1569 context['handle_traceback'] = \
1570 self._current_handle._source_traceback
Victor Stinner9b524d52015-01-26 11:05:12 +01001571
Yury Selivanov569efa22014-02-18 18:02:19 -05001572 log_lines = [message]
1573 for key in sorted(context):
1574 if key in {'message', 'exception'}:
1575 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001576 value = context[key]
1577 if key == 'source_traceback':
1578 tb = ''.join(traceback.format_list(value))
1579 value = 'Object created at (most recent call last):\n'
1580 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001581 elif key == 'handle_traceback':
1582 tb = ''.join(traceback.format_list(value))
1583 value = 'Handle created at (most recent call last):\n'
1584 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001585 else:
1586 value = repr(value)
Yury Selivanov6370f342017-12-10 18:36:12 -05001587 log_lines.append(f'{key}: {value}')
Yury Selivanov569efa22014-02-18 18:02:19 -05001588
1589 logger.error('\n'.join(log_lines), exc_info=exc_info)
1590
1591 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001592 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001593
Victor Stinneracdb7822014-07-14 18:33:40 +02001594 The context argument is a dict containing the following keys:
1595
Yury Selivanov569efa22014-02-18 18:02:19 -05001596 - 'message': Error message;
1597 - 'exception' (optional): Exception object;
1598 - 'future' (optional): Future instance;
Yury Selivanova4afcdf2018-01-21 14:56:59 -05001599 - 'task' (optional): Task instance;
Yury Selivanov569efa22014-02-18 18:02:19 -05001600 - 'handle' (optional): Handle instance;
1601 - 'protocol' (optional): Protocol instance;
1602 - 'transport' (optional): Transport instance;
Yury Selivanoveb636452016-09-08 22:01:51 -07001603 - 'socket' (optional): Socket instance;
1604 - 'asyncgen' (optional): Asynchronous generator that caused
1605 the exception.
Yury Selivanov569efa22014-02-18 18:02:19 -05001606
Victor Stinneracdb7822014-07-14 18:33:40 +02001607 New keys maybe introduced in the future.
1608
1609 Note: do not overload this method in an event loop subclass.
1610 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001611 `set_exception_handler()` method.
1612 """
1613 if self._exception_handler is None:
1614 try:
1615 self.default_exception_handler(context)
1616 except Exception:
1617 # Second protection layer for unexpected errors
1618 # in the default implementation, as well as for subclassed
1619 # event loops with overloaded "default_exception_handler".
1620 logger.error('Exception in default exception handler',
1621 exc_info=True)
1622 else:
1623 try:
1624 self._exception_handler(self, context)
1625 except Exception as exc:
1626 # Exception in the user set custom exception handler.
1627 try:
1628 # Let's try default handler.
1629 self.default_exception_handler({
1630 'message': 'Unhandled error in exception handler',
1631 'exception': exc,
1632 'context': context,
1633 })
1634 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001635 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001636 # overloaded.
1637 logger.error('Exception in default exception handler '
1638 'while handling an unexpected error '
1639 'in custom exception handler',
1640 exc_info=True)
1641
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001642 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001643 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001644 assert isinstance(handle, events.Handle), 'A Handle is required here'
1645 if handle._cancelled:
1646 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001647 assert not isinstance(handle, events.TimerHandle)
1648 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001649
1650 def _add_callback_signalsafe(self, handle):
1651 """Like _add_callback() but called from a signal handler."""
1652 self._add_callback(handle)
1653 self._write_to_self()
1654
Yury Selivanov592ada92014-09-25 12:07:56 -04001655 def _timer_handle_cancelled(self, handle):
1656 """Notification that a TimerHandle has been cancelled."""
1657 if handle._scheduled:
1658 self._timer_cancelled_count += 1
1659
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001660 def _run_once(self):
1661 """Run one full iteration of the event loop.
1662
1663 This calls all currently ready callbacks, polls for I/O,
1664 schedules the resulting callbacks, and finally schedules
1665 'call_later' callbacks.
1666 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001667
Yury Selivanov592ada92014-09-25 12:07:56 -04001668 sched_count = len(self._scheduled)
1669 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1670 self._timer_cancelled_count / sched_count >
1671 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001672 # Remove delayed calls that were cancelled if their number
1673 # is too high
1674 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001675 for handle in self._scheduled:
1676 if handle._cancelled:
1677 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001678 else:
1679 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001680
Victor Stinner68da8fc2014-09-30 18:08:36 +02001681 heapq.heapify(new_scheduled)
1682 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001683 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001684 else:
1685 # Remove delayed calls that were cancelled from head of queue.
1686 while self._scheduled and self._scheduled[0]._cancelled:
1687 self._timer_cancelled_count -= 1
1688 handle = heapq.heappop(self._scheduled)
1689 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001690
1691 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001692 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001693 timeout = 0
1694 elif self._scheduled:
1695 # Compute the desired timeout.
1696 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001697 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001698
Victor Stinner770e48d2014-07-11 11:58:33 +02001699 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001700 t0 = self.time()
1701 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001702 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001703 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001704 level = logging.INFO
1705 else:
1706 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001707 nevent = len(event_list)
1708 if timeout is None:
1709 logger.log(level, 'poll took %.3f ms: %s events',
1710 dt * 1e3, nevent)
1711 elif nevent:
1712 logger.log(level,
1713 'poll %.3f ms took %.3f ms: %s events',
1714 timeout * 1e3, dt * 1e3, nevent)
1715 elif dt >= 1.0:
1716 logger.log(level,
1717 'poll %.3f ms took %.3f ms: timeout',
1718 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001719 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001720 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001721 self._process_events(event_list)
1722
1723 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001724 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001725 while self._scheduled:
1726 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001727 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001728 break
1729 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001730 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001731 self._ready.append(handle)
1732
1733 # This is the only place where callbacks are actually *called*.
1734 # All other places just add them to ready.
1735 # Note: We run all currently scheduled callbacks, but not any
1736 # callbacks scheduled by callbacks run this time around --
1737 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001738 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001739 ntodo = len(self._ready)
1740 for i in range(ntodo):
1741 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001742 if handle._cancelled:
1743 continue
1744 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001745 try:
1746 self._current_handle = handle
1747 t0 = self.time()
1748 handle._run()
1749 dt = self.time() - t0
1750 if dt >= self.slow_callback_duration:
1751 logger.warning('Executing %s took %.3f seconds',
1752 _format_handle(handle), dt)
1753 finally:
1754 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001755 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001756 handle._run()
1757 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001758
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001759 def _set_coroutine_origin_tracking(self, enabled):
1760 if bool(enabled) == bool(self._coroutine_origin_tracking_enabled):
Yury Selivanove8944cb2015-05-12 11:43:04 -04001761 return
1762
Yury Selivanove8944cb2015-05-12 11:43:04 -04001763 if enabled:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001764 self._coroutine_origin_tracking_saved_depth = (
1765 sys.get_coroutine_origin_tracking_depth())
1766 sys.set_coroutine_origin_tracking_depth(
1767 constants.DEBUG_STACK_DEPTH)
Yury Selivanove8944cb2015-05-12 11:43:04 -04001768 else:
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001769 sys.set_coroutine_origin_tracking_depth(
1770 self._coroutine_origin_tracking_saved_depth)
1771
1772 self._coroutine_origin_tracking_enabled = enabled
Yury Selivanove8944cb2015-05-12 11:43:04 -04001773
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001774 def get_debug(self):
1775 return self._debug
1776
1777 def set_debug(self, enabled):
1778 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001779
Yury Selivanove8944cb2015-05-12 11:43:04 -04001780 if self.is_running():
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001781 self.call_soon_threadsafe(self._set_coroutine_origin_tracking, enabled)