blob: 3a5dbadbb105bfc88fc9b269b53793da98484628 [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
Neil Aspinallf7686c12017-12-19 19:45:42 +0000308 async def create_unix_connection(
309 self, protocol_factory, path=None, *,
310 ssl=None, sock=None,
311 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200312 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500313 raise NotImplementedError
314
Neil Aspinallf7686c12017-12-19 19:45:42 +0000315 async def create_unix_server(
316 self, protocol_factory, path=None, *,
317 sock=None, backlog=100, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200318 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500319 """A coroutine which creates a UNIX Domain Socket server.
320
Yury Selivanovdec1a452014-02-18 22:27:48 -0500321 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500322 the service.
323
324 path is a str, representing a file systsem path to bind the
325 server socket to.
326
327 sock can optionally be specified in order to use a preexisting
328 socket object.
329
330 backlog is the maximum number of queued connections passed to
331 listen() (defaults to 100).
332
333 ssl can be set to an SSLContext to enable SSL over the
334 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000335
336 ssl_handshake_timeout is the time in seconds that an SSL server
337 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovb057c522014-02-18 12:15:06 -0500338 """
339 raise NotImplementedError
340
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200341 async def create_datagram_endpoint(self, protocol_factory,
342 local_addr=None, remote_addr=None, *,
343 family=0, proto=0, flags=0,
344 reuse_address=None, reuse_port=None,
345 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700346 """A coroutine which creates a datagram endpoint.
347
348 This method will try to establish the endpoint in the background.
349 When successful, the coroutine returns a (transport, protocol) pair.
350
351 protocol_factory must be a callable returning a protocol instance.
352
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100353 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
354 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700355
356 reuse_address tells the kernel to reuse a local socket in
357 TIME_WAIT state, without waiting for its natural timeout to
358 expire. If not specified it will automatically be set to True on
359 UNIX.
360
361 reuse_port tells the kernel to allow this endpoint to be bound to
362 the same port as other existing endpoints are bound to, so long as
363 they all set this flag when being created. This option is not
364 supported on Windows and some UNIX's. If the
365 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
366 capability is unsupported.
367
368 allow_broadcast tells the kernel to allow this endpoint to send
369 messages to the broadcast address.
370
371 sock can optionally be specified in order to use a preexisting
372 socket object.
373 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700374 raise NotImplementedError
375
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700376 # Pipes and subprocesses.
377
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200378 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200379 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380
381 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200382 pipe is a file-like object.
383 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800384 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700385 # The reason to accept file-like object instead of just file descriptor
386 # is: we need to own pipe and close it at transport finishing
387 # Can got complicated errors if pass f.fileno(),
388 # close fd in pipe transport then close f and vise versa.
389 raise NotImplementedError
390
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200391 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500392 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700393
394 protocol_factory should instantiate object with BaseProtocol interface.
395 Pipe is file-like object already switched to nonblocking.
396 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800397 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700398 # The reason to accept file-like object instead of just file descriptor
399 # is: we need to own pipe and close it at transport finishing
400 # Can got complicated errors if pass f.fileno(),
401 # close fd in pipe transport then close f and vise versa.
402 raise NotImplementedError
403
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200404 async def subprocess_shell(self, protocol_factory, cmd, *,
405 stdin=subprocess.PIPE,
406 stdout=subprocess.PIPE,
407 stderr=subprocess.PIPE,
408 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700409 raise NotImplementedError
410
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200411 async def subprocess_exec(self, protocol_factory, *args,
412 stdin=subprocess.PIPE,
413 stdout=subprocess.PIPE,
414 stderr=subprocess.PIPE,
415 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700416 raise NotImplementedError
417
418 # Ready-based callback registration methods.
419 # The add_*() methods return None.
420 # The remove_*() methods return True if something was removed,
421 # False if there was nothing to delete.
422
423 def add_reader(self, fd, callback, *args):
424 raise NotImplementedError
425
426 def remove_reader(self, fd):
427 raise NotImplementedError
428
429 def add_writer(self, fd, callback, *args):
430 raise NotImplementedError
431
432 def remove_writer(self, fd):
433 raise NotImplementedError
434
435 # Completion based I/O methods returning Futures.
436
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200437 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700438 raise NotImplementedError
439
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200440 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200441 raise NotImplementedError
442
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200443 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700444 raise NotImplementedError
445
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200446 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700447 raise NotImplementedError
448
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200449 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700450 raise NotImplementedError
451
452 # Signal handling.
453
454 def add_signal_handler(self, sig, callback, *args):
455 raise NotImplementedError
456
457 def remove_signal_handler(self, sig):
458 raise NotImplementedError
459
Yury Selivanov740169c2015-05-11 14:23:38 -0400460 # Task factory.
461
462 def set_task_factory(self, factory):
463 raise NotImplementedError
464
465 def get_task_factory(self):
466 raise NotImplementedError
467
Yury Selivanov569efa22014-02-18 18:02:19 -0500468 # Error handlers.
469
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400470 def get_exception_handler(self):
471 raise NotImplementedError
472
Yury Selivanov569efa22014-02-18 18:02:19 -0500473 def set_exception_handler(self, handler):
474 raise NotImplementedError
475
476 def default_exception_handler(self, context):
477 raise NotImplementedError
478
479 def call_exception_handler(self, context):
480 raise NotImplementedError
481
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100482 # Debug flag management.
483
484 def get_debug(self):
485 raise NotImplementedError
486
487 def set_debug(self, enabled):
488 raise NotImplementedError
489
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490
491class AbstractEventLoopPolicy:
492 """Abstract policy for accessing the event loop."""
493
494 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200495 """Get the event loop for the current context.
496
497 Returns an event loop object implementing the BaseEventLoop interface,
498 or raises an exception in case no event loop has been set for the
499 current context and the current policy does not specify to create one.
500
501 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700502 raise NotImplementedError
503
504 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200505 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506 raise NotImplementedError
507
508 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200509 """Create and return a new event loop object according to this
510 policy's rules. If there's need to set this loop as the event loop for
511 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700512 raise NotImplementedError
513
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800514 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700515
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800516 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200517 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800518 raise NotImplementedError
519
520 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200521 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800522 raise NotImplementedError
523
524
525class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526 """Default policy implementation for accessing the event loop.
527
528 In this policy, each thread has its own event loop. However, we
529 only automatically create an event loop by default for the main
530 thread; other threads by default have no event loop.
531
532 Other policies may have different rules (e.g. a single global
533 event loop, or automatically creating an event loop per thread, or
534 using some other notion of context to which an event loop is
535 associated).
536 """
537
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800538 _loop_factory = None
539
540 class _Local(threading.local):
541 _loop = None
542 _set_called = False
543
544 def __init__(self):
545 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700546
547 def get_event_loop(self):
548 """Get the event loop.
549
550 This may be None or an instance of EventLoop.
551 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800552 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500553 not self._local._set_called and
554 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800555 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500556
Victor Stinner3a1c7382014-12-18 01:20:10 +0100557 if self._local._loop is None:
558 raise RuntimeError('There is no current event loop in thread %r.'
559 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500560
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800561 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562
563 def set_event_loop(self, loop):
564 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800565 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800567 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700568
569 def new_event_loop(self):
570 """Create a new event loop.
571
572 You must call set_event_loop() to make this the current event
573 loop.
574 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800575 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700576
577
578# Event loop policy. The policy itself is always global, even if the
579# policy's rules say that there is an event loop per thread (or other
580# notion of context). The default policy is installed by the first
581# call to get_event_loop_policy().
582_event_loop_policy = None
583
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800584# Lock for protecting the on-the-fly creation of the event loop policy.
585_lock = threading.Lock()
586
587
Yury Selivanov600a3492016-11-04 14:29:28 -0400588# A TLS for the running event loop, used by _get_running_loop.
589class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700590 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500591
592
Yury Selivanov600a3492016-11-04 14:29:28 -0400593_running_loop = _RunningLoop()
594
595
Yury Selivanovabae67e2017-12-11 10:07:44 -0500596def get_running_loop():
597 """Return the running event loop. Raise a RuntimeError if there is none.
598
599 This function is thread-specific.
600 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500601 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500602 loop = _get_running_loop()
603 if loop is None:
604 raise RuntimeError('no running event loop')
605 return loop
606
607
Yury Selivanov600a3492016-11-04 14:29:28 -0400608def _get_running_loop():
609 """Return the running event loop or None.
610
611 This is a low-level function intended to be used by event loops.
612 This function is thread-specific.
613 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500614 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700615 running_loop, pid = _running_loop.loop_pid
616 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500617 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400618
619
620def _set_running_loop(loop):
621 """Set the running event loop.
622
623 This is a low-level function intended to be used by event loops.
624 This function is thread-specific.
625 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500626 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700627 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400628
629
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800630def _init_event_loop_policy():
631 global _event_loop_policy
632 with _lock:
633 if _event_loop_policy is None: # pragma: no branch
634 from . import DefaultEventLoopPolicy
635 _event_loop_policy = DefaultEventLoopPolicy()
636
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637
638def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200639 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700640 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800641 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700642 return _event_loop_policy
643
644
645def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200646 """Set the current event loop policy.
647
648 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700649 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700650 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
651 _event_loop_policy = policy
652
653
654def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400655 """Return an asyncio event loop.
656
657 When called from a coroutine or a callback (e.g. scheduled with call_soon
658 or similar API), this function will always return the running event loop.
659
660 If there is no running event loop set, the function will return
661 the result of `get_event_loop_policy().get_event_loop()` call.
662 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500663 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400664 current_loop = _get_running_loop()
665 if current_loop is not None:
666 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700667 return get_event_loop_policy().get_event_loop()
668
669
670def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200671 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700672 get_event_loop_policy().set_event_loop(loop)
673
674
675def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200676 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700677 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800678
679
680def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200681 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800682 return get_event_loop_policy().get_child_watcher()
683
684
685def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200686 """Equivalent to calling
687 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800688 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500689
690
691# Alias pure-Python implementations for testing purposes.
692_py__get_running_loop = _get_running_loop
693_py__set_running_loop = _set_running_loop
694_py_get_running_loop = get_running_loop
695_py_get_event_loop = get_event_loop
696
697
698try:
699 # get_event_loop() is one of the most frequently called
700 # functions in asyncio. Pure Python implementation is
701 # about 4 times slower than C-accelerated.
702 from _asyncio import (_get_running_loop, _set_running_loop,
703 get_running_loop, get_event_loop)
704except ImportError:
705 pass
706else:
707 # Alias C implementations for testing purposes.
708 _c__get_running_loop = _get_running_loop
709 _c__set_running_loop = _set_running_loop
710 _c_get_running_loop = get_running_loop
711 _c_get_event_loop = get_event_loop