blob: 9d07673fbad2120f7d65e0963b601f7eb0f0ea06 [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():
415 warnings.warn("unclosed event loop %r" % self, ResourceWarning)
416 if not self.is_running():
417 self.close()
418
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700419 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200420 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100421 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700422
423 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200424 """Return the time according to the event loop's clock.
425
426 This is a float expressed in seconds since an epoch, but the
427 epoch, precision, accuracy and drift are unspecified and may
428 differ per event loop.
429 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700430 return time.monotonic()
431
432 def call_later(self, delay, callback, *args):
433 """Arrange for a callback to be called at a given time.
434
435 Return a Handle: an opaque object with a cancel() method that
436 can be used to cancel the call.
437
438 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200439 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700440
441 Each callback will be called exactly once. If two callbacks
442 are scheduled for exactly the same time, it undefined which
443 will be called first.
444
445 Any positional arguments after the callback will be passed to
446 the callback when it is called.
447 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200448 timer = self.call_at(self.time() + delay, callback, *args)
449 if timer._source_traceback:
450 del timer._source_traceback[-1]
451 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700452
453 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200454 """Like call_later(), but uses an absolute time.
455
456 Absolute time corresponds to the event loop's time() method.
457 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100458 if (coroutines.iscoroutine(callback)
459 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100460 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100461 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100462 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100463 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500464 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200465 if timer._source_traceback:
466 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400468 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700469 return timer
470
471 def call_soon(self, callback, *args):
472 """Arrange for a callback to be called as soon as possible.
473
Victor Stinneracdb7822014-07-14 18:33:40 +0200474 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700475 order in which they are registered. Each callback will be
476 called exactly once.
477
478 Any positional arguments after the callback will be passed to
479 the callback when it is called.
480 """
Victor Stinner956de692014-12-26 21:07:52 +0100481 if self._debug:
482 self._check_thread()
483 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200484 if handle._source_traceback:
485 del handle._source_traceback[-1]
486 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100487
Victor Stinner956de692014-12-26 21:07:52 +0100488 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100489 if (coroutines.iscoroutine(callback)
490 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100491 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100492 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500493 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200494 if handle._source_traceback:
495 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700496 self._ready.append(handle)
497 return handle
498
Victor Stinner956de692014-12-26 21:07:52 +0100499 def _check_thread(self):
500 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100501
Victor Stinneracdb7822014-07-14 18:33:40 +0200502 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100503 likely behave incorrectly when the assumption is violated.
504
Victor Stinneracdb7822014-07-14 18:33:40 +0200505 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100506 responsible for checking this condition for performance reasons.
507 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100508 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200509 return
Victor Stinner956de692014-12-26 21:07:52 +0100510 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100511 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100512 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200513 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100514 "than the current one")
515
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200517 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100518 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200519 if handle._source_traceback:
520 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700521 self._write_to_self()
522 return handle
523
Yury Selivanov740169c2015-05-11 14:23:38 -0400524 def run_in_executor(self, executor, func, *args):
525 if (coroutines.iscoroutine(func)
526 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100527 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100528 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400529 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400531 assert not isinstance(func, events.TimerHandle)
532 if func._cancelled:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 f = futures.Future(loop=self)
534 f.set_result(None)
535 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400536 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 if executor is None:
538 executor = self._default_executor
539 if executor is None:
540 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
541 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400542 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700543
544 def set_default_executor(self, executor):
545 self._default_executor = executor
546
Victor Stinnere912e652014-07-12 03:11:53 +0200547 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
548 msg = ["%s:%r" % (host, port)]
549 if family:
550 msg.append('family=%r' % family)
551 if type:
552 msg.append('type=%r' % type)
553 if proto:
554 msg.append('proto=%r' % proto)
555 if flags:
556 msg.append('flags=%r' % flags)
557 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200558 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200559
560 t0 = self.time()
561 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
562 dt = self.time() - t0
563
Victor Stinneracdb7822014-07-14 18:33:40 +0200564 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200565 % (msg, dt * 1e3, addrinfo))
566 if dt >= self.slow_callback_duration:
567 logger.info(msg)
568 else:
569 logger.debug(msg)
570 return addrinfo
571
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700572 def getaddrinfo(self, host, port, *,
573 family=0, type=0, proto=0, flags=0):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500574 info = _ipaddr_info(host, port, family, type, proto)
575 if info is not None:
576 fut = futures.Future(loop=self)
577 fut.set_result([info])
578 return fut
579 elif self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200580 return self.run_in_executor(None, self._getaddrinfo_debug,
581 host, port, family, type, proto, flags)
582 else:
583 return self.run_in_executor(None, socket.getaddrinfo,
584 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585
586 def getnameinfo(self, sockaddr, flags=0):
587 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
588
Victor Stinnerf951d282014-06-29 00:46:45 +0200589 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700590 def create_connection(self, protocol_factory, host=None, port=None, *,
591 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700592 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200593 """Connect to a TCP server.
594
595 Create a streaming transport connection to a given Internet host and
596 port: socket family AF_INET or socket.AF_INET6 depending on host (or
597 family if specified), socket type SOCK_STREAM. protocol_factory must be
598 a callable returning a protocol instance.
599
600 This method is a coroutine which will try to establish the connection
601 in the background. When successful, the coroutine returns a
602 (transport, protocol) pair.
603 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700604 if server_hostname is not None and not ssl:
605 raise ValueError('server_hostname is only meaningful with ssl')
606
607 if server_hostname is None and ssl:
608 # Use host as default for server_hostname. It is an error
609 # if host is empty or not set, e.g. when an
610 # already-connected socket was passed or when only a port
611 # is given. To avoid this error, you can pass
612 # server_hostname='' -- this will bypass the hostname
613 # check. (This also means that if host is a numeric
614 # IP/IPv6 address, we will attempt to verify that exact
615 # address; this will probably fail, but it is possible to
616 # create a certificate for a specific IP address, so we
617 # don't judge it here.)
618 if not host:
619 raise ValueError('You must set server_hostname '
620 'when using ssl without a host')
621 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700622
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623 if host is not None or port is not None:
624 if sock is not None:
625 raise ValueError(
626 'host/port and sock can not be specified at the same time')
627
628 f1 = self.getaddrinfo(
629 host, port, family=family,
630 type=socket.SOCK_STREAM, proto=proto, flags=flags)
631 fs = [f1]
632 if local_addr is not None:
633 f2 = self.getaddrinfo(
634 *local_addr, family=family,
635 type=socket.SOCK_STREAM, proto=proto, flags=flags)
636 fs.append(f2)
637 else:
638 f2 = None
639
640 yield from tasks.wait(fs, loop=self)
641
642 infos = f1.result()
643 if not infos:
644 raise OSError('getaddrinfo() returned empty list')
645 if f2 is not None:
646 laddr_infos = f2.result()
647 if not laddr_infos:
648 raise OSError('getaddrinfo() returned empty list')
649
650 exceptions = []
651 for family, type, proto, cname, address in infos:
652 try:
653 sock = socket.socket(family=family, type=type, proto=proto)
654 sock.setblocking(False)
655 if f2 is not None:
656 for _, _, _, _, laddr in laddr_infos:
657 try:
658 sock.bind(laddr)
659 break
660 except OSError as exc:
661 exc = OSError(
662 exc.errno, 'error while '
663 'attempting to bind on address '
664 '{!r}: {}'.format(
665 laddr, exc.strerror.lower()))
666 exceptions.append(exc)
667 else:
668 sock.close()
669 sock = None
670 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200671 if self._debug:
672 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700673 yield from self.sock_connect(sock, address)
674 except OSError as exc:
675 if sock is not None:
676 sock.close()
677 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200678 except:
679 if sock is not None:
680 sock.close()
681 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700682 else:
683 break
684 else:
685 if len(exceptions) == 1:
686 raise exceptions[0]
687 else:
688 # If they all have the same str(), raise one.
689 model = str(exceptions[0])
690 if all(str(exc) == model for exc in exceptions):
691 raise exceptions[0]
692 # Raise a combined exception so the user can see all
693 # the various error messages.
694 raise OSError('Multiple exceptions: {}'.format(
695 ', '.join(str(exc) for exc in exceptions)))
696
697 elif sock is None:
698 raise ValueError(
699 'host and port was not specified and no sock specified')
700
701 sock.setblocking(False)
702
Yury Selivanovb057c522014-02-18 12:15:06 -0500703 transport, protocol = yield from self._create_connection_transport(
704 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200705 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200706 # Get the socket from the transport because SSL transport closes
707 # the old socket and creates a new SSL socket
708 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200709 logger.debug("%r connected to %s:%r: (%r, %r)",
710 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500711 return transport, protocol
712
Victor Stinnerf951d282014-06-29 00:46:45 +0200713 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500714 def _create_connection_transport(self, sock, protocol_factory, ssl,
715 server_hostname):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700716 protocol = protocol_factory()
717 waiter = futures.Future(loop=self)
718 if ssl:
719 sslcontext = None if isinstance(ssl, bool) else ssl
720 transport = self._make_ssl_transport(
721 sock, protocol, sslcontext, waiter,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700722 server_side=False, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700723 else:
724 transport = self._make_socket_transport(sock, protocol, waiter)
725
Victor Stinner29ad0112015-01-15 00:04:21 +0100726 try:
727 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100728 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100729 transport.close()
730 raise
731
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700732 return transport, protocol
733
Victor Stinnerf951d282014-06-29 00:46:45 +0200734 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700735 def create_datagram_endpoint(self, protocol_factory,
736 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700737 family=0, proto=0, flags=0,
738 reuse_address=None, reuse_port=None,
739 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700740 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700741 if sock is not None:
742 if (local_addr or remote_addr or
743 family or proto or flags or
744 reuse_address or reuse_port or allow_broadcast):
745 # show the problematic kwargs in exception msg
746 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
747 family=family, proto=proto, flags=flags,
748 reuse_address=reuse_address, reuse_port=reuse_port,
749 allow_broadcast=allow_broadcast)
750 problems = ', '.join(
751 '{}={}'.format(k, v) for k, v in opts.items() if v)
752 raise ValueError(
753 'socket modifier keyword arguments can not be used '
754 'when sock is specified. ({})'.format(problems))
755 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700756 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700757 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700758 if not (local_addr or remote_addr):
759 if family == 0:
760 raise ValueError('unexpected address family')
761 addr_pairs_info = (((family, proto), (None, None)),)
762 else:
763 # join address by (family, protocol)
764 addr_infos = collections.OrderedDict()
765 for idx, addr in ((0, local_addr), (1, remote_addr)):
766 if addr is not None:
767 assert isinstance(addr, tuple) and len(addr) == 2, (
768 '2-tuple is expected')
769
770 infos = yield from self.getaddrinfo(
771 *addr, family=family, type=socket.SOCK_DGRAM,
772 proto=proto, flags=flags)
773 if not infos:
774 raise OSError('getaddrinfo() returned empty list')
775
776 for fam, _, pro, _, address in infos:
777 key = (fam, pro)
778 if key not in addr_infos:
779 addr_infos[key] = [None, None]
780 addr_infos[key][idx] = address
781
782 # each addr has to have info for each (family, proto) pair
783 addr_pairs_info = [
784 (key, addr_pair) for key, addr_pair in addr_infos.items()
785 if not ((local_addr and addr_pair[0] is None) or
786 (remote_addr and addr_pair[1] is None))]
787
788 if not addr_pairs_info:
789 raise ValueError('can not get address information')
790
791 exceptions = []
792
793 if reuse_address is None:
794 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
795
796 for ((family, proto),
797 (local_address, remote_address)) in addr_pairs_info:
798 sock = None
799 r_addr = None
800 try:
801 sock = socket.socket(
802 family=family, type=socket.SOCK_DGRAM, proto=proto)
803 if reuse_address:
804 sock.setsockopt(
805 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
806 if reuse_port:
807 if not hasattr(socket, 'SO_REUSEPORT'):
808 raise ValueError(
809 'reuse_port not supported by socket module')
810 else:
811 sock.setsockopt(
812 socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
813 if allow_broadcast:
814 sock.setsockopt(
815 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
816 sock.setblocking(False)
817
818 if local_addr:
819 sock.bind(local_address)
820 if remote_addr:
821 yield from self.sock_connect(sock, remote_address)
822 r_addr = remote_address
823 except OSError as exc:
824 if sock is not None:
825 sock.close()
826 exceptions.append(exc)
827 except:
828 if sock is not None:
829 sock.close()
830 raise
831 else:
832 break
833 else:
834 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700835
836 protocol = protocol_factory()
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200837 waiter = futures.Future(loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700838 transport = self._make_datagram_transport(
839 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200840 if self._debug:
841 if local_addr:
842 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
843 "created: (%r, %r)",
844 local_addr, remote_addr, transport, protocol)
845 else:
846 logger.debug("Datagram endpoint remote_addr=%r created: "
847 "(%r, %r)",
848 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100849
850 try:
851 yield from waiter
852 except:
853 transport.close()
854 raise
855
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700856 return transport, protocol
857
Victor Stinnerf951d282014-06-29 00:46:45 +0200858 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200859 def _create_server_getaddrinfo(self, host, port, family, flags):
860 infos = yield from self.getaddrinfo(host, port, family=family,
861 type=socket.SOCK_STREAM,
862 flags=flags)
863 if not infos:
864 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
865 return infos
866
867 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700868 def create_server(self, protocol_factory, host=None, port=None,
869 *,
870 family=socket.AF_UNSPEC,
871 flags=socket.AI_PASSIVE,
872 sock=None,
873 backlog=100,
874 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700875 reuse_address=None,
876 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200877 """Create a TCP server.
878
879 The host parameter can be a string, in that case the TCP server is bound
880 to host and port.
881
882 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500883 the TCP server is bound to all hosts of the sequence. If a host
884 appears multiple times (possibly indirectly e.g. when hostnames
885 resolve to the same IP address), the server is only bound once to that
886 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200887
Victor Stinneracdb7822014-07-14 18:33:40 +0200888 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200889
890 This method is a coroutine.
891 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700892 if isinstance(ssl, bool):
893 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700894 if host is not None or port is not None:
895 if sock is not None:
896 raise ValueError(
897 'host/port and sock can not be specified at the same time')
898
899 AF_INET6 = getattr(socket, 'AF_INET6', 0)
900 if reuse_address is None:
901 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
902 sockets = []
903 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200904 hosts = [None]
905 elif (isinstance(host, str) or
906 not isinstance(host, collections.Iterable)):
907 hosts = [host]
908 else:
909 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700910
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200911 fs = [self._create_server_getaddrinfo(host, port, family=family,
912 flags=flags)
913 for host in hosts]
914 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500915 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700916
917 completed = False
918 try:
919 for res in infos:
920 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700921 try:
922 sock = socket.socket(af, socktype, proto)
923 except socket.error:
924 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200925 if self._debug:
926 logger.warning('create_server() failed to create '
927 'socket.socket(%r, %r, %r)',
928 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700929 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700930 sockets.append(sock)
931 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700932 sock.setsockopt(
933 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
934 if reuse_port:
935 if not hasattr(socket, 'SO_REUSEPORT'):
936 raise ValueError(
937 'reuse_port not supported by socket module')
938 else:
939 sock.setsockopt(
940 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700941 # Disable IPv4/IPv6 dual stack support (enabled by
942 # default on Linux) which makes a single socket
943 # listen on both address families.
944 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
945 sock.setsockopt(socket.IPPROTO_IPV6,
946 socket.IPV6_V6ONLY,
947 True)
948 try:
949 sock.bind(sa)
950 except OSError as err:
951 raise OSError(err.errno, 'error while attempting '
952 'to bind on address %r: %s'
953 % (sa, err.strerror.lower()))
954 completed = True
955 finally:
956 if not completed:
957 for sock in sockets:
958 sock.close()
959 else:
960 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +0200961 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700962 sockets = [sock]
963
964 server = Server(self, sockets)
965 for sock in sockets:
966 sock.listen(backlog)
967 sock.setblocking(False)
968 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +0200969 if self._debug:
970 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700971 return server
972
Victor Stinnerf951d282014-06-29 00:46:45 +0200973 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700974 def connect_read_pipe(self, protocol_factory, pipe):
975 protocol = protocol_factory()
976 waiter = futures.Future(loop=self)
977 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100978
979 try:
980 yield from waiter
981 except:
982 transport.close()
983 raise
984
Victor Stinneracdb7822014-07-14 18:33:40 +0200985 if self._debug:
986 logger.debug('Read pipe %r connected: (%r, %r)',
987 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700988 return transport, protocol
989
Victor Stinnerf951d282014-06-29 00:46:45 +0200990 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700991 def connect_write_pipe(self, protocol_factory, pipe):
992 protocol = protocol_factory()
993 waiter = futures.Future(loop=self)
994 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100995
996 try:
997 yield from waiter
998 except:
999 transport.close()
1000 raise
1001
Victor Stinneracdb7822014-07-14 18:33:40 +02001002 if self._debug:
1003 logger.debug('Write pipe %r connected: (%r, %r)',
1004 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001005 return transport, protocol
1006
Victor Stinneracdb7822014-07-14 18:33:40 +02001007 def _log_subprocess(self, msg, stdin, stdout, stderr):
1008 info = [msg]
1009 if stdin is not None:
1010 info.append('stdin=%s' % _format_pipe(stdin))
1011 if stdout is not None and stderr == subprocess.STDOUT:
1012 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1013 else:
1014 if stdout is not None:
1015 info.append('stdout=%s' % _format_pipe(stdout))
1016 if stderr is not None:
1017 info.append('stderr=%s' % _format_pipe(stderr))
1018 logger.debug(' '.join(info))
1019
Victor Stinnerf951d282014-06-29 00:46:45 +02001020 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001021 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1022 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1023 universal_newlines=False, shell=True, bufsize=0,
1024 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001025 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001026 raise ValueError("cmd must be a string")
1027 if universal_newlines:
1028 raise ValueError("universal_newlines must be False")
1029 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001030 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001031 if bufsize != 0:
1032 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001033 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001034 if self._debug:
1035 # don't log parameters: they may contain sensitive information
1036 # (password) and may be too long
1037 debug_log = 'run shell command %r' % cmd
1038 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001039 transport = yield from self._make_subprocess_transport(
1040 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001041 if self._debug:
1042 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001043 return transport, protocol
1044
Victor Stinnerf951d282014-06-29 00:46:45 +02001045 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001046 def subprocess_exec(self, protocol_factory, program, *args,
1047 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1048 stderr=subprocess.PIPE, universal_newlines=False,
1049 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001050 if universal_newlines:
1051 raise ValueError("universal_newlines must be False")
1052 if shell:
1053 raise ValueError("shell must be False")
1054 if bufsize != 0:
1055 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001056 popen_args = (program,) + args
1057 for arg in popen_args:
1058 if not isinstance(arg, (str, bytes)):
1059 raise TypeError("program arguments must be "
1060 "a bytes or text string, not %s"
1061 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001062 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001063 if self._debug:
1064 # don't log parameters: they may contain sensitive information
1065 # (password) and may be too long
1066 debug_log = 'execute program %r' % program
1067 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001068 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001069 protocol, popen_args, False, stdin, stdout, stderr,
1070 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001071 if self._debug:
1072 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001073 return transport, protocol
1074
Yury Selivanov569efa22014-02-18 18:02:19 -05001075 def set_exception_handler(self, handler):
1076 """Set handler as the new event loop exception handler.
1077
1078 If handler is None, the default exception handler will
1079 be set.
1080
1081 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001082 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001083 will be a reference to the active event loop, 'context'
1084 will be a dict object (see `call_exception_handler()`
1085 documentation for details about context).
1086 """
1087 if handler is not None and not callable(handler):
1088 raise TypeError('A callable object or None is expected, '
1089 'got {!r}'.format(handler))
1090 self._exception_handler = handler
1091
1092 def default_exception_handler(self, context):
1093 """Default exception handler.
1094
1095 This is called when an exception occurs and no exception
1096 handler is set, and can be called by a custom exception
1097 handler that wants to defer to the default behavior.
1098
Victor Stinneracdb7822014-07-14 18:33:40 +02001099 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001100 `call_exception_handler()`.
1101 """
1102 message = context.get('message')
1103 if not message:
1104 message = 'Unhandled exception in event loop'
1105
1106 exception = context.get('exception')
1107 if exception is not None:
1108 exc_info = (type(exception), exception, exception.__traceback__)
1109 else:
1110 exc_info = False
1111
Victor Stinnerff018e42015-01-28 00:30:40 +01001112 if ('source_traceback' not in context
1113 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001114 and self._current_handle._source_traceback):
1115 context['handle_traceback'] = self._current_handle._source_traceback
1116
Yury Selivanov569efa22014-02-18 18:02:19 -05001117 log_lines = [message]
1118 for key in sorted(context):
1119 if key in {'message', 'exception'}:
1120 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001121 value = context[key]
1122 if key == 'source_traceback':
1123 tb = ''.join(traceback.format_list(value))
1124 value = 'Object created at (most recent call last):\n'
1125 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001126 elif key == 'handle_traceback':
1127 tb = ''.join(traceback.format_list(value))
1128 value = 'Handle created at (most recent call last):\n'
1129 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001130 else:
1131 value = repr(value)
1132 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001133
1134 logger.error('\n'.join(log_lines), exc_info=exc_info)
1135
1136 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001137 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001138
Victor Stinneracdb7822014-07-14 18:33:40 +02001139 The context argument is a dict containing the following keys:
1140
Yury Selivanov569efa22014-02-18 18:02:19 -05001141 - 'message': Error message;
1142 - 'exception' (optional): Exception object;
1143 - 'future' (optional): Future instance;
1144 - 'handle' (optional): Handle instance;
1145 - 'protocol' (optional): Protocol instance;
1146 - 'transport' (optional): Transport instance;
1147 - 'socket' (optional): Socket instance.
1148
Victor Stinneracdb7822014-07-14 18:33:40 +02001149 New keys maybe introduced in the future.
1150
1151 Note: do not overload this method in an event loop subclass.
1152 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001153 `set_exception_handler()` method.
1154 """
1155 if self._exception_handler is None:
1156 try:
1157 self.default_exception_handler(context)
1158 except Exception:
1159 # Second protection layer for unexpected errors
1160 # in the default implementation, as well as for subclassed
1161 # event loops with overloaded "default_exception_handler".
1162 logger.error('Exception in default exception handler',
1163 exc_info=True)
1164 else:
1165 try:
1166 self._exception_handler(self, context)
1167 except Exception as exc:
1168 # Exception in the user set custom exception handler.
1169 try:
1170 # Let's try default handler.
1171 self.default_exception_handler({
1172 'message': 'Unhandled error in exception handler',
1173 'exception': exc,
1174 'context': context,
1175 })
1176 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001177 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001178 # overloaded.
1179 logger.error('Exception in default exception handler '
1180 'while handling an unexpected error '
1181 'in custom exception handler',
1182 exc_info=True)
1183
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001184 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001185 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001186 assert isinstance(handle, events.Handle), 'A Handle is required here'
1187 if handle._cancelled:
1188 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001189 assert not isinstance(handle, events.TimerHandle)
1190 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001191
1192 def _add_callback_signalsafe(self, handle):
1193 """Like _add_callback() but called from a signal handler."""
1194 self._add_callback(handle)
1195 self._write_to_self()
1196
Yury Selivanov592ada92014-09-25 12:07:56 -04001197 def _timer_handle_cancelled(self, handle):
1198 """Notification that a TimerHandle has been cancelled."""
1199 if handle._scheduled:
1200 self._timer_cancelled_count += 1
1201
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001202 def _run_once(self):
1203 """Run one full iteration of the event loop.
1204
1205 This calls all currently ready callbacks, polls for I/O,
1206 schedules the resulting callbacks, and finally schedules
1207 'call_later' callbacks.
1208 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001209
Yury Selivanov592ada92014-09-25 12:07:56 -04001210 sched_count = len(self._scheduled)
1211 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1212 self._timer_cancelled_count / sched_count >
1213 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001214 # Remove delayed calls that were cancelled if their number
1215 # is too high
1216 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001217 for handle in self._scheduled:
1218 if handle._cancelled:
1219 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001220 else:
1221 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001222
Victor Stinner68da8fc2014-09-30 18:08:36 +02001223 heapq.heapify(new_scheduled)
1224 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001225 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001226 else:
1227 # Remove delayed calls that were cancelled from head of queue.
1228 while self._scheduled and self._scheduled[0]._cancelled:
1229 self._timer_cancelled_count -= 1
1230 handle = heapq.heappop(self._scheduled)
1231 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001232
1233 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001234 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001235 timeout = 0
1236 elif self._scheduled:
1237 # Compute the desired timeout.
1238 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001239 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001240
Victor Stinner770e48d2014-07-11 11:58:33 +02001241 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001242 t0 = self.time()
1243 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001244 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001245 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001246 level = logging.INFO
1247 else:
1248 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001249 nevent = len(event_list)
1250 if timeout is None:
1251 logger.log(level, 'poll took %.3f ms: %s events',
1252 dt * 1e3, nevent)
1253 elif nevent:
1254 logger.log(level,
1255 'poll %.3f ms took %.3f ms: %s events',
1256 timeout * 1e3, dt * 1e3, nevent)
1257 elif dt >= 1.0:
1258 logger.log(level,
1259 'poll %.3f ms took %.3f ms: timeout',
1260 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001261 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001262 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001263 self._process_events(event_list)
1264
1265 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001266 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001267 while self._scheduled:
1268 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001269 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001270 break
1271 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001272 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001273 self._ready.append(handle)
1274
1275 # This is the only place where callbacks are actually *called*.
1276 # All other places just add them to ready.
1277 # Note: We run all currently scheduled callbacks, but not any
1278 # callbacks scheduled by callbacks run this time around --
1279 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001280 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001281 ntodo = len(self._ready)
1282 for i in range(ntodo):
1283 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001284 if handle._cancelled:
1285 continue
1286 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001287 try:
1288 self._current_handle = handle
1289 t0 = self.time()
1290 handle._run()
1291 dt = self.time() - t0
1292 if dt >= self.slow_callback_duration:
1293 logger.warning('Executing %s took %.3f seconds',
1294 _format_handle(handle), dt)
1295 finally:
1296 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001297 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001298 handle._run()
1299 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001300
Yury Selivanove8944cb2015-05-12 11:43:04 -04001301 def _set_coroutine_wrapper(self, enabled):
1302 try:
1303 set_wrapper = sys.set_coroutine_wrapper
1304 get_wrapper = sys.get_coroutine_wrapper
1305 except AttributeError:
1306 return
1307
1308 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001309 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001310 return
1311
1312 wrapper = coroutines.debug_wrapper
1313 current_wrapper = get_wrapper()
1314
1315 if enabled:
1316 if current_wrapper not in (None, wrapper):
1317 warnings.warn(
1318 "loop.set_debug(True): cannot set debug coroutine "
1319 "wrapper; another wrapper is already set %r" %
1320 current_wrapper, RuntimeWarning)
1321 else:
1322 set_wrapper(wrapper)
1323 self._coroutine_wrapper_set = True
1324 else:
1325 if current_wrapper not in (None, wrapper):
1326 warnings.warn(
1327 "loop.set_debug(False): cannot unset debug coroutine "
1328 "wrapper; another wrapper was set %r" %
1329 current_wrapper, RuntimeWarning)
1330 else:
1331 set_wrapper(None)
1332 self._coroutine_wrapper_set = False
1333
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001334 def get_debug(self):
1335 return self._debug
1336
1337 def set_debug(self, enabled):
1338 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001339
Yury Selivanove8944cb2015-05-12 11:43:04 -04001340 if self.is_running():
1341 self._set_coroutine_wrapper(enabled)