blob: 017437552fc72422c449992ada45e91f3e55ffd8 [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
16
17import collections
18import concurrent.futures
19import heapq
Victor Stinner0e6f52a2014-06-20 17:34:15 +020020import inspect
Victor Stinner5e4a7d82015-09-21 18:33:43 +020021import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070022import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020023import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070024import socket
25import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010026import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070027import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020028import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070029import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010030import warnings
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031
Yury Selivanov2a8911c2015-08-04 15:56:33 -040032from . import compat
Victor Stinnerf951d282014-06-29 00:46:45 +020033from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070034from . import events
35from . import futures
36from . import tasks
Victor Stinnerf951d282014-06-29 00:46:45 +020037from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070038from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039
40
Victor Stinner8c1a4a22015-01-06 01:03:58 +010041__all__ = ['BaseEventLoop']
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070042
43
44# Argument for default thread pool executor creation.
45_MAX_WORKERS = 5
46
Yury Selivanov592ada92014-09-25 12:07:56 -040047# Minimum number of _scheduled timer handles before cleanup of
48# cancelled handles is performed.
49_MIN_SCHEDULED_TIMER_HANDLES = 100
50
51# Minimum fraction of _scheduled timer handles that are cancelled
52# before cleanup of cancelled handles is performed.
53_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070054
Victor Stinnerc94a93a2016-04-01 21:43:39 +020055# Exceptions which must not call the exception handler in fatal error
56# methods (_fatal_error())
57_FATAL_ERROR_IGNORE = (BrokenPipeError,
58 ConnectionResetError, ConnectionAbortedError)
59
60
Victor Stinner0e6f52a2014-06-20 17:34:15 +020061def _format_handle(handle):
62 cb = handle._callback
63 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
64 # format the task
65 return repr(cb.__self__)
66 else:
67 return str(handle)
68
69
Victor Stinneracdb7822014-07-14 18:33:40 +020070def _format_pipe(fd):
71 if fd == subprocess.PIPE:
72 return '<pipe>'
73 elif fd == subprocess.STDOUT:
74 return '<stdout>'
75 else:
76 return repr(fd)
77
78
Yury Selivanovd5c2a622015-12-16 19:31:17 -050079# Linux's sock.type is a bitmask that can include extra info about socket.
80_SOCKET_TYPE_MASK = 0
81if hasattr(socket, 'SOCK_NONBLOCK'):
82 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
83if hasattr(socket, 'SOCK_CLOEXEC'):
84 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
85
86
Yury Selivanovd5c2a622015-12-16 19:31:17 -050087def _ipaddr_info(host, port, family, type, proto):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -040088 # Try to skip getaddrinfo if "host" is already an IP. Users might have
89 # handled name resolution in their own code and pass in resolved IPs.
90 if not hasattr(socket, 'inet_pton'):
91 return
92
93 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or \
94 host is None:
Yury Selivanovd5c2a622015-12-16 19:31:17 -050095 return None
96
97 type &= ~_SOCKET_TYPE_MASK
98 if type == socket.SOCK_STREAM:
99 proto = socket.IPPROTO_TCP
100 elif type == socket.SOCK_DGRAM:
101 proto = socket.IPPROTO_UDP
102 else:
103 return None
104
Yury Selivanova7146162016-06-02 16:51:07 -0400105 if port is None:
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400106 port = 0
Yury Selivanova7146162016-06-02 16:51:07 -0400107 elif isinstance(port, bytes):
108 if port == b'':
109 port = 0
110 else:
111 try:
112 port = int(port)
113 except ValueError:
114 # Might be a service name like b"http".
115 port = socket.getservbyname(port.decode('ascii'))
116 elif isinstance(port, str):
117 if port == '':
118 port = 0
119 else:
120 try:
121 port = int(port)
122 except ValueError:
123 # Might be a service name like "http".
124 port = socket.getservbyname(port)
Yury Selivanoveaaaee82016-05-20 17:44:19 -0400125
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400126 if family == socket.AF_UNSPEC:
127 afs = [socket.AF_INET, socket.AF_INET6]
128 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
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400150def _ensure_resolved(address, *, family=0, type=socket.SOCK_STREAM, proto=0,
151 flags=0, loop):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500152 host, port = address[:2]
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400153 info = _ipaddr_info(host, port, family, type, proto)
154 if info is not None:
155 # "host" is already a resolved IP.
156 fut = loop.create_future()
157 fut.set_result([info])
158 return fut
159 else:
160 return loop.getaddrinfo(host, port, family=family, type=type,
161 proto=proto, flags=flags)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100162
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700163
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100164def _run_until_complete_cb(fut):
165 exc = fut._exception
166 if (isinstance(exc, BaseException)
167 and not isinstance(exc, Exception)):
168 # Issue #22429: run_forever() already finished, no need to
169 # stop it.
170 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800171 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100172
173
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174class Server(events.AbstractServer):
175
176 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200177 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700178 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200179 self._active_count = 0
180 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700181
Victor Stinnere912e652014-07-12 03:11:53 +0200182 def __repr__(self):
183 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
184
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200185 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700188
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200189 def _detach(self):
190 assert self._active_count > 0
191 self._active_count -= 1
192 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193 self._wakeup()
194
195 def close(self):
196 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200197 if sockets is None:
198 return
199 self.sockets = None
200 for sock in sockets:
201 self._loop._stop_serving(sock)
202 if self._active_count == 0:
203 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204
205 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 waiters = self._waiters
207 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208 for waiter in waiters:
209 if not waiter.done():
210 waiter.set_result(waiter)
211
Victor Stinnerf951d282014-06-29 00:46:45 +0200212 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700213 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200214 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700215 return
Yury Selivanov7661db62016-05-16 15:38:39 -0400216 waiter = self._loop.create_future()
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200217 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 yield from waiter
219
220
221class BaseEventLoop(events.AbstractEventLoop):
222
223 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400224 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200225 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800226 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700227 self._ready = collections.deque()
228 self._scheduled = []
229 self._default_executor = None
230 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100231 # Identifier of the thread running the event loop, or None if the
232 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100233 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100234 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500235 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400236 self.set_debug((not sys.flags.ignore_environment
237 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200238 # In debug mode, if the execution of a callback or a step of a task
239 # exceed this duration in seconds, the slow callback/task is logged.
240 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100241 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400242 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400243 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700244
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200245 def __repr__(self):
246 return ('<%s running=%s closed=%s debug=%s>'
247 % (self.__class__.__name__, self.is_running(),
248 self.is_closed(), self.get_debug()))
249
Yury Selivanov7661db62016-05-16 15:38:39 -0400250 def create_future(self):
251 """Create a Future object attached to the loop."""
252 return futures.Future(loop=self)
253
Victor Stinner896a25a2014-07-08 11:29:25 +0200254 def create_task(self, coro):
255 """Schedule a coroutine object.
256
Victor Stinneracdb7822014-07-14 18:33:40 +0200257 Return a task object.
258 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100259 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400260 if self._task_factory is None:
261 task = tasks.Task(coro, loop=self)
262 if task._source_traceback:
263 del task._source_traceback[-1]
264 else:
265 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200266 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200267
Yury Selivanov740169c2015-05-11 14:23:38 -0400268 def set_task_factory(self, factory):
269 """Set a task factory that will be used by loop.create_task().
270
271 If factory is None the default task factory will be set.
272
273 If factory is a callable, it should have a signature matching
274 '(loop, coro)', where 'loop' will be a reference to the active
275 event loop, 'coro' will be a coroutine object. The callable
276 must return a Future.
277 """
278 if factory is not None and not callable(factory):
279 raise TypeError('task factory must be a callable or None')
280 self._task_factory = factory
281
282 def get_task_factory(self):
283 """Return a task factory, or None if the default one is in use."""
284 return self._task_factory
285
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700286 def _make_socket_transport(self, sock, protocol, waiter=None, *,
287 extra=None, server=None):
288 """Create socket transport."""
289 raise NotImplementedError
290
Victor Stinner15cc6782015-01-09 00:09:10 +0100291 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
292 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700293 extra=None, server=None):
294 """Create SSL transport."""
295 raise NotImplementedError
296
297 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200298 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700299 """Create datagram transport."""
300 raise NotImplementedError
301
302 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
303 extra=None):
304 """Create read pipe transport."""
305 raise NotImplementedError
306
307 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
308 extra=None):
309 """Create write pipe transport."""
310 raise NotImplementedError
311
Victor Stinnerf951d282014-06-29 00:46:45 +0200312 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700313 def _make_subprocess_transport(self, protocol, args, shell,
314 stdin, stdout, stderr, bufsize,
315 extra=None, **kwargs):
316 """Create subprocess transport."""
317 raise NotImplementedError
318
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700319 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200320 """Write a byte to self-pipe, to wake up the event loop.
321
322 This may be called from a different thread.
323
324 The subclass is responsible for implementing the self-pipe.
325 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700326 raise NotImplementedError
327
328 def _process_events(self, event_list):
329 """Process selector events."""
330 raise NotImplementedError
331
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200332 def _check_closed(self):
333 if self._closed:
334 raise RuntimeError('Event loop is closed')
335
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700336 def run_forever(self):
337 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200338 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100339 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700340 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400341 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100342 self._thread_id = threading.get_ident()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700343 try:
344 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800345 self._run_once()
346 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700347 break
348 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800349 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100350 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400351 self._set_coroutine_wrapper(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700352
353 def run_until_complete(self, future):
354 """Run until the Future is done.
355
356 If the argument is a coroutine, it is wrapped in a Task.
357
Victor Stinneracdb7822014-07-14 18:33:40 +0200358 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700359 with the same coroutine twice -- it would wrap it in two
360 different Tasks and that can't be good.
361
362 Return the Future's result, or raise its exception.
363 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200364 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200365
366 new_task = not isinstance(future, futures.Future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400367 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200368 if new_task:
369 # An exception is raised if the future didn't complete, so there
370 # is no need to log the "destroy pending task" message
371 future._log_destroy_pending = False
372
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100373 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200374 try:
375 self.run_forever()
376 except:
377 if new_task and future.done() and not future.cancelled():
378 # The coroutine raised a BaseException. Consume the exception
379 # to not log a warning, the caller doesn't have access to the
380 # local task.
381 future.exception()
382 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100383 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700384 if not future.done():
385 raise RuntimeError('Event loop stopped before Future completed.')
386
387 return future.result()
388
389 def stop(self):
390 """Stop running the event loop.
391
Guido van Rossum41f69f42015-11-19 13:28:47 -0800392 Every callback already scheduled will still run. This simply informs
393 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700394 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800395 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700396
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200397 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700398 """Close the event loop.
399
400 This clears the queues and shuts down the executor,
401 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200402
403 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700404 """
Victor Stinner956de692014-12-26 21:07:52 +0100405 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200406 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200407 if self._closed:
408 return
Victor Stinnere912e652014-07-12 03:11:53 +0200409 if self._debug:
410 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400411 self._closed = True
412 self._ready.clear()
413 self._scheduled.clear()
414 executor = self._default_executor
415 if executor is not None:
416 self._default_executor = None
417 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200418
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200419 def is_closed(self):
420 """Returns True if the event loop was closed."""
421 return self._closed
422
Victor Stinner978a9af2015-01-29 17:50:58 +0100423 # On Python 3.3 and older, objects with a destructor part of a reference
424 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
425 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400426 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100427 def __del__(self):
428 if not self.is_closed():
429 warnings.warn("unclosed event loop %r" % self, ResourceWarning)
430 if not self.is_running():
431 self.close()
432
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700433 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200434 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100435 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700436
437 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200438 """Return the time according to the event loop's clock.
439
440 This is a float expressed in seconds since an epoch, but the
441 epoch, precision, accuracy and drift are unspecified and may
442 differ per event loop.
443 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700444 return time.monotonic()
445
446 def call_later(self, delay, callback, *args):
447 """Arrange for a callback to be called at a given time.
448
449 Return a Handle: an opaque object with a cancel() method that
450 can be used to cancel the call.
451
452 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200453 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700454
455 Each callback will be called exactly once. If two callbacks
456 are scheduled for exactly the same time, it undefined which
457 will be called first.
458
459 Any positional arguments after the callback will be passed to
460 the callback when it is called.
461 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200462 timer = self.call_at(self.time() + delay, callback, *args)
463 if timer._source_traceback:
464 del timer._source_traceback[-1]
465 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466
467 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200468 """Like call_later(), but uses an absolute time.
469
470 Absolute time corresponds to the event loop's time() method.
471 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100472 if (coroutines.iscoroutine(callback)
473 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100474 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100475 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100476 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100477 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500478 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200479 if timer._source_traceback:
480 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700481 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400482 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700483 return timer
484
485 def call_soon(self, callback, *args):
486 """Arrange for a callback to be called as soon as possible.
487
Victor Stinneracdb7822014-07-14 18:33:40 +0200488 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700489 order in which they are registered. Each callback will be
490 called exactly once.
491
492 Any positional arguments after the callback will be passed to
493 the callback when it is called.
494 """
Victor Stinner956de692014-12-26 21:07:52 +0100495 if self._debug:
496 self._check_thread()
497 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200498 if handle._source_traceback:
499 del handle._source_traceback[-1]
500 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100501
Victor Stinner956de692014-12-26 21:07:52 +0100502 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100503 if (coroutines.iscoroutine(callback)
504 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100505 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100506 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500507 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200508 if handle._source_traceback:
509 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700510 self._ready.append(handle)
511 return handle
512
Victor Stinner956de692014-12-26 21:07:52 +0100513 def _check_thread(self):
514 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100515
Victor Stinneracdb7822014-07-14 18:33:40 +0200516 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100517 likely behave incorrectly when the assumption is violated.
518
Victor Stinneracdb7822014-07-14 18:33:40 +0200519 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100520 responsible for checking this condition for performance reasons.
521 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100522 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200523 return
Victor Stinner956de692014-12-26 21:07:52 +0100524 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100525 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100526 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200527 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100528 "than the current one")
529
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200531 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100532 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200533 if handle._source_traceback:
534 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700535 self._write_to_self()
536 return handle
537
Yury Selivanov740169c2015-05-11 14:23:38 -0400538 def run_in_executor(self, executor, func, *args):
539 if (coroutines.iscoroutine(func)
540 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100541 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100542 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400543 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400545 assert not isinstance(func, events.TimerHandle)
546 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400547 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700548 f.set_result(None)
549 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400550 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 if executor is None:
552 executor = self._default_executor
553 if executor is None:
554 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
555 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400556 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557
558 def set_default_executor(self, executor):
559 self._default_executor = executor
560
Victor Stinnere912e652014-07-12 03:11:53 +0200561 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
562 msg = ["%s:%r" % (host, port)]
563 if family:
564 msg.append('family=%r' % family)
565 if type:
566 msg.append('type=%r' % type)
567 if proto:
568 msg.append('proto=%r' % proto)
569 if flags:
570 msg.append('flags=%r' % flags)
571 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200572 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200573
574 t0 = self.time()
575 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
576 dt = self.time() - t0
577
Victor Stinneracdb7822014-07-14 18:33:40 +0200578 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200579 % (msg, dt * 1e3, addrinfo))
580 if dt >= self.slow_callback_duration:
581 logger.info(msg)
582 else:
583 logger.debug(msg)
584 return addrinfo
585
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700586 def getaddrinfo(self, host, port, *,
587 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400588 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200589 return self.run_in_executor(None, self._getaddrinfo_debug,
590 host, port, family, type, proto, flags)
591 else:
592 return self.run_in_executor(None, socket.getaddrinfo,
593 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700594
595 def getnameinfo(self, sockaddr, flags=0):
596 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
597
Victor Stinnerf951d282014-06-29 00:46:45 +0200598 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700599 def create_connection(self, protocol_factory, host=None, port=None, *,
600 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700601 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200602 """Connect to a TCP server.
603
604 Create a streaming transport connection to a given Internet host and
605 port: socket family AF_INET or socket.AF_INET6 depending on host (or
606 family if specified), socket type SOCK_STREAM. protocol_factory must be
607 a callable returning a protocol instance.
608
609 This method is a coroutine which will try to establish the connection
610 in the background. When successful, the coroutine returns a
611 (transport, protocol) pair.
612 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700613 if server_hostname is not None and not ssl:
614 raise ValueError('server_hostname is only meaningful with ssl')
615
616 if server_hostname is None and ssl:
617 # Use host as default for server_hostname. It is an error
618 # if host is empty or not set, e.g. when an
619 # already-connected socket was passed or when only a port
620 # is given. To avoid this error, you can pass
621 # server_hostname='' -- this will bypass the hostname
622 # check. (This also means that if host is a numeric
623 # IP/IPv6 address, we will attempt to verify that exact
624 # address; this will probably fail, but it is possible to
625 # create a certificate for a specific IP address, so we
626 # don't judge it here.)
627 if not host:
628 raise ValueError('You must set server_hostname '
629 'when using ssl without a host')
630 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700631
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700632 if host is not None or port is not None:
633 if sock is not None:
634 raise ValueError(
635 'host/port and sock can not be specified at the same time')
636
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400637 f1 = _ensure_resolved((host, port), family=family,
638 type=socket.SOCK_STREAM, proto=proto,
639 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700640 fs = [f1]
641 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400642 f2 = _ensure_resolved(local_addr, family=family,
643 type=socket.SOCK_STREAM, proto=proto,
644 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700645 fs.append(f2)
646 else:
647 f2 = None
648
649 yield from tasks.wait(fs, loop=self)
650
651 infos = f1.result()
652 if not infos:
653 raise OSError('getaddrinfo() returned empty list')
654 if f2 is not None:
655 laddr_infos = f2.result()
656 if not laddr_infos:
657 raise OSError('getaddrinfo() returned empty list')
658
659 exceptions = []
660 for family, type, proto, cname, address in infos:
661 try:
662 sock = socket.socket(family=family, type=type, proto=proto)
663 sock.setblocking(False)
664 if f2 is not None:
665 for _, _, _, _, laddr in laddr_infos:
666 try:
667 sock.bind(laddr)
668 break
669 except OSError as exc:
670 exc = OSError(
671 exc.errno, 'error while '
672 'attempting to bind on address '
673 '{!r}: {}'.format(
674 laddr, exc.strerror.lower()))
675 exceptions.append(exc)
676 else:
677 sock.close()
678 sock = None
679 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200680 if self._debug:
681 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700682 yield from self.sock_connect(sock, address)
683 except OSError as exc:
684 if sock is not None:
685 sock.close()
686 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200687 except:
688 if sock is not None:
689 sock.close()
690 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700691 else:
692 break
693 else:
694 if len(exceptions) == 1:
695 raise exceptions[0]
696 else:
697 # If they all have the same str(), raise one.
698 model = str(exceptions[0])
699 if all(str(exc) == model for exc in exceptions):
700 raise exceptions[0]
701 # Raise a combined exception so the user can see all
702 # the various error messages.
703 raise OSError('Multiple exceptions: {}'.format(
704 ', '.join(str(exc) for exc in exceptions)))
705
706 elif sock is None:
707 raise ValueError(
708 'host and port was not specified and no sock specified')
709
Yury Selivanovb057c522014-02-18 12:15:06 -0500710 transport, protocol = yield from self._create_connection_transport(
711 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200712 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200713 # Get the socket from the transport because SSL transport closes
714 # the old socket and creates a new SSL socket
715 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200716 logger.debug("%r connected to %s:%r: (%r, %r)",
717 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500718 return transport, protocol
719
Victor Stinnerf951d282014-06-29 00:46:45 +0200720 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500721 def _create_connection_transport(self, sock, protocol_factory, ssl,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400722 server_hostname, server_side=False):
723
724 sock.setblocking(False)
725
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700726 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400727 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700728 if ssl:
729 sslcontext = None if isinstance(ssl, bool) else ssl
730 transport = self._make_ssl_transport(
731 sock, protocol, sslcontext, waiter,
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400732 server_side=server_side, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700733 else:
734 transport = self._make_socket_transport(sock, protocol, waiter)
735
Victor Stinner29ad0112015-01-15 00:04:21 +0100736 try:
737 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100738 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100739 transport.close()
740 raise
741
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700742 return transport, protocol
743
Victor Stinnerf951d282014-06-29 00:46:45 +0200744 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700745 def create_datagram_endpoint(self, protocol_factory,
746 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700747 family=0, proto=0, flags=0,
748 reuse_address=None, reuse_port=None,
749 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700750 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700751 if sock is not None:
752 if (local_addr or remote_addr or
753 family or proto or flags or
754 reuse_address or reuse_port or allow_broadcast):
755 # show the problematic kwargs in exception msg
756 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
757 family=family, proto=proto, flags=flags,
758 reuse_address=reuse_address, reuse_port=reuse_port,
759 allow_broadcast=allow_broadcast)
760 problems = ', '.join(
761 '{}={}'.format(k, v) for k, v in opts.items() if v)
762 raise ValueError(
763 'socket modifier keyword arguments can not be used '
764 'when sock is specified. ({})'.format(problems))
765 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700766 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700767 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700768 if not (local_addr or remote_addr):
769 if family == 0:
770 raise ValueError('unexpected address family')
771 addr_pairs_info = (((family, proto), (None, None)),)
772 else:
773 # join address by (family, protocol)
774 addr_infos = collections.OrderedDict()
775 for idx, addr in ((0, local_addr), (1, remote_addr)):
776 if addr is not None:
777 assert isinstance(addr, tuple) and len(addr) == 2, (
778 '2-tuple is expected')
779
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400780 infos = yield from _ensure_resolved(
781 addr, family=family, type=socket.SOCK_DGRAM,
782 proto=proto, flags=flags, loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700783 if not infos:
784 raise OSError('getaddrinfo() returned empty list')
785
786 for fam, _, pro, _, address in infos:
787 key = (fam, pro)
788 if key not in addr_infos:
789 addr_infos[key] = [None, None]
790 addr_infos[key][idx] = address
791
792 # each addr has to have info for each (family, proto) pair
793 addr_pairs_info = [
794 (key, addr_pair) for key, addr_pair in addr_infos.items()
795 if not ((local_addr and addr_pair[0] is None) or
796 (remote_addr and addr_pair[1] is None))]
797
798 if not addr_pairs_info:
799 raise ValueError('can not get address information')
800
801 exceptions = []
802
803 if reuse_address is None:
804 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
805
806 for ((family, proto),
807 (local_address, remote_address)) in addr_pairs_info:
808 sock = None
809 r_addr = None
810 try:
811 sock = socket.socket(
812 family=family, type=socket.SOCK_DGRAM, proto=proto)
813 if reuse_address:
814 sock.setsockopt(
815 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
816 if reuse_port:
817 if not hasattr(socket, 'SO_REUSEPORT'):
818 raise ValueError(
819 'reuse_port not supported by socket module')
820 else:
821 sock.setsockopt(
822 socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
823 if allow_broadcast:
824 sock.setsockopt(
825 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
826 sock.setblocking(False)
827
828 if local_addr:
829 sock.bind(local_address)
830 if remote_addr:
831 yield from self.sock_connect(sock, remote_address)
832 r_addr = remote_address
833 except OSError as exc:
834 if sock is not None:
835 sock.close()
836 exceptions.append(exc)
837 except:
838 if sock is not None:
839 sock.close()
840 raise
841 else:
842 break
843 else:
844 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700845
846 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400847 waiter = self.create_future()
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700848 transport = self._make_datagram_transport(
849 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200850 if self._debug:
851 if local_addr:
852 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
853 "created: (%r, %r)",
854 local_addr, remote_addr, transport, protocol)
855 else:
856 logger.debug("Datagram endpoint remote_addr=%r created: "
857 "(%r, %r)",
858 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100859
860 try:
861 yield from waiter
862 except:
863 transport.close()
864 raise
865
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700866 return transport, protocol
867
Victor Stinnerf951d282014-06-29 00:46:45 +0200868 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200869 def _create_server_getaddrinfo(self, host, port, family, flags):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400870 infos = yield from _ensure_resolved((host, port), family=family,
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200871 type=socket.SOCK_STREAM,
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400872 flags=flags, loop=self)
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200873 if not infos:
874 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
875 return infos
876
877 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700878 def create_server(self, protocol_factory, host=None, port=None,
879 *,
880 family=socket.AF_UNSPEC,
881 flags=socket.AI_PASSIVE,
882 sock=None,
883 backlog=100,
884 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700885 reuse_address=None,
886 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200887 """Create a TCP server.
888
889 The host parameter can be a string, in that case the TCP server is bound
890 to host and port.
891
892 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500893 the TCP server is bound to all hosts of the sequence. If a host
894 appears multiple times (possibly indirectly e.g. when hostnames
895 resolve to the same IP address), the server is only bound once to that
896 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200897
Victor Stinneracdb7822014-07-14 18:33:40 +0200898 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200899
900 This method is a coroutine.
901 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700902 if isinstance(ssl, bool):
903 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700904 if host is not None or port is not None:
905 if sock is not None:
906 raise ValueError(
907 'host/port and sock can not be specified at the same time')
908
909 AF_INET6 = getattr(socket, 'AF_INET6', 0)
910 if reuse_address is None:
911 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
912 sockets = []
913 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200914 hosts = [None]
915 elif (isinstance(host, str) or
916 not isinstance(host, collections.Iterable)):
917 hosts = [host]
918 else:
919 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700920
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200921 fs = [self._create_server_getaddrinfo(host, port, family=family,
922 flags=flags)
923 for host in hosts]
924 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500925 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700926
927 completed = False
928 try:
929 for res in infos:
930 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700931 try:
932 sock = socket.socket(af, socktype, proto)
933 except socket.error:
934 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200935 if self._debug:
936 logger.warning('create_server() failed to create '
937 'socket.socket(%r, %r, %r)',
938 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700939 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700940 sockets.append(sock)
941 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700942 sock.setsockopt(
943 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
944 if reuse_port:
945 if not hasattr(socket, 'SO_REUSEPORT'):
946 raise ValueError(
947 'reuse_port not supported by socket module')
948 else:
949 sock.setsockopt(
950 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700951 # Disable IPv4/IPv6 dual stack support (enabled by
952 # default on Linux) which makes a single socket
953 # listen on both address families.
954 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
955 sock.setsockopt(socket.IPPROTO_IPV6,
956 socket.IPV6_V6ONLY,
957 True)
958 try:
959 sock.bind(sa)
960 except OSError as err:
961 raise OSError(err.errno, 'error while attempting '
962 'to bind on address %r: %s'
963 % (sa, err.strerror.lower()))
964 completed = True
965 finally:
966 if not completed:
967 for sock in sockets:
968 sock.close()
969 else:
970 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +0200971 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700972 sockets = [sock]
973
974 server = Server(self, sockets)
975 for sock in sockets:
976 sock.listen(backlog)
977 sock.setblocking(False)
978 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +0200979 if self._debug:
980 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700981 return server
982
Victor Stinnerf951d282014-06-29 00:46:45 +0200983 @coroutine
Yury Selivanov252e9ed2016-07-12 18:23:10 -0400984 def connect_accepted_socket(self, protocol_factory, sock, *, ssl=None):
985 """Handle an accepted connection.
986
987 This is used by servers that accept connections outside of
988 asyncio but that use asyncio to handle connections.
989
990 This method is a coroutine. When completed, the coroutine
991 returns a (transport, protocol) pair.
992 """
993 transport, protocol = yield from self._create_connection_transport(
994 sock, protocol_factory, ssl, '', server_side=True)
995 if self._debug:
996 # Get the socket from the transport because SSL transport closes
997 # the old socket and creates a new SSL socket
998 sock = transport.get_extra_info('socket')
999 logger.debug("%r handled: (%r, %r)", sock, transport, protocol)
1000 return transport, protocol
1001
1002 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001003 def connect_read_pipe(self, protocol_factory, pipe):
1004 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001005 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001006 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001007
1008 try:
1009 yield from waiter
1010 except:
1011 transport.close()
1012 raise
1013
Victor Stinneracdb7822014-07-14 18:33:40 +02001014 if self._debug:
1015 logger.debug('Read pipe %r connected: (%r, %r)',
1016 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001017 return transport, protocol
1018
Victor Stinnerf951d282014-06-29 00:46:45 +02001019 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001020 def connect_write_pipe(self, protocol_factory, pipe):
1021 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001022 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001023 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001024
1025 try:
1026 yield from waiter
1027 except:
1028 transport.close()
1029 raise
1030
Victor Stinneracdb7822014-07-14 18:33:40 +02001031 if self._debug:
1032 logger.debug('Write pipe %r connected: (%r, %r)',
1033 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001034 return transport, protocol
1035
Victor Stinneracdb7822014-07-14 18:33:40 +02001036 def _log_subprocess(self, msg, stdin, stdout, stderr):
1037 info = [msg]
1038 if stdin is not None:
1039 info.append('stdin=%s' % _format_pipe(stdin))
1040 if stdout is not None and stderr == subprocess.STDOUT:
1041 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1042 else:
1043 if stdout is not None:
1044 info.append('stdout=%s' % _format_pipe(stdout))
1045 if stderr is not None:
1046 info.append('stderr=%s' % _format_pipe(stderr))
1047 logger.debug(' '.join(info))
1048
Victor Stinnerf951d282014-06-29 00:46:45 +02001049 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001050 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1051 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1052 universal_newlines=False, shell=True, bufsize=0,
1053 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001054 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001055 raise ValueError("cmd must be a string")
1056 if universal_newlines:
1057 raise ValueError("universal_newlines must be False")
1058 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001059 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001060 if bufsize != 0:
1061 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001062 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001063 if self._debug:
1064 # don't log parameters: they may contain sensitive information
1065 # (password) and may be too long
1066 debug_log = 'run shell command %r' % cmd
1067 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001068 transport = yield from self._make_subprocess_transport(
1069 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001070 if self._debug:
1071 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001072 return transport, protocol
1073
Victor Stinnerf951d282014-06-29 00:46:45 +02001074 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001075 def subprocess_exec(self, protocol_factory, program, *args,
1076 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1077 stderr=subprocess.PIPE, universal_newlines=False,
1078 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001079 if universal_newlines:
1080 raise ValueError("universal_newlines must be False")
1081 if shell:
1082 raise ValueError("shell must be False")
1083 if bufsize != 0:
1084 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001085 popen_args = (program,) + args
1086 for arg in popen_args:
1087 if not isinstance(arg, (str, bytes)):
1088 raise TypeError("program arguments must be "
1089 "a bytes or text string, not %s"
1090 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001091 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001092 if self._debug:
1093 # don't log parameters: they may contain sensitive information
1094 # (password) and may be too long
1095 debug_log = 'execute program %r' % program
1096 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001097 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001098 protocol, popen_args, False, stdin, stdout, stderr,
1099 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001100 if self._debug:
1101 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001102 return transport, protocol
1103
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001104 def get_exception_handler(self):
1105 """Return an exception handler, or None if the default one is in use.
1106 """
1107 return self._exception_handler
1108
Yury Selivanov569efa22014-02-18 18:02:19 -05001109 def set_exception_handler(self, handler):
1110 """Set handler as the new event loop exception handler.
1111
1112 If handler is None, the default exception handler will
1113 be set.
1114
1115 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001116 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001117 will be a reference to the active event loop, 'context'
1118 will be a dict object (see `call_exception_handler()`
1119 documentation for details about context).
1120 """
1121 if handler is not None and not callable(handler):
1122 raise TypeError('A callable object or None is expected, '
1123 'got {!r}'.format(handler))
1124 self._exception_handler = handler
1125
1126 def default_exception_handler(self, context):
1127 """Default exception handler.
1128
1129 This is called when an exception occurs and no exception
1130 handler is set, and can be called by a custom exception
1131 handler that wants to defer to the default behavior.
1132
Victor Stinneracdb7822014-07-14 18:33:40 +02001133 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001134 `call_exception_handler()`.
1135 """
1136 message = context.get('message')
1137 if not message:
1138 message = 'Unhandled exception in event loop'
1139
1140 exception = context.get('exception')
1141 if exception is not None:
1142 exc_info = (type(exception), exception, exception.__traceback__)
1143 else:
1144 exc_info = False
1145
Victor Stinnerff018e42015-01-28 00:30:40 +01001146 if ('source_traceback' not in context
1147 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001148 and self._current_handle._source_traceback):
1149 context['handle_traceback'] = self._current_handle._source_traceback
1150
Yury Selivanov569efa22014-02-18 18:02:19 -05001151 log_lines = [message]
1152 for key in sorted(context):
1153 if key in {'message', 'exception'}:
1154 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001155 value = context[key]
1156 if key == 'source_traceback':
1157 tb = ''.join(traceback.format_list(value))
1158 value = 'Object created at (most recent call last):\n'
1159 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001160 elif key == 'handle_traceback':
1161 tb = ''.join(traceback.format_list(value))
1162 value = 'Handle created at (most recent call last):\n'
1163 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001164 else:
1165 value = repr(value)
1166 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001167
1168 logger.error('\n'.join(log_lines), exc_info=exc_info)
1169
1170 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001171 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001172
Victor Stinneracdb7822014-07-14 18:33:40 +02001173 The context argument is a dict containing the following keys:
1174
Yury Selivanov569efa22014-02-18 18:02:19 -05001175 - 'message': Error message;
1176 - 'exception' (optional): Exception object;
1177 - 'future' (optional): Future instance;
1178 - 'handle' (optional): Handle instance;
1179 - 'protocol' (optional): Protocol instance;
1180 - 'transport' (optional): Transport instance;
1181 - 'socket' (optional): Socket instance.
1182
Victor Stinneracdb7822014-07-14 18:33:40 +02001183 New keys maybe introduced in the future.
1184
1185 Note: do not overload this method in an event loop subclass.
1186 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001187 `set_exception_handler()` method.
1188 """
1189 if self._exception_handler is None:
1190 try:
1191 self.default_exception_handler(context)
1192 except Exception:
1193 # Second protection layer for unexpected errors
1194 # in the default implementation, as well as for subclassed
1195 # event loops with overloaded "default_exception_handler".
1196 logger.error('Exception in default exception handler',
1197 exc_info=True)
1198 else:
1199 try:
1200 self._exception_handler(self, context)
1201 except Exception as exc:
1202 # Exception in the user set custom exception handler.
1203 try:
1204 # Let's try default handler.
1205 self.default_exception_handler({
1206 'message': 'Unhandled error in exception handler',
1207 'exception': exc,
1208 'context': context,
1209 })
1210 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001211 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001212 # overloaded.
1213 logger.error('Exception in default exception handler '
1214 'while handling an unexpected error '
1215 'in custom exception handler',
1216 exc_info=True)
1217
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001218 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001219 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001220 assert isinstance(handle, events.Handle), 'A Handle is required here'
1221 if handle._cancelled:
1222 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001223 assert not isinstance(handle, events.TimerHandle)
1224 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001225
1226 def _add_callback_signalsafe(self, handle):
1227 """Like _add_callback() but called from a signal handler."""
1228 self._add_callback(handle)
1229 self._write_to_self()
1230
Yury Selivanov592ada92014-09-25 12:07:56 -04001231 def _timer_handle_cancelled(self, handle):
1232 """Notification that a TimerHandle has been cancelled."""
1233 if handle._scheduled:
1234 self._timer_cancelled_count += 1
1235
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001236 def _run_once(self):
1237 """Run one full iteration of the event loop.
1238
1239 This calls all currently ready callbacks, polls for I/O,
1240 schedules the resulting callbacks, and finally schedules
1241 'call_later' callbacks.
1242 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001243
Yury Selivanov592ada92014-09-25 12:07:56 -04001244 sched_count = len(self._scheduled)
1245 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1246 self._timer_cancelled_count / sched_count >
1247 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001248 # Remove delayed calls that were cancelled if their number
1249 # is too high
1250 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001251 for handle in self._scheduled:
1252 if handle._cancelled:
1253 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001254 else:
1255 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001256
Victor Stinner68da8fc2014-09-30 18:08:36 +02001257 heapq.heapify(new_scheduled)
1258 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001259 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001260 else:
1261 # Remove delayed calls that were cancelled from head of queue.
1262 while self._scheduled and self._scheduled[0]._cancelled:
1263 self._timer_cancelled_count -= 1
1264 handle = heapq.heappop(self._scheduled)
1265 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001266
1267 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001268 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001269 timeout = 0
1270 elif self._scheduled:
1271 # Compute the desired timeout.
1272 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001273 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001274
Victor Stinner770e48d2014-07-11 11:58:33 +02001275 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001276 t0 = self.time()
1277 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001278 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001279 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001280 level = logging.INFO
1281 else:
1282 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001283 nevent = len(event_list)
1284 if timeout is None:
1285 logger.log(level, 'poll took %.3f ms: %s events',
1286 dt * 1e3, nevent)
1287 elif nevent:
1288 logger.log(level,
1289 'poll %.3f ms took %.3f ms: %s events',
1290 timeout * 1e3, dt * 1e3, nevent)
1291 elif dt >= 1.0:
1292 logger.log(level,
1293 'poll %.3f ms took %.3f ms: timeout',
1294 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001295 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001296 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001297 self._process_events(event_list)
1298
1299 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001300 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001301 while self._scheduled:
1302 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001303 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001304 break
1305 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001306 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001307 self._ready.append(handle)
1308
1309 # This is the only place where callbacks are actually *called*.
1310 # All other places just add them to ready.
1311 # Note: We run all currently scheduled callbacks, but not any
1312 # callbacks scheduled by callbacks run this time around --
1313 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001314 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001315 ntodo = len(self._ready)
1316 for i in range(ntodo):
1317 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001318 if handle._cancelled:
1319 continue
1320 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001321 try:
1322 self._current_handle = handle
1323 t0 = self.time()
1324 handle._run()
1325 dt = self.time() - t0
1326 if dt >= self.slow_callback_duration:
1327 logger.warning('Executing %s took %.3f seconds',
1328 _format_handle(handle), dt)
1329 finally:
1330 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001331 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001332 handle._run()
1333 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001334
Yury Selivanove8944cb2015-05-12 11:43:04 -04001335 def _set_coroutine_wrapper(self, enabled):
1336 try:
1337 set_wrapper = sys.set_coroutine_wrapper
1338 get_wrapper = sys.get_coroutine_wrapper
1339 except AttributeError:
1340 return
1341
1342 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001343 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001344 return
1345
1346 wrapper = coroutines.debug_wrapper
1347 current_wrapper = get_wrapper()
1348
1349 if enabled:
1350 if current_wrapper not in (None, wrapper):
1351 warnings.warn(
1352 "loop.set_debug(True): cannot set debug coroutine "
1353 "wrapper; another wrapper is already set %r" %
1354 current_wrapper, RuntimeWarning)
1355 else:
1356 set_wrapper(wrapper)
1357 self._coroutine_wrapper_set = True
1358 else:
1359 if current_wrapper not in (None, wrapper):
1360 warnings.warn(
1361 "loop.set_debug(False): cannot unset debug coroutine "
1362 "wrapper; another wrapper was set %r" %
1363 current_wrapper, RuntimeWarning)
1364 else:
1365 set_wrapper(None)
1366 self._coroutine_wrapper_set = False
1367
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001368 def get_debug(self):
1369 return self._debug
1370
1371 def set_debug(self, enabled):
1372 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001373
Yury Selivanove8944cb2015-05-12 11:43:04 -04001374 if self.is_running():
1375 self._set_coroutine_wrapper(enabled)