blob: 4505732f9ac02bdf3919a678b2347ff1ee353cae [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
883 the TCP server is bound to all hosts of the sequence.
Victor Stinnerd1432092014-06-19 17:11:49 +0200884
Victor Stinneracdb7822014-07-14 18:33:40 +0200885 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200886
887 This method is a coroutine.
888 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700889 if isinstance(ssl, bool):
890 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700891 if host is not None or port is not None:
892 if sock is not None:
893 raise ValueError(
894 'host/port and sock can not be specified at the same time')
895
896 AF_INET6 = getattr(socket, 'AF_INET6', 0)
897 if reuse_address is None:
898 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
899 sockets = []
900 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200901 hosts = [None]
902 elif (isinstance(host, str) or
903 not isinstance(host, collections.Iterable)):
904 hosts = [host]
905 else:
906 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700907
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200908 fs = [self._create_server_getaddrinfo(host, port, family=family,
909 flags=flags)
910 for host in hosts]
911 infos = yield from tasks.gather(*fs, loop=self)
912 infos = itertools.chain.from_iterable(infos)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700913
914 completed = False
915 try:
916 for res in infos:
917 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700918 try:
919 sock = socket.socket(af, socktype, proto)
920 except socket.error:
921 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200922 if self._debug:
923 logger.warning('create_server() failed to create '
924 'socket.socket(%r, %r, %r)',
925 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700926 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700927 sockets.append(sock)
928 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700929 sock.setsockopt(
930 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
931 if reuse_port:
932 if not hasattr(socket, 'SO_REUSEPORT'):
933 raise ValueError(
934 'reuse_port not supported by socket module')
935 else:
936 sock.setsockopt(
937 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700938 # Disable IPv4/IPv6 dual stack support (enabled by
939 # default on Linux) which makes a single socket
940 # listen on both address families.
941 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
942 sock.setsockopt(socket.IPPROTO_IPV6,
943 socket.IPV6_V6ONLY,
944 True)
945 try:
946 sock.bind(sa)
947 except OSError as err:
948 raise OSError(err.errno, 'error while attempting '
949 'to bind on address %r: %s'
950 % (sa, err.strerror.lower()))
951 completed = True
952 finally:
953 if not completed:
954 for sock in sockets:
955 sock.close()
956 else:
957 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +0200958 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700959 sockets = [sock]
960
961 server = Server(self, sockets)
962 for sock in sockets:
963 sock.listen(backlog)
964 sock.setblocking(False)
965 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +0200966 if self._debug:
967 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700968 return server
969
Victor Stinnerf951d282014-06-29 00:46:45 +0200970 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700971 def connect_read_pipe(self, protocol_factory, pipe):
972 protocol = protocol_factory()
973 waiter = futures.Future(loop=self)
974 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100975
976 try:
977 yield from waiter
978 except:
979 transport.close()
980 raise
981
Victor Stinneracdb7822014-07-14 18:33:40 +0200982 if self._debug:
983 logger.debug('Read pipe %r connected: (%r, %r)',
984 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700985 return transport, protocol
986
Victor Stinnerf951d282014-06-29 00:46:45 +0200987 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700988 def connect_write_pipe(self, protocol_factory, pipe):
989 protocol = protocol_factory()
990 waiter = futures.Future(loop=self)
991 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100992
993 try:
994 yield from waiter
995 except:
996 transport.close()
997 raise
998
Victor Stinneracdb7822014-07-14 18:33:40 +0200999 if self._debug:
1000 logger.debug('Write pipe %r connected: (%r, %r)',
1001 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001002 return transport, protocol
1003
Victor Stinneracdb7822014-07-14 18:33:40 +02001004 def _log_subprocess(self, msg, stdin, stdout, stderr):
1005 info = [msg]
1006 if stdin is not None:
1007 info.append('stdin=%s' % _format_pipe(stdin))
1008 if stdout is not None and stderr == subprocess.STDOUT:
1009 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1010 else:
1011 if stdout is not None:
1012 info.append('stdout=%s' % _format_pipe(stdout))
1013 if stderr is not None:
1014 info.append('stderr=%s' % _format_pipe(stderr))
1015 logger.debug(' '.join(info))
1016
Victor Stinnerf951d282014-06-29 00:46:45 +02001017 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001018 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1019 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1020 universal_newlines=False, shell=True, bufsize=0,
1021 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001022 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001023 raise ValueError("cmd must be a string")
1024 if universal_newlines:
1025 raise ValueError("universal_newlines must be False")
1026 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001027 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001028 if bufsize != 0:
1029 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001030 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001031 if self._debug:
1032 # don't log parameters: they may contain sensitive information
1033 # (password) and may be too long
1034 debug_log = 'run shell command %r' % cmd
1035 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001036 transport = yield from self._make_subprocess_transport(
1037 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001038 if self._debug:
1039 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001040 return transport, protocol
1041
Victor Stinnerf951d282014-06-29 00:46:45 +02001042 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001043 def subprocess_exec(self, protocol_factory, program, *args,
1044 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1045 stderr=subprocess.PIPE, universal_newlines=False,
1046 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001047 if universal_newlines:
1048 raise ValueError("universal_newlines must be False")
1049 if shell:
1050 raise ValueError("shell must be False")
1051 if bufsize != 0:
1052 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001053 popen_args = (program,) + args
1054 for arg in popen_args:
1055 if not isinstance(arg, (str, bytes)):
1056 raise TypeError("program arguments must be "
1057 "a bytes or text string, not %s"
1058 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001059 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001060 if self._debug:
1061 # don't log parameters: they may contain sensitive information
1062 # (password) and may be too long
1063 debug_log = 'execute program %r' % program
1064 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001065 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001066 protocol, popen_args, False, stdin, stdout, stderr,
1067 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001068 if self._debug:
1069 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001070 return transport, protocol
1071
Yury Selivanov569efa22014-02-18 18:02:19 -05001072 def set_exception_handler(self, handler):
1073 """Set handler as the new event loop exception handler.
1074
1075 If handler is None, the default exception handler will
1076 be set.
1077
1078 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001079 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001080 will be a reference to the active event loop, 'context'
1081 will be a dict object (see `call_exception_handler()`
1082 documentation for details about context).
1083 """
1084 if handler is not None and not callable(handler):
1085 raise TypeError('A callable object or None is expected, '
1086 'got {!r}'.format(handler))
1087 self._exception_handler = handler
1088
1089 def default_exception_handler(self, context):
1090 """Default exception handler.
1091
1092 This is called when an exception occurs and no exception
1093 handler is set, and can be called by a custom exception
1094 handler that wants to defer to the default behavior.
1095
Victor Stinneracdb7822014-07-14 18:33:40 +02001096 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001097 `call_exception_handler()`.
1098 """
1099 message = context.get('message')
1100 if not message:
1101 message = 'Unhandled exception in event loop'
1102
1103 exception = context.get('exception')
1104 if exception is not None:
1105 exc_info = (type(exception), exception, exception.__traceback__)
1106 else:
1107 exc_info = False
1108
Victor Stinnerff018e42015-01-28 00:30:40 +01001109 if ('source_traceback' not in context
1110 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001111 and self._current_handle._source_traceback):
1112 context['handle_traceback'] = self._current_handle._source_traceback
1113
Yury Selivanov569efa22014-02-18 18:02:19 -05001114 log_lines = [message]
1115 for key in sorted(context):
1116 if key in {'message', 'exception'}:
1117 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001118 value = context[key]
1119 if key == 'source_traceback':
1120 tb = ''.join(traceback.format_list(value))
1121 value = 'Object created at (most recent call last):\n'
1122 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001123 elif key == 'handle_traceback':
1124 tb = ''.join(traceback.format_list(value))
1125 value = 'Handle created at (most recent call last):\n'
1126 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001127 else:
1128 value = repr(value)
1129 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001130
1131 logger.error('\n'.join(log_lines), exc_info=exc_info)
1132
1133 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001134 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001135
Victor Stinneracdb7822014-07-14 18:33:40 +02001136 The context argument is a dict containing the following keys:
1137
Yury Selivanov569efa22014-02-18 18:02:19 -05001138 - 'message': Error message;
1139 - 'exception' (optional): Exception object;
1140 - 'future' (optional): Future instance;
1141 - 'handle' (optional): Handle instance;
1142 - 'protocol' (optional): Protocol instance;
1143 - 'transport' (optional): Transport instance;
1144 - 'socket' (optional): Socket instance.
1145
Victor Stinneracdb7822014-07-14 18:33:40 +02001146 New keys maybe introduced in the future.
1147
1148 Note: do not overload this method in an event loop subclass.
1149 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001150 `set_exception_handler()` method.
1151 """
1152 if self._exception_handler is None:
1153 try:
1154 self.default_exception_handler(context)
1155 except Exception:
1156 # Second protection layer for unexpected errors
1157 # in the default implementation, as well as for subclassed
1158 # event loops with overloaded "default_exception_handler".
1159 logger.error('Exception in default exception handler',
1160 exc_info=True)
1161 else:
1162 try:
1163 self._exception_handler(self, context)
1164 except Exception as exc:
1165 # Exception in the user set custom exception handler.
1166 try:
1167 # Let's try default handler.
1168 self.default_exception_handler({
1169 'message': 'Unhandled error in exception handler',
1170 'exception': exc,
1171 'context': context,
1172 })
1173 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001174 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001175 # overloaded.
1176 logger.error('Exception in default exception handler '
1177 'while handling an unexpected error '
1178 'in custom exception handler',
1179 exc_info=True)
1180
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001181 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001182 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001183 assert isinstance(handle, events.Handle), 'A Handle is required here'
1184 if handle._cancelled:
1185 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001186 assert not isinstance(handle, events.TimerHandle)
1187 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001188
1189 def _add_callback_signalsafe(self, handle):
1190 """Like _add_callback() but called from a signal handler."""
1191 self._add_callback(handle)
1192 self._write_to_self()
1193
Yury Selivanov592ada92014-09-25 12:07:56 -04001194 def _timer_handle_cancelled(self, handle):
1195 """Notification that a TimerHandle has been cancelled."""
1196 if handle._scheduled:
1197 self._timer_cancelled_count += 1
1198
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001199 def _run_once(self):
1200 """Run one full iteration of the event loop.
1201
1202 This calls all currently ready callbacks, polls for I/O,
1203 schedules the resulting callbacks, and finally schedules
1204 'call_later' callbacks.
1205 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001206
Yury Selivanov592ada92014-09-25 12:07:56 -04001207 sched_count = len(self._scheduled)
1208 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1209 self._timer_cancelled_count / sched_count >
1210 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001211 # Remove delayed calls that were cancelled if their number
1212 # is too high
1213 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001214 for handle in self._scheduled:
1215 if handle._cancelled:
1216 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001217 else:
1218 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001219
Victor Stinner68da8fc2014-09-30 18:08:36 +02001220 heapq.heapify(new_scheduled)
1221 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001222 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001223 else:
1224 # Remove delayed calls that were cancelled from head of queue.
1225 while self._scheduled and self._scheduled[0]._cancelled:
1226 self._timer_cancelled_count -= 1
1227 handle = heapq.heappop(self._scheduled)
1228 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001229
1230 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001231 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001232 timeout = 0
1233 elif self._scheduled:
1234 # Compute the desired timeout.
1235 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001236 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001237
Victor Stinner770e48d2014-07-11 11:58:33 +02001238 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001239 t0 = self.time()
1240 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001241 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001242 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001243 level = logging.INFO
1244 else:
1245 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001246 nevent = len(event_list)
1247 if timeout is None:
1248 logger.log(level, 'poll took %.3f ms: %s events',
1249 dt * 1e3, nevent)
1250 elif nevent:
1251 logger.log(level,
1252 'poll %.3f ms took %.3f ms: %s events',
1253 timeout * 1e3, dt * 1e3, nevent)
1254 elif dt >= 1.0:
1255 logger.log(level,
1256 'poll %.3f ms took %.3f ms: timeout',
1257 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001258 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001259 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001260 self._process_events(event_list)
1261
1262 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001263 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001264 while self._scheduled:
1265 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001266 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001267 break
1268 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001269 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001270 self._ready.append(handle)
1271
1272 # This is the only place where callbacks are actually *called*.
1273 # All other places just add them to ready.
1274 # Note: We run all currently scheduled callbacks, but not any
1275 # callbacks scheduled by callbacks run this time around --
1276 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001277 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001278 ntodo = len(self._ready)
1279 for i in range(ntodo):
1280 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001281 if handle._cancelled:
1282 continue
1283 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001284 try:
1285 self._current_handle = handle
1286 t0 = self.time()
1287 handle._run()
1288 dt = self.time() - t0
1289 if dt >= self.slow_callback_duration:
1290 logger.warning('Executing %s took %.3f seconds',
1291 _format_handle(handle), dt)
1292 finally:
1293 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001294 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001295 handle._run()
1296 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001297
Yury Selivanove8944cb2015-05-12 11:43:04 -04001298 def _set_coroutine_wrapper(self, enabled):
1299 try:
1300 set_wrapper = sys.set_coroutine_wrapper
1301 get_wrapper = sys.get_coroutine_wrapper
1302 except AttributeError:
1303 return
1304
1305 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001306 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001307 return
1308
1309 wrapper = coroutines.debug_wrapper
1310 current_wrapper = get_wrapper()
1311
1312 if enabled:
1313 if current_wrapper not in (None, wrapper):
1314 warnings.warn(
1315 "loop.set_debug(True): cannot set debug coroutine "
1316 "wrapper; another wrapper is already set %r" %
1317 current_wrapper, RuntimeWarning)
1318 else:
1319 set_wrapper(wrapper)
1320 self._coroutine_wrapper_set = True
1321 else:
1322 if current_wrapper not in (None, wrapper):
1323 warnings.warn(
1324 "loop.set_debug(False): cannot unset debug coroutine "
1325 "wrapper; another wrapper was set %r" %
1326 current_wrapper, RuntimeWarning)
1327 else:
1328 set_wrapper(None)
1329 self._coroutine_wrapper_set = False
1330
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001331 def get_debug(self):
1332 return self._debug
1333
1334 def set_debug(self, enabled):
1335 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001336
Yury Selivanove8944cb2015-05-12 11:43:04 -04001337 if self.is_running():
1338 self._set_coroutine_wrapper(enabled)