blob: 99d503fe1f1641998e5b0ce4281e3b37d41bc6e2 [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 Stinnerc94a93a2016-04-01 21:43:39 +020057# Exceptions which must not call the exception handler in fatal error
58# methods (_fatal_error())
59_FATAL_ERROR_IGNORE = (BrokenPipeError,
60 ConnectionResetError, ConnectionAbortedError)
61
62
Victor Stinner0e6f52a2014-06-20 17:34:15 +020063def _format_handle(handle):
64 cb = handle._callback
65 if inspect.ismethod(cb) and isinstance(cb.__self__, tasks.Task):
66 # format the task
67 return repr(cb.__self__)
68 else:
69 return str(handle)
70
71
Victor Stinneracdb7822014-07-14 18:33:40 +020072def _format_pipe(fd):
73 if fd == subprocess.PIPE:
74 return '<pipe>'
75 elif fd == subprocess.STDOUT:
76 return '<stdout>'
77 else:
78 return repr(fd)
79
80
Yury Selivanovd5c2a622015-12-16 19:31:17 -050081# Linux's sock.type is a bitmask that can include extra info about socket.
82_SOCKET_TYPE_MASK = 0
83if hasattr(socket, 'SOCK_NONBLOCK'):
84 _SOCKET_TYPE_MASK |= socket.SOCK_NONBLOCK
85if hasattr(socket, 'SOCK_CLOEXEC'):
86 _SOCKET_TYPE_MASK |= socket.SOCK_CLOEXEC
87
88
89@functools.lru_cache(maxsize=1024)
90def _ipaddr_info(host, port, family, type, proto):
91 # Try to skip getaddrinfo if "host" is already an IP. Since getaddrinfo
92 # blocks on an exclusive lock on some platforms, users might handle name
93 # resolution in their own code and pass in resolved IPs.
94 if proto not in {0, socket.IPPROTO_TCP, socket.IPPROTO_UDP} or host is None:
95 return None
96
97 type &= ~_SOCKET_TYPE_MASK
98 if type == socket.SOCK_STREAM:
99 proto = socket.IPPROTO_TCP
100 elif type == socket.SOCK_DGRAM:
101 proto = socket.IPPROTO_UDP
102 else:
103 return None
104
105 if hasattr(socket, 'inet_pton'):
106 if family == socket.AF_UNSPEC:
107 afs = [socket.AF_INET, socket.AF_INET6]
108 else:
109 afs = [family]
110
111 for af in afs:
112 # Linux's inet_pton doesn't accept an IPv6 zone index after host,
113 # like '::1%lo0', so strip it. If we happen to make an invalid
114 # address look valid, we fail later in sock.connect or sock.bind.
115 try:
116 if af == socket.AF_INET6:
117 socket.inet_pton(af, host.partition('%')[0])
118 else:
119 socket.inet_pton(af, host)
120 return af, type, proto, '', (host, port)
121 except OSError:
122 pass
123
124 # "host" is not an IP address.
125 return None
126
127 # No inet_pton. (On Windows it's only available since Python 3.4.)
128 # Even though getaddrinfo with AI_NUMERICHOST would be non-blocking, it
129 # still requires a lock on some platforms, and waiting for that lock could
130 # block the event loop. Use ipaddress instead, it's just text parsing.
131 try:
132 addr = ipaddress.IPv4Address(host)
133 except ValueError:
134 try:
135 addr = ipaddress.IPv6Address(host.partition('%')[0])
136 except ValueError:
137 return None
138
139 af = socket.AF_INET if addr.version == 4 else socket.AF_INET6
140 if family not in (socket.AF_UNSPEC, af):
141 # "host" is wrong IP version for "family".
142 return None
143
144 return af, type, proto, '', (host, port)
145
146
Victor Stinner1b0580b2014-02-13 09:24:37 +0100147def _check_resolved_address(sock, address):
148 # Ensure that the address is already resolved to avoid the trap of hanging
149 # the entire event loop when the address requires doing a DNS lookup.
Victor Stinner2fc23132015-02-04 14:51:23 +0100150
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500151 if hasattr(socket, 'AF_UNIX') and sock.family == socket.AF_UNIX:
Victor Stinner1b0580b2014-02-13 09:24:37 +0100152 return
153
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500154 host, port = address[:2]
155 if _ipaddr_info(host, port, sock.family, sock.type, sock.proto) is None:
156 raise ValueError("address must be resolved (IP address),"
157 " got host %r" % host)
Victor Stinner1b0580b2014-02-13 09:24:37 +0100158
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700159
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100160def _run_until_complete_cb(fut):
161 exc = fut._exception
162 if (isinstance(exc, BaseException)
163 and not isinstance(exc, Exception)):
164 # Issue #22429: run_forever() already finished, no need to
165 # stop it.
166 return
Guido van Rossum41f69f42015-11-19 13:28:47 -0800167 fut._loop.stop()
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100168
169
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170class Server(events.AbstractServer):
171
172 def __init__(self, loop, sockets):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200173 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174 self.sockets = sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200175 self._active_count = 0
176 self._waiters = []
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700177
Victor Stinnere912e652014-07-12 03:11:53 +0200178 def __repr__(self):
179 return '<%s sockets=%r>' % (self.__class__.__name__, self.sockets)
180
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200181 def _attach(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700182 assert self.sockets is not None
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200183 self._active_count += 1
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700184
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200185 def _detach(self):
186 assert self._active_count > 0
187 self._active_count -= 1
188 if self._active_count == 0 and self.sockets is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700189 self._wakeup()
190
191 def close(self):
192 sockets = self.sockets
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200193 if sockets is None:
194 return
195 self.sockets = None
196 for sock in sockets:
197 self._loop._stop_serving(sock)
198 if self._active_count == 0:
199 self._wakeup()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700200
201 def _wakeup(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200202 waiters = self._waiters
203 self._waiters = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204 for waiter in waiters:
205 if not waiter.done():
206 waiter.set_result(waiter)
207
Victor Stinnerf951d282014-06-29 00:46:45 +0200208 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700209 def wait_closed(self):
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200210 if self.sockets is None or self._waiters is None:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700211 return
Victor Stinnerb28dbac2014-07-11 22:52:21 +0200212 waiter = futures.Future(loop=self._loop)
213 self._waiters.append(waiter)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700214 yield from waiter
215
216
217class BaseEventLoop(events.AbstractEventLoop):
218
219 def __init__(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400220 self._timer_cancelled_count = 0
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200221 self._closed = False
Guido van Rossum41f69f42015-11-19 13:28:47 -0800222 self._stopping = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700223 self._ready = collections.deque()
224 self._scheduled = []
225 self._default_executor = None
226 self._internal_fds = 0
Victor Stinner956de692014-12-26 21:07:52 +0100227 # Identifier of the thread running the event loop, or None if the
228 # event loop is not running
Victor Stinnera87501f2015-02-05 11:45:33 +0100229 self._thread_id = None
Victor Stinnered1654f2014-02-10 23:42:32 +0100230 self._clock_resolution = time.get_clock_info('monotonic').resolution
Yury Selivanov569efa22014-02-18 18:02:19 -0500231 self._exception_handler = None
Yury Selivanov1af2bf72015-05-11 22:27:25 -0400232 self.set_debug((not sys.flags.ignore_environment
233 and bool(os.environ.get('PYTHONASYNCIODEBUG'))))
Victor Stinner0e6f52a2014-06-20 17:34:15 +0200234 # In debug mode, if the execution of a callback or a step of a task
235 # exceed this duration in seconds, the slow callback/task is logged.
236 self.slow_callback_duration = 0.1
Victor Stinner9b524d52015-01-26 11:05:12 +0100237 self._current_handle = None
Yury Selivanov740169c2015-05-11 14:23:38 -0400238 self._task_factory = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400239 self._coroutine_wrapper_set = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700240
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200241 def __repr__(self):
242 return ('<%s running=%s closed=%s debug=%s>'
243 % (self.__class__.__name__, self.is_running(),
244 self.is_closed(), self.get_debug()))
245
Victor Stinner896a25a2014-07-08 11:29:25 +0200246 def create_task(self, coro):
247 """Schedule a coroutine object.
248
Victor Stinneracdb7822014-07-14 18:33:40 +0200249 Return a task object.
250 """
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100251 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400252 if self._task_factory is None:
253 task = tasks.Task(coro, loop=self)
254 if task._source_traceback:
255 del task._source_traceback[-1]
256 else:
257 task = self._task_factory(self, coro)
Victor Stinnerc39ba7d2014-07-11 00:21:27 +0200258 return task
Victor Stinner896a25a2014-07-08 11:29:25 +0200259
Yury Selivanov740169c2015-05-11 14:23:38 -0400260 def set_task_factory(self, factory):
261 """Set a task factory that will be used by loop.create_task().
262
263 If factory is None the default task factory will be set.
264
265 If factory is a callable, it should have a signature matching
266 '(loop, coro)', where 'loop' will be a reference to the active
267 event loop, 'coro' will be a coroutine object. The callable
268 must return a Future.
269 """
270 if factory is not None and not callable(factory):
271 raise TypeError('task factory must be a callable or None')
272 self._task_factory = factory
273
274 def get_task_factory(self):
275 """Return a task factory, or None if the default one is in use."""
276 return self._task_factory
277
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700278 def _make_socket_transport(self, sock, protocol, waiter=None, *,
279 extra=None, server=None):
280 """Create socket transport."""
281 raise NotImplementedError
282
Victor Stinner15cc6782015-01-09 00:09:10 +0100283 def _make_ssl_transport(self, rawsock, protocol, sslcontext, waiter=None,
284 *, server_side=False, server_hostname=None,
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700285 extra=None, server=None):
286 """Create SSL transport."""
287 raise NotImplementedError
288
289 def _make_datagram_transport(self, sock, protocol,
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200290 address=None, waiter=None, extra=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700291 """Create datagram transport."""
292 raise NotImplementedError
293
294 def _make_read_pipe_transport(self, pipe, protocol, waiter=None,
295 extra=None):
296 """Create read pipe transport."""
297 raise NotImplementedError
298
299 def _make_write_pipe_transport(self, pipe, protocol, waiter=None,
300 extra=None):
301 """Create write pipe transport."""
302 raise NotImplementedError
303
Victor Stinnerf951d282014-06-29 00:46:45 +0200304 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 def _make_subprocess_transport(self, protocol, args, shell,
306 stdin, stdout, stderr, bufsize,
307 extra=None, **kwargs):
308 """Create subprocess transport."""
309 raise NotImplementedError
310
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311 def _write_to_self(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200312 """Write a byte to self-pipe, to wake up the event loop.
313
314 This may be called from a different thread.
315
316 The subclass is responsible for implementing the self-pipe.
317 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700318 raise NotImplementedError
319
320 def _process_events(self, event_list):
321 """Process selector events."""
322 raise NotImplementedError
323
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200324 def _check_closed(self):
325 if self._closed:
326 raise RuntimeError('Event loop is closed')
327
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700328 def run_forever(self):
329 """Run until stop() is called."""
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200330 self._check_closed()
Victor Stinner956de692014-12-26 21:07:52 +0100331 if self.is_running():
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700332 raise RuntimeError('Event loop is running.')
Yury Selivanove8944cb2015-05-12 11:43:04 -0400333 self._set_coroutine_wrapper(self._debug)
Victor Stinnera87501f2015-02-05 11:45:33 +0100334 self._thread_id = threading.get_ident()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700335 try:
336 while True:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800337 self._run_once()
338 if self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700339 break
340 finally:
Guido van Rossum41f69f42015-11-19 13:28:47 -0800341 self._stopping = False
Victor Stinnera87501f2015-02-05 11:45:33 +0100342 self._thread_id = None
Yury Selivanove8944cb2015-05-12 11:43:04 -0400343 self._set_coroutine_wrapper(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344
345 def run_until_complete(self, future):
346 """Run until the Future is done.
347
348 If the argument is a coroutine, it is wrapped in a Task.
349
Victor Stinneracdb7822014-07-14 18:33:40 +0200350 WARNING: It would be disastrous to call run_until_complete()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700351 with the same coroutine twice -- it would wrap it in two
352 different Tasks and that can't be good.
353
354 Return the Future's result, or raise its exception.
355 """
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200356 self._check_closed()
Victor Stinner98b63912014-06-30 14:51:04 +0200357
358 new_task = not isinstance(future, futures.Future)
Yury Selivanov59eb9a42015-05-11 14:48:38 -0400359 future = tasks.ensure_future(future, loop=self)
Victor Stinner98b63912014-06-30 14:51:04 +0200360 if new_task:
361 # An exception is raised if the future didn't complete, so there
362 # is no need to log the "destroy pending task" message
363 future._log_destroy_pending = False
364
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100365 future.add_done_callback(_run_until_complete_cb)
Victor Stinnerc8bd53f2014-10-11 14:30:18 +0200366 try:
367 self.run_forever()
368 except:
369 if new_task and future.done() and not future.cancelled():
370 # The coroutine raised a BaseException. Consume the exception
371 # to not log a warning, the caller doesn't have access to the
372 # local task.
373 future.exception()
374 raise
Victor Stinnerf3e2e092014-12-05 01:44:10 +0100375 future.remove_done_callback(_run_until_complete_cb)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700376 if not future.done():
377 raise RuntimeError('Event loop stopped before Future completed.')
378
379 return future.result()
380
381 def stop(self):
382 """Stop running the event loop.
383
Guido van Rossum41f69f42015-11-19 13:28:47 -0800384 Every callback already scheduled will still run. This simply informs
385 run_forever to stop looping after a complete iteration.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700386 """
Guido van Rossum41f69f42015-11-19 13:28:47 -0800387 self._stopping = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700388
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200389 def close(self):
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700390 """Close the event loop.
391
392 This clears the queues and shuts down the executor,
393 but does not wait for the executor to finish.
Victor Stinnerf328c7d2014-06-23 01:02:37 +0200394
395 The event loop must not be running.
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700396 """
Victor Stinner956de692014-12-26 21:07:52 +0100397 if self.is_running():
Victor Stinneracdb7822014-07-14 18:33:40 +0200398 raise RuntimeError("Cannot close a running event loop")
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200399 if self._closed:
400 return
Victor Stinnere912e652014-07-12 03:11:53 +0200401 if self._debug:
402 logger.debug("Close %r", self)
Yury Selivanove8944cb2015-05-12 11:43:04 -0400403 self._closed = True
404 self._ready.clear()
405 self._scheduled.clear()
406 executor = self._default_executor
407 if executor is not None:
408 self._default_executor = None
409 executor.shutdown(wait=False)
Antoine Pitrou4ca73552013-10-20 00:54:10 +0200410
Victor Stinnerbb2fc5b2014-06-10 10:23:10 +0200411 def is_closed(self):
412 """Returns True if the event loop was closed."""
413 return self._closed
414
Victor Stinner978a9af2015-01-29 17:50:58 +0100415 # On Python 3.3 and older, objects with a destructor part of a reference
416 # cycle are never destroyed. It's not more the case on Python 3.4 thanks
417 # to the PEP 442.
Yury Selivanov2a8911c2015-08-04 15:56:33 -0400418 if compat.PY34:
Victor Stinner978a9af2015-01-29 17:50:58 +0100419 def __del__(self):
420 if not self.is_closed():
Victor Stinnere19558a2016-03-23 00:28:08 +0100421 warnings.warn("unclosed event loop %r" % self, ResourceWarning,
422 source=self)
Victor Stinner978a9af2015-01-29 17:50:58 +0100423 if not self.is_running():
424 self.close()
425
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700426 def is_running(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200427 """Returns True if the event loop is running."""
Victor Stinnera87501f2015-02-05 11:45:33 +0100428 return (self._thread_id is not None)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700429
430 def time(self):
Victor Stinneracdb7822014-07-14 18:33:40 +0200431 """Return the time according to the event loop's clock.
432
433 This is a float expressed in seconds since an epoch, but the
434 epoch, precision, accuracy and drift are unspecified and may
435 differ per event loop.
436 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700437 return time.monotonic()
438
439 def call_later(self, delay, callback, *args):
440 """Arrange for a callback to be called at a given time.
441
442 Return a Handle: an opaque object with a cancel() method that
443 can be used to cancel the call.
444
445 The delay can be an int or float, expressed in seconds. It is
Victor Stinneracdb7822014-07-14 18:33:40 +0200446 always relative to the current time.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447
448 Each callback will be called exactly once. If two callbacks
449 are scheduled for exactly the same time, it undefined which
450 will be called first.
451
452 Any positional arguments after the callback will be passed to
453 the callback when it is called.
454 """
Victor Stinner80f53aa2014-06-27 13:52:20 +0200455 timer = self.call_at(self.time() + delay, callback, *args)
456 if timer._source_traceback:
457 del timer._source_traceback[-1]
458 return timer
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459
460 def call_at(self, when, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200461 """Like call_later(), but uses an absolute time.
462
463 Absolute time corresponds to the event loop's time() method.
464 """
Victor Stinner2d99d932014-11-20 15:03:52 +0100465 if (coroutines.iscoroutine(callback)
466 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100467 raise TypeError("coroutines cannot be used with call_at()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100468 self._check_closed()
Victor Stinner93569c22014-03-21 10:00:52 +0100469 if self._debug:
Victor Stinner956de692014-12-26 21:07:52 +0100470 self._check_thread()
Yury Selivanov569efa22014-02-18 18:02:19 -0500471 timer = events.TimerHandle(when, callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200472 if timer._source_traceback:
473 del timer._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700474 heapq.heappush(self._scheduled, timer)
Yury Selivanov592ada92014-09-25 12:07:56 -0400475 timer._scheduled = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476 return timer
477
478 def call_soon(self, callback, *args):
479 """Arrange for a callback to be called as soon as possible.
480
Victor Stinneracdb7822014-07-14 18:33:40 +0200481 This operates as a FIFO queue: callbacks are called in the
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700482 order in which they are registered. Each callback will be
483 called exactly once.
484
485 Any positional arguments after the callback will be passed to
486 the callback when it is called.
487 """
Victor Stinner956de692014-12-26 21:07:52 +0100488 if self._debug:
489 self._check_thread()
490 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200491 if handle._source_traceback:
492 del handle._source_traceback[-1]
493 return handle
Victor Stinner93569c22014-03-21 10:00:52 +0100494
Victor Stinner956de692014-12-26 21:07:52 +0100495 def _call_soon(self, callback, args):
Victor Stinner2d99d932014-11-20 15:03:52 +0100496 if (coroutines.iscoroutine(callback)
497 or coroutines.iscoroutinefunction(callback)):
Victor Stinner9af4a242014-02-11 11:34:30 +0100498 raise TypeError("coroutines cannot be used with call_soon()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100499 self._check_closed()
Yury Selivanov569efa22014-02-18 18:02:19 -0500500 handle = events.Handle(callback, args, self)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200501 if handle._source_traceback:
502 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700503 self._ready.append(handle)
504 return handle
505
Victor Stinner956de692014-12-26 21:07:52 +0100506 def _check_thread(self):
507 """Check that the current thread is the thread running the event loop.
Victor Stinner93569c22014-03-21 10:00:52 +0100508
Victor Stinneracdb7822014-07-14 18:33:40 +0200509 Non-thread-safe methods of this class make this assumption and will
Victor Stinner93569c22014-03-21 10:00:52 +0100510 likely behave incorrectly when the assumption is violated.
511
Victor Stinneracdb7822014-07-14 18:33:40 +0200512 Should only be called when (self._debug == True). The caller is
Victor Stinner93569c22014-03-21 10:00:52 +0100513 responsible for checking this condition for performance reasons.
514 """
Victor Stinnera87501f2015-02-05 11:45:33 +0100515 if self._thread_id is None:
Victor Stinner751c7c02014-06-23 15:14:13 +0200516 return
Victor Stinner956de692014-12-26 21:07:52 +0100517 thread_id = threading.get_ident()
Victor Stinnera87501f2015-02-05 11:45:33 +0100518 if thread_id != self._thread_id:
Victor Stinner93569c22014-03-21 10:00:52 +0100519 raise RuntimeError(
Victor Stinneracdb7822014-07-14 18:33:40 +0200520 "Non-thread-safe operation invoked on an event loop other "
Victor Stinner93569c22014-03-21 10:00:52 +0100521 "than the current one")
522
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700523 def call_soon_threadsafe(self, callback, *args):
Victor Stinneracdb7822014-07-14 18:33:40 +0200524 """Like call_soon(), but thread-safe."""
Victor Stinner956de692014-12-26 21:07:52 +0100525 handle = self._call_soon(callback, args)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200526 if handle._source_traceback:
527 del handle._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 self._write_to_self()
529 return handle
530
Yury Selivanov740169c2015-05-11 14:23:38 -0400531 def run_in_executor(self, executor, func, *args):
532 if (coroutines.iscoroutine(func)
533 or coroutines.iscoroutinefunction(func)):
Victor Stinner2d99d932014-11-20 15:03:52 +0100534 raise TypeError("coroutines cannot be used with run_in_executor()")
Victor Stinnere80bf0d2014-12-04 23:07:47 +0100535 self._check_closed()
Yury Selivanov740169c2015-05-11 14:23:38 -0400536 if isinstance(func, events.Handle):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 assert not args
Yury Selivanov740169c2015-05-11 14:23:38 -0400538 assert not isinstance(func, events.TimerHandle)
539 if func._cancelled:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700540 f = futures.Future(loop=self)
541 f.set_result(None)
542 return f
Yury Selivanov740169c2015-05-11 14:23:38 -0400543 func, args = func._callback, func._args
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544 if executor is None:
545 executor = self._default_executor
546 if executor is None:
547 executor = concurrent.futures.ThreadPoolExecutor(_MAX_WORKERS)
548 self._default_executor = executor
Yury Selivanov740169c2015-05-11 14:23:38 -0400549 return futures.wrap_future(executor.submit(func, *args), loop=self)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700550
551 def set_default_executor(self, executor):
552 self._default_executor = executor
553
Victor Stinnere912e652014-07-12 03:11:53 +0200554 def _getaddrinfo_debug(self, host, port, family, type, proto, flags):
555 msg = ["%s:%r" % (host, port)]
556 if family:
557 msg.append('family=%r' % family)
558 if type:
559 msg.append('type=%r' % type)
560 if proto:
561 msg.append('proto=%r' % proto)
562 if flags:
563 msg.append('flags=%r' % flags)
564 msg = ', '.join(msg)
Victor Stinneracdb7822014-07-14 18:33:40 +0200565 logger.debug('Get address info %s', msg)
Victor Stinnere912e652014-07-12 03:11:53 +0200566
567 t0 = self.time()
568 addrinfo = socket.getaddrinfo(host, port, family, type, proto, flags)
569 dt = self.time() - t0
570
Victor Stinneracdb7822014-07-14 18:33:40 +0200571 msg = ('Getting address info %s took %.3f ms: %r'
Victor Stinnere912e652014-07-12 03:11:53 +0200572 % (msg, dt * 1e3, addrinfo))
573 if dt >= self.slow_callback_duration:
574 logger.info(msg)
575 else:
576 logger.debug(msg)
577 return addrinfo
578
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700579 def getaddrinfo(self, host, port, *,
580 family=0, type=0, proto=0, flags=0):
Yury Selivanovd5c2a622015-12-16 19:31:17 -0500581 info = _ipaddr_info(host, port, family, type, proto)
582 if info is not None:
583 fut = futures.Future(loop=self)
584 fut.set_result([info])
585 return fut
586 elif self._debug:
Victor Stinnere912e652014-07-12 03:11:53 +0200587 return self.run_in_executor(None, self._getaddrinfo_debug,
588 host, port, family, type, proto, flags)
589 else:
590 return self.run_in_executor(None, socket.getaddrinfo,
591 host, port, family, type, proto, flags)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592
593 def getnameinfo(self, sockaddr, flags=0):
594 return self.run_in_executor(None, socket.getnameinfo, sockaddr, flags)
595
Victor Stinnerf951d282014-06-29 00:46:45 +0200596 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700597 def create_connection(self, protocol_factory, host=None, port=None, *,
598 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700599 local_addr=None, server_hostname=None):
Victor Stinnerd1432092014-06-19 17:11:49 +0200600 """Connect to a TCP server.
601
602 Create a streaming transport connection to a given Internet host and
603 port: socket family AF_INET or socket.AF_INET6 depending on host (or
604 family if specified), socket type SOCK_STREAM. protocol_factory must be
605 a callable returning a protocol instance.
606
607 This method is a coroutine which will try to establish the connection
608 in the background. When successful, the coroutine returns a
609 (transport, protocol) pair.
610 """
Guido van Rossum21c85a72013-11-01 14:16:54 -0700611 if server_hostname is not None and not ssl:
612 raise ValueError('server_hostname is only meaningful with ssl')
613
614 if server_hostname is None and ssl:
615 # Use host as default for server_hostname. It is an error
616 # if host is empty or not set, e.g. when an
617 # already-connected socket was passed or when only a port
618 # is given. To avoid this error, you can pass
619 # server_hostname='' -- this will bypass the hostname
620 # check. (This also means that if host is a numeric
621 # IP/IPv6 address, we will attempt to verify that exact
622 # address; this will probably fail, but it is possible to
623 # create a certificate for a specific IP address, so we
624 # don't judge it here.)
625 if not host:
626 raise ValueError('You must set server_hostname '
627 'when using ssl without a host')
628 server_hostname = host
Guido van Rossuma8d630a2013-11-01 14:20:55 -0700629
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630 if host is not None or port is not None:
631 if sock is not None:
632 raise ValueError(
633 'host/port and sock can not be specified at the same time')
634
635 f1 = self.getaddrinfo(
636 host, port, family=family,
637 type=socket.SOCK_STREAM, proto=proto, flags=flags)
638 fs = [f1]
639 if local_addr is not None:
640 f2 = self.getaddrinfo(
641 *local_addr, family=family,
642 type=socket.SOCK_STREAM, proto=proto, flags=flags)
643 fs.append(f2)
644 else:
645 f2 = None
646
647 yield from tasks.wait(fs, loop=self)
648
649 infos = f1.result()
650 if not infos:
651 raise OSError('getaddrinfo() returned empty list')
652 if f2 is not None:
653 laddr_infos = f2.result()
654 if not laddr_infos:
655 raise OSError('getaddrinfo() returned empty list')
656
657 exceptions = []
658 for family, type, proto, cname, address in infos:
659 try:
660 sock = socket.socket(family=family, type=type, proto=proto)
661 sock.setblocking(False)
662 if f2 is not None:
663 for _, _, _, _, laddr in laddr_infos:
664 try:
665 sock.bind(laddr)
666 break
667 except OSError as exc:
668 exc = OSError(
669 exc.errno, 'error while '
670 'attempting to bind on address '
671 '{!r}: {}'.format(
672 laddr, exc.strerror.lower()))
673 exceptions.append(exc)
674 else:
675 sock.close()
676 sock = None
677 continue
Victor Stinnere912e652014-07-12 03:11:53 +0200678 if self._debug:
679 logger.debug("connect %r to %r", sock, address)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700680 yield from self.sock_connect(sock, address)
681 except OSError as exc:
682 if sock is not None:
683 sock.close()
684 exceptions.append(exc)
Victor Stinner223a6242014-06-04 00:11:52 +0200685 except:
686 if sock is not None:
687 sock.close()
688 raise
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700689 else:
690 break
691 else:
692 if len(exceptions) == 1:
693 raise exceptions[0]
694 else:
695 # If they all have the same str(), raise one.
696 model = str(exceptions[0])
697 if all(str(exc) == model for exc in exceptions):
698 raise exceptions[0]
699 # Raise a combined exception so the user can see all
700 # the various error messages.
701 raise OSError('Multiple exceptions: {}'.format(
702 ', '.join(str(exc) for exc in exceptions)))
703
704 elif sock is None:
705 raise ValueError(
706 'host and port was not specified and no sock specified')
707
708 sock.setblocking(False)
709
Yury Selivanovb057c522014-02-18 12:15:06 -0500710 transport, protocol = yield from self._create_connection_transport(
711 sock, protocol_factory, ssl, server_hostname)
Victor Stinnere912e652014-07-12 03:11:53 +0200712 if self._debug:
Victor Stinnerb2614752014-08-25 23:20:52 +0200713 # Get the socket from the transport because SSL transport closes
714 # the old socket and creates a new SSL socket
715 sock = transport.get_extra_info('socket')
Victor Stinneracdb7822014-07-14 18:33:40 +0200716 logger.debug("%r connected to %s:%r: (%r, %r)",
717 sock, host, port, transport, protocol)
Yury Selivanovb057c522014-02-18 12:15:06 -0500718 return transport, protocol
719
Victor Stinnerf951d282014-06-29 00:46:45 +0200720 @coroutine
Yury Selivanovb057c522014-02-18 12:15:06 -0500721 def _create_connection_transport(self, sock, protocol_factory, ssl,
722 server_hostname):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700723 protocol = protocol_factory()
724 waiter = futures.Future(loop=self)
725 if ssl:
726 sslcontext = None if isinstance(ssl, bool) else ssl
727 transport = self._make_ssl_transport(
728 sock, protocol, sslcontext, waiter,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700729 server_side=False, server_hostname=server_hostname)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700730 else:
731 transport = self._make_socket_transport(sock, protocol, waiter)
732
Victor Stinner29ad0112015-01-15 00:04:21 +0100733 try:
734 yield from waiter
Victor Stinner0c2e4082015-01-22 00:17:41 +0100735 except:
Victor Stinner29ad0112015-01-15 00:04:21 +0100736 transport.close()
737 raise
738
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700739 return transport, protocol
740
Victor Stinnerf951d282014-06-29 00:46:45 +0200741 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700742 def create_datagram_endpoint(self, protocol_factory,
743 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700744 family=0, proto=0, flags=0,
745 reuse_address=None, reuse_port=None,
746 allow_broadcast=None, sock=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700747 """Create datagram connection."""
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700748 if sock is not None:
749 if (local_addr or remote_addr or
750 family or proto or flags or
751 reuse_address or reuse_port or allow_broadcast):
752 # show the problematic kwargs in exception msg
753 opts = dict(local_addr=local_addr, remote_addr=remote_addr,
754 family=family, proto=proto, flags=flags,
755 reuse_address=reuse_address, reuse_port=reuse_port,
756 allow_broadcast=allow_broadcast)
757 problems = ', '.join(
758 '{}={}'.format(k, v) for k, v in opts.items() if v)
759 raise ValueError(
760 'socket modifier keyword arguments can not be used '
761 'when sock is specified. ({})'.format(problems))
762 sock.setblocking(False)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700763 r_addr = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700764 else:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700765 if not (local_addr or remote_addr):
766 if family == 0:
767 raise ValueError('unexpected address family')
768 addr_pairs_info = (((family, proto), (None, None)),)
769 else:
770 # join address by (family, protocol)
771 addr_infos = collections.OrderedDict()
772 for idx, addr in ((0, local_addr), (1, remote_addr)):
773 if addr is not None:
774 assert isinstance(addr, tuple) and len(addr) == 2, (
775 '2-tuple is expected')
776
777 infos = yield from self.getaddrinfo(
778 *addr, family=family, type=socket.SOCK_DGRAM,
779 proto=proto, flags=flags)
780 if not infos:
781 raise OSError('getaddrinfo() returned empty list')
782
783 for fam, _, pro, _, address in infos:
784 key = (fam, pro)
785 if key not in addr_infos:
786 addr_infos[key] = [None, None]
787 addr_infos[key][idx] = address
788
789 # each addr has to have info for each (family, proto) pair
790 addr_pairs_info = [
791 (key, addr_pair) for key, addr_pair in addr_infos.items()
792 if not ((local_addr and addr_pair[0] is None) or
793 (remote_addr and addr_pair[1] is None))]
794
795 if not addr_pairs_info:
796 raise ValueError('can not get address information')
797
798 exceptions = []
799
800 if reuse_address is None:
801 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
802
803 for ((family, proto),
804 (local_address, remote_address)) in addr_pairs_info:
805 sock = None
806 r_addr = None
807 try:
808 sock = socket.socket(
809 family=family, type=socket.SOCK_DGRAM, proto=proto)
810 if reuse_address:
811 sock.setsockopt(
812 socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
813 if reuse_port:
814 if not hasattr(socket, 'SO_REUSEPORT'):
815 raise ValueError(
816 'reuse_port not supported by socket module')
817 else:
818 sock.setsockopt(
819 socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
820 if allow_broadcast:
821 sock.setsockopt(
822 socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
823 sock.setblocking(False)
824
825 if local_addr:
826 sock.bind(local_address)
827 if remote_addr:
828 yield from self.sock_connect(sock, remote_address)
829 r_addr = remote_address
830 except OSError as exc:
831 if sock is not None:
832 sock.close()
833 exceptions.append(exc)
834 except:
835 if sock is not None:
836 sock.close()
837 raise
838 else:
839 break
840 else:
841 raise exceptions[0]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700842
843 protocol = protocol_factory()
Victor Stinnerbfff45d2014-07-08 23:57:31 +0200844 waiter = futures.Future(loop=self)
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700845 transport = self._make_datagram_transport(
846 sock, protocol, r_addr, waiter)
Victor Stinnere912e652014-07-12 03:11:53 +0200847 if self._debug:
848 if local_addr:
849 logger.info("Datagram endpoint local_addr=%r remote_addr=%r "
850 "created: (%r, %r)",
851 local_addr, remote_addr, transport, protocol)
852 else:
853 logger.debug("Datagram endpoint remote_addr=%r created: "
854 "(%r, %r)",
855 remote_addr, transport, protocol)
Victor Stinner2596dd02015-01-26 11:02:18 +0100856
857 try:
858 yield from waiter
859 except:
860 transport.close()
861 raise
862
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700863 return transport, protocol
864
Victor Stinnerf951d282014-06-29 00:46:45 +0200865 @coroutine
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200866 def _create_server_getaddrinfo(self, host, port, family, flags):
867 infos = yield from self.getaddrinfo(host, port, family=family,
868 type=socket.SOCK_STREAM,
869 flags=flags)
870 if not infos:
871 raise OSError('getaddrinfo({!r}) returned empty list'.format(host))
872 return infos
873
874 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700875 def create_server(self, protocol_factory, host=None, port=None,
876 *,
877 family=socket.AF_UNSPEC,
878 flags=socket.AI_PASSIVE,
879 sock=None,
880 backlog=100,
881 ssl=None,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700882 reuse_address=None,
883 reuse_port=None):
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200884 """Create a TCP server.
885
886 The host parameter can be a string, in that case the TCP server is bound
887 to host and port.
888
889 The host parameter can also be a sequence of strings and in that case
Yury Selivanove076ffb2016-03-02 11:17:01 -0500890 the TCP server is bound to all hosts of the sequence. If a host
891 appears multiple times (possibly indirectly e.g. when hostnames
892 resolve to the same IP address), the server is only bound once to that
893 host.
Victor Stinnerd1432092014-06-19 17:11:49 +0200894
Victor Stinneracdb7822014-07-14 18:33:40 +0200895 Return a Server object which can be used to stop the service.
Victor Stinnerd1432092014-06-19 17:11:49 +0200896
897 This method is a coroutine.
898 """
Guido van Rossum28dff0d2013-11-01 14:22:30 -0700899 if isinstance(ssl, bool):
900 raise TypeError('ssl argument must be an SSLContext or None')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700901 if host is not None or port is not None:
902 if sock is not None:
903 raise ValueError(
904 'host/port and sock can not be specified at the same time')
905
906 AF_INET6 = getattr(socket, 'AF_INET6', 0)
907 if reuse_address is None:
908 reuse_address = os.name == 'posix' and sys.platform != 'cygwin'
909 sockets = []
910 if host == '':
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200911 hosts = [None]
912 elif (isinstance(host, str) or
913 not isinstance(host, collections.Iterable)):
914 hosts = [host]
915 else:
916 hosts = host
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700917
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200918 fs = [self._create_server_getaddrinfo(host, port, family=family,
919 flags=flags)
920 for host in hosts]
921 infos = yield from tasks.gather(*fs, loop=self)
Yury Selivanove076ffb2016-03-02 11:17:01 -0500922 infos = set(itertools.chain.from_iterable(infos))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700923
924 completed = False
925 try:
926 for res in infos:
927 af, socktype, proto, canonname, sa = res
Guido van Rossum32e46852013-10-19 17:04:25 -0700928 try:
929 sock = socket.socket(af, socktype, proto)
930 except socket.error:
931 # Assume it's a bad family/type/protocol combination.
Victor Stinnerb2614752014-08-25 23:20:52 +0200932 if self._debug:
933 logger.warning('create_server() failed to create '
934 'socket.socket(%r, %r, %r)',
935 af, socktype, proto, exc_info=True)
Guido van Rossum32e46852013-10-19 17:04:25 -0700936 continue
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700937 sockets.append(sock)
938 if reuse_address:
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700939 sock.setsockopt(
940 socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
941 if reuse_port:
942 if not hasattr(socket, 'SO_REUSEPORT'):
943 raise ValueError(
944 'reuse_port not supported by socket module')
945 else:
946 sock.setsockopt(
947 socket.SOL_SOCKET, socket.SO_REUSEPORT, True)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700948 # Disable IPv4/IPv6 dual stack support (enabled by
949 # default on Linux) which makes a single socket
950 # listen on both address families.
951 if af == AF_INET6 and hasattr(socket, 'IPPROTO_IPV6'):
952 sock.setsockopt(socket.IPPROTO_IPV6,
953 socket.IPV6_V6ONLY,
954 True)
955 try:
956 sock.bind(sa)
957 except OSError as err:
958 raise OSError(err.errno, 'error while attempting '
959 'to bind on address %r: %s'
960 % (sa, err.strerror.lower()))
961 completed = True
962 finally:
963 if not completed:
964 for sock in sockets:
965 sock.close()
966 else:
967 if sock is None:
Victor Stinneracdb7822014-07-14 18:33:40 +0200968 raise ValueError('Neither host/port nor sock were specified')
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700969 sockets = [sock]
970
971 server = Server(self, sockets)
972 for sock in sockets:
973 sock.listen(backlog)
974 sock.setblocking(False)
975 self._start_serving(protocol_factory, sock, ssl, server)
Victor Stinnere912e652014-07-12 03:11:53 +0200976 if self._debug:
977 logger.info("%r is serving", server)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700978 return server
979
Victor Stinnerf951d282014-06-29 00:46:45 +0200980 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700981 def connect_read_pipe(self, protocol_factory, pipe):
982 protocol = protocol_factory()
983 waiter = futures.Future(loop=self)
984 transport = self._make_read_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +0100985
986 try:
987 yield from waiter
988 except:
989 transport.close()
990 raise
991
Victor Stinneracdb7822014-07-14 18:33:40 +0200992 if self._debug:
993 logger.debug('Read pipe %r connected: (%r, %r)',
994 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700995 return transport, protocol
996
Victor Stinnerf951d282014-06-29 00:46:45 +0200997 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700998 def connect_write_pipe(self, protocol_factory, pipe):
999 protocol = protocol_factory()
1000 waiter = futures.Future(loop=self)
1001 transport = self._make_write_pipe_transport(pipe, protocol, waiter)
Victor Stinner2596dd02015-01-26 11:02:18 +01001002
1003 try:
1004 yield from waiter
1005 except:
1006 transport.close()
1007 raise
1008
Victor Stinneracdb7822014-07-14 18:33:40 +02001009 if self._debug:
1010 logger.debug('Write pipe %r connected: (%r, %r)',
1011 pipe.fileno(), transport, protocol)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001012 return transport, protocol
1013
Victor Stinneracdb7822014-07-14 18:33:40 +02001014 def _log_subprocess(self, msg, stdin, stdout, stderr):
1015 info = [msg]
1016 if stdin is not None:
1017 info.append('stdin=%s' % _format_pipe(stdin))
1018 if stdout is not None and stderr == subprocess.STDOUT:
1019 info.append('stdout=stderr=%s' % _format_pipe(stdout))
1020 else:
1021 if stdout is not None:
1022 info.append('stdout=%s' % _format_pipe(stdout))
1023 if stderr is not None:
1024 info.append('stderr=%s' % _format_pipe(stderr))
1025 logger.debug(' '.join(info))
1026
Victor Stinnerf951d282014-06-29 00:46:45 +02001027 @coroutine
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001028 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
1029 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1030 universal_newlines=False, shell=True, bufsize=0,
1031 **kwargs):
Victor Stinner20e07432014-02-11 11:44:56 +01001032 if not isinstance(cmd, (bytes, str)):
Victor Stinnere623a122014-01-29 14:35:15 -08001033 raise ValueError("cmd must be a string")
1034 if universal_newlines:
1035 raise ValueError("universal_newlines must be False")
1036 if not shell:
Victor Stinner323748e2014-01-31 12:28:30 +01001037 raise ValueError("shell must be True")
Victor Stinnere623a122014-01-29 14:35:15 -08001038 if bufsize != 0:
1039 raise ValueError("bufsize must be 0")
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001040 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001041 if self._debug:
1042 # don't log parameters: they may contain sensitive information
1043 # (password) and may be too long
1044 debug_log = 'run shell command %r' % cmd
1045 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001046 transport = yield from self._make_subprocess_transport(
1047 protocol, cmd, True, stdin, stdout, stderr, bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001048 if self._debug:
1049 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001050 return transport, protocol
1051
Victor Stinnerf951d282014-06-29 00:46:45 +02001052 @coroutine
Yury Selivanov57797522014-02-18 22:56:15 -05001053 def subprocess_exec(self, protocol_factory, program, *args,
1054 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1055 stderr=subprocess.PIPE, universal_newlines=False,
1056 shell=False, bufsize=0, **kwargs):
Victor Stinnere623a122014-01-29 14:35:15 -08001057 if universal_newlines:
1058 raise ValueError("universal_newlines must be False")
1059 if shell:
1060 raise ValueError("shell must be False")
1061 if bufsize != 0:
1062 raise ValueError("bufsize must be 0")
Victor Stinner20e07432014-02-11 11:44:56 +01001063 popen_args = (program,) + args
1064 for arg in popen_args:
1065 if not isinstance(arg, (str, bytes)):
1066 raise TypeError("program arguments must be "
1067 "a bytes or text string, not %s"
1068 % type(arg).__name__)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001069 protocol = protocol_factory()
Victor Stinneracdb7822014-07-14 18:33:40 +02001070 if self._debug:
1071 # don't log parameters: they may contain sensitive information
1072 # (password) and may be too long
1073 debug_log = 'execute program %r' % program
1074 self._log_subprocess(debug_log, stdin, stdout, stderr)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001075 transport = yield from self._make_subprocess_transport(
Yury Selivanov57797522014-02-18 22:56:15 -05001076 protocol, popen_args, False, stdin, stdout, stderr,
1077 bufsize, **kwargs)
Victor Stinneracdb7822014-07-14 18:33:40 +02001078 if self._debug:
1079 logger.info('%s: %r' % (debug_log, transport))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001080 return transport, protocol
1081
Yury Selivanov569efa22014-02-18 18:02:19 -05001082 def set_exception_handler(self, handler):
1083 """Set handler as the new event loop exception handler.
1084
1085 If handler is None, the default exception handler will
1086 be set.
1087
1088 If handler is a callable object, it should have a
Victor Stinneracdb7822014-07-14 18:33:40 +02001089 signature matching '(loop, context)', where 'loop'
Yury Selivanov569efa22014-02-18 18:02:19 -05001090 will be a reference to the active event loop, 'context'
1091 will be a dict object (see `call_exception_handler()`
1092 documentation for details about context).
1093 """
1094 if handler is not None and not callable(handler):
1095 raise TypeError('A callable object or None is expected, '
1096 'got {!r}'.format(handler))
1097 self._exception_handler = handler
1098
1099 def default_exception_handler(self, context):
1100 """Default exception handler.
1101
1102 This is called when an exception occurs and no exception
1103 handler is set, and can be called by a custom exception
1104 handler that wants to defer to the default behavior.
1105
Victor Stinneracdb7822014-07-14 18:33:40 +02001106 The context parameter has the same meaning as in
Yury Selivanov569efa22014-02-18 18:02:19 -05001107 `call_exception_handler()`.
1108 """
1109 message = context.get('message')
1110 if not message:
1111 message = 'Unhandled exception in event loop'
1112
1113 exception = context.get('exception')
1114 if exception is not None:
1115 exc_info = (type(exception), exception, exception.__traceback__)
1116 else:
1117 exc_info = False
1118
Victor Stinnerff018e42015-01-28 00:30:40 +01001119 if ('source_traceback' not in context
1120 and self._current_handle is not None
Victor Stinner9b524d52015-01-26 11:05:12 +01001121 and self._current_handle._source_traceback):
1122 context['handle_traceback'] = self._current_handle._source_traceback
1123
Yury Selivanov569efa22014-02-18 18:02:19 -05001124 log_lines = [message]
1125 for key in sorted(context):
1126 if key in {'message', 'exception'}:
1127 continue
Victor Stinner80f53aa2014-06-27 13:52:20 +02001128 value = context[key]
1129 if key == 'source_traceback':
1130 tb = ''.join(traceback.format_list(value))
1131 value = 'Object created at (most recent call last):\n'
1132 value += tb.rstrip()
Victor Stinner9b524d52015-01-26 11:05:12 +01001133 elif key == 'handle_traceback':
1134 tb = ''.join(traceback.format_list(value))
1135 value = 'Handle created at (most recent call last):\n'
1136 value += tb.rstrip()
Victor Stinner80f53aa2014-06-27 13:52:20 +02001137 else:
1138 value = repr(value)
1139 log_lines.append('{}: {}'.format(key, value))
Yury Selivanov569efa22014-02-18 18:02:19 -05001140
1141 logger.error('\n'.join(log_lines), exc_info=exc_info)
1142
1143 def call_exception_handler(self, context):
Victor Stinneracdb7822014-07-14 18:33:40 +02001144 """Call the current event loop's exception handler.
Yury Selivanov569efa22014-02-18 18:02:19 -05001145
Victor Stinneracdb7822014-07-14 18:33:40 +02001146 The context argument is a dict containing the following keys:
1147
Yury Selivanov569efa22014-02-18 18:02:19 -05001148 - 'message': Error message;
1149 - 'exception' (optional): Exception object;
1150 - 'future' (optional): Future instance;
1151 - 'handle' (optional): Handle instance;
1152 - 'protocol' (optional): Protocol instance;
1153 - 'transport' (optional): Transport instance;
1154 - 'socket' (optional): Socket instance.
1155
Victor Stinneracdb7822014-07-14 18:33:40 +02001156 New keys maybe introduced in the future.
1157
1158 Note: do not overload this method in an event loop subclass.
1159 For custom exception handling, use the
Yury Selivanov569efa22014-02-18 18:02:19 -05001160 `set_exception_handler()` method.
1161 """
1162 if self._exception_handler is None:
1163 try:
1164 self.default_exception_handler(context)
1165 except Exception:
1166 # Second protection layer for unexpected errors
1167 # in the default implementation, as well as for subclassed
1168 # event loops with overloaded "default_exception_handler".
1169 logger.error('Exception in default exception handler',
1170 exc_info=True)
1171 else:
1172 try:
1173 self._exception_handler(self, context)
1174 except Exception as exc:
1175 # Exception in the user set custom exception handler.
1176 try:
1177 # Let's try default handler.
1178 self.default_exception_handler({
1179 'message': 'Unhandled error in exception handler',
1180 'exception': exc,
1181 'context': context,
1182 })
1183 except Exception:
Victor Stinneracdb7822014-07-14 18:33:40 +02001184 # Guard 'default_exception_handler' in case it is
Yury Selivanov569efa22014-02-18 18:02:19 -05001185 # overloaded.
1186 logger.error('Exception in default exception handler '
1187 'while handling an unexpected error '
1188 'in custom exception handler',
1189 exc_info=True)
1190
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001191 def _add_callback(self, handle):
Victor Stinneracdb7822014-07-14 18:33:40 +02001192 """Add a Handle to _scheduled (TimerHandle) or _ready."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001193 assert isinstance(handle, events.Handle), 'A Handle is required here'
1194 if handle._cancelled:
1195 return
Yury Selivanov592ada92014-09-25 12:07:56 -04001196 assert not isinstance(handle, events.TimerHandle)
1197 self._ready.append(handle)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001198
1199 def _add_callback_signalsafe(self, handle):
1200 """Like _add_callback() but called from a signal handler."""
1201 self._add_callback(handle)
1202 self._write_to_self()
1203
Yury Selivanov592ada92014-09-25 12:07:56 -04001204 def _timer_handle_cancelled(self, handle):
1205 """Notification that a TimerHandle has been cancelled."""
1206 if handle._scheduled:
1207 self._timer_cancelled_count += 1
1208
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001209 def _run_once(self):
1210 """Run one full iteration of the event loop.
1211
1212 This calls all currently ready callbacks, polls for I/O,
1213 schedules the resulting callbacks, and finally schedules
1214 'call_later' callbacks.
1215 """
Yury Selivanov592ada92014-09-25 12:07:56 -04001216
Yury Selivanov592ada92014-09-25 12:07:56 -04001217 sched_count = len(self._scheduled)
1218 if (sched_count > _MIN_SCHEDULED_TIMER_HANDLES and
1219 self._timer_cancelled_count / sched_count >
1220 _MIN_CANCELLED_TIMER_HANDLES_FRACTION):
Victor Stinner68da8fc2014-09-30 18:08:36 +02001221 # Remove delayed calls that were cancelled if their number
1222 # is too high
1223 new_scheduled = []
Yury Selivanov592ada92014-09-25 12:07:56 -04001224 for handle in self._scheduled:
1225 if handle._cancelled:
1226 handle._scheduled = False
Victor Stinner68da8fc2014-09-30 18:08:36 +02001227 else:
1228 new_scheduled.append(handle)
Yury Selivanov592ada92014-09-25 12:07:56 -04001229
Victor Stinner68da8fc2014-09-30 18:08:36 +02001230 heapq.heapify(new_scheduled)
1231 self._scheduled = new_scheduled
Yury Selivanov592ada92014-09-25 12:07:56 -04001232 self._timer_cancelled_count = 0
Yury Selivanov592ada92014-09-25 12:07:56 -04001233 else:
1234 # Remove delayed calls that were cancelled from head of queue.
1235 while self._scheduled and self._scheduled[0]._cancelled:
1236 self._timer_cancelled_count -= 1
1237 handle = heapq.heappop(self._scheduled)
1238 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001239
1240 timeout = None
Guido van Rossum41f69f42015-11-19 13:28:47 -08001241 if self._ready or self._stopping:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001242 timeout = 0
1243 elif self._scheduled:
1244 # Compute the desired timeout.
1245 when = self._scheduled[0]._when
Guido van Rossum3d1bc602014-05-10 15:47:15 -07001246 timeout = max(0, when - self.time())
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001247
Victor Stinner770e48d2014-07-11 11:58:33 +02001248 if self._debug and timeout != 0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001249 t0 = self.time()
1250 event_list = self._selector.select(timeout)
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001251 dt = self.time() - t0
Victor Stinner770e48d2014-07-11 11:58:33 +02001252 if dt >= 1.0:
Victor Stinner22463aa2014-01-20 23:56:40 +01001253 level = logging.INFO
1254 else:
1255 level = logging.DEBUG
Victor Stinner770e48d2014-07-11 11:58:33 +02001256 nevent = len(event_list)
1257 if timeout is None:
1258 logger.log(level, 'poll took %.3f ms: %s events',
1259 dt * 1e3, nevent)
1260 elif nevent:
1261 logger.log(level,
1262 'poll %.3f ms took %.3f ms: %s events',
1263 timeout * 1e3, dt * 1e3, nevent)
1264 elif dt >= 1.0:
1265 logger.log(level,
1266 'poll %.3f ms took %.3f ms: timeout',
1267 timeout * 1e3, dt * 1e3)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001268 else:
Victor Stinner22463aa2014-01-20 23:56:40 +01001269 event_list = self._selector.select(timeout)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001270 self._process_events(event_list)
1271
1272 # Handle 'later' callbacks that are ready.
Victor Stinnered1654f2014-02-10 23:42:32 +01001273 end_time = self.time() + self._clock_resolution
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001274 while self._scheduled:
1275 handle = self._scheduled[0]
Victor Stinnered1654f2014-02-10 23:42:32 +01001276 if handle._when >= end_time:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001277 break
1278 handle = heapq.heappop(self._scheduled)
Yury Selivanov592ada92014-09-25 12:07:56 -04001279 handle._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001280 self._ready.append(handle)
1281
1282 # This is the only place where callbacks are actually *called*.
1283 # All other places just add them to ready.
1284 # Note: We run all currently scheduled callbacks, but not any
1285 # callbacks scheduled by callbacks run this time around --
1286 # they will be run the next time (after another I/O poll).
Victor Stinneracdb7822014-07-14 18:33:40 +02001287 # Use an idiom that is thread-safe without using locks.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001288 ntodo = len(self._ready)
1289 for i in range(ntodo):
1290 handle = self._ready.popleft()
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001291 if handle._cancelled:
1292 continue
1293 if self._debug:
Victor Stinner9b524d52015-01-26 11:05:12 +01001294 try:
1295 self._current_handle = handle
1296 t0 = self.time()
1297 handle._run()
1298 dt = self.time() - t0
1299 if dt >= self.slow_callback_duration:
1300 logger.warning('Executing %s took %.3f seconds',
1301 _format_handle(handle), dt)
1302 finally:
1303 self._current_handle = None
Victor Stinner0e6f52a2014-06-20 17:34:15 +02001304 else:
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001305 handle._run()
1306 handle = None # Needed to break cycles when an exception occurs.
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001307
Yury Selivanove8944cb2015-05-12 11:43:04 -04001308 def _set_coroutine_wrapper(self, enabled):
1309 try:
1310 set_wrapper = sys.set_coroutine_wrapper
1311 get_wrapper = sys.get_coroutine_wrapper
1312 except AttributeError:
1313 return
1314
1315 enabled = bool(enabled)
Yury Selivanov996083d2015-08-04 15:37:24 -04001316 if self._coroutine_wrapper_set == enabled:
Yury Selivanove8944cb2015-05-12 11:43:04 -04001317 return
1318
1319 wrapper = coroutines.debug_wrapper
1320 current_wrapper = get_wrapper()
1321
1322 if enabled:
1323 if current_wrapper not in (None, wrapper):
1324 warnings.warn(
1325 "loop.set_debug(True): cannot set debug coroutine "
1326 "wrapper; another wrapper is already set %r" %
1327 current_wrapper, RuntimeWarning)
1328 else:
1329 set_wrapper(wrapper)
1330 self._coroutine_wrapper_set = True
1331 else:
1332 if current_wrapper not in (None, wrapper):
1333 warnings.warn(
1334 "loop.set_debug(False): cannot unset debug coroutine "
1335 "wrapper; another wrapper was set %r" %
1336 current_wrapper, RuntimeWarning)
1337 else:
1338 set_wrapper(None)
1339 self._coroutine_wrapper_set = False
1340
Victor Stinner0f3e6bc2014-02-19 23:15:02 +01001341 def get_debug(self):
1342 return self._debug
1343
1344 def set_debug(self, enabled):
1345 self._debug = enabled
Yury Selivanov1af2bf72015-05-11 22:27:25 -04001346
Yury Selivanove8944cb2015-05-12 11:43:04 -04001347 if self.is_running():
1348 self._set_coroutine_wrapper(enabled)