blob: f55a36e0828b103511f888858170df063df18f3a [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():
Victor Stinnere19558a2016-03-23 00:28:08 +0100429 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
430 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100431 if not self.is_running():
432 self.close()
433
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700434 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200435 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100436 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700437
438 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200439 """Return the time according to the event loop's clock.
440
441 This is a float expressed in seconds since an epoch, but the
442 epoch, precision, accuracy and drift are unspecified and may
443 differ per event loop.
444 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700445 return time.monotonic()
446
447 def call_later(self, delay, callback, *args):
448 """Arrange for a callback to be called at a given time.
449
450 Return a Handle: an opaque object with a cancel() method that
451 can be used to cancel the call.
452
453 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200454 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700455
456 Each callback will be called exactly once. If two callbacks
457 are scheduled for exactly the same time, it undefined which
458 will be called first.
459
460 Any positional arguments after the callback will be passed to
461 the callback when it is called.
462 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200463 timer = self.call_at(self.time() + delay, callback, *args)
464 if timer._source_traceback:
465 del timer._source_traceback[-1]
466 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467
468 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200469 """Like call_later(), but uses an absolute time.
470
471 Absolute time corresponds to the event loop's time() method.
472 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100473 if (coroutines.iscoroutine(callback)
474 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100475 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100476 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100477 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100478 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500479 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200480 if timer._source_traceback:
481 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700482 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400483 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700484 return timer
485
486 def call_soon(self, callback, *args):
487 """Arrange for a callback to be called as soon as possible.
488
Victor Stinneracdb7822014-07-14 18:33:40 +0200489 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 order in which they are registered. Each callback will be
491 called exactly once.
492
493 Any positional arguments after the callback will be passed to
494 the callback when it is called.
495 """
Victor Stinner956de692014-12-26 21:07:52 +0100496 if self._debug:
497 self._check_thread()
498 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200499 if handle._source_traceback:
500 del handle._source_traceback[-1]
501 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100502
Victor Stinner956de692014-12-26 21:07:52 +0100503 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100504 if (coroutines.iscoroutine(callback)
505 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100506 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100507 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500508 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200509 if handle._source_traceback:
510 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700511 self._ready.append(handle)
512 return handle
513
Victor Stinner956de692014-12-26 21:07:52 +0100514 def _check_thread(self):
515 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100516
Victor Stinneracdb7822014-07-14 18:33:40 +0200517 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100518 likely behave incorrectly when the assumption is violated.
519
Victor Stinneracdb7822014-07-14 18:33:40 +0200520 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100521 responsible for checking this condition for performance reasons.
522 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100523 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200524 return
Victor Stinner956de692014-12-26 21:07:52 +0100525 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100526 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100527 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200528 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100529 "than the current one")
530
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200532 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100533 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200534 if handle._source_traceback:
535 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700536 self._write_to_self()
537 return handle
538
Yury Selivanov740169c2015-05-11 14:23:38 -0400539 def run_in_executor(self, executor, func, *args):
540 if (coroutines.iscoroutine(func)
541 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100542 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100543 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400544 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700545 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400546 assert not isinstance(func, events.TimerHandle)
547 if func._cancelled:
Yury Selivanov7661db62016-05-16 15:38:39 -0400548 f = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700549 f.set_result(None)
550 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400551 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552 if executor is None:
553 executor = self._default_executor
554 if executor is None:
555 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
556 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400557 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700558
559 def set_default_executor(self, executor):
560 self._default_executor = executor
561
Victor Stinnere912e652014-07-12 03:11:53 +0200562 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
563 msg = ["%s:%r" % (host, port)]
564 if family:
565 msg.append('family=%r' % family)
566 if type:
567 msg.append('type=%r' % type)
568 if proto:
569 msg.append('proto=%r' % proto)
570 if flags:
571 msg.append('flags=%r' % flags)
572 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200573 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200574
575 t0 = self.time()
576 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
577 dt = self.time() - t0
578
Victor Stinneracdb7822014-07-14 18:33:40 +0200579 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200580 % (msg, dt * 1e3, addrinfo))
581 if dt >= self.slow_callback_duration:
582 logger.info(msg)
583 else:
584 logger.debug(msg)
585 return addrinfo
586
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587 def getaddrinfo(self, host, port, *,
588 family=0, type=0, proto=0, flags=0):
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400589 if self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200590 return self.run_in_executor(None, self._getaddrinfo_debug,
591 host, port, family, type, proto, flags)
592 else:
593 return self.run_in_executor(None, socket.getaddrinfo,
594 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700595
596 def getnameinfo(self, sockaddr, flags=0):
597 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
598
Victor Stinnerf951d282014-06-29 00:46:45 +0200599 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600 def create_connection(self, protocol_factory, host=None, port=None, *,
601 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700602 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200603 """Connect to a TCP server.
604
605 Create a streaming transport connection to a given Internet host and
606 port: socket family AF_INET or socket.AF_INET6 depending on host (or
607 family if specified), socket type SOCK_STREAM. protocol_factory must be
608 a callable returning a protocol instance.
609
610 This method is a coroutine which will try to establish the connection
611 in the background. When successful, the coroutine returns a
612 (transport, protocol) pair.
613 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700614 if server_hostname is not None and not ssl:
615 raise ValueError('server_hostname is only meaningful with ssl')
616
617 if server_hostname is None and ssl:
618 # Use host as default for server_hostname. It is an error
619 # if host is empty or not set, e.g. when an
620 # already-connected socket was passed or when only a port
621 # is given. To avoid this error, you can pass
622 # server_hostname='' -- this will bypass the hostname
623 # check. (This also means that if host is a numeric
624 # IP/IPv6 address, we will attempt to verify that exact
625 # address; this will probably fail, but it is possible to
626 # create a certificate for a specific IP address, so we
627 # don't judge it here.)
628 if not host:
629 raise ValueError('You must set server_hostname '
630 'when using ssl without a host')
631 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700632
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700633 if host is not None or port is not None:
634 if sock is not None:
635 raise ValueError(
636 'host/port and sock can not be specified at the same time')
637
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400638 f1 = _ensure_resolved((host, port), family=family,
639 type=socket.SOCK_STREAM, proto=proto,
640 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700641 fs = [f1]
642 if local_addr is not None:
Yury Selivanovf1c6fa92016-06-08 12:33:31 -0400643 f2 = _ensure_resolved(local_addr, family=family,
644 type=socket.SOCK_STREAM, proto=proto,
645 flags=flags, loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700646 fs.append(f2)
647 else:
648 f2 = None
649
650 yield from tasks.wait(fs, loop=self)
651
652 infos = f1.result()
653 if not infos:
654 raise OSError('getaddrinfo() returned empty list')
655 if f2 is not None:
656 laddr_infos = f2.result()
657 if not laddr_infos:
658 raise OSError('getaddrinfo() returned empty list')
659
660 exceptions = []
661 for family, type, proto, cname, address in infos:
662 try:
663 sock = socket.socket(family=family, type=type, proto=proto)
664 sock.setblocking(False)
665 if f2 is not None:
666 for _, _, _, _, laddr in laddr_infos:
667 try:
668 sock.bind(laddr)
669 break
670 except OSError as exc:
671 exc = OSError(
672 exc.errno, 'error while '
673 'attempting to bind on address '
674 '{!r}: {}'.format(
675 laddr, exc.strerror.lower()))
676 exceptions.append(exc)
677 else:
678 sock.close()
679 sock = None
680 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200681 if self._debug:
682 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700683 yield from self.sock_connect(sock, address)
684 except OSError as exc:
685 if sock is not None:
686 sock.close()
687 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200688 except:
689 if sock is not None:
690 sock.close()
691 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700692 else:
693 break
694 else:
695 if len(exceptions) == 1:
696 raise exceptions[0]
697 else:
698 # If they all have the same str(), raise one.
699 model = str(exceptions[0])
700 if all(str(exc) == model for exc in exceptions):
701 raise exceptions[0]
702 # Raise a combined exception so the user can see all
703 # the various error messages.
704 raise OSError('Multiple exceptions: {}'.format(
705 ', '.join(str(exc) for exc in exceptions)))
706
707 elif sock is None:
708 raise ValueError(
709 'host and port was not specified and no sock specified')
710
711 sock.setblocking(False)
712
Yury Selivanovb057c522014-02-18 12:15:06 -0500713 transport, protocol = yield from self._create_connection_transport(
714 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200715 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200716 # Get the socket from the transport because SSL transport closes
717 # the old socket and creates a new SSL socket
718 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200719 logger.debug("%r connected to %s:%r: (%r, %r)",
720 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500721 return transport, protocol
722
Victor Stinnerf951d282014-06-29 00:46:45 +0200723 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500724 def _create_connection_transport(self, sock, protocol_factory, ssl,
725 server_hostname):
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,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700732 server_side=False, 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
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700984 def connect_read_pipe(self, protocol_factory, pipe):
985 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -0400986 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700987 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100988
989 try:
990 yield from waiter
991 except:
992 transport.close()
993 raise
994
Victor Stinneracdb7822014-07-14 18:33:40 +0200995 if self._debug:
996 logger.debug('Read pipe %r connected: (%r, %r)',
997 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700998 return transport, protocol
999
Victor Stinnerf951d282014-06-29 00:46:45 +02001000 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001001 def connect_write_pipe(self, protocol_factory, pipe):
1002 protocol = protocol_factory()
Yury Selivanov7661db62016-05-16 15:38:39 -04001003 waiter = self.create_future()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001004 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001005
1006 try:
1007 yield from waiter
1008 except:
1009 transport.close()
1010 raise
1011
Victor Stinneracdb7822014-07-14 18:33:40 +02001012 if self._debug:
1013 logger.debug('Write pipe %r connected: (%r, %r)',
1014 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001015 return transport, protocol
1016
Victor Stinneracdb7822014-07-14 18:33:40 +02001017 def _log_subprocess(self, msg, stdin, stdout, stderr):
1018 info = [msg]
1019 if stdin is not None:
1020 info.append('stdin=%s' % _format_pipe(stdin))
1021 if stdout is not None and stderr == subprocess.STDOUT:
1022 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1023 else:
1024 if stdout is not None:
1025 info.append('stdout=%s' % _format_pipe(stdout))
1026 if stderr is not None:
1027 info.append('stderr=%s' % _format_pipe(stderr))
1028 logger.debug(' '.join(info))
1029
Victor Stinnerf951d282014-06-29 00:46:45 +02001030 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001031 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1032 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1033 universal_newlines=False, shell=True, bufsize=0,
1034 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001035 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001036 raise ValueError("cmd must be a string")
1037 if universal_newlines:
1038 raise ValueError("universal_newlines must be False")
1039 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001040 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001041 if bufsize != 0:
1042 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001043 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001044 if self._debug:
1045 # don't log parameters: they may contain sensitive information
1046 # (password) and may be too long
1047 debug_log = 'run shell command %r' % cmd
1048 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001049 transport = yield from self._make_subprocess_transport(
1050 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001051 if self._debug:
1052 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001053 return transport, protocol
1054
Victor Stinnerf951d282014-06-29 00:46:45 +02001055 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001056 def subprocess_exec(self, protocol_factory, program, *args,
1057 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1058 stderr=subprocess.PIPE, universal_newlines=False,
1059 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001060 if universal_newlines:
1061 raise ValueError("universal_newlines must be False")
1062 if shell:
1063 raise ValueError("shell must be False")
1064 if bufsize != 0:
1065 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001066 popen_args = (program,) + args
1067 for arg in popen_args:
1068 if not isinstance(arg, (str, bytes)):
1069 raise TypeError("program arguments must be "
1070 "a bytes or text string, not %s"
1071 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001072 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001073 if self._debug:
1074 # don't log parameters: they may contain sensitive information
1075 # (password) and may be too long
1076 debug_log = 'execute program %r' % program
1077 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001078 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001079 protocol, popen_args, False, stdin, stdout, stderr,
1080 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001081 if self._debug:
1082 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001083 return transport, protocol
1084
Yury Selivanov7ed7ce62016-05-16 15:20:38 -04001085 def get_exception_handler(self):
1086 """Return an exception handler, or None if the default one is in use.
1087 """
1088 return self._exception_handler
1089
Yury Selivanov569efa22014-02-18 18:02:19 -05001090 def set_exception_handler(self, handler):
1091 """Set handler as the new event loop exception handler.
1092
1093 If handler is None, the default exception handler will
1094 be set.
1095
1096 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001097 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001098 will be a reference to the active event loop, 'context'
1099 will be a dict object (see `call_exception_handler()`
1100 documentation for details about context).
1101 """
1102 if handler is not None and not callable(handler):
1103 raise TypeError('A callable object or None is expected, '
1104 'got {!r}'.format(handler))
1105 self._exception_handler = handler
1106
1107 def default_exception_handler(self, context):
1108 """Default exception handler.
1109
1110 This is called when an exception occurs and no exception
1111 handler is set, and can be called by a custom exception
1112 handler that wants to defer to the default behavior.
1113
Victor Stinneracdb7822014-07-14 18:33:40 +02001114 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001115 `call_exception_handler()`.
1116 """
1117 message = context.get('message')
1118 if not message:
1119 message = 'Unhandled exception in event loop'
1120
1121 exception = context.get('exception')
1122 if exception is not None:
1123 exc_info = (type(exception), exception, exception.__traceback__)
1124 else:
1125 exc_info = False
1126
Victor Stinnerff018e42015-01-28 00:30:40 +01001127 if ('source_traceback' not in context
1128 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001129 and self._current_handle._source_traceback):
1130 context['handle_traceback'] = self._current_handle._source_traceback
1131
Yury Selivanov569efa22014-02-18 18:02:19 -05001132 log_lines = [message]
1133 for key in sorted(context):
1134 if key in {'message', 'exception'}:
1135 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001136 value = context[key]
1137 if key == 'source_traceback':
1138 tb = ''.join(traceback.format_list(value))
1139 value = 'Object created at (most recent call last):\n'
1140 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001141 elif key == 'handle_traceback':
1142 tb = ''.join(traceback.format_list(value))
1143 value = 'Handle created at (most recent call last):\n'
1144 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001145 else:
1146 value = repr(value)
1147 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001148
1149 logger.error('\n'.join(log_lines), exc_info=exc_info)
1150
1151 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001152 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001153
Victor Stinneracdb7822014-07-14 18:33:40 +02001154 The context argument is a dict containing the following keys:
1155
Yury Selivanov569efa22014-02-18 18:02:19 -05001156 - 'message': Error message;
1157 - 'exception' (optional): Exception object;
1158 - 'future' (optional): Future instance;
1159 - 'handle' (optional): Handle instance;
1160 - 'protocol' (optional): Protocol instance;
1161 - 'transport' (optional): Transport instance;
1162 - 'socket' (optional): Socket instance.
1163
Victor Stinneracdb7822014-07-14 18:33:40 +02001164 New keys maybe introduced in the future.
1165
1166 Note: do not overload this method in an event loop subclass.
1167 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001168 `set_exception_handler()` method.
1169 """
1170 if self._exception_handler is None:
1171 try:
1172 self.default_exception_handler(context)
1173 except Exception:
1174 # Second protection layer for unexpected errors
1175 # in the default implementation, as well as for subclassed
1176 # event loops with overloaded "default_exception_handler".
1177 logger.error('Exception in default exception handler',
1178 exc_info=True)
1179 else:
1180 try:
1181 self._exception_handler(self, context)
1182 except Exception as exc:
1183 # Exception in the user set custom exception handler.
1184 try:
1185 # Let's try default handler.
1186 self.default_exception_handler({
1187 'message': 'Unhandled error in exception handler',
1188 'exception': exc,
1189 'context': context,
1190 })
1191 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001192 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001193 # overloaded.
1194 logger.error('Exception in default exception handler '
1195 'while handling an unexpected error '
1196 'in custom exception handler',
1197 exc_info=True)
1198
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001199 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001200 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001201 assert isinstance(handle, events.Handle), 'A Handle is required here'
1202 if handle._cancelled:
1203 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001204 assert not isinstance(handle, events.TimerHandle)
1205 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001206
1207 def _add_callback_signalsafe(self, handle):
1208 """Like _add_callback() but called from a signal handler."""
1209 self._add_callback(handle)
1210 self._write_to_self()
1211
Yury Selivanov592ada92014-09-25 12:07:56 -04001212 def _timer_handle_cancelled(self, handle):
1213 """Notification that a TimerHandle has been cancelled."""
1214 if handle._scheduled:
1215 self._timer_cancelled_count += 1
1216
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001217 def _run_once(self):
1218 """Run one full iteration of the event loop.
1219
1220 This calls all currently ready callbacks, polls for I/O,
1221 schedules the resulting callbacks, and finally schedules
1222 'call_later' callbacks.
1223 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001224
Yury Selivanov592ada92014-09-25 12:07:56 -04001225 sched_count = len(self._scheduled)
1226 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1227 self._timer_cancelled_count / sched_count >
1228 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001229 # Remove delayed calls that were cancelled if their number
1230 # is too high
1231 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001232 for handle in self._scheduled:
1233 if handle._cancelled:
1234 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001235 else:
1236 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001237
Victor Stinner68da8fc2014-09-30 18:08:36 +02001238 heapq.heapify(new_scheduled)
1239 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001240 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001241 else:
1242 # Remove delayed calls that were cancelled from head of queue.
1243 while self._scheduled and self._scheduled[0]._cancelled:
1244 self._timer_cancelled_count -= 1
1245 handle = heapq.heappop(self._scheduled)
1246 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001247
1248 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001249 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001250 timeout = 0
1251 elif self._scheduled:
1252 # Compute the desired timeout.
1253 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001254 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001255
Victor Stinner770e48d2014-07-11 11:58:33 +02001256 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001257 t0 = self.time()
1258 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001259 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001260 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001261 level = logging.INFO
1262 else:
1263 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001264 nevent = len(event_list)
1265 if timeout is None:
1266 logger.log(level, 'poll took %.3f ms: %s events',
1267 dt * 1e3, nevent)
1268 elif nevent:
1269 logger.log(level,
1270 'poll %.3f ms took %.3f ms: %s events',
1271 timeout * 1e3, dt * 1e3, nevent)
1272 elif dt >= 1.0:
1273 logger.log(level,
1274 'poll %.3f ms took %.3f ms: timeout',
1275 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001276 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001277 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001278 self._process_events(event_list)
1279
1280 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001281 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001282 while self._scheduled:
1283 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001284 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001285 break
1286 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001287 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001288 self._ready.append(handle)
1289
1290 # This is the only place where callbacks are actually *called*.
1291 # All other places just add them to ready.
1292 # Note: We run all currently scheduled callbacks, but not any
1293 # callbacks scheduled by callbacks run this time around --
1294 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001295 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001296 ntodo = len(self._ready)
1297 for i in range(ntodo):
1298 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001299 if handle._cancelled:
1300 continue
1301 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001302 try:
1303 self._current_handle = handle
1304 t0 = self.time()
1305 handle._run()
1306 dt = self.time() - t0
1307 if dt >= self.slow_callback_duration:
1308 logger.warning('Executing %s took %.3f seconds',
1309 _format_handle(handle), dt)
1310 finally:
1311 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001312 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001313 handle._run()
1314 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001315
Yury Selivanove8944cb2015-05-12 11:43:04 -04001316 def _set_coroutine_wrapper(self, enabled):
1317 try:
1318 set_wrapper = sys.set_coroutine_wrapper
1319 get_wrapper = sys.get_coroutine_wrapper
1320 except AttributeError:
1321 return
1322
1323 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001324 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001325 return
1326
1327 wrapper = coroutines.debug_wrapper
1328 current_wrapper = get_wrapper()
1329
1330 if enabled:
1331 if current_wrapper not in (None, wrapper):
1332 warnings.warn(
1333 "loop.set_debug(True): cannot set debug coroutine "
1334 "wrapper; another wrapper is already set %r" %
1335 current_wrapper, RuntimeWarning)
1336 else:
1337 set_wrapper(wrapper)
1338 self._coroutine_wrapper_set = True
1339 else:
1340 if current_wrapper not in (None, wrapper):
1341 warnings.warn(
1342 "loop.set_debug(False): cannot unset debug coroutine "
1343 "wrapper; another wrapper was set %r" %
1344 current_wrapper, RuntimeWarning)
1345 else:
1346 set_wrapper(None)
1347 self._coroutine_wrapper_set = False
1348
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001349 def get_debug(self):
1350 return self._debug
1351
1352 def set_debug(self, enabled):
1353 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001354
Yury Selivanove8944cb2015-05-12 11:43:04 -04001355 if self.is_running():
1356 self._set_coroutine_wrapper(enabled)