blob: d5254fa5e7e73edf66608ec52fd24ad03d97bee2 [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 Svetlov0baa72f2018-09-11 10:13:04 -07006 'Handle', 'TimerHandle',
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
Andrew Svetlov7464e872018-01-19 20:04:29 +020022
23
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070024class Handle:
25 """Object returned by callback registration methods."""
26
Victor Stinner80f53aa2014-06-27 13:52:20 +020027 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Yury Selivanovf23746a2018-01-22 19:11:18 -050028 '_source_traceback', '_repr', '__weakref__',
29 '_context')
Yury Selivanovb1317782014-02-12 17:01:52 -050030
Yury Selivanovf23746a2018-01-22 19:11:18 -050031 def __init__(self, callback, args, loop, context=None):
32 if context is None:
33 context = contextvars.copy_context()
34 self._context = context
Yury Selivanov569efa22014-02-18 18:02:19 -050035 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070036 self._callback = callback
37 self._args = args
38 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020039 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020040 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020041 self._source_traceback = format_helpers.extract_stack(
42 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020043 else:
44 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070045
Victor Stinner1b38bc62014-09-17 23:24:13 +020046 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020047 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070048 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020049 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020050 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020051 info.append(format_helpers._format_callback_source(
52 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020053 if self._source_traceback:
54 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050055 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020056 return info
57
58 def __repr__(self):
59 if self._repr is not None:
60 return self._repr
61 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050062 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070063
64 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040065 if not self._cancelled:
66 self._cancelled = True
67 if self._loop.get_debug():
68 # Keep a representation in debug mode to keep callback and
69 # parameters. For example, to log the warning
70 # "Executing <Handle...> took 2.5 second"
71 self._repr = repr(self)
72 self._callback = None
73 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070074
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030075 def cancelled(self):
76 return self._cancelled
77
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070078 def _run(self):
79 try:
Yury Selivanovf23746a2018-01-22 19:11:18 -050080 self._context.run(self._callback, *self._args)
Yury Selivanov431b5402019-05-27 14:45:12 +020081 except (SystemExit, KeyboardInterrupt):
82 raise
83 except BaseException as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020084 cb = format_helpers._format_callback_source(
85 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050086 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020087 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050088 'message': msg,
89 'exception': exc,
90 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020091 }
92 if self._source_traceback:
93 context['source_traceback'] = self._source_traceback
94 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070095 self = None # Needed to break cycles when an exception occurs.
96
97
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070098class TimerHandle(Handle):
99 """Object returned by timed callback registration methods."""
100
Yury Selivanov592ada92014-09-25 12:07:56 -0400101 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500102
Yury Selivanovf23746a2018-01-22 19:11:18 -0500103 def __init__(self, when, callback, args, loop, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700104 assert when is not None
Yury Selivanovf23746a2018-01-22 19:11:18 -0500105 super().__init__(callback, args, loop, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200106 if self._source_traceback:
107 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700108 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400109 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700110
Victor Stinner1b38bc62014-09-17 23:24:13 +0200111 def _repr_info(self):
112 info = super()._repr_info()
113 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500114 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200115 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700116
117 def __hash__(self):
118 return hash(self._when)
119
120 def __lt__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300121 if isinstance(other, TimerHandle):
122 return self._when < other._when
123 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700124
125 def __le__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300126 if isinstance(other, TimerHandle):
127 return self._when < other._when or self.__eq__(other)
128 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700129
130 def __gt__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300131 if isinstance(other, TimerHandle):
132 return self._when > other._when
133 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700134
135 def __ge__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300136 if isinstance(other, TimerHandle):
137 return self._when > other._when or self.__eq__(other)
138 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700139
140 def __eq__(self, other):
141 if isinstance(other, TimerHandle):
142 return (self._when == other._when and
143 self._callback == other._callback and
144 self._args == other._args and
145 self._cancelled == other._cancelled)
146 return NotImplemented
147
Yury Selivanov592ada92014-09-25 12:07:56 -0400148 def cancel(self):
149 if not self._cancelled:
150 self._loop._timer_handle_cancelled(self)
151 super().cancel()
152
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +0200153 def when(self):
154 """Return a scheduled callback time.
155
156 The time is an absolute timestamp, using the same time
157 reference as loop.time().
158 """
159 return self._when
160
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700161
162class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100163 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700164
165 def close(self):
166 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200167 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700168
Yury Selivanovc9070d02018-01-25 18:08:09 -0500169 def get_loop(self):
170 """Get the event loop the Server object is attached to."""
171 raise NotImplementedError
172
173 def is_serving(self):
174 """Return True if the server is accepting connections."""
175 raise NotImplementedError
176
177 async def start_serving(self):
178 """Start accepting connections.
179
180 This method is idempotent, so it can be called when
181 the server is already being serving.
182 """
183 raise NotImplementedError
184
185 async def serve_forever(self):
186 """Start accepting connections until the coroutine is cancelled.
187
188 The server is closed when the coroutine is cancelled.
189 """
190 raise NotImplementedError
191
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200192 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200194 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195
Yury Selivanovc9070d02018-01-25 18:08:09 -0500196 async def __aenter__(self):
197 return self
198
199 async def __aexit__(self, *exc):
200 self.close()
201 await self.wait_closed()
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530202
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700203
204class AbstractEventLoop:
205 """Abstract event loop."""
206
207 # Running and stopping the event loop.
208
209 def run_forever(self):
210 """Run the event loop until stop() is called."""
211 raise NotImplementedError
212
213 def run_until_complete(self, future):
214 """Run the event loop until a Future is done.
215
216 Return the Future's result, or raise its exception.
217 """
218 raise NotImplementedError
219
220 def stop(self):
221 """Stop the event loop as soon as reasonable.
222
223 Exactly how soon that is may depend on the implementation, but
224 no more I/O callbacks should be scheduled.
225 """
226 raise NotImplementedError
227
228 def is_running(self):
229 """Return whether the event loop is currently running."""
230 raise NotImplementedError
231
Victor Stinner896a25a2014-07-08 11:29:25 +0200232 def is_closed(self):
233 """Returns True if the event loop was closed."""
234 raise NotImplementedError
235
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700236 def close(self):
237 """Close the loop.
238
239 The loop should not be running.
240
241 This is idempotent and irreversible.
242
243 No other methods should be called after this one.
244 """
245 raise NotImplementedError
246
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200247 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400248 """Shutdown all active asynchronous generators."""
249 raise NotImplementedError
250
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400251 async def shutdown_default_executor(self):
252 """Schedule the shutdown of the default executor."""
253 raise NotImplementedError
254
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700255 # Methods scheduling callbacks. All these return Handles.
256
Yury Selivanov592ada92014-09-25 12:07:56 -0400257 def _timer_handle_cancelled(self, handle):
258 """Notification that a TimerHandle has been cancelled."""
259 raise NotImplementedError
260
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700261 def call_soon(self, callback, *args):
262 return self.call_later(0, callback, *args)
263
264 def call_later(self, delay, callback, *args):
265 raise NotImplementedError
266
267 def call_at(self, when, callback, *args):
268 raise NotImplementedError
269
270 def time(self):
271 raise NotImplementedError
272
Yury Selivanov7661db62016-05-16 15:38:39 -0400273 def create_future(self):
274 raise NotImplementedError
275
Victor Stinner896a25a2014-07-08 11:29:25 +0200276 # Method scheduling a coroutine object: create a task.
277
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300278 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200279 raise NotImplementedError
280
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700281 # Methods for interacting with threads.
282
283 def call_soon_threadsafe(self, callback, *args):
284 raise NotImplementedError
285
James Weaver29f84292020-08-17 15:19:46 +0100286 def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700287 raise NotImplementedError
288
289 def set_default_executor(self, executor):
290 raise NotImplementedError
291
292 # Network I/O methods returning Futures.
293
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200294 async def getaddrinfo(self, host, port, *,
295 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700296 raise NotImplementedError
297
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200298 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700299 raise NotImplementedError
300
Neil Aspinallf7686c12017-12-19 19:45:42 +0000301 async def create_connection(
302 self, protocol_factory, host=None, port=None,
303 *, ssl=None, family=0, proto=0,
304 flags=0, sock=None, local_addr=None,
305 server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800306 ssl_handshake_timeout=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300307 ssl_shutdown_timeout=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800308 happy_eyeballs_delay=None, interleave=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700309 raise NotImplementedError
310
Neil Aspinallf7686c12017-12-19 19:45:42 +0000311 async def create_server(
312 self, protocol_factory, host=None, port=None,
313 *, family=socket.AF_UNSPEC,
314 flags=socket.AI_PASSIVE, sock=None, backlog=100,
315 ssl=None, reuse_address=None, reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500316 ssl_handshake_timeout=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300317 ssl_shutdown_timeout=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500318 start_serving=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700319 """A coroutine which creates a TCP server bound to host and port.
320
321 The return value is a Server object which can be used to stop
322 the service.
323
324 If host is an empty string or None all interfaces are assumed
325 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500326 one for IPv4 and another one for IPv6). The host parameter can also be
327 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700328
329 family can be set to either AF_INET or AF_INET6 to force the
330 socket to use IPv4 or IPv6. If not set it will be determined
331 from host (defaults to AF_UNSPEC).
332
333 flags is a bitmask for getaddrinfo().
334
335 sock can optionally be specified in order to use a preexisting
336 socket object.
337
338 backlog is the maximum number of queued connections passed to
339 listen() (defaults to 100).
340
341 ssl can be set to an SSLContext to enable SSL over the
342 accepted connections.
343
344 reuse_address tells the kernel to reuse a local socket in
345 TIME_WAIT state, without waiting for its natural timeout to
346 expire. If not specified will automatically be set to True on
347 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700348
349 reuse_port tells the kernel to allow this endpoint to be bound to
350 the same port as other existing endpoints are bound to, so long as
351 they all set this flag when being created. This option is not
352 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000353
354 ssl_handshake_timeout is the time in seconds that an SSL server
355 will wait for completion of the SSL handshake before aborting the
Yury Selivanov96026432018-06-04 11:32:35 -0400356 connection. Default is 60s.
Yury Selivanovc9070d02018-01-25 18:08:09 -0500357
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300358 ssl_shutdown_timeout is the time in seconds that an SSL server
359 will wait for completion of the SSL shutdown procedure
360 before aborting the connection. Default is 30s.
361
Yury Selivanovc9070d02018-01-25 18:08:09 -0500362 start_serving set to True (default) causes the created server
363 to start accepting connections immediately. When set to False,
364 the user should await Server.start_serving() or Server.serve_forever()
365 to make the server to start accepting connections.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700366 """
367 raise NotImplementedError
368
Andrew Svetlov7c684072018-01-27 21:22:47 +0200369 async def sendfile(self, transport, file, offset=0, count=None,
370 *, fallback=True):
371 """Send a file through a transport.
372
373 Return an amount of sent bytes.
374 """
375 raise NotImplementedError
376
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500377 async def start_tls(self, transport, protocol, sslcontext, *,
378 server_side=False,
379 server_hostname=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300380 ssl_handshake_timeout=None,
381 ssl_shutdown_timeout=None):
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500382 """Upgrade a transport to TLS.
383
384 Return a new transport that *protocol* should start using
385 immediately.
386 """
387 raise NotImplementedError
388
Neil Aspinallf7686c12017-12-19 19:45:42 +0000389 async def create_unix_connection(
390 self, protocol_factory, path=None, *,
391 ssl=None, sock=None,
392 server_hostname=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300393 ssl_handshake_timeout=None,
394 ssl_shutdown_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500395 raise NotImplementedError
396
Neil Aspinallf7686c12017-12-19 19:45:42 +0000397 async def create_unix_server(
398 self, protocol_factory, path=None, *,
399 sock=None, backlog=100, ssl=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500400 ssl_handshake_timeout=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300401 ssl_shutdown_timeout=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500402 start_serving=True):
Yury Selivanovb057c522014-02-18 12:15:06 -0500403 """A coroutine which creates a UNIX Domain Socket server.
404
Yury Selivanovdec1a452014-02-18 22:27:48 -0500405 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500406 the service.
407
Galden02152b72020-04-14 08:04:32 +0800408 path is a str, representing a file system path to bind the
Yury Selivanovb057c522014-02-18 12:15:06 -0500409 server socket to.
410
411 sock can optionally be specified in order to use a preexisting
412 socket object.
413
414 backlog is the maximum number of queued connections passed to
415 listen() (defaults to 100).
416
417 ssl can be set to an SSLContext to enable SSL over the
418 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000419
420 ssl_handshake_timeout is the time in seconds that an SSL server
Yury Selivanov96026432018-06-04 11:32:35 -0400421 will wait for the SSL handshake to complete (defaults to 60s).
Yury Selivanovc9070d02018-01-25 18:08:09 -0500422
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300423 ssl_shutdown_timeout is the time in seconds that an SSL server
424 will wait for the SSL shutdown to finish (defaults to 30s).
425
Yury Selivanovc9070d02018-01-25 18:08:09 -0500426 start_serving set to True (default) causes the created server
427 to start accepting connections immediately. When set to False,
428 the user should await Server.start_serving() or Server.serve_forever()
429 to make the server to start accepting connections.
Yury Selivanovb057c522014-02-18 12:15:06 -0500430 """
431 raise NotImplementedError
432
Alex Grönholme3ef4d72020-11-26 12:09:12 +0200433 async def connect_accepted_socket(
434 self, protocol_factory, sock,
435 *, ssl=None,
Andrew Svetlov5fb06ed2021-05-03 00:34:15 +0300436 ssl_handshake_timeout=None,
437 ssl_shutdown_timeout=None):
Alex Grönholme3ef4d72020-11-26 12:09:12 +0200438 """Handle an accepted connection.
439
440 This is used by servers that accept connections outside of
441 asyncio, but use asyncio to handle connections.
442
443 This method is a coroutine. When completed, the coroutine
444 returns a (transport, protocol) pair.
445 """
446 raise NotImplementedError
447
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200448 async def create_datagram_endpoint(self, protocol_factory,
449 local_addr=None, remote_addr=None, *,
450 family=0, proto=0, flags=0,
451 reuse_address=None, reuse_port=None,
452 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700453 """A coroutine which creates a datagram endpoint.
454
455 This method will try to establish the endpoint in the background.
456 When successful, the coroutine returns a (transport, protocol) pair.
457
458 protocol_factory must be a callable returning a protocol instance.
459
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100460 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
461 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700462
463 reuse_address tells the kernel to reuse a local socket in
464 TIME_WAIT state, without waiting for its natural timeout to
465 expire. If not specified it will automatically be set to True on
466 UNIX.
467
468 reuse_port tells the kernel to allow this endpoint to be bound to
469 the same port as other existing endpoints are bound to, so long as
470 they all set this flag when being created. This option is not
471 supported on Windows and some UNIX's. If the
472 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
473 capability is unsupported.
474
475 allow_broadcast tells the kernel to allow this endpoint to send
476 messages to the broadcast address.
477
478 sock can optionally be specified in order to use a preexisting
479 socket object.
480 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700481 raise NotImplementedError
482
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700483 # Pipes and subprocesses.
484
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200485 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200486 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700487
488 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200489 pipe is a file-like object.
490 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800491 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700492 # The reason to accept file-like object instead of just file descriptor
493 # is: we need to own pipe and close it at transport finishing
494 # Can got complicated errors if pass f.fileno(),
495 # close fd in pipe transport then close f and vise versa.
496 raise NotImplementedError
497
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200498 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500499 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700500
501 protocol_factory should instantiate object with BaseProtocol interface.
502 Pipe is file-like object already switched to nonblocking.
503 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800504 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700505 # The reason to accept file-like object instead of just file descriptor
506 # is: we need to own pipe and close it at transport finishing
507 # Can got complicated errors if pass f.fileno(),
508 # close fd in pipe transport then close f and vise versa.
509 raise NotImplementedError
510
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200511 async def subprocess_shell(self, protocol_factory, cmd, *,
512 stdin=subprocess.PIPE,
513 stdout=subprocess.PIPE,
514 stderr=subprocess.PIPE,
515 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516 raise NotImplementedError
517
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200518 async def subprocess_exec(self, protocol_factory, *args,
519 stdin=subprocess.PIPE,
520 stdout=subprocess.PIPE,
521 stderr=subprocess.PIPE,
522 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700523 raise NotImplementedError
524
525 # Ready-based callback registration methods.
526 # The add_*() methods return None.
527 # The remove_*() methods return True if something was removed,
528 # False if there was nothing to delete.
529
530 def add_reader(self, fd, callback, *args):
531 raise NotImplementedError
532
533 def remove_reader(self, fd):
534 raise NotImplementedError
535
536 def add_writer(self, fd, callback, *args):
537 raise NotImplementedError
538
539 def remove_writer(self, fd):
540 raise NotImplementedError
541
542 # Completion based I/O methods returning Futures.
543
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200544 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700545 raise NotImplementedError
546
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200547 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200548 raise NotImplementedError
549
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200550 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 raise NotImplementedError
552
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200553 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700554 raise NotImplementedError
555
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200556 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557 raise NotImplementedError
558
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200559 async def sock_sendfile(self, sock, file, offset=0, count=None,
560 *, fallback=None):
561 raise NotImplementedError
562
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700563 # Signal handling.
564
565 def add_signal_handler(self, sig, callback, *args):
566 raise NotImplementedError
567
568 def remove_signal_handler(self, sig):
569 raise NotImplementedError
570
Yury Selivanov740169c2015-05-11 14:23:38 -0400571 # Task factory.
572
573 def set_task_factory(self, factory):
574 raise NotImplementedError
575
576 def get_task_factory(self):
577 raise NotImplementedError
578
Yury Selivanov569efa22014-02-18 18:02:19 -0500579 # Error handlers.
580
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400581 def get_exception_handler(self):
582 raise NotImplementedError
583
Yury Selivanov569efa22014-02-18 18:02:19 -0500584 def set_exception_handler(self, handler):
585 raise NotImplementedError
586
587 def default_exception_handler(self, context):
588 raise NotImplementedError
589
590 def call_exception_handler(self, context):
591 raise NotImplementedError
592
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100593 # Debug flag management.
594
595 def get_debug(self):
596 raise NotImplementedError
597
598 def set_debug(self, enabled):
599 raise NotImplementedError
600
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601
602class AbstractEventLoopPolicy:
603 """Abstract policy for accessing the event loop."""
604
605 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200606 """Get the event loop for the current context.
607
608 Returns an event loop object implementing the BaseEventLoop interface,
609 or raises an exception in case no event loop has been set for the
610 current context and the current policy does not specify to create one.
611
612 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700613 raise NotImplementedError
614
615 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200616 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700617 raise NotImplementedError
618
619 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200620 """Create and return a new event loop object according to this
621 policy's rules. If there's need to set this loop as the event loop for
622 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623 raise NotImplementedError
624
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800625 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700626
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800627 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200628 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800629 raise NotImplementedError
630
631 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200632 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800633 raise NotImplementedError
634
635
636class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637 """Default policy implementation for accessing the event loop.
638
639 In this policy, each thread has its own event loop. However, we
640 only automatically create an event loop by default for the main
641 thread; other threads by default have no event loop.
642
643 Other policies may have different rules (e.g. a single global
644 event loop, or automatically creating an event loop per thread, or
645 using some other notion of context to which an event loop is
646 associated).
647 """
648
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800649 _loop_factory = None
650
651 class _Local(threading.local):
652 _loop = None
653 _set_called = False
654
655 def __init__(self):
656 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657
658 def get_event_loop(self):
idomicb23a8422019-10-04 00:08:29 +0300659 """Get the event loop for the current context.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700660
idomicb23a8422019-10-04 00:08:29 +0300661 Returns an instance of EventLoop or raises an exception.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700662 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800663 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500664 not self._local._set_called and
Hill Ma99eb70a2019-12-05 04:40:12 -0800665 threading.current_thread() is threading.main_thread()):
Guido van Rossumcced0762013-11-27 10:37:13 -0800666 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500667
Victor Stinner3a1c7382014-12-18 01:20:10 +0100668 if self._local._loop is None:
669 raise RuntimeError('There is no current event loop in thread %r.'
670 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500671
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800672 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700673
674 def set_event_loop(self, loop):
675 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800676 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700677 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800678 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700679
680 def new_event_loop(self):
681 """Create a new event loop.
682
683 You must call set_event_loop() to make this the current event
684 loop.
685 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800686 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700687
688
689# Event loop policy. The policy itself is always global, even if the
690# policy's rules say that there is an event loop per thread (or other
691# notion of context). The default policy is installed by the first
692# call to get_event_loop_policy().
693_event_loop_policy = None
694
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800695# Lock for protecting the on-the-fly creation of the event loop policy.
696_lock = threading.Lock()
697
698
Yury Selivanov600a3492016-11-04 14:29:28 -0400699# A TLS for the running event loop, used by _get_running_loop.
700class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700701 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500702
703
Yury Selivanov600a3492016-11-04 14:29:28 -0400704_running_loop = _RunningLoop()
705
706
Yury Selivanovabae67e2017-12-11 10:07:44 -0500707def get_running_loop():
708 """Return the running event loop. Raise a RuntimeError if there is none.
709
710 This function is thread-specific.
711 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500712 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500713 loop = _get_running_loop()
714 if loop is None:
715 raise RuntimeError('no running event loop')
716 return loop
717
718
Yury Selivanov600a3492016-11-04 14:29:28 -0400719def _get_running_loop():
720 """Return the running event loop or None.
721
722 This is a low-level function intended to be used by event loops.
723 This function is thread-specific.
724 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500725 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700726 running_loop, pid = _running_loop.loop_pid
727 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500728 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400729
730
731def _set_running_loop(loop):
732 """Set the running event loop.
733
734 This is a low-level function intended to be used by event loops.
735 This function is thread-specific.
736 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500737 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700738 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400739
740
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800741def _init_event_loop_policy():
742 global _event_loop_policy
743 with _lock:
744 if _event_loop_policy is None: # pragma: no branch
745 from . import DefaultEventLoopPolicy
746 _event_loop_policy = DefaultEventLoopPolicy()
747
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700748
749def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200750 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700751 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800752 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700753 return _event_loop_policy
754
755
756def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200757 """Set the current event loop policy.
758
759 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700760 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700761 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
762 _event_loop_policy = policy
763
764
765def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400766 """Return an asyncio event loop.
767
768 When called from a coroutine or a callback (e.g. scheduled with call_soon
769 or similar API), this function will always return the running event loop.
770
771 If there is no running event loop set, the function will return
772 the result of `get_event_loop_policy().get_event_loop()` call.
773 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500774 # NOTE: this function is implemented in C (see _asynciomodule.c)
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300775 return _py__get_event_loop()
776
777
778def _get_event_loop(stacklevel=3):
Yury Selivanov600a3492016-11-04 14:29:28 -0400779 current_loop = _get_running_loop()
780 if current_loop is not None:
781 return current_loop
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300782 import warnings
783 warnings.warn('There is no current event loop',
784 DeprecationWarning, stacklevel=stacklevel)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700785 return get_event_loop_policy().get_event_loop()
786
787
788def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200789 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700790 get_event_loop_policy().set_event_loop(loop)
791
792
793def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200794 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700795 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800796
797
798def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200799 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800800 return get_event_loop_policy().get_child_watcher()
801
802
803def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200804 """Equivalent to calling
805 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800806 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500807
808
809# Alias pure-Python implementations for testing purposes.
810_py__get_running_loop = _get_running_loop
811_py__set_running_loop = _set_running_loop
812_py_get_running_loop = get_running_loop
813_py_get_event_loop = get_event_loop
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300814_py__get_event_loop = _get_event_loop
Yury Selivanova70232f2017-12-13 14:49:42 -0500815
816
817try:
818 # get_event_loop() is one of the most frequently called
819 # functions in asyncio. Pure Python implementation is
820 # about 4 times slower than C-accelerated.
821 from _asyncio import (_get_running_loop, _set_running_loop,
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300822 get_running_loop, get_event_loop, _get_event_loop)
Yury Selivanova70232f2017-12-13 14:49:42 -0500823except ImportError:
824 pass
825else:
826 # Alias C implementations for testing purposes.
827 _c__get_running_loop = _get_running_loop
828 _c__set_running_loop = _set_running_loop
829 _c_get_running_loop = get_running_loop
830 _c_get_event_loop = get_event_loop
Serhiy Storchaka172c0f22021-04-25 13:40:44 +0300831 _c__get_event_loop = _get_event_loop