blob: 9496d5c765fafc0a4ae90cb8c2a9a51bd567f77f [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
Yury Selivanovba7e1f92017-03-02 20:07:11 -050014import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070015import socket
Victor Stinner313a9802014-07-29 12:58:23 +020016import subprocess
Victor Stinner307bccc2014-06-12 18:39:26 +020017import sys
Victor Stinner313a9802014-07-29 12:58:23 +020018import threading
Victor Stinner307bccc2014-06-12 18:39:26 +020019
Andrew Svetlovf74ef452017-12-15 07:04:38 +020020from . import format_helpers
Antoine Pitrou921e9432017-11-07 17:23:29 +010021
22
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023class Handle:
24 """Object returned by callback registration methods."""
25
Victor Stinner80f53aa2014-06-27 13:52:20 +020026 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020027 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050028
Yury Selivanov569efa22014-02-18 18:02:19 -050029 def __init__(self, callback, args, loop):
Yury Selivanov569efa22014-02-18 18:02:19 -050030 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031 self._callback = callback
32 self._args = args
33 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020034 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020035 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020036 self._source_traceback = format_helpers.extract_stack(
37 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020038 else:
39 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040
Victor Stinner1b38bc62014-09-17 23:24:13 +020041 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020042 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070043 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020044 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020045 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020046 info.append(format_helpers._format_callback_source(
47 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020048 if self._source_traceback:
49 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050050 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020051 return info
52
53 def __repr__(self):
54 if self._repr is not None:
55 return self._repr
56 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050057 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070058
59 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040060 if not self._cancelled:
61 self._cancelled = True
62 if self._loop.get_debug():
63 # Keep a representation in debug mode to keep callback and
64 # parameters. For example, to log the warning
65 # "Executing <Handle...> took 2.5 second"
66 self._repr = repr(self)
67 self._callback = None
68 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070069
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030070 def cancelled(self):
71 return self._cancelled
72
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070073 def _run(self):
74 try:
75 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050076 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020077 cb = format_helpers._format_callback_source(
78 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050079 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020080 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050081 'message': msg,
82 'exception': exc,
83 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020084 }
85 if self._source_traceback:
86 context['source_traceback'] = self._source_traceback
87 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070088 self = None # Needed to break cycles when an exception occurs.
89
90
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070091class TimerHandle(Handle):
92 """Object returned by timed callback registration methods."""
93
Yury Selivanov592ada92014-09-25 12:07:56 -040094 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -050095
Yury Selivanov569efa22014-02-18 18:02:19 -050096 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070097 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -050098 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +020099 if self._source_traceback:
100 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700101 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400102 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700103
Victor Stinner1b38bc62014-09-17 23:24:13 +0200104 def _repr_info(self):
105 info = super()._repr_info()
106 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500107 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200108 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700109
110 def __hash__(self):
111 return hash(self._when)
112
113 def __lt__(self, other):
114 return self._when < other._when
115
116 def __le__(self, other):
117 if self._when < other._when:
118 return True
119 return self.__eq__(other)
120
121 def __gt__(self, other):
122 return self._when > other._when
123
124 def __ge__(self, other):
125 if self._when > other._when:
126 return True
127 return self.__eq__(other)
128
129 def __eq__(self, other):
130 if isinstance(other, TimerHandle):
131 return (self._when == other._when and
132 self._callback == other._callback and
133 self._args == other._args and
134 self._cancelled == other._cancelled)
135 return NotImplemented
136
137 def __ne__(self, other):
138 equal = self.__eq__(other)
139 return NotImplemented if equal is NotImplemented else not equal
140
Yury Selivanov592ada92014-09-25 12:07:56 -0400141 def cancel(self):
142 if not self._cancelled:
143 self._loop._timer_handle_cancelled(self)
144 super().cancel()
145
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700146
147class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100148 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700149
150 def close(self):
151 """Stop serving. This leaves existing connections open."""
152 return NotImplemented
153
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200154 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700155 """Coroutine to wait until service is closed."""
156 return NotImplemented
157
158
159class AbstractEventLoop:
160 """Abstract event loop."""
161
162 # Running and stopping the event loop.
163
164 def run_forever(self):
165 """Run the event loop until stop() is called."""
166 raise NotImplementedError
167
168 def run_until_complete(self, future):
169 """Run the event loop until a Future is done.
170
171 Return the Future's result, or raise its exception.
172 """
173 raise NotImplementedError
174
175 def stop(self):
176 """Stop the event loop as soon as reasonable.
177
178 Exactly how soon that is may depend on the implementation, but
179 no more I/O callbacks should be scheduled.
180 """
181 raise NotImplementedError
182
183 def is_running(self):
184 """Return whether the event loop is currently running."""
185 raise NotImplementedError
186
Victor Stinner896a25a2014-07-08 11:29:25 +0200187 def is_closed(self):
188 """Returns True if the event loop was closed."""
189 raise NotImplementedError
190
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700191 def close(self):
192 """Close the loop.
193
194 The loop should not be running.
195
196 This is idempotent and irreversible.
197
198 No other methods should be called after this one.
199 """
200 raise NotImplementedError
201
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200202 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400203 """Shutdown all active asynchronous generators."""
204 raise NotImplementedError
205
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700206 # Methods scheduling callbacks. All these return Handles.
207
Yury Selivanov592ada92014-09-25 12:07:56 -0400208 def _timer_handle_cancelled(self, handle):
209 """Notification that a TimerHandle has been cancelled."""
210 raise NotImplementedError
211
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700212 def call_soon(self, callback, *args):
213 return self.call_later(0, callback, *args)
214
215 def call_later(self, delay, callback, *args):
216 raise NotImplementedError
217
218 def call_at(self, when, callback, *args):
219 raise NotImplementedError
220
221 def time(self):
222 raise NotImplementedError
223
Yury Selivanov7661db62016-05-16 15:38:39 -0400224 def create_future(self):
225 raise NotImplementedError
226
Victor Stinner896a25a2014-07-08 11:29:25 +0200227 # Method scheduling a coroutine object: create a task.
228
229 def create_task(self, coro):
230 raise NotImplementedError
231
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700232 # Methods for interacting with threads.
233
234 def call_soon_threadsafe(self, callback, *args):
235 raise NotImplementedError
236
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200237 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700238 raise NotImplementedError
239
240 def set_default_executor(self, executor):
241 raise NotImplementedError
242
243 # Network I/O methods returning Futures.
244
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200245 async def getaddrinfo(self, host, port, *,
246 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700247 raise NotImplementedError
248
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200249 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250 raise NotImplementedError
251
Neil Aspinallf7686c12017-12-19 19:45:42 +0000252 async def create_connection(
253 self, protocol_factory, host=None, port=None,
254 *, ssl=None, family=0, proto=0,
255 flags=0, sock=None, local_addr=None,
256 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200257 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700258 raise NotImplementedError
259
Neil Aspinallf7686c12017-12-19 19:45:42 +0000260 async def create_server(
261 self, protocol_factory, host=None, port=None,
262 *, family=socket.AF_UNSPEC,
263 flags=socket.AI_PASSIVE, sock=None, backlog=100,
264 ssl=None, reuse_address=None, reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200265 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700266 """A coroutine which creates a TCP server bound to host and port.
267
268 The return value is a Server object which can be used to stop
269 the service.
270
271 If host is an empty string or None all interfaces are assumed
272 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500273 one for IPv4 and another one for IPv6). The host parameter can also be
274 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700275
276 family can be set to either AF_INET or AF_INET6 to force the
277 socket to use IPv4 or IPv6. If not set it will be determined
278 from host (defaults to AF_UNSPEC).
279
280 flags is a bitmask for getaddrinfo().
281
282 sock can optionally be specified in order to use a preexisting
283 socket object.
284
285 backlog is the maximum number of queued connections passed to
286 listen() (defaults to 100).
287
288 ssl can be set to an SSLContext to enable SSL over the
289 accepted connections.
290
291 reuse_address tells the kernel to reuse a local socket in
292 TIME_WAIT state, without waiting for its natural timeout to
293 expire. If not specified will automatically be set to True on
294 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700295
296 reuse_port tells the kernel to allow this endpoint to be bound to
297 the same port as other existing endpoints are bound to, so long as
298 they all set this flag when being created. This option is not
299 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000300
301 ssl_handshake_timeout is the time in seconds that an SSL server
302 will wait for completion of the SSL handshake before aborting the
303 connection. Default is 10s, longer timeouts may increase vulnerability
304 to DoS attacks (see https://support.f5.com/csp/article/K13834)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700305 """
306 raise NotImplementedError
307
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500308 async def start_tls(self, transport, protocol, sslcontext, *,
309 server_side=False,
310 server_hostname=None,
311 ssl_handshake_timeout=None):
312 """Upgrade a transport to TLS.
313
314 Return a new transport that *protocol* should start using
315 immediately.
316 """
317 raise NotImplementedError
318
Neil Aspinallf7686c12017-12-19 19:45:42 +0000319 async def create_unix_connection(
320 self, protocol_factory, path=None, *,
321 ssl=None, sock=None,
322 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200323 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500324 raise NotImplementedError
325
Neil Aspinallf7686c12017-12-19 19:45:42 +0000326 async def create_unix_server(
327 self, protocol_factory, path=None, *,
328 sock=None, backlog=100, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200329 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500330 """A coroutine which creates a UNIX Domain Socket server.
331
Yury Selivanovdec1a452014-02-18 22:27:48 -0500332 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500333 the service.
334
335 path is a str, representing a file systsem path to bind the
336 server socket to.
337
338 sock can optionally be specified in order to use a preexisting
339 socket object.
340
341 backlog is the maximum number of queued connections passed to
342 listen() (defaults to 100).
343
344 ssl can be set to an SSLContext to enable SSL over the
345 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000346
347 ssl_handshake_timeout is the time in seconds that an SSL server
348 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovb057c522014-02-18 12:15:06 -0500349 """
350 raise NotImplementedError
351
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200352 async def create_datagram_endpoint(self, protocol_factory,
353 local_addr=None, remote_addr=None, *,
354 family=0, proto=0, flags=0,
355 reuse_address=None, reuse_port=None,
356 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700357 """A coroutine which creates a datagram endpoint.
358
359 This method will try to establish the endpoint in the background.
360 When successful, the coroutine returns a (transport, protocol) pair.
361
362 protocol_factory must be a callable returning a protocol instance.
363
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100364 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
365 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700366
367 reuse_address tells the kernel to reuse a local socket in
368 TIME_WAIT state, without waiting for its natural timeout to
369 expire. If not specified it will automatically be set to True on
370 UNIX.
371
372 reuse_port tells the kernel to allow this endpoint to be bound to
373 the same port as other existing endpoints are bound to, so long as
374 they all set this flag when being created. This option is not
375 supported on Windows and some UNIX's. If the
376 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
377 capability is unsupported.
378
379 allow_broadcast tells the kernel to allow this endpoint to send
380 messages to the broadcast address.
381
382 sock can optionally be specified in order to use a preexisting
383 socket object.
384 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700385 raise NotImplementedError
386
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700387 # Pipes and subprocesses.
388
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200389 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200390 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700391
392 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200393 pipe is a file-like object.
394 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800395 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700396 # The reason to accept file-like object instead of just file descriptor
397 # is: we need to own pipe and close it at transport finishing
398 # Can got complicated errors if pass f.fileno(),
399 # close fd in pipe transport then close f and vise versa.
400 raise NotImplementedError
401
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200402 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500403 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700404
405 protocol_factory should instantiate object with BaseProtocol interface.
406 Pipe is file-like object already switched to nonblocking.
407 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800408 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700409 # The reason to accept file-like object instead of just file descriptor
410 # is: we need to own pipe and close it at transport finishing
411 # Can got complicated errors if pass f.fileno(),
412 # close fd in pipe transport then close f and vise versa.
413 raise NotImplementedError
414
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200415 async def subprocess_shell(self, protocol_factory, cmd, *,
416 stdin=subprocess.PIPE,
417 stdout=subprocess.PIPE,
418 stderr=subprocess.PIPE,
419 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700420 raise NotImplementedError
421
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200422 async def subprocess_exec(self, protocol_factory, *args,
423 stdin=subprocess.PIPE,
424 stdout=subprocess.PIPE,
425 stderr=subprocess.PIPE,
426 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700427 raise NotImplementedError
428
429 # Ready-based callback registration methods.
430 # The add_*() methods return None.
431 # The remove_*() methods return True if something was removed,
432 # False if there was nothing to delete.
433
434 def add_reader(self, fd, callback, *args):
435 raise NotImplementedError
436
437 def remove_reader(self, fd):
438 raise NotImplementedError
439
440 def add_writer(self, fd, callback, *args):
441 raise NotImplementedError
442
443 def remove_writer(self, fd):
444 raise NotImplementedError
445
446 # Completion based I/O methods returning Futures.
447
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200448 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700449 raise NotImplementedError
450
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200451 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200452 raise NotImplementedError
453
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200454 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700455 raise NotImplementedError
456
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200457 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700458 raise NotImplementedError
459
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200460 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700461 raise NotImplementedError
462
463 # Signal handling.
464
465 def add_signal_handler(self, sig, callback, *args):
466 raise NotImplementedError
467
468 def remove_signal_handler(self, sig):
469 raise NotImplementedError
470
Yury Selivanov740169c2015-05-11 14:23:38 -0400471 # Task factory.
472
473 def set_task_factory(self, factory):
474 raise NotImplementedError
475
476 def get_task_factory(self):
477 raise NotImplementedError
478
Yury Selivanov569efa22014-02-18 18:02:19 -0500479 # Error handlers.
480
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400481 def get_exception_handler(self):
482 raise NotImplementedError
483
Yury Selivanov569efa22014-02-18 18:02:19 -0500484 def set_exception_handler(self, handler):
485 raise NotImplementedError
486
487 def default_exception_handler(self, context):
488 raise NotImplementedError
489
490 def call_exception_handler(self, context):
491 raise NotImplementedError
492
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100493 # Debug flag management.
494
495 def get_debug(self):
496 raise NotImplementedError
497
498 def set_debug(self, enabled):
499 raise NotImplementedError
500
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700501
502class AbstractEventLoopPolicy:
503 """Abstract policy for accessing the event loop."""
504
505 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200506 """Get the event loop for the current context.
507
508 Returns an event loop object implementing the BaseEventLoop interface,
509 or raises an exception in case no event loop has been set for the
510 current context and the current policy does not specify to create one.
511
512 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700513 raise NotImplementedError
514
515 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200516 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517 raise NotImplementedError
518
519 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200520 """Create and return a new event loop object according to this
521 policy's rules. If there's need to set this loop as the event loop for
522 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700523 raise NotImplementedError
524
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800525 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800527 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200528 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800529 raise NotImplementedError
530
531 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200532 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800533 raise NotImplementedError
534
535
536class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 """Default policy implementation for accessing the event loop.
538
539 In this policy, each thread has its own event loop. However, we
540 only automatically create an event loop by default for the main
541 thread; other threads by default have no event loop.
542
543 Other policies may have different rules (e.g. a single global
544 event loop, or automatically creating an event loop per thread, or
545 using some other notion of context to which an event loop is
546 associated).
547 """
548
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800549 _loop_factory = None
550
551 class _Local(threading.local):
552 _loop = None
553 _set_called = False
554
555 def __init__(self):
556 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557
558 def get_event_loop(self):
559 """Get the event loop.
560
561 This may be None or an instance of EventLoop.
562 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800563 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500564 not self._local._set_called and
565 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800566 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500567
Victor Stinner3a1c7382014-12-18 01:20:10 +0100568 if self._local._loop is None:
569 raise RuntimeError('There is no current event loop in thread %r.'
570 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500571
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800572 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573
574 def set_event_loop(self, loop):
575 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800576 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700577 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800578 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700579
580 def new_event_loop(self):
581 """Create a new event loop.
582
583 You must call set_event_loop() to make this the current event
584 loop.
585 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800586 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587
588
589# Event loop policy. The policy itself is always global, even if the
590# policy's rules say that there is an event loop per thread (or other
591# notion of context). The default policy is installed by the first
592# call to get_event_loop_policy().
593_event_loop_policy = None
594
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800595# Lock for protecting the on-the-fly creation of the event loop policy.
596_lock = threading.Lock()
597
598
Yury Selivanov600a3492016-11-04 14:29:28 -0400599# A TLS for the running event loop, used by _get_running_loop.
600class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700601 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500602
603
Yury Selivanov600a3492016-11-04 14:29:28 -0400604_running_loop = _RunningLoop()
605
606
Yury Selivanovabae67e2017-12-11 10:07:44 -0500607def get_running_loop():
608 """Return the running event loop. Raise a RuntimeError if there is none.
609
610 This function is thread-specific.
611 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500612 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500613 loop = _get_running_loop()
614 if loop is None:
615 raise RuntimeError('no running event loop')
616 return loop
617
618
Yury Selivanov600a3492016-11-04 14:29:28 -0400619def _get_running_loop():
620 """Return the running event loop or None.
621
622 This is a low-level function intended to be used by event loops.
623 This function is thread-specific.
624 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500625 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700626 running_loop, pid = _running_loop.loop_pid
627 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500628 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400629
630
631def _set_running_loop(loop):
632 """Set the running event loop.
633
634 This is a low-level function intended to be used by event loops.
635 This function is thread-specific.
636 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500637 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700638 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400639
640
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800641def _init_event_loop_policy():
642 global _event_loop_policy
643 with _lock:
644 if _event_loop_policy is None: # pragma: no branch
645 from . import DefaultEventLoopPolicy
646 _event_loop_policy = DefaultEventLoopPolicy()
647
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700648
649def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200650 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700651 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800652 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700653 return _event_loop_policy
654
655
656def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200657 """Set the current event loop policy.
658
659 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700660 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700661 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
662 _event_loop_policy = policy
663
664
665def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400666 """Return an asyncio event loop.
667
668 When called from a coroutine or a callback (e.g. scheduled with call_soon
669 or similar API), this function will always return the running event loop.
670
671 If there is no running event loop set, the function will return
672 the result of `get_event_loop_policy().get_event_loop()` call.
673 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500674 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400675 current_loop = _get_running_loop()
676 if current_loop is not None:
677 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700678 return get_event_loop_policy().get_event_loop()
679
680
681def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200682 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700683 get_event_loop_policy().set_event_loop(loop)
684
685
686def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200687 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700688 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800689
690
691def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200692 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800693 return get_event_loop_policy().get_child_watcher()
694
695
696def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200697 """Equivalent to calling
698 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800699 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500700
701
702# Alias pure-Python implementations for testing purposes.
703_py__get_running_loop = _get_running_loop
704_py__set_running_loop = _set_running_loop
705_py_get_running_loop = get_running_loop
706_py_get_event_loop = get_event_loop
707
708
709try:
710 # get_event_loop() is one of the most frequently called
711 # functions in asyncio. Pure Python implementation is
712 # about 4 times slower than C-accelerated.
713 from _asyncio import (_get_running_loop, _set_running_loop,
714 get_running_loop, get_event_loop)
715except ImportError:
716 pass
717else:
718 # Alias C implementations for testing purposes.
719 _c__get_running_loop = _get_running_loop
720 _c__set_running_loop = _set_running_loop
721 _c_get_running_loop = get_running_loop
722 _c_get_event_loop = get_event_loop