blob: 3a42b10cb1bcf4f609c3efb9ea6d5e8ba2376306 [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
Yury Selivanovd5c2a622015-12-16 19:31:17 -050019import functools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070020import heapq
Victor Stinner0e6f52a2014-06-20 17:34:15 +020021import inspect
Yury Selivanovd5c2a622015-12-16 19:31:17 -050022import ipaddress
Victor Stinner5e4a7d82015-09-21 18:33:43 +020023import itertools
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070024import logging
Victor Stinnerb75380f2014-06-30 14:39:11 +020025import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070026import socket
27import subprocess
Victor Stinner956de692014-12-26 21:07:52 +010028import threading
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070029import time
Victor Stinnerb75380f2014-06-30 14:39:11 +020030import traceback
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031import sys
Victor Stinner978a9af2015-01-29 17:50:58 +010032import warnings
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070033
Yury Selivanov2a8911c2015-08-04 15:56:33 -040034from . import compat
Victor Stinnerf951d282014-06-29 00:46:45 +020035from . import coroutines
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070036from . import events
37from . import futures
38from . import tasks
Victor Stinnerf951d282014-06-29 00:46:45 +020039from .coroutines import coroutine
Guido van Rossumfc29e0f2013-10-17 15:39:45 -070040from .log import logger
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070041
42
Victor Stinner8c1a4a22015-01-06 01:03:58 +010043__all__ = ['BaseEventLoop']
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044
45
46# Argument for default thread pool executor creation.
47_MAX_WORKERS = 5
48
Yury Selivanov592ada92014-09-25 12:07:56 -040049# Minimum number of _scheduled timer handles before cleanup of
50# cancelled handles is performed.
51_MIN_SCHEDULED_TIMER_HANDLES = 100
52
53# Minimum fraction of _scheduled timer handles that are cancelled
54# before cleanup of cancelled handles is performed.
55_MIN_CANCELLED_TIMER_HANDLES_FRACTION = 0.5
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070056
Victor Stinner0e6f52a2014-06-20 17:34:15 +020057def _format_handle(handle):
58 cb = handle._callback
59 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
60 # format the task
61 return repr(cb.__self__)
62 else:
63 return str(handle)
64
65
Victor Stinneracdb7822014-07-14 18:33:40 +020066def _format_pipe(fd):
67 if fd == subprocess.PIPE:
68 return '<pipe>'
69 elif fd == subprocess.STDOUT:
70 return '<stdout>'
71 else:
72 return repr(fd)
73
74
Yury Selivanovd5c2a622015-12-16 19:31:17 -050075# Linux's sock.type is a bitmask that can include extra info about socket.
76_SOCKET_TYPE_MASK = 0
77if hasattr(socket, 'SOCK_NONBLOCK'):
78 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
79if hasattr(socket, 'SOCK_CLOEXEC'):
80 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
81
82
83@functools.lru_cache(maxsize=1024)
84def _ipaddr_info(host, port, family, type, proto):
85 # Try to skip getaddrinfo if "host" is already an IP. Since getaddrinfo
86 # blocks on an exclusive lock on some platforms, users might handle name
87 # resolution in their own code and pass in resolved IPs.
88 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or host is None:
89 return None
90
91 type &= ~_SOCKET_TYPE_MASK
92 if type == socket.SOCK_STREAM:
93 proto = socket.IPPROTO_TCP
94 elif type == socket.SOCK_DGRAM:
95 proto = socket.IPPROTO_UDP
96 else:
97 return None
98
99 if hasattr(socket, 'inet_pton'):
100 if family == socket.AF_UNSPEC:
101 afs = [socket.AF_INET, socket.AF_INET6]
102 else:
103 afs = [family]
104
105 for af in afs:
106 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
107 # like '::1%lo0', so strip it. If we happen to make an invalid
108 # address look valid, we fail later in sock.connect or sock.bind.
109 try:
110 if af == socket.AF_INET6:
111 socket.inet_pton(af, host.partition('%')[0])
112 else:
113 socket.inet_pton(af, host)
114 return af, type, proto, '', (host, port)
115 except OSError:
116 pass
117
118 # "host" is not an IP address.
119 return None
120
121 # No inet_pton. (On Windows it's only available since Python 3.4.)
122 # Even though getaddrinfo with AI_NUMERICHOST would be non-blocking, it
123 # still requires a lock on some platforms, and waiting for that lock could
124 # block the event loop. Use ipaddress instead, it's just text parsing.
125 try:
126 addr = ipaddress.IPv4Address(host)
127 except ValueError:
128 try:
129 addr = ipaddress.IPv6Address(host.partition('%')[0])
130 except ValueError:
131 return None
132
133 af = socket.AF_INET if addr.version == 4 else socket.AF_INET6
134 if family not in (socket.AF_UNSPEC, af):
135 # "host" is wrong IP version for "family".
136 return None
137
138 return af, type, proto, '', (host, port)
139
140
Victor Stinner1b0580b2014-02-13 09:24:37 +0100141def _check_resolved_address(sock, address):
142 # Ensure that the address is already resolved to avoid the trap of hanging
143 # the entire event loop when the address requires doing a DNS lookup.
Victor Stinner2fc23132015-02-04 14:51:23 +0100144
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500145 if hasattr(socket, 'AF_UNIX') and sock.family == socket.AF_UNIX:
Victor Stinner1b0580b2014-02-13 09:24:37 +0100146 return
147
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500148 host, port = address[:2]
149 if _ipaddr_info(host, port, sock.family, sock.type, sock.proto) is None:
150 raise ValueError("address must be resolved (IP address),"
151 " got host %r" % host)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100152
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700153
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100154def _run_until_complete_cb(fut):
155 exc = fut._exception
156 if (isinstance(exc, BaseException)
157 and not isinstance(exc, Exception)):
158 # Issue #22429: run_forever() already finished, no need to
159 # stop it.
160 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800161 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100162
163
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700164class Server(events.AbstractServer):
165
166 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200167 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700168 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200169 self._active_count = 0
170 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700171
Victor Stinnere912e652014-07-12 03:11:53 +0200172 def __repr__(self):
173 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
174
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200175 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700176 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200177 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700178
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200179 def _detach(self):
180 assert self._active_count > 0
181 self._active_count -= 1
182 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700183 self._wakeup()
184
185 def close(self):
186 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200187 if sockets is None:
188 return
189 self.sockets = None
190 for sock in sockets:
191 self._loop._stop_serving(sock)
192 if self._active_count == 0:
193 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194
195 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200196 waiters = self._waiters
197 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198 for waiter in waiters:
199 if not waiter.done():
200 waiter.set_result(waiter)
201
Victor Stinnerf951d282014-06-29 00:46:45 +0200202 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700203 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200204 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700205 return
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200206 waiter = futures.Future(loop=self._loop)
207 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700208 yield from waiter
209
210
211class BaseEventLoop(events.AbstractEventLoop):
212
213 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400214 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200215 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800216 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700217 self._ready = collections.deque()
218 self._scheduled = []
219 self._default_executor = None
220 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100221 # Identifier of the thread running the event loop, or None if the
222 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100223 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100224 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500225 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400226 self.set_debug((not sys.flags.ignore_environment
227 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200228 # In debug mode, if the execution of a callback or a step of a task
229 # exceed this duration in seconds, the slow callback/task is logged.
230 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100231 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400232 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400233 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700234
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200235 def __repr__(self):
236 return ('<%s running=%s closed=%s debug=%s>'
237 % (self.__class__.__name__, self.is_running(),
238 self.is_closed(), self.get_debug()))
239
Victor Stinner896a25a2014-07-08 11:29:25 +0200240 def create_task(self, coro):
241 """Schedule a coroutine object.
242
Victor Stinneracdb7822014-07-14 18:33:40 +0200243 Return a task object.
244 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100245 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400246 if self._task_factory is None:
247 task = tasks.Task(coro, loop=self)
248 if task._source_traceback:
249 del task._source_traceback[-1]
250 else:
251 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200252 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200253
Yury Selivanov740169c2015-05-11 14:23:38 -0400254 def set_task_factory(self, factory):
255 """Set a task factory that will be used by loop.create_task().
256
257 If factory is None the default task factory will be set.
258
259 If factory is a callable, it should have a signature matching
260 '(loop, coro)', where 'loop' will be a reference to the active
261 event loop, 'coro' will be a coroutine object. The callable
262 must return a Future.
263 """
264 if factory is not None and not callable(factory):
265 raise TypeError('task factory must be a callable or None')
266 self._task_factory = factory
267
268 def get_task_factory(self):
269 """Return a task factory, or None if the default one is in use."""
270 return self._task_factory
271
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700272 def _make_socket_transport(self, sock, protocol, waiter=None, *,
273 extra=None, server=None):
274 """Create socket transport."""
275 raise NotImplementedError
276
Victor Stinner15cc6782015-01-09 00:09:10 +0100277 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
278 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279 extra=None, server=None):
280 """Create SSL transport."""
281 raise NotImplementedError
282
283 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200284 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700285 """Create datagram transport."""
286 raise NotImplementedError
287
288 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
289 extra=None):
290 """Create read pipe transport."""
291 raise NotImplementedError
292
293 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
294 extra=None):
295 """Create write pipe transport."""
296 raise NotImplementedError
297
Victor Stinnerf951d282014-06-29 00:46:45 +0200298 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700299 def _make_subprocess_transport(self, protocol, args, shell,
300 stdin, stdout, stderr, bufsize,
301 extra=None, **kwargs):
302 """Create subprocess transport."""
303 raise NotImplementedError
304
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200306 """Write a byte to self-pipe, to wake up the event loop.
307
308 This may be called from a different thread.
309
310 The subclass is responsible for implementing the self-pipe.
311 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700312 raise NotImplementedError
313
314 def _process_events(self, event_list):
315 """Process selector events."""
316 raise NotImplementedError
317
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200318 def _check_closed(self):
319 if self._closed:
320 raise RuntimeError('Event loop is closed')
321
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700322 def run_forever(self):
323 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200324 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100325 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700326 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400327 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100328 self._thread_id = threading.get_ident()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700329 try:
330 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800331 self._run_once()
332 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700333 break
334 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800335 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100336 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400337 self._set_coroutine_wrapper(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700338
339 def run_until_complete(self, future):
340 """Run until the Future is done.
341
342 If the argument is a coroutine, it is wrapped in a Task.
343
Victor Stinneracdb7822014-07-14 18:33:40 +0200344 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700345 with the same coroutine twice -- it would wrap it in two
346 different Tasks and that can't be good.
347
348 Return the Future's result, or raise its exception.
349 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200350 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200351
352 new_task = not isinstance(future, futures.Future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400353 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200354 if new_task:
355 # An exception is raised if the future didn't complete, so there
356 # is no need to log the "destroy pending task" message
357 future._log_destroy_pending = False
358
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100359 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200360 try:
361 self.run_forever()
362 except:
363 if new_task and future.done() and not future.cancelled():
364 # The coroutine raised a BaseException. Consume the exception
365 # to not log a warning, the caller doesn't have access to the
366 # local task.
367 future.exception()
368 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100369 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700370 if not future.done():
371 raise RuntimeError('Event loop stopped before Future completed.')
372
373 return future.result()
374
375 def stop(self):
376 """Stop running the event loop.
377
Guido van Rossum41f69f42015-11-19 13:28:47 -0800378 Every callback already scheduled will still run. This simply informs
379 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800381 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700382
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200383 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700384 """Close the event loop.
385
386 This clears the queues and shuts down the executor,
387 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200388
389 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700390 """
Victor Stinner956de692014-12-26 21:07:52 +0100391 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200392 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200393 if self._closed:
394 return
Victor Stinnere912e652014-07-12 03:11:53 +0200395 if self._debug:
396 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400397 self._closed = True
398 self._ready.clear()
399 self._scheduled.clear()
400 executor = self._default_executor
401 if executor is not None:
402 self._default_executor = None
403 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200404
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200405 def is_closed(self):
406 """Returns True if the event loop was closed."""
407 return self._closed
408
Victor Stinner978a9af2015-01-29 17:50:58 +0100409 # On Python 3.3 and older, objects with a destructor part of a reference
410 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
411 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400412 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100413 def __del__(self):
414 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100415 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
416 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100417 if not self.is_running():
418 self.close()
419
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700420 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200421 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100422 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700423
424 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200425 """Return the time according to the event loop's clock.
426
427 This is a float expressed in seconds since an epoch, but the
428 epoch, precision, accuracy and drift are unspecified and may
429 differ per event loop.
430 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 return time.monotonic()
432
433 def call_later(self, delay, callback, *args):
434 """Arrange for a callback to be called at a given time.
435
436 Return a Handle: an opaque object with a cancel() method that
437 can be used to cancel the call.
438
439 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200440 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700441
442 Each callback will be called exactly once. If two callbacks
443 are scheduled for exactly the same time, it undefined which
444 will be called first.
445
446 Any positional arguments after the callback will be passed to
447 the callback when it is called.
448 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200449 timer = self.call_at(self.time() + delay, callback, *args)
450 if timer._source_traceback:
451 del timer._source_traceback[-1]
452 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700453
454 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200455 """Like call_later(), but uses an absolute time.
456
457 Absolute time corresponds to the event loop's time() method.
458 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100459 if (coroutines.iscoroutine(callback)
460 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100461 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100462 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100463 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100464 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500465 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200466 if timer._source_traceback:
467 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700468 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400469 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700470 return timer
471
472 def call_soon(self, callback, *args):
473 """Arrange for a callback to be called as soon as possible.
474
Victor Stinneracdb7822014-07-14 18:33:40 +0200475 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476 order in which they are registered. Each callback will be
477 called exactly once.
478
479 Any positional arguments after the callback will be passed to
480 the callback when it is called.
481 """
Victor Stinner956de692014-12-26 21:07:52 +0100482 if self._debug:
483 self._check_thread()
484 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200485 if handle._source_traceback:
486 del handle._source_traceback[-1]
487 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100488
Victor Stinner956de692014-12-26 21:07:52 +0100489 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100490 if (coroutines.iscoroutine(callback)
491 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100492 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100493 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500494 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200495 if handle._source_traceback:
496 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700497 self._ready.append(handle)
498 return handle
499
Victor Stinner956de692014-12-26 21:07:52 +0100500 def _check_thread(self):
501 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100502
Victor Stinneracdb7822014-07-14 18:33:40 +0200503 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100504 likely behave incorrectly when the assumption is violated.
505
Victor Stinneracdb7822014-07-14 18:33:40 +0200506 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100507 responsible for checking this condition for performance reasons.
508 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100509 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200510 return
Victor Stinner956de692014-12-26 21:07:52 +0100511 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100512 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100513 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200514 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100515 "than the current one")
516
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200518 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100519 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200520 if handle._source_traceback:
521 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700522 self._write_to_self()
523 return handle
524
Yury Selivanov740169c2015-05-11 14:23:38 -0400525 def run_in_executor(self, executor, func, *args):
526 if (coroutines.iscoroutine(func)
527 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100528 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100529 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400530 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400532 assert not isinstance(func, events.TimerHandle)
533 if func._cancelled:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700534 f = futures.Future(loop=self)
535 f.set_result(None)
536 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400537 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538 if executor is None:
539 executor = self._default_executor
540 if executor is None:
541 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
542 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400543 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544
545 def set_default_executor(self, executor):
546 self._default_executor = executor
547
Victor Stinnere912e652014-07-12 03:11:53 +0200548 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
549 msg = ["%s:%r" % (host, port)]
550 if family:
551 msg.append('family=%r' % family)
552 if type:
553 msg.append('type=%r' % type)
554 if proto:
555 msg.append('proto=%r' % proto)
556 if flags:
557 msg.append('flags=%r' % flags)
558 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200559 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200560
561 t0 = self.time()
562 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
563 dt = self.time() - t0
564
Victor Stinneracdb7822014-07-14 18:33:40 +0200565 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200566 % (msg, dt * 1e3, addrinfo))
567 if dt >= self.slow_callback_duration:
568 logger.info(msg)
569 else:
570 logger.debug(msg)
571 return addrinfo
572
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573 def getaddrinfo(self, host, port, *,
574 family=0, type=0, proto=0, flags=0):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500575 info = _ipaddr_info(host, port, family, type, proto)
576 if info is not None:
577 fut = futures.Future(loop=self)
578 fut.set_result([info])
579 return fut
580 elif self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200581 return self.run_in_executor(None, self._getaddrinfo_debug,
582 host, port, family, type, proto, flags)
583 else:
584 return self.run_in_executor(None, socket.getaddrinfo,
585 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700586
587 def getnameinfo(self, sockaddr, flags=0):
588 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
589
Victor Stinnerf951d282014-06-29 00:46:45 +0200590 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591 def create_connection(self, protocol_factory, host=None, port=None, *,
592 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700593 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200594 """Connect to a TCP server.
595
596 Create a streaming transport connection to a given Internet host and
597 port: socket family AF_INET or socket.AF_INET6 depending on host (or
598 family if specified), socket type SOCK_STREAM. protocol_factory must be
599 a callable returning a protocol instance.
600
601 This method is a coroutine which will try to establish the connection
602 in the background. When successful, the coroutine returns a
603 (transport, protocol) pair.
604 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700605 if server_hostname is not None and not ssl:
606 raise ValueError('server_hostname is only meaningful with ssl')
607
608 if server_hostname is None and ssl:
609 # Use host as default for server_hostname. It is an error
610 # if host is empty or not set, e.g. when an
611 # already-connected socket was passed or when only a port
612 # is given. To avoid this error, you can pass
613 # server_hostname='' -- this will bypass the hostname
614 # check. (This also means that if host is a numeric
615 # IP/IPv6 address, we will attempt to verify that exact
616 # address; this will probably fail, but it is possible to
617 # create a certificate for a specific IP address, so we
618 # don't judge it here.)
619 if not host:
620 raise ValueError('You must set server_hostname '
621 'when using ssl without a host')
622 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700623
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700624 if host is not None or port is not None:
625 if sock is not None:
626 raise ValueError(
627 'host/port and sock can not be specified at the same time')
628
629 f1 = self.getaddrinfo(
630 host, port, family=family,
631 type=socket.SOCK_STREAM, proto=proto, flags=flags)
632 fs = [f1]
633 if local_addr is not None:
634 f2 = self.getaddrinfo(
635 *local_addr, family=family,
636 type=socket.SOCK_STREAM, proto=proto, flags=flags)
637 fs.append(f2)
638 else:
639 f2 = None
640
641 yield from tasks.wait(fs, loop=self)
642
643 infos = f1.result()
644 if not infos:
645 raise OSError('getaddrinfo() returned empty list')
646 if f2 is not None:
647 laddr_infos = f2.result()
648 if not laddr_infos:
649 raise OSError('getaddrinfo() returned empty list')
650
651 exceptions = []
652 for family, type, proto, cname, address in infos:
653 try:
654 sock = socket.socket(family=family, type=type, proto=proto)
655 sock.setblocking(False)
656 if f2 is not None:
657 for _, _, _, _, laddr in laddr_infos:
658 try:
659 sock.bind(laddr)
660 break
661 except OSError as exc:
662 exc = OSError(
663 exc.errno, 'error while '
664 'attempting to bind on address '
665 '{!r}: {}'.format(
666 laddr, exc.strerror.lower()))
667 exceptions.append(exc)
668 else:
669 sock.close()
670 sock = None
671 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200672 if self._debug:
673 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700674 yield from self.sock_connect(sock, address)
675 except OSError as exc:
676 if sock is not None:
677 sock.close()
678 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200679 except:
680 if sock is not None:
681 sock.close()
682 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700683 else:
684 break
685 else:
686 if len(exceptions) == 1:
687 raise exceptions[0]
688 else:
689 # If they all have the same str(), raise one.
690 model = str(exceptions[0])
691 if all(str(exc) == model for exc in exceptions):
692 raise exceptions[0]
693 # Raise a combined exception so the user can see all
694 # the various error messages.
695 raise OSError('Multiple exceptions: {}'.format(
696 ', '.join(str(exc) for exc in exceptions)))
697
698 elif sock is None:
699 raise ValueError(
700 'host and port was not specified and no sock specified')
701
702 sock.setblocking(False)
703
Yury Selivanovb057c522014-02-18 12:15:06 -0500704 transport, protocol = yield from self._create_connection_transport(
705 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200706 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200707 # Get the socket from the transport because SSL transport closes
708 # the old socket and creates a new SSL socket
709 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200710 logger.debug("%r connected to %s:%r: (%r, %r)",
711 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500712 return transport, protocol
713
Victor Stinnerf951d282014-06-29 00:46:45 +0200714 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500715 def _create_connection_transport(self, sock, protocol_factory, ssl,
716 server_hostname):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700717 protocol = protocol_factory()
718 waiter = futures.Future(loop=self)
719 if ssl:
720 sslcontext = None if isinstance(ssl, bool) else ssl
721 transport = self._make_ssl_transport(
722 sock, protocol, sslcontext, waiter,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700723 server_side=False, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700724 else:
725 transport = self._make_socket_transport(sock, protocol, waiter)
726
Victor Stinner29ad0112015-01-15 00:04:21 +0100727 try:
728 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100729 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100730 transport.close()
731 raise
732
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700733 return transport, protocol
734
Victor Stinnerf951d282014-06-29 00:46:45 +0200735 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700736 def create_datagram_endpoint(self, protocol_factory,
737 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700738 family=0, proto=0, flags=0,
739 reuse_address=None, reuse_port=None,
740 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700741 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700742 if sock is not None:
743 if (local_addr or remote_addr or
744 family or proto or flags or
745 reuse_address or reuse_port or allow_broadcast):
746 # show the problematic kwargs in exception msg
747 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
748 family=family, proto=proto, flags=flags,
749 reuse_address=reuse_address, reuse_port=reuse_port,
750 allow_broadcast=allow_broadcast)
751 problems = ', '.join(
752 '{}={}'.format(k, v) for k, v in opts.items() if v)
753 raise ValueError(
754 'socket modifier keyword arguments can not be used '
755 'when sock is specified. ({})'.format(problems))
756 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700757 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700758 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700759 if not (local_addr or remote_addr):
760 if family == 0:
761 raise ValueError('unexpected address family')
762 addr_pairs_info = (((family, proto), (None, None)),)
763 else:
764 # join address by (family, protocol)
765 addr_infos = collections.OrderedDict()
766 for idx, addr in ((0, local_addr), (1, remote_addr)):
767 if addr is not None:
768 assert isinstance(addr, tuple) and len(addr) == 2, (
769 '2-tuple is expected')
770
771 infos = yield from self.getaddrinfo(
772 *addr, family=family, type=socket.SOCK_DGRAM,
773 proto=proto, flags=flags)
774 if not infos:
775 raise OSError('getaddrinfo() returned empty list')
776
777 for fam, _, pro, _, address in infos:
778 key = (fam, pro)
779 if key not in addr_infos:
780 addr_infos[key] = [None, None]
781 addr_infos[key][idx] = address
782
783 # each addr has to have info for each (family, proto) pair
784 addr_pairs_info = [
785 (key, addr_pair) for key, addr_pair in addr_infos.items()
786 if not ((local_addr and addr_pair[0] is None) or
787 (remote_addr and addr_pair[1] is None))]
788
789 if not addr_pairs_info:
790 raise ValueError('can not get address information')
791
792 exceptions = []
793
794 if reuse_address is None:
795 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
796
797 for ((family, proto),
798 (local_address, remote_address)) in addr_pairs_info:
799 sock = None
800 r_addr = None
801 try:
802 sock = socket.socket(
803 family=family, type=socket.SOCK_DGRAM, proto=proto)
804 if reuse_address:
805 sock.setsockopt(
806 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
807 if reuse_port:
808 if not hasattr(socket, 'SO_REUSEPORT'):
809 raise ValueError(
810 'reuse_port not supported by socket module')
811 else:
812 sock.setsockopt(
813 socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
814 if allow_broadcast:
815 sock.setsockopt(
816 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
817 sock.setblocking(False)
818
819 if local_addr:
820 sock.bind(local_address)
821 if remote_addr:
822 yield from self.sock_connect(sock, remote_address)
823 r_addr = remote_address
824 except OSError as exc:
825 if sock is not None:
826 sock.close()
827 exceptions.append(exc)
828 except:
829 if sock is not None:
830 sock.close()
831 raise
832 else:
833 break
834 else:
835 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700836
837 protocol = protocol_factory()
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200838 waiter = futures.Future(loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700839 transport = self._make_datagram_transport(
840 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200841 if self._debug:
842 if local_addr:
843 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
844 "created: (%r, %r)",
845 local_addr, remote_addr, transport, protocol)
846 else:
847 logger.debug("Datagram endpoint remote_addr=%r created: "
848 "(%r, %r)",
849 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100850
851 try:
852 yield from waiter
853 except:
854 transport.close()
855 raise
856
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700857 return transport, protocol
858
Victor Stinnerf951d282014-06-29 00:46:45 +0200859 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200860 def _create_server_getaddrinfo(self, host, port, family, flags):
861 infos = yield from self.getaddrinfo(host, port, family=family,
862 type=socket.SOCK_STREAM,
863 flags=flags)
864 if not infos:
865 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
866 return infos
867
868 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700869 def create_server(self, protocol_factory, host=None, port=None,
870 *,
871 family=socket.AF_UNSPEC,
872 flags=socket.AI_PASSIVE,
873 sock=None,
874 backlog=100,
875 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700876 reuse_address=None,
877 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200878 """Create a TCP server.
879
880 The host parameter can be a string, in that case the TCP server is bound
881 to host and port.
882
883 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500884 the TCP server is bound to all hosts of the sequence. If a host
885 appears multiple times (possibly indirectly e.g. when hostnames
886 resolve to the same IP address), the server is only bound once to that
887 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200888
Victor Stinneracdb7822014-07-14 18:33:40 +0200889 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200890
891 This method is a coroutine.
892 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700893 if isinstance(ssl, bool):
894 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700895 if host is not None or port is not None:
896 if sock is not None:
897 raise ValueError(
898 'host/port and sock can not be specified at the same time')
899
900 AF_INET6 = getattr(socket, 'AF_INET6', 0)
901 if reuse_address is None:
902 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
903 sockets = []
904 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200905 hosts = [None]
906 elif (isinstance(host, str) or
907 not isinstance(host, collections.Iterable)):
908 hosts = [host]
909 else:
910 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700911
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200912 fs = [self._create_server_getaddrinfo(host, port, family=family,
913 flags=flags)
914 for host in hosts]
915 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500916 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700917
918 completed = False
919 try:
920 for res in infos:
921 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700922 try:
923 sock = socket.socket(af, socktype, proto)
924 except socket.error:
925 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200926 if self._debug:
927 logger.warning('create_server() failed to create '
928 'socket.socket(%r, %r, %r)',
929 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700930 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700931 sockets.append(sock)
932 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700933 sock.setsockopt(
934 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
935 if reuse_port:
936 if not hasattr(socket, 'SO_REUSEPORT'):
937 raise ValueError(
938 'reuse_port not supported by socket module')
939 else:
940 sock.setsockopt(
941 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700942 # Disable IPv4/IPv6 dual stack support (enabled by
943 # default on Linux) which makes a single socket
944 # listen on both address families.
945 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
946 sock.setsockopt(socket.IPPROTO_IPV6,
947 socket.IPV6_V6ONLY,
948 True)
949 try:
950 sock.bind(sa)
951 except OSError as err:
952 raise OSError(err.errno, 'error while attempting '
953 'to bind on address %r: %s'
954 % (sa, err.strerror.lower()))
955 completed = True
956 finally:
957 if not completed:
958 for sock in sockets:
959 sock.close()
960 else:
961 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +0200962 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700963 sockets = [sock]
964
965 server = Server(self, sockets)
966 for sock in sockets:
967 sock.listen(backlog)
968 sock.setblocking(False)
969 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +0200970 if self._debug:
971 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700972 return server
973
Victor Stinnerf951d282014-06-29 00:46:45 +0200974 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700975 def connect_read_pipe(self, protocol_factory, pipe):
976 protocol = protocol_factory()
977 waiter = futures.Future(loop=self)
978 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100979
980 try:
981 yield from waiter
982 except:
983 transport.close()
984 raise
985
Victor Stinneracdb7822014-07-14 18:33:40 +0200986 if self._debug:
987 logger.debug('Read pipe %r connected: (%r, %r)',
988 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700989 return transport, protocol
990
Victor Stinnerf951d282014-06-29 00:46:45 +0200991 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700992 def connect_write_pipe(self, protocol_factory, pipe):
993 protocol = protocol_factory()
994 waiter = futures.Future(loop=self)
995 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100996
997 try:
998 yield from waiter
999 except:
1000 transport.close()
1001 raise
1002
Victor Stinneracdb7822014-07-14 18:33:40 +02001003 if self._debug:
1004 logger.debug('Write pipe %r connected: (%r, %r)',
1005 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001006 return transport, protocol
1007
Victor Stinneracdb7822014-07-14 18:33:40 +02001008 def _log_subprocess(self, msg, stdin, stdout, stderr):
1009 info = [msg]
1010 if stdin is not None:
1011 info.append('stdin=%s' % _format_pipe(stdin))
1012 if stdout is not None and stderr == subprocess.STDOUT:
1013 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1014 else:
1015 if stdout is not None:
1016 info.append('stdout=%s' % _format_pipe(stdout))
1017 if stderr is not None:
1018 info.append('stderr=%s' % _format_pipe(stderr))
1019 logger.debug(' '.join(info))
1020
Victor Stinnerf951d282014-06-29 00:46:45 +02001021 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001022 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1023 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1024 universal_newlines=False, shell=True, bufsize=0,
1025 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001026 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001027 raise ValueError("cmd must be a string")
1028 if universal_newlines:
1029 raise ValueError("universal_newlines must be False")
1030 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001031 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001032 if bufsize != 0:
1033 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001034 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001035 if self._debug:
1036 # don't log parameters: they may contain sensitive information
1037 # (password) and may be too long
1038 debug_log = 'run shell command %r' % cmd
1039 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001040 transport = yield from self._make_subprocess_transport(
1041 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001042 if self._debug:
1043 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001044 return transport, protocol
1045
Victor Stinnerf951d282014-06-29 00:46:45 +02001046 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001047 def subprocess_exec(self, protocol_factory, program, *args,
1048 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1049 stderr=subprocess.PIPE, universal_newlines=False,
1050 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001051 if universal_newlines:
1052 raise ValueError("universal_newlines must be False")
1053 if shell:
1054 raise ValueError("shell must be False")
1055 if bufsize != 0:
1056 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001057 popen_args = (program,) + args
1058 for arg in popen_args:
1059 if not isinstance(arg, (str, bytes)):
1060 raise TypeError("program arguments must be "
1061 "a bytes or text string, not %s"
1062 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001063 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001064 if self._debug:
1065 # don't log parameters: they may contain sensitive information
1066 # (password) and may be too long
1067 debug_log = 'execute program %r' % program
1068 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001069 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001070 protocol, popen_args, False, stdin, stdout, stderr,
1071 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001072 if self._debug:
1073 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001074 return transport, protocol
1075
Yury Selivanov569efa22014-02-18 18:02:19 -05001076 def set_exception_handler(self, handler):
1077 """Set handler as the new event loop exception handler.
1078
1079 If handler is None, the default exception handler will
1080 be set.
1081
1082 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001083 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001084 will be a reference to the active event loop, 'context'
1085 will be a dict object (see `call_exception_handler()`
1086 documentation for details about context).
1087 """
1088 if handler is not None and not callable(handler):
1089 raise TypeError('A callable object or None is expected, '
1090 'got {!r}'.format(handler))
1091 self._exception_handler = handler
1092
1093 def default_exception_handler(self, context):
1094 """Default exception handler.
1095
1096 This is called when an exception occurs and no exception
1097 handler is set, and can be called by a custom exception
1098 handler that wants to defer to the default behavior.
1099
Victor Stinneracdb7822014-07-14 18:33:40 +02001100 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001101 `call_exception_handler()`.
1102 """
1103 message = context.get('message')
1104 if not message:
1105 message = 'Unhandled exception in event loop'
1106
1107 exception = context.get('exception')
1108 if exception is not None:
1109 exc_info = (type(exception), exception, exception.__traceback__)
1110 else:
1111 exc_info = False
1112
Victor Stinnerff018e42015-01-28 00:30:40 +01001113 if ('source_traceback' not in context
1114 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001115 and self._current_handle._source_traceback):
1116 context['handle_traceback'] = self._current_handle._source_traceback
1117
Yury Selivanov569efa22014-02-18 18:02:19 -05001118 log_lines = [message]
1119 for key in sorted(context):
1120 if key in {'message', 'exception'}:
1121 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001122 value = context[key]
1123 if key == 'source_traceback':
1124 tb = ''.join(traceback.format_list(value))
1125 value = 'Object created at (most recent call last):\n'
1126 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001127 elif key == 'handle_traceback':
1128 tb = ''.join(traceback.format_list(value))
1129 value = 'Handle created at (most recent call last):\n'
1130 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001131 else:
1132 value = repr(value)
1133 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001134
1135 logger.error('\n'.join(log_lines), exc_info=exc_info)
1136
1137 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001138 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001139
Victor Stinneracdb7822014-07-14 18:33:40 +02001140 The context argument is a dict containing the following keys:
1141
Yury Selivanov569efa22014-02-18 18:02:19 -05001142 - 'message': Error message;
1143 - 'exception' (optional): Exception object;
1144 - 'future' (optional): Future instance;
1145 - 'handle' (optional): Handle instance;
1146 - 'protocol' (optional): Protocol instance;
1147 - 'transport' (optional): Transport instance;
1148 - 'socket' (optional): Socket instance.
1149
Victor Stinneracdb7822014-07-14 18:33:40 +02001150 New keys maybe introduced in the future.
1151
1152 Note: do not overload this method in an event loop subclass.
1153 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001154 `set_exception_handler()` method.
1155 """
1156 if self._exception_handler is None:
1157 try:
1158 self.default_exception_handler(context)
1159 except Exception:
1160 # Second protection layer for unexpected errors
1161 # in the default implementation, as well as for subclassed
1162 # event loops with overloaded "default_exception_handler".
1163 logger.error('Exception in default exception handler',
1164 exc_info=True)
1165 else:
1166 try:
1167 self._exception_handler(self, context)
1168 except Exception as exc:
1169 # Exception in the user set custom exception handler.
1170 try:
1171 # Let's try default handler.
1172 self.default_exception_handler({
1173 'message': 'Unhandled error in exception handler',
1174 'exception': exc,
1175 'context': context,
1176 })
1177 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001178 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001179 # overloaded.
1180 logger.error('Exception in default exception handler '
1181 'while handling an unexpected error '
1182 'in custom exception handler',
1183 exc_info=True)
1184
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001185 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001186 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001187 assert isinstance(handle, events.Handle), 'A Handle is required here'
1188 if handle._cancelled:
1189 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001190 assert not isinstance(handle, events.TimerHandle)
1191 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001192
1193 def _add_callback_signalsafe(self, handle):
1194 """Like _add_callback() but called from a signal handler."""
1195 self._add_callback(handle)
1196 self._write_to_self()
1197
Yury Selivanov592ada92014-09-25 12:07:56 -04001198 def _timer_handle_cancelled(self, handle):
1199 """Notification that a TimerHandle has been cancelled."""
1200 if handle._scheduled:
1201 self._timer_cancelled_count += 1
1202
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001203 def _run_once(self):
1204 """Run one full iteration of the event loop.
1205
1206 This calls all currently ready callbacks, polls for I/O,
1207 schedules the resulting callbacks, and finally schedules
1208 'call_later' callbacks.
1209 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001210
Yury Selivanov592ada92014-09-25 12:07:56 -04001211 sched_count = len(self._scheduled)
1212 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1213 self._timer_cancelled_count / sched_count >
1214 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001215 # Remove delayed calls that were cancelled if their number
1216 # is too high
1217 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001218 for handle in self._scheduled:
1219 if handle._cancelled:
1220 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001221 else:
1222 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001223
Victor Stinner68da8fc2014-09-30 18:08:36 +02001224 heapq.heapify(new_scheduled)
1225 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001226 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001227 else:
1228 # Remove delayed calls that were cancelled from head of queue.
1229 while self._scheduled and self._scheduled[0]._cancelled:
1230 self._timer_cancelled_count -= 1
1231 handle = heapq.heappop(self._scheduled)
1232 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001233
1234 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001235 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001236 timeout = 0
1237 elif self._scheduled:
1238 # Compute the desired timeout.
1239 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001240 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001241
Victor Stinner770e48d2014-07-11 11:58:33 +02001242 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001243 t0 = self.time()
1244 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001245 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001246 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001247 level = logging.INFO
1248 else:
1249 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001250 nevent = len(event_list)
1251 if timeout is None:
1252 logger.log(level, 'poll took %.3f ms: %s events',
1253 dt * 1e3, nevent)
1254 elif nevent:
1255 logger.log(level,
1256 'poll %.3f ms took %.3f ms: %s events',
1257 timeout * 1e3, dt * 1e3, nevent)
1258 elif dt >= 1.0:
1259 logger.log(level,
1260 'poll %.3f ms took %.3f ms: timeout',
1261 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001262 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001263 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001264 self._process_events(event_list)
1265
1266 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001267 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001268 while self._scheduled:
1269 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001270 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001271 break
1272 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001273 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001274 self._ready.append(handle)
1275
1276 # This is the only place where callbacks are actually *called*.
1277 # All other places just add them to ready.
1278 # Note: We run all currently scheduled callbacks, but not any
1279 # callbacks scheduled by callbacks run this time around --
1280 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001281 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001282 ntodo = len(self._ready)
1283 for i in range(ntodo):
1284 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001285 if handle._cancelled:
1286 continue
1287 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001288 try:
1289 self._current_handle = handle
1290 t0 = self.time()
1291 handle._run()
1292 dt = self.time() - t0
1293 if dt >= self.slow_callback_duration:
1294 logger.warning('Executing %s took %.3f seconds',
1295 _format_handle(handle), dt)
1296 finally:
1297 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001298 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001299 handle._run()
1300 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001301
Yury Selivanove8944cb2015-05-12 11:43:04 -04001302 def _set_coroutine_wrapper(self, enabled):
1303 try:
1304 set_wrapper = sys.set_coroutine_wrapper
1305 get_wrapper = sys.get_coroutine_wrapper
1306 except AttributeError:
1307 return
1308
1309 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001310 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001311 return
1312
1313 wrapper = coroutines.debug_wrapper
1314 current_wrapper = get_wrapper()
1315
1316 if enabled:
1317 if current_wrapper not in (None, wrapper):
1318 warnings.warn(
1319 "loop.set_debug(True): cannot set debug coroutine "
1320 "wrapper; another wrapper is already set %r" %
1321 current_wrapper, RuntimeWarning)
1322 else:
1323 set_wrapper(wrapper)
1324 self._coroutine_wrapper_set = True
1325 else:
1326 if current_wrapper not in (None, wrapper):
1327 warnings.warn(
1328 "loop.set_debug(False): cannot unset debug coroutine "
1329 "wrapper; another wrapper was set %r" %
1330 current_wrapper, RuntimeWarning)
1331 else:
1332 set_wrapper(None)
1333 self._coroutine_wrapper_set = False
1334
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001335 def get_debug(self):
1336 return self._debug
1337
1338 def set_debug(self, enabled):
1339 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001340
Yury Selivanove8944cb2015-05-12 11:43:04 -04001341 if self.is_running():
1342 self._set_coroutine_wrapper(enabled)