blob: e425b06e42fa3692cf4b32230661bc19f41f64eb [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Event loop and event loop policy."""
2
Yury Selivanov6370f342017-12-10 18:36:12 -05003__all__ = (
4 'AbstractEventLoopPolicy',
5 'AbstractEventLoop', 'AbstractServer',
6 'Handle', 'TimerHandle',
7 'get_event_loop_policy', 'set_event_loop_policy',
8 'get_event_loop', 'set_event_loop', 'new_event_loop',
9 'get_child_watcher', 'set_child_watcher',
Yury Selivanovabae67e2017-12-11 10:07:44 -050010 '_set_running_loop', 'get_running_loop',
11 '_get_running_loop',
Yury Selivanov6370f342017-12-10 18:36:12 -050012)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070013
Victor Stinner307bccc2014-06-12 18:39:26 +020014import functools
15import inspect
Yury Selivanovba7e1f92017-03-02 20:07:11 -050016import os
Victor Stinner313a9802014-07-29 12:58:23 +020017import reprlib
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070018import socket
Victor Stinner313a9802014-07-29 12:58:23 +020019import subprocess
Victor Stinner307bccc2014-06-12 18:39:26 +020020import sys
Victor Stinner313a9802014-07-29 12:58:23 +020021import threading
22import traceback
Victor Stinner307bccc2014-06-12 18:39:26 +020023
Antoine Pitrou921e9432017-11-07 17:23:29 +010024from . import constants
25
Victor Stinner975735f2014-06-25 21:41:58 +020026
Victor Stinner307bccc2014-06-12 18:39:26 +020027def _get_function_source(func):
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090028 func = inspect.unwrap(func)
Victor Stinner307bccc2014-06-12 18:39:26 +020029 if inspect.isfunction(func):
30 code = func.__code__
31 return (code.co_filename, code.co_firstlineno)
32 if isinstance(func, functools.partial):
33 return _get_function_source(func.func)
INADA Naoki3e2ad8e2017-04-25 10:57:18 +090034 if isinstance(func, functools.partialmethod):
Victor Stinner307bccc2014-06-12 18:39:26 +020035 return _get_function_source(func.func)
36 return None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070038
Yury Selivanov45dccda2016-09-15 15:58:15 -040039def _format_args_and_kwargs(args, kwargs):
40 """Format function arguments and keyword arguments.
Victor Stinner313a9802014-07-29 12:58:23 +020041
42 Special case for a single parameter: ('hello',) is formatted as ('hello').
43 """
44 # use reprlib to limit the length of the output
Yury Selivanov45dccda2016-09-15 15:58:15 -040045 items = []
46 if args:
47 items.extend(reprlib.repr(arg) for arg in args)
48 if kwargs:
Yury Selivanov6370f342017-12-10 18:36:12 -050049 items.extend(f'{k}={reprlib.repr(v)}' for k, v in kwargs.items())
50 return '({})'.format(', '.join(items))
Victor Stinner975735f2014-06-25 21:41:58 +020051
52
Yury Selivanov45dccda2016-09-15 15:58:15 -040053def _format_callback(func, args, kwargs, suffix=''):
Victor Stinner975735f2014-06-25 21:41:58 +020054 if isinstance(func, functools.partial):
Yury Selivanov45dccda2016-09-15 15:58:15 -040055 suffix = _format_args_and_kwargs(args, kwargs) + suffix
56 return _format_callback(func.func, func.args, func.keywords, suffix)
Victor Stinner975735f2014-06-25 21:41:58 +020057
Guido van Rossum0a9933e2015-05-02 18:38:24 -070058 if hasattr(func, '__qualname__'):
59 func_repr = getattr(func, '__qualname__')
60 elif hasattr(func, '__name__'):
61 func_repr = getattr(func, '__name__')
62 else:
Victor Stinner975735f2014-06-25 21:41:58 +020063 func_repr = repr(func)
64
Yury Selivanov45dccda2016-09-15 15:58:15 -040065 func_repr += _format_args_and_kwargs(args, kwargs)
Victor Stinner975735f2014-06-25 21:41:58 +020066 if suffix:
67 func_repr += suffix
Guido van Rossum0a9933e2015-05-02 18:38:24 -070068 return func_repr
Victor Stinner975735f2014-06-25 21:41:58 +020069
Yury Selivanov6370f342017-12-10 18:36:12 -050070
Guido van Rossum0a9933e2015-05-02 18:38:24 -070071def _format_callback_source(func, args):
Yury Selivanov45dccda2016-09-15 15:58:15 -040072 func_repr = _format_callback(func, args, None)
Victor Stinner975735f2014-06-25 21:41:58 +020073 source = _get_function_source(func)
74 if source:
Yury Selivanov6370f342017-12-10 18:36:12 -050075 func_repr += f' at {source[0]}:{source[1]}'
Victor Stinner975735f2014-06-25 21:41:58 +020076 return func_repr
77
78
Antoine Pitrou921e9432017-11-07 17:23:29 +010079def extract_stack(f=None, limit=None):
80 """Replacement for traceback.extract_stack() that only does the
81 necessary work for asyncio debug mode.
82 """
83 if f is None:
84 f = sys._getframe().f_back
85 if limit is None:
86 # Limit the amount of work to a reasonable amount, as extract_stack()
87 # can be called for each coroutine and future in debug mode.
88 limit = constants.DEBUG_STACK_DEPTH
89 stack = traceback.StackSummary.extract(traceback.walk_stack(f),
90 limit=limit,
91 lookup_lines=False)
92 stack.reverse()
93 return stack
94
95
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070096class Handle:
97 """Object returned by callback registration methods."""
98
Victor Stinner80f53aa2014-06-27 13:52:20 +020099 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +0200100 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -0500101
Yury Selivanov569efa22014-02-18 18:02:19 -0500102 def __init__(self, callback, args, loop):
Yury Selivanov569efa22014-02-18 18:02:19 -0500103 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700104 self._callback = callback
105 self._args = args
106 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +0200107 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +0200108 if self._loop.get_debug():
Antoine Pitrou921e9432017-11-07 17:23:29 +0100109 self._source_traceback = extract_stack(sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +0200110 else:
111 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700112
Victor Stinner1b38bc62014-09-17 23:24:13 +0200113 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +0200114 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700115 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +0200116 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +0200117 if self._callback is not None:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700118 info.append(_format_callback_source(self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +0200119 if self._source_traceback:
120 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -0500121 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200122 return info
123
124 def __repr__(self):
125 if self._repr is not None:
126 return self._repr
127 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -0500128 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700129
130 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400131 if not self._cancelled:
132 self._cancelled = True
133 if self._loop.get_debug():
134 # Keep a representation in debug mode to keep callback and
135 # parameters. For example, to log the warning
136 # "Executing <Handle...> took 2.5 second"
137 self._repr = repr(self)
138 self._callback = None
139 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700140
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +0300141 def cancelled(self):
142 return self._cancelled
143
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700144 def _run(self):
145 try:
146 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -0500147 except Exception as exc:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700148 cb = _format_callback_source(self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -0500149 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +0200150 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -0500151 'message': msg,
152 'exception': exc,
153 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +0200154 }
155 if self._source_traceback:
156 context['source_traceback'] = self._source_traceback
157 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700158 self = None # Needed to break cycles when an exception occurs.
159
160
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700161class TimerHandle(Handle):
162 """Object returned by timed callback registration methods."""
163
Yury Selivanov592ada92014-09-25 12:07:56 -0400164 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500165
Yury Selivanov569efa22014-02-18 18:02:19 -0500166 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700167 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -0500168 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200169 if self._source_traceback:
170 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700171 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400172 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700173
Victor Stinner1b38bc62014-09-17 23:24:13 +0200174 def _repr_info(self):
175 info = super()._repr_info()
176 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500177 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200178 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700179
180 def __hash__(self):
181 return hash(self._when)
182
183 def __lt__(self, other):
184 return self._when < other._when
185
186 def __le__(self, other):
187 if self._when < other._when:
188 return True
189 return self.__eq__(other)
190
191 def __gt__(self, other):
192 return self._when > other._when
193
194 def __ge__(self, other):
195 if self._when > other._when:
196 return True
197 return self.__eq__(other)
198
199 def __eq__(self, other):
200 if isinstance(other, TimerHandle):
201 return (self._when == other._when and
202 self._callback == other._callback and
203 self._args == other._args and
204 self._cancelled == other._cancelled)
205 return NotImplemented
206
207 def __ne__(self, other):
208 equal = self.__eq__(other)
209 return NotImplemented if equal is NotImplemented else not equal
210
Yury Selivanov592ada92014-09-25 12:07:56 -0400211 def cancel(self):
212 if not self._cancelled:
213 self._loop._timer_handle_cancelled(self)
214 super().cancel()
215
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700216
217class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100218 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700219
220 def close(self):
221 """Stop serving. This leaves existing connections open."""
222 return NotImplemented
223
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200224 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700225 """Coroutine to wait until service is closed."""
226 return NotImplemented
227
228
229class AbstractEventLoop:
230 """Abstract event loop."""
231
232 # Running and stopping the event loop.
233
234 def run_forever(self):
235 """Run the event loop until stop() is called."""
236 raise NotImplementedError
237
238 def run_until_complete(self, future):
239 """Run the event loop until a Future is done.
240
241 Return the Future's result, or raise its exception.
242 """
243 raise NotImplementedError
244
245 def stop(self):
246 """Stop the event loop as soon as reasonable.
247
248 Exactly how soon that is may depend on the implementation, but
249 no more I/O callbacks should be scheduled.
250 """
251 raise NotImplementedError
252
253 def is_running(self):
254 """Return whether the event loop is currently running."""
255 raise NotImplementedError
256
Victor Stinner896a25a2014-07-08 11:29:25 +0200257 def is_closed(self):
258 """Returns True if the event loop was closed."""
259 raise NotImplementedError
260
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700261 def close(self):
262 """Close the loop.
263
264 The loop should not be running.
265
266 This is idempotent and irreversible.
267
268 No other methods should be called after this one.
269 """
270 raise NotImplementedError
271
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200272 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400273 """Shutdown all active asynchronous generators."""
274 raise NotImplementedError
275
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700276 # Methods scheduling callbacks. All these return Handles.
277
Yury Selivanov592ada92014-09-25 12:07:56 -0400278 def _timer_handle_cancelled(self, handle):
279 """Notification that a TimerHandle has been cancelled."""
280 raise NotImplementedError
281
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700282 def call_soon(self, callback, *args):
283 return self.call_later(0, callback, *args)
284
285 def call_later(self, delay, callback, *args):
286 raise NotImplementedError
287
288 def call_at(self, when, callback, *args):
289 raise NotImplementedError
290
291 def time(self):
292 raise NotImplementedError
293
Yury Selivanov7661db62016-05-16 15:38:39 -0400294 def create_future(self):
295 raise NotImplementedError
296
Victor Stinner896a25a2014-07-08 11:29:25 +0200297 # Method scheduling a coroutine object: create a task.
298
299 def create_task(self, coro):
300 raise NotImplementedError
301
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700302 # Methods for interacting with threads.
303
304 def call_soon_threadsafe(self, callback, *args):
305 raise NotImplementedError
306
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200307 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700308 raise NotImplementedError
309
310 def set_default_executor(self, executor):
311 raise NotImplementedError
312
313 # Network I/O methods returning Futures.
314
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200315 async def getaddrinfo(self, host, port, *,
316 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700317 raise NotImplementedError
318
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200319 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700320 raise NotImplementedError
321
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200322 async def create_connection(self, protocol_factory, host=None, port=None,
323 *, ssl=None, family=0, proto=0,
324 flags=0, sock=None, local_addr=None,
325 server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700326 raise NotImplementedError
327
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200328 async def create_server(self, protocol_factory, host=None, port=None,
329 *, family=socket.AF_UNSPEC,
330 flags=socket.AI_PASSIVE, sock=None, backlog=100,
331 ssl=None, reuse_address=None, reuse_port=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700332 """A coroutine which creates a TCP server bound to host and port.
333
334 The return value is a Server object which can be used to stop
335 the service.
336
337 If host is an empty string or None all interfaces are assumed
338 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500339 one for IPv4 and another one for IPv6). The host parameter can also be
340 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700341
342 family can be set to either AF_INET or AF_INET6 to force the
343 socket to use IPv4 or IPv6. If not set it will be determined
344 from host (defaults to AF_UNSPEC).
345
346 flags is a bitmask for getaddrinfo().
347
348 sock can optionally be specified in order to use a preexisting
349 socket object.
350
351 backlog is the maximum number of queued connections passed to
352 listen() (defaults to 100).
353
354 ssl can be set to an SSLContext to enable SSL over the
355 accepted connections.
356
357 reuse_address tells the kernel to reuse a local socket in
358 TIME_WAIT state, without waiting for its natural timeout to
359 expire. If not specified will automatically be set to True on
360 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700361
362 reuse_port tells the kernel to allow this endpoint to be bound to
363 the same port as other existing endpoints are bound to, so long as
364 they all set this flag when being created. This option is not
365 supported on Windows.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700366 """
367 raise NotImplementedError
368
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200369 async def create_unix_connection(self, protocol_factory, path=None, *,
370 ssl=None, sock=None,
371 server_hostname=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500372 raise NotImplementedError
373
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200374 async def create_unix_server(self, protocol_factory, path=None, *,
375 sock=None, backlog=100, ssl=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500376 """A coroutine which creates a UNIX Domain Socket server.
377
Yury Selivanovdec1a452014-02-18 22:27:48 -0500378 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500379 the service.
380
381 path is a str, representing a file systsem path to bind the
382 server socket to.
383
384 sock can optionally be specified in order to use a preexisting
385 socket object.
386
387 backlog is the maximum number of queued connections passed to
388 listen() (defaults to 100).
389
390 ssl can be set to an SSLContext to enable SSL over the
391 accepted connections.
392 """
393 raise NotImplementedError
394
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200395 async def create_datagram_endpoint(self, protocol_factory,
396 local_addr=None, remote_addr=None, *,
397 family=0, proto=0, flags=0,
398 reuse_address=None, reuse_port=None,
399 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700400 """A coroutine which creates a datagram endpoint.
401
402 This method will try to establish the endpoint in the background.
403 When successful, the coroutine returns a (transport, protocol) pair.
404
405 protocol_factory must be a callable returning a protocol instance.
406
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100407 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
408 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700409
410 reuse_address tells the kernel to reuse a local socket in
411 TIME_WAIT state, without waiting for its natural timeout to
412 expire. If not specified it will automatically be set to True on
413 UNIX.
414
415 reuse_port tells the kernel to allow this endpoint to be bound to
416 the same port as other existing endpoints are bound to, so long as
417 they all set this flag when being created. This option is not
418 supported on Windows and some UNIX's. If the
419 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
420 capability is unsupported.
421
422 allow_broadcast tells the kernel to allow this endpoint to send
423 messages to the broadcast address.
424
425 sock can optionally be specified in order to use a preexisting
426 socket object.
427 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700428 raise NotImplementedError
429
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700430 # Pipes and subprocesses.
431
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200432 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200433 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700434
435 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200436 pipe is a file-like object.
437 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800438 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700439 # The reason to accept file-like object instead of just file descriptor
440 # is: we need to own pipe and close it at transport finishing
441 # Can got complicated errors if pass f.fileno(),
442 # close fd in pipe transport then close f and vise versa.
443 raise NotImplementedError
444
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200445 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500446 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447
448 protocol_factory should instantiate object with BaseProtocol interface.
449 Pipe is file-like object already switched to nonblocking.
450 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800451 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700452 # The reason to accept file-like object instead of just file descriptor
453 # is: we need to own pipe and close it at transport finishing
454 # Can got complicated errors if pass f.fileno(),
455 # close fd in pipe transport then close f and vise versa.
456 raise NotImplementedError
457
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200458 async def subprocess_shell(self, protocol_factory, cmd, *,
459 stdin=subprocess.PIPE,
460 stdout=subprocess.PIPE,
461 stderr=subprocess.PIPE,
462 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700463 raise NotImplementedError
464
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200465 async def subprocess_exec(self, protocol_factory, *args,
466 stdin=subprocess.PIPE,
467 stdout=subprocess.PIPE,
468 stderr=subprocess.PIPE,
469 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700470 raise NotImplementedError
471
472 # Ready-based callback registration methods.
473 # The add_*() methods return None.
474 # The remove_*() methods return True if something was removed,
475 # False if there was nothing to delete.
476
477 def add_reader(self, fd, callback, *args):
478 raise NotImplementedError
479
480 def remove_reader(self, fd):
481 raise NotImplementedError
482
483 def add_writer(self, fd, callback, *args):
484 raise NotImplementedError
485
486 def remove_writer(self, fd):
487 raise NotImplementedError
488
489 # Completion based I/O methods returning Futures.
490
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200491 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700492 raise NotImplementedError
493
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200494 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200495 raise NotImplementedError
496
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200497 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700498 raise NotImplementedError
499
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200500 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700501 raise NotImplementedError
502
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200503 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504 raise NotImplementedError
505
506 # Signal handling.
507
508 def add_signal_handler(self, sig, callback, *args):
509 raise NotImplementedError
510
511 def remove_signal_handler(self, sig):
512 raise NotImplementedError
513
Yury Selivanov740169c2015-05-11 14:23:38 -0400514 # Task factory.
515
516 def set_task_factory(self, factory):
517 raise NotImplementedError
518
519 def get_task_factory(self):
520 raise NotImplementedError
521
Yury Selivanov569efa22014-02-18 18:02:19 -0500522 # Error handlers.
523
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400524 def get_exception_handler(self):
525 raise NotImplementedError
526
Yury Selivanov569efa22014-02-18 18:02:19 -0500527 def set_exception_handler(self, handler):
528 raise NotImplementedError
529
530 def default_exception_handler(self, context):
531 raise NotImplementedError
532
533 def call_exception_handler(self, context):
534 raise NotImplementedError
535
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100536 # Debug flag management.
537
538 def get_debug(self):
539 raise NotImplementedError
540
541 def set_debug(self, enabled):
542 raise NotImplementedError
543
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544
545class AbstractEventLoopPolicy:
546 """Abstract policy for accessing the event loop."""
547
548 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200549 """Get the event loop for the current context.
550
551 Returns an event loop object implementing the BaseEventLoop interface,
552 or raises an exception in case no event loop has been set for the
553 current context and the current policy does not specify to create one.
554
555 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700556 raise NotImplementedError
557
558 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200559 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560 raise NotImplementedError
561
562 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200563 """Create and return a new event loop object according to this
564 policy's rules. If there's need to set this loop as the event loop for
565 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566 raise NotImplementedError
567
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800568 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700569
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800570 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200571 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800572 raise NotImplementedError
573
574 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200575 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800576 raise NotImplementedError
577
578
579class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700580 """Default policy implementation for accessing the event loop.
581
582 In this policy, each thread has its own event loop. However, we
583 only automatically create an event loop by default for the main
584 thread; other threads by default have no event loop.
585
586 Other policies may have different rules (e.g. a single global
587 event loop, or automatically creating an event loop per thread, or
588 using some other notion of context to which an event loop is
589 associated).
590 """
591
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800592 _loop_factory = None
593
594 class _Local(threading.local):
595 _loop = None
596 _set_called = False
597
598 def __init__(self):
599 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600
601 def get_event_loop(self):
602 """Get the event loop.
603
604 This may be None or an instance of EventLoop.
605 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800606 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500607 not self._local._set_called and
608 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800609 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500610
Victor Stinner3a1c7382014-12-18 01:20:10 +0100611 if self._local._loop is None:
612 raise RuntimeError('There is no current event loop in thread %r.'
613 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500614
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800615 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700616
617 def set_event_loop(self, loop):
618 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800619 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700620 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800621 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700622
623 def new_event_loop(self):
624 """Create a new event loop.
625
626 You must call set_event_loop() to make this the current event
627 loop.
628 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800629 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630
631
632# Event loop policy. The policy itself is always global, even if the
633# policy's rules say that there is an event loop per thread (or other
634# notion of context). The default policy is installed by the first
635# call to get_event_loop_policy().
636_event_loop_policy = None
637
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800638# Lock for protecting the on-the-fly creation of the event loop policy.
639_lock = threading.Lock()
640
641
Yury Selivanov600a3492016-11-04 14:29:28 -0400642# A TLS for the running event loop, used by _get_running_loop.
643class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700644 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500645
646
Yury Selivanov600a3492016-11-04 14:29:28 -0400647_running_loop = _RunningLoop()
648
649
Yury Selivanovabae67e2017-12-11 10:07:44 -0500650def get_running_loop():
651 """Return the running event loop. Raise a RuntimeError if there is none.
652
653 This function is thread-specific.
654 """
655 loop = _get_running_loop()
656 if loop is None:
657 raise RuntimeError('no running event loop')
658 return loop
659
660
Yury Selivanov600a3492016-11-04 14:29:28 -0400661def _get_running_loop():
662 """Return the running event loop or None.
663
664 This is a low-level function intended to be used by event loops.
665 This function is thread-specific.
666 """
jimmylai80bbe6a72017-09-05 17:36:59 -0700667 running_loop, pid = _running_loop.loop_pid
668 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500669 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400670
671
672def _set_running_loop(loop):
673 """Set the running event loop.
674
675 This is a low-level function intended to be used by event loops.
676 This function is thread-specific.
677 """
jimmylai80bbe6a72017-09-05 17:36:59 -0700678 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400679
680
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800681def _init_event_loop_policy():
682 global _event_loop_policy
683 with _lock:
684 if _event_loop_policy is None: # pragma: no branch
685 from . import DefaultEventLoopPolicy
686 _event_loop_policy = DefaultEventLoopPolicy()
687
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700688
689def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200690 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700691 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800692 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700693 return _event_loop_policy
694
695
696def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200697 """Set the current event loop policy.
698
699 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700700 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700701 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
702 _event_loop_policy = policy
703
704
705def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400706 """Return an asyncio event loop.
707
708 When called from a coroutine or a callback (e.g. scheduled with call_soon
709 or similar API), this function will always return the running event loop.
710
711 If there is no running event loop set, the function will return
712 the result of `get_event_loop_policy().get_event_loop()` call.
713 """
714 current_loop = _get_running_loop()
715 if current_loop is not None:
716 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700717 return get_event_loop_policy().get_event_loop()
718
719
720def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200721 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700722 get_event_loop_policy().set_event_loop(loop)
723
724
725def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200726 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700727 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800728
729
730def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200731 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800732 return get_event_loop_policy().get_child_watcher()
733
734
735def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200736 """Equivalent to calling
737 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800738 return get_event_loop_policy().set_child_watcher(watcher)