blob: 5c68d4cb97d8d6778231f737d90231f1d7715033 [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',
Andrew Svetlov7464e872018-01-19 20:04:29 +02006 'Handle', 'TimerHandle', 'SendfileNotAvailableError',
Yury Selivanov6370f342017-12-10 18:36:12 -05007 '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
Yury Selivanovf23746a2018-01-22 19:11:18 -050014import contextvars
Yury Selivanovba7e1f92017-03-02 20:07:11 -050015import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070016import socket
Victor Stinner313a9802014-07-29 12:58:23 +020017import subprocess
Victor Stinner307bccc2014-06-12 18:39:26 +020018import sys
Victor Stinner313a9802014-07-29 12:58:23 +020019import threading
Victor Stinner307bccc2014-06-12 18:39:26 +020020
Andrew Svetlovf74ef452017-12-15 07:04:38 +020021from . import format_helpers
Antoine Pitrou921e9432017-11-07 17:23:29 +010022
23
Andrew Svetlov7464e872018-01-19 20:04:29 +020024class SendfileNotAvailableError(RuntimeError):
25 """Sendfile syscall is not available.
26
27 Raised if OS does not support senfile syscall for given socket or
28 file type.
29 """
30
31
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032class Handle:
33 """Object returned by callback registration methods."""
34
Victor Stinner80f53aa2014-06-27 13:52:20 +020035 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Yury Selivanovf23746a2018-01-22 19:11:18 -050036 '_source_traceback', '_repr', '__weakref__',
37 '_context')
Yury Selivanovb1317782014-02-12 17:01:52 -050038
Yury Selivanovf23746a2018-01-22 19:11:18 -050039 def __init__(self, callback, args, loop, context=None):
40 if context is None:
41 context = contextvars.copy_context()
42 self._context = context
Yury Selivanov569efa22014-02-18 18:02:19 -050043 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044 self._callback = callback
45 self._args = args
46 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020047 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020048 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020049 self._source_traceback = format_helpers.extract_stack(
50 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020051 else:
52 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070053
Victor Stinner1b38bc62014-09-17 23:24:13 +020054 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020055 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070056 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020057 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020058 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020059 info.append(format_helpers._format_callback_source(
60 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020061 if self._source_traceback:
62 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050063 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020064 return info
65
66 def __repr__(self):
67 if self._repr is not None:
68 return self._repr
69 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050070 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070071
72 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040073 if not self._cancelled:
74 self._cancelled = True
75 if self._loop.get_debug():
76 # Keep a representation in debug mode to keep callback and
77 # parameters. For example, to log the warning
78 # "Executing <Handle...> took 2.5 second"
79 self._repr = repr(self)
80 self._callback = None
81 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070082
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030083 def cancelled(self):
84 return self._cancelled
85
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086 def _run(self):
87 try:
Yury Selivanovf23746a2018-01-22 19:11:18 -050088 self._context.run(self._callback, *self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050089 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020090 cb = format_helpers._format_callback_source(
91 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050092 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020093 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050094 'message': msg,
95 'exception': exc,
96 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020097 }
98 if self._source_traceback:
99 context['source_traceback'] = self._source_traceback
100 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700101 self = None # Needed to break cycles when an exception occurs.
102
103
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700104class TimerHandle(Handle):
105 """Object returned by timed callback registration methods."""
106
Yury Selivanov592ada92014-09-25 12:07:56 -0400107 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500108
Yury Selivanovf23746a2018-01-22 19:11:18 -0500109 def __init__(self, when, callback, args, loop, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700110 assert when is not None
Yury Selivanovf23746a2018-01-22 19:11:18 -0500111 super().__init__(callback, args, loop, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200112 if self._source_traceback:
113 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700114 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400115 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700116
Victor Stinner1b38bc62014-09-17 23:24:13 +0200117 def _repr_info(self):
118 info = super()._repr_info()
119 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500120 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200121 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700122
123 def __hash__(self):
124 return hash(self._when)
125
126 def __lt__(self, other):
127 return self._when < other._when
128
129 def __le__(self, other):
130 if self._when < other._when:
131 return True
132 return self.__eq__(other)
133
134 def __gt__(self, other):
135 return self._when > other._when
136
137 def __ge__(self, other):
138 if self._when > other._when:
139 return True
140 return self.__eq__(other)
141
142 def __eq__(self, other):
143 if isinstance(other, TimerHandle):
144 return (self._when == other._when and
145 self._callback == other._callback and
146 self._args == other._args and
147 self._cancelled == other._cancelled)
148 return NotImplemented
149
150 def __ne__(self, other):
151 equal = self.__eq__(other)
152 return NotImplemented if equal is NotImplemented else not equal
153
Yury Selivanov592ada92014-09-25 12:07:56 -0400154 def cancel(self):
155 if not self._cancelled:
156 self._loop._timer_handle_cancelled(self)
157 super().cancel()
158
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700159
160class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100161 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162
163 def close(self):
164 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200165 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700166
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200167 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700168 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200169 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530171 def get_loop(self):
172 """ Get the event loop the Server object is attached to."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200173 raise NotImplementedError
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530174
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700175
176class AbstractEventLoop:
177 """Abstract event loop."""
178
179 # Running and stopping the event loop.
180
181 def run_forever(self):
182 """Run the event loop until stop() is called."""
183 raise NotImplementedError
184
185 def run_until_complete(self, future):
186 """Run the event loop until a Future is done.
187
188 Return the Future's result, or raise its exception.
189 """
190 raise NotImplementedError
191
192 def stop(self):
193 """Stop the event loop as soon as reasonable.
194
195 Exactly how soon that is may depend on the implementation, but
196 no more I/O callbacks should be scheduled.
197 """
198 raise NotImplementedError
199
200 def is_running(self):
201 """Return whether the event loop is currently running."""
202 raise NotImplementedError
203
Victor Stinner896a25a2014-07-08 11:29:25 +0200204 def is_closed(self):
205 """Returns True if the event loop was closed."""
206 raise NotImplementedError
207
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700208 def close(self):
209 """Close the loop.
210
211 The loop should not be running.
212
213 This is idempotent and irreversible.
214
215 No other methods should be called after this one.
216 """
217 raise NotImplementedError
218
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200219 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400220 """Shutdown all active asynchronous generators."""
221 raise NotImplementedError
222
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700223 # Methods scheduling callbacks. All these return Handles.
224
Yury Selivanov592ada92014-09-25 12:07:56 -0400225 def _timer_handle_cancelled(self, handle):
226 """Notification that a TimerHandle has been cancelled."""
227 raise NotImplementedError
228
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700229 def call_soon(self, callback, *args):
230 return self.call_later(0, callback, *args)
231
232 def call_later(self, delay, callback, *args):
233 raise NotImplementedError
234
235 def call_at(self, when, callback, *args):
236 raise NotImplementedError
237
238 def time(self):
239 raise NotImplementedError
240
Yury Selivanov7661db62016-05-16 15:38:39 -0400241 def create_future(self):
242 raise NotImplementedError
243
Victor Stinner896a25a2014-07-08 11:29:25 +0200244 # Method scheduling a coroutine object: create a task.
245
246 def create_task(self, coro):
247 raise NotImplementedError
248
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700249 # Methods for interacting with threads.
250
251 def call_soon_threadsafe(self, callback, *args):
252 raise NotImplementedError
253
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200254 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700255 raise NotImplementedError
256
257 def set_default_executor(self, executor):
258 raise NotImplementedError
259
260 # Network I/O methods returning Futures.
261
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200262 async def getaddrinfo(self, host, port, *,
263 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700264 raise NotImplementedError
265
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200266 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700267 raise NotImplementedError
268
Neil Aspinallf7686c12017-12-19 19:45:42 +0000269 async def create_connection(
270 self, protocol_factory, host=None, port=None,
271 *, ssl=None, family=0, proto=0,
272 flags=0, sock=None, local_addr=None,
273 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200274 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700275 raise NotImplementedError
276
Neil Aspinallf7686c12017-12-19 19:45:42 +0000277 async def create_server(
278 self, protocol_factory, host=None, port=None,
279 *, family=socket.AF_UNSPEC,
280 flags=socket.AI_PASSIVE, sock=None, backlog=100,
281 ssl=None, reuse_address=None, reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200282 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700283 """A coroutine which creates a TCP server bound to host and port.
284
285 The return value is a Server object which can be used to stop
286 the service.
287
288 If host is an empty string or None all interfaces are assumed
289 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500290 one for IPv4 and another one for IPv6). The host parameter can also be
291 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700292
293 family can be set to either AF_INET or AF_INET6 to force the
294 socket to use IPv4 or IPv6. If not set it will be determined
295 from host (defaults to AF_UNSPEC).
296
297 flags is a bitmask for getaddrinfo().
298
299 sock can optionally be specified in order to use a preexisting
300 socket object.
301
302 backlog is the maximum number of queued connections passed to
303 listen() (defaults to 100).
304
305 ssl can be set to an SSLContext to enable SSL over the
306 accepted connections.
307
308 reuse_address tells the kernel to reuse a local socket in
309 TIME_WAIT state, without waiting for its natural timeout to
310 expire. If not specified will automatically be set to True on
311 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700312
313 reuse_port tells the kernel to allow this endpoint to be bound to
314 the same port as other existing endpoints are bound to, so long as
315 they all set this flag when being created. This option is not
316 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000317
318 ssl_handshake_timeout is the time in seconds that an SSL server
319 will wait for completion of the SSL handshake before aborting the
320 connection. Default is 10s, longer timeouts may increase vulnerability
321 to DoS attacks (see https://support.f5.com/csp/article/K13834)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700322 """
323 raise NotImplementedError
324
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500325 async def start_tls(self, transport, protocol, sslcontext, *,
326 server_side=False,
327 server_hostname=None,
328 ssl_handshake_timeout=None):
329 """Upgrade a transport to TLS.
330
331 Return a new transport that *protocol* should start using
332 immediately.
333 """
334 raise NotImplementedError
335
Neil Aspinallf7686c12017-12-19 19:45:42 +0000336 async def create_unix_connection(
337 self, protocol_factory, path=None, *,
338 ssl=None, sock=None,
339 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200340 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500341 raise NotImplementedError
342
Neil Aspinallf7686c12017-12-19 19:45:42 +0000343 async def create_unix_server(
344 self, protocol_factory, path=None, *,
345 sock=None, backlog=100, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200346 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500347 """A coroutine which creates a UNIX Domain Socket server.
348
Yury Selivanovdec1a452014-02-18 22:27:48 -0500349 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500350 the service.
351
352 path is a str, representing a file systsem path to bind the
353 server socket to.
354
355 sock can optionally be specified in order to use a preexisting
356 socket object.
357
358 backlog is the maximum number of queued connections passed to
359 listen() (defaults to 100).
360
361 ssl can be set to an SSLContext to enable SSL over the
362 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000363
364 ssl_handshake_timeout is the time in seconds that an SSL server
365 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovb057c522014-02-18 12:15:06 -0500366 """
367 raise NotImplementedError
368
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200369 async def create_datagram_endpoint(self, protocol_factory,
370 local_addr=None, remote_addr=None, *,
371 family=0, proto=0, flags=0,
372 reuse_address=None, reuse_port=None,
373 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700374 """A coroutine which creates a datagram endpoint.
375
376 This method will try to establish the endpoint in the background.
377 When successful, the coroutine returns a (transport, protocol) pair.
378
379 protocol_factory must be a callable returning a protocol instance.
380
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100381 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
382 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700383
384 reuse_address tells the kernel to reuse a local socket in
385 TIME_WAIT state, without waiting for its natural timeout to
386 expire. If not specified it will automatically be set to True on
387 UNIX.
388
389 reuse_port tells the kernel to allow this endpoint to be bound to
390 the same port as other existing endpoints are bound to, so long as
391 they all set this flag when being created. This option is not
392 supported on Windows and some UNIX's. If the
393 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
394 capability is unsupported.
395
396 allow_broadcast tells the kernel to allow this endpoint to send
397 messages to the broadcast address.
398
399 sock can optionally be specified in order to use a preexisting
400 socket object.
401 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700402 raise NotImplementedError
403
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700404 # Pipes and subprocesses.
405
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200406 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200407 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408
409 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200410 pipe is a file-like object.
411 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800412 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700413 # The reason to accept file-like object instead of just file descriptor
414 # is: we need to own pipe and close it at transport finishing
415 # Can got complicated errors if pass f.fileno(),
416 # close fd in pipe transport then close f and vise versa.
417 raise NotImplementedError
418
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200419 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500420 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700421
422 protocol_factory should instantiate object with BaseProtocol interface.
423 Pipe is file-like object already switched to nonblocking.
424 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800425 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700426 # The reason to accept file-like object instead of just file descriptor
427 # is: we need to own pipe and close it at transport finishing
428 # Can got complicated errors if pass f.fileno(),
429 # close fd in pipe transport then close f and vise versa.
430 raise NotImplementedError
431
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200432 async def subprocess_shell(self, protocol_factory, cmd, *,
433 stdin=subprocess.PIPE,
434 stdout=subprocess.PIPE,
435 stderr=subprocess.PIPE,
436 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700437 raise NotImplementedError
438
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200439 async def subprocess_exec(self, protocol_factory, *args,
440 stdin=subprocess.PIPE,
441 stdout=subprocess.PIPE,
442 stderr=subprocess.PIPE,
443 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700444 raise NotImplementedError
445
446 # Ready-based callback registration methods.
447 # The add_*() methods return None.
448 # The remove_*() methods return True if something was removed,
449 # False if there was nothing to delete.
450
451 def add_reader(self, fd, callback, *args):
452 raise NotImplementedError
453
454 def remove_reader(self, fd):
455 raise NotImplementedError
456
457 def add_writer(self, fd, callback, *args):
458 raise NotImplementedError
459
460 def remove_writer(self, fd):
461 raise NotImplementedError
462
463 # Completion based I/O methods returning Futures.
464
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200465 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 raise NotImplementedError
467
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200468 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200469 raise NotImplementedError
470
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200471 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700472 raise NotImplementedError
473
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200474 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700475 raise NotImplementedError
476
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200477 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700478 raise NotImplementedError
479
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200480 async def sock_sendfile(self, sock, file, offset=0, count=None,
481 *, fallback=None):
482 raise NotImplementedError
483
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700484 # Signal handling.
485
486 def add_signal_handler(self, sig, callback, *args):
487 raise NotImplementedError
488
489 def remove_signal_handler(self, sig):
490 raise NotImplementedError
491
Yury Selivanov740169c2015-05-11 14:23:38 -0400492 # Task factory.
493
494 def set_task_factory(self, factory):
495 raise NotImplementedError
496
497 def get_task_factory(self):
498 raise NotImplementedError
499
Yury Selivanov569efa22014-02-18 18:02:19 -0500500 # Error handlers.
501
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400502 def get_exception_handler(self):
503 raise NotImplementedError
504
Yury Selivanov569efa22014-02-18 18:02:19 -0500505 def set_exception_handler(self, handler):
506 raise NotImplementedError
507
508 def default_exception_handler(self, context):
509 raise NotImplementedError
510
511 def call_exception_handler(self, context):
512 raise NotImplementedError
513
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100514 # Debug flag management.
515
516 def get_debug(self):
517 raise NotImplementedError
518
519 def set_debug(self, enabled):
520 raise NotImplementedError
521
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700522
523class AbstractEventLoopPolicy:
524 """Abstract policy for accessing the event loop."""
525
526 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200527 """Get the event loop for the current context.
528
529 Returns an event loop object implementing the BaseEventLoop interface,
530 or raises an exception in case no event loop has been set for the
531 current context and the current policy does not specify to create one.
532
533 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700534 raise NotImplementedError
535
536 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200537 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538 raise NotImplementedError
539
540 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200541 """Create and return a new event loop object according to this
542 policy's rules. If there's need to set this loop as the event loop for
543 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544 raise NotImplementedError
545
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800546 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700547
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800548 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200549 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800550 raise NotImplementedError
551
552 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200553 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800554 raise NotImplementedError
555
556
557class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700558 """Default policy implementation for accessing the event loop.
559
560 In this policy, each thread has its own event loop. However, we
561 only automatically create an event loop by default for the main
562 thread; other threads by default have no event loop.
563
564 Other policies may have different rules (e.g. a single global
565 event loop, or automatically creating an event loop per thread, or
566 using some other notion of context to which an event loop is
567 associated).
568 """
569
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800570 _loop_factory = None
571
572 class _Local(threading.local):
573 _loop = None
574 _set_called = False
575
576 def __init__(self):
577 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700578
579 def get_event_loop(self):
580 """Get the event loop.
581
582 This may be None or an instance of EventLoop.
583 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800584 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500585 not self._local._set_called and
586 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800587 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500588
Victor Stinner3a1c7382014-12-18 01:20:10 +0100589 if self._local._loop is None:
590 raise RuntimeError('There is no current event loop in thread %r.'
591 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500592
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800593 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700594
595 def set_event_loop(self, loop):
596 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800597 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800599 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600
601 def new_event_loop(self):
602 """Create a new event loop.
603
604 You must call set_event_loop() to make this the current event
605 loop.
606 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800607 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700608
609
610# Event loop policy. The policy itself is always global, even if the
611# policy's rules say that there is an event loop per thread (or other
612# notion of context). The default policy is installed by the first
613# call to get_event_loop_policy().
614_event_loop_policy = None
615
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800616# Lock for protecting the on-the-fly creation of the event loop policy.
617_lock = threading.Lock()
618
619
Yury Selivanov600a3492016-11-04 14:29:28 -0400620# A TLS for the running event loop, used by _get_running_loop.
621class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700622 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500623
624
Yury Selivanov600a3492016-11-04 14:29:28 -0400625_running_loop = _RunningLoop()
626
627
Yury Selivanovabae67e2017-12-11 10:07:44 -0500628def get_running_loop():
629 """Return the running event loop. Raise a RuntimeError if there is none.
630
631 This function is thread-specific.
632 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500633 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500634 loop = _get_running_loop()
635 if loop is None:
636 raise RuntimeError('no running event loop')
637 return loop
638
639
Yury Selivanov600a3492016-11-04 14:29:28 -0400640def _get_running_loop():
641 """Return the running event loop or None.
642
643 This is a low-level function intended to be used by event loops.
644 This function is thread-specific.
645 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500646 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700647 running_loop, pid = _running_loop.loop_pid
648 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500649 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400650
651
652def _set_running_loop(loop):
653 """Set the running event loop.
654
655 This is a low-level function intended to be used by event loops.
656 This function is thread-specific.
657 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500658 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700659 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400660
661
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800662def _init_event_loop_policy():
663 global _event_loop_policy
664 with _lock:
665 if _event_loop_policy is None: # pragma: no branch
666 from . import DefaultEventLoopPolicy
667 _event_loop_policy = DefaultEventLoopPolicy()
668
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700669
670def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200671 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700672 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800673 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700674 return _event_loop_policy
675
676
677def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200678 """Set the current event loop policy.
679
680 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700681 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700682 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
683 _event_loop_policy = policy
684
685
686def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400687 """Return an asyncio event loop.
688
689 When called from a coroutine or a callback (e.g. scheduled with call_soon
690 or similar API), this function will always return the running event loop.
691
692 If there is no running event loop set, the function will return
693 the result of `get_event_loop_policy().get_event_loop()` call.
694 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500695 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400696 current_loop = _get_running_loop()
697 if current_loop is not None:
698 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700699 return get_event_loop_policy().get_event_loop()
700
701
702def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200703 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700704 get_event_loop_policy().set_event_loop(loop)
705
706
707def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200708 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700709 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800710
711
712def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200713 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800714 return get_event_loop_policy().get_child_watcher()
715
716
717def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200718 """Equivalent to calling
719 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800720 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500721
722
723# Alias pure-Python implementations for testing purposes.
724_py__get_running_loop = _get_running_loop
725_py__set_running_loop = _set_running_loop
726_py_get_running_loop = get_running_loop
727_py_get_event_loop = get_event_loop
728
729
730try:
731 # get_event_loop() is one of the most frequently called
732 # functions in asyncio. Pure Python implementation is
733 # about 4 times slower than C-accelerated.
734 from _asyncio import (_get_running_loop, _set_running_loop,
735 get_running_loop, get_event_loop)
736except ImportError:
737 pass
738else:
739 # Alias C implementations for testing purposes.
740 _c__get_running_loop = _get_running_loop
741 _c__set_running_loop = _set_running_loop
742 _c_get_running_loop = get_running_loop
743 _c_get_event_loop = get_event_loop