blob: 9a923514db099399adbf0864be619eed5f856379 [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 Svetlov0baa72f2018-09-11 10:13:04 -070022from . import exceptions
Andrew Svetlov7464e872018-01-19 20:04:29 +020023
24
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070025class Handle:
26 """Object returned by callback registration methods."""
27
Victor Stinner80f53aa2014-06-27 13:52:20 +020028 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Yury Selivanovf23746a2018-01-22 19:11:18 -050029 '_source_traceback', '_repr', '__weakref__',
30 '_context')
Yury Selivanovb1317782014-02-12 17:01:52 -050031
Yury Selivanovf23746a2018-01-22 19:11:18 -050032 def __init__(self, callback, args, loop, context=None):
33 if context is None:
34 context = contextvars.copy_context()
35 self._context = context
Yury Selivanov569efa22014-02-18 18:02:19 -050036 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037 self._callback = callback
38 self._args = args
39 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020040 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020041 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020042 self._source_traceback = format_helpers.extract_stack(
43 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020044 else:
45 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070046
Victor Stinner1b38bc62014-09-17 23:24:13 +020047 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020048 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070049 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020050 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020051 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020052 info.append(format_helpers._format_callback_source(
53 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020054 if self._source_traceback:
55 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050056 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020057 return info
58
59 def __repr__(self):
60 if self._repr is not None:
61 return self._repr
62 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050063 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070064
65 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040066 if not self._cancelled:
67 self._cancelled = True
68 if self._loop.get_debug():
69 # Keep a representation in debug mode to keep callback and
70 # parameters. For example, to log the warning
71 # "Executing <Handle...> took 2.5 second"
72 self._repr = repr(self)
73 self._callback = None
74 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070075
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030076 def cancelled(self):
77 return self._cancelled
78
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070079 def _run(self):
80 try:
Yury Selivanovf23746a2018-01-22 19:11:18 -050081 self._context.run(self._callback, *self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050082 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020083 cb = format_helpers._format_callback_source(
84 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050085 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020086 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050087 'message': msg,
88 'exception': exc,
89 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020090 }
91 if self._source_traceback:
92 context['source_traceback'] = self._source_traceback
93 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070094 self = None # Needed to break cycles when an exception occurs.
95
96
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070097class TimerHandle(Handle):
98 """Object returned by timed callback registration methods."""
99
Yury Selivanov592ada92014-09-25 12:07:56 -0400100 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500101
Yury Selivanovf23746a2018-01-22 19:11:18 -0500102 def __init__(self, when, callback, args, loop, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700103 assert when is not None
Yury Selivanovf23746a2018-01-22 19:11:18 -0500104 super().__init__(callback, args, loop, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200105 if self._source_traceback:
106 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700107 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400108 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700109
Victor Stinner1b38bc62014-09-17 23:24:13 +0200110 def _repr_info(self):
111 info = super()._repr_info()
112 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500113 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200114 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700115
116 def __hash__(self):
117 return hash(self._when)
118
119 def __lt__(self, other):
120 return self._when < other._when
121
122 def __le__(self, other):
123 if self._when < other._when:
124 return True
125 return self.__eq__(other)
126
127 def __gt__(self, other):
128 return self._when > other._when
129
130 def __ge__(self, other):
131 if self._when > other._when:
132 return True
133 return self.__eq__(other)
134
135 def __eq__(self, other):
136 if isinstance(other, TimerHandle):
137 return (self._when == other._when and
138 self._callback == other._callback and
139 self._args == other._args and
140 self._cancelled == other._cancelled)
141 return NotImplemented
142
143 def __ne__(self, other):
144 equal = self.__eq__(other)
145 return NotImplemented if equal is NotImplemented else not equal
146
Yury Selivanov592ada92014-09-25 12:07:56 -0400147 def cancel(self):
148 if not self._cancelled:
149 self._loop._timer_handle_cancelled(self)
150 super().cancel()
151
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +0200152 def when(self):
153 """Return a scheduled callback time.
154
155 The time is an absolute timestamp, using the same time
156 reference as loop.time().
157 """
158 return self._when
159
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700160
161class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100162 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700163
164 def close(self):
165 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200166 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700167
Yury Selivanovc9070d02018-01-25 18:08:09 -0500168 def get_loop(self):
169 """Get the event loop the Server object is attached to."""
170 raise NotImplementedError
171
172 def is_serving(self):
173 """Return True if the server is accepting connections."""
174 raise NotImplementedError
175
176 async def start_serving(self):
177 """Start accepting connections.
178
179 This method is idempotent, so it can be called when
180 the server is already being serving.
181 """
182 raise NotImplementedError
183
184 async def serve_forever(self):
185 """Start accepting connections until the coroutine is cancelled.
186
187 The server is closed when the coroutine is cancelled.
188 """
189 raise NotImplementedError
190
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200191 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700192 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200193 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194
Yury Selivanovc9070d02018-01-25 18:08:09 -0500195 async def __aenter__(self):
196 return self
197
198 async def __aexit__(self, *exc):
199 self.close()
200 await self.wait_closed()
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530201
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700202
203class AbstractEventLoop:
204 """Abstract event loop."""
205
206 # Running and stopping the event loop.
207
208 def run_forever(self):
209 """Run the event loop until stop() is called."""
210 raise NotImplementedError
211
212 def run_until_complete(self, future):
213 """Run the event loop until a Future is done.
214
215 Return the Future's result, or raise its exception.
216 """
217 raise NotImplementedError
218
219 def stop(self):
220 """Stop the event loop as soon as reasonable.
221
222 Exactly how soon that is may depend on the implementation, but
223 no more I/O callbacks should be scheduled.
224 """
225 raise NotImplementedError
226
227 def is_running(self):
228 """Return whether the event loop is currently running."""
229 raise NotImplementedError
230
Victor Stinner896a25a2014-07-08 11:29:25 +0200231 def is_closed(self):
232 """Returns True if the event loop was closed."""
233 raise NotImplementedError
234
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700235 def close(self):
236 """Close the loop.
237
238 The loop should not be running.
239
240 This is idempotent and irreversible.
241
242 No other methods should be called after this one.
243 """
244 raise NotImplementedError
245
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200246 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400247 """Shutdown all active asynchronous generators."""
248 raise NotImplementedError
249
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250 # Methods scheduling callbacks. All these return Handles.
251
Yury Selivanov592ada92014-09-25 12:07:56 -0400252 def _timer_handle_cancelled(self, handle):
253 """Notification that a TimerHandle has been cancelled."""
254 raise NotImplementedError
255
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256 def call_soon(self, callback, *args):
257 return self.call_later(0, callback, *args)
258
259 def call_later(self, delay, callback, *args):
260 raise NotImplementedError
261
262 def call_at(self, when, callback, *args):
263 raise NotImplementedError
264
265 def time(self):
266 raise NotImplementedError
267
Yury Selivanov7661db62016-05-16 15:38:39 -0400268 def create_future(self):
269 raise NotImplementedError
270
Victor Stinner896a25a2014-07-08 11:29:25 +0200271 # Method scheduling a coroutine object: create a task.
272
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300273 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200274 raise NotImplementedError
275
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700276 # Methods for interacting with threads.
277
278 def call_soon_threadsafe(self, callback, *args):
279 raise NotImplementedError
280
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200281 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700282 raise NotImplementedError
283
284 def set_default_executor(self, executor):
285 raise NotImplementedError
286
287 # Network I/O methods returning Futures.
288
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200289 async def getaddrinfo(self, host, port, *,
290 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700291 raise NotImplementedError
292
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200293 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700294 raise NotImplementedError
295
Neil Aspinallf7686c12017-12-19 19:45:42 +0000296 async def create_connection(
297 self, protocol_factory, host=None, port=None,
298 *, ssl=None, family=0, proto=0,
299 flags=0, sock=None, local_addr=None,
300 server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800301 ssl_handshake_timeout=None,
302 happy_eyeballs_delay=None, interleave=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700303 raise NotImplementedError
304
Neil Aspinallf7686c12017-12-19 19:45:42 +0000305 async def create_server(
306 self, protocol_factory, host=None, port=None,
307 *, family=socket.AF_UNSPEC,
308 flags=socket.AI_PASSIVE, sock=None, backlog=100,
309 ssl=None, reuse_address=None, reuse_port=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500310 ssl_handshake_timeout=None,
311 start_serving=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700312 """A coroutine which creates a TCP server bound to host and port.
313
314 The return value is a Server object which can be used to stop
315 the service.
316
317 If host is an empty string or None all interfaces are assumed
318 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500319 one for IPv4 and another one for IPv6). The host parameter can also be
320 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700321
322 family can be set to either AF_INET or AF_INET6 to force the
323 socket to use IPv4 or IPv6. If not set it will be determined
324 from host (defaults to AF_UNSPEC).
325
326 flags is a bitmask for getaddrinfo().
327
328 sock can optionally be specified in order to use a preexisting
329 socket object.
330
331 backlog is the maximum number of queued connections passed to
332 listen() (defaults to 100).
333
334 ssl can be set to an SSLContext to enable SSL over the
335 accepted connections.
336
337 reuse_address tells the kernel to reuse a local socket in
338 TIME_WAIT state, without waiting for its natural timeout to
339 expire. If not specified will automatically be set to True on
340 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700341
342 reuse_port tells the kernel to allow this endpoint to be bound to
343 the same port as other existing endpoints are bound to, so long as
344 they all set this flag when being created. This option is not
345 supported on Windows.
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 completion of the SSL handshake before aborting the
Yury Selivanov96026432018-06-04 11:32:35 -0400349 connection. Default is 60s.
Yury Selivanovc9070d02018-01-25 18:08:09 -0500350
351 start_serving set to True (default) causes the created server
352 to start accepting connections immediately. When set to False,
353 the user should await Server.start_serving() or Server.serve_forever()
354 to make the server to start accepting connections.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700355 """
356 raise NotImplementedError
357
Andrew Svetlov7c684072018-01-27 21:22:47 +0200358 async def sendfile(self, transport, file, offset=0, count=None,
359 *, fallback=True):
360 """Send a file through a transport.
361
362 Return an amount of sent bytes.
363 """
364 raise NotImplementedError
365
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500366 async def start_tls(self, transport, protocol, sslcontext, *,
367 server_side=False,
368 server_hostname=None,
369 ssl_handshake_timeout=None):
370 """Upgrade a transport to TLS.
371
372 Return a new transport that *protocol* should start using
373 immediately.
374 """
375 raise NotImplementedError
376
Neil Aspinallf7686c12017-12-19 19:45:42 +0000377 async def create_unix_connection(
378 self, protocol_factory, path=None, *,
379 ssl=None, sock=None,
380 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200381 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500382 raise NotImplementedError
383
Neil Aspinallf7686c12017-12-19 19:45:42 +0000384 async def create_unix_server(
385 self, protocol_factory, path=None, *,
386 sock=None, backlog=100, ssl=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500387 ssl_handshake_timeout=None,
388 start_serving=True):
Yury Selivanovb057c522014-02-18 12:15:06 -0500389 """A coroutine which creates a UNIX Domain Socket server.
390
Yury Selivanovdec1a452014-02-18 22:27:48 -0500391 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500392 the service.
393
394 path is a str, representing a file systsem path to bind the
395 server socket to.
396
397 sock can optionally be specified in order to use a preexisting
398 socket object.
399
400 backlog is the maximum number of queued connections passed to
401 listen() (defaults to 100).
402
403 ssl can be set to an SSLContext to enable SSL over the
404 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000405
406 ssl_handshake_timeout is the time in seconds that an SSL server
Yury Selivanov96026432018-06-04 11:32:35 -0400407 will wait for the SSL handshake to complete (defaults to 60s).
Yury Selivanovc9070d02018-01-25 18:08:09 -0500408
409 start_serving set to True (default) causes the created server
410 to start accepting connections immediately. When set to False,
411 the user should await Server.start_serving() or Server.serve_forever()
412 to make the server to start accepting connections.
Yury Selivanovb057c522014-02-18 12:15:06 -0500413 """
414 raise NotImplementedError
415
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200416 async def create_datagram_endpoint(self, protocol_factory,
417 local_addr=None, remote_addr=None, *,
418 family=0, proto=0, flags=0,
419 reuse_address=None, reuse_port=None,
420 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700421 """A coroutine which creates a datagram endpoint.
422
423 This method will try to establish the endpoint in the background.
424 When successful, the coroutine returns a (transport, protocol) pair.
425
426 protocol_factory must be a callable returning a protocol instance.
427
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100428 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
429 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700430
431 reuse_address tells the kernel to reuse a local socket in
432 TIME_WAIT state, without waiting for its natural timeout to
433 expire. If not specified it will automatically be set to True on
434 UNIX.
435
436 reuse_port tells the kernel to allow this endpoint to be bound to
437 the same port as other existing endpoints are bound to, so long as
438 they all set this flag when being created. This option is not
439 supported on Windows and some UNIX's. If the
440 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
441 capability is unsupported.
442
443 allow_broadcast tells the kernel to allow this endpoint to send
444 messages to the broadcast address.
445
446 sock can optionally be specified in order to use a preexisting
447 socket object.
448 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700449 raise NotImplementedError
450
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700451 # Pipes and subprocesses.
452
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200453 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200454 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700455
456 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200457 pipe is a file-like object.
458 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800459 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700460 # The reason to accept file-like object instead of just file descriptor
461 # is: we need to own pipe and close it at transport finishing
462 # Can got complicated errors if pass f.fileno(),
463 # close fd in pipe transport then close f and vise versa.
464 raise NotImplementedError
465
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200466 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500467 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700468
469 protocol_factory should instantiate object with BaseProtocol interface.
470 Pipe is file-like object already switched to nonblocking.
471 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800472 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700473 # The reason to accept file-like object instead of just file descriptor
474 # is: we need to own pipe and close it at transport finishing
475 # Can got complicated errors if pass f.fileno(),
476 # close fd in pipe transport then close f and vise versa.
477 raise NotImplementedError
478
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200479 async def subprocess_shell(self, protocol_factory, cmd, *,
480 stdin=subprocess.PIPE,
481 stdout=subprocess.PIPE,
482 stderr=subprocess.PIPE,
483 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700484 raise NotImplementedError
485
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200486 async def subprocess_exec(self, protocol_factory, *args,
487 stdin=subprocess.PIPE,
488 stdout=subprocess.PIPE,
489 stderr=subprocess.PIPE,
490 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700491 raise NotImplementedError
492
493 # Ready-based callback registration methods.
494 # The add_*() methods return None.
495 # The remove_*() methods return True if something was removed,
496 # False if there was nothing to delete.
497
498 def add_reader(self, fd, callback, *args):
499 raise NotImplementedError
500
501 def remove_reader(self, fd):
502 raise NotImplementedError
503
504 def add_writer(self, fd, callback, *args):
505 raise NotImplementedError
506
507 def remove_writer(self, fd):
508 raise NotImplementedError
509
510 # Completion based I/O methods returning Futures.
511
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200512 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700513 raise NotImplementedError
514
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200515 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200516 raise NotImplementedError
517
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200518 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700519 raise NotImplementedError
520
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200521 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700522 raise NotImplementedError
523
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200524 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 raise NotImplementedError
526
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200527 async def sock_sendfile(self, sock, file, offset=0, count=None,
528 *, fallback=None):
529 raise NotImplementedError
530
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 # Signal handling.
532
533 def add_signal_handler(self, sig, callback, *args):
534 raise NotImplementedError
535
536 def remove_signal_handler(self, sig):
537 raise NotImplementedError
538
Yury Selivanov740169c2015-05-11 14:23:38 -0400539 # Task factory.
540
541 def set_task_factory(self, factory):
542 raise NotImplementedError
543
544 def get_task_factory(self):
545 raise NotImplementedError
546
Yury Selivanov569efa22014-02-18 18:02:19 -0500547 # Error handlers.
548
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400549 def get_exception_handler(self):
550 raise NotImplementedError
551
Yury Selivanov569efa22014-02-18 18:02:19 -0500552 def set_exception_handler(self, handler):
553 raise NotImplementedError
554
555 def default_exception_handler(self, context):
556 raise NotImplementedError
557
558 def call_exception_handler(self, context):
559 raise NotImplementedError
560
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100561 # Debug flag management.
562
563 def get_debug(self):
564 raise NotImplementedError
565
566 def set_debug(self, enabled):
567 raise NotImplementedError
568
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700569
570class AbstractEventLoopPolicy:
571 """Abstract policy for accessing the event loop."""
572
573 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200574 """Get the event loop for the current context.
575
576 Returns an event loop object implementing the BaseEventLoop interface,
577 or raises an exception in case no event loop has been set for the
578 current context and the current policy does not specify to create one.
579
580 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700581 raise NotImplementedError
582
583 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200584 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585 raise NotImplementedError
586
587 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200588 """Create and return a new event loop object according to this
589 policy's rules. If there's need to set this loop as the event loop for
590 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591 raise NotImplementedError
592
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800593 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700594
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800595 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200596 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800597 raise NotImplementedError
598
599 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200600 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800601 raise NotImplementedError
602
603
604class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700605 """Default policy implementation for accessing the event loop.
606
607 In this policy, each thread has its own event loop. However, we
608 only automatically create an event loop by default for the main
609 thread; other threads by default have no event loop.
610
611 Other policies may have different rules (e.g. a single global
612 event loop, or automatically creating an event loop per thread, or
613 using some other notion of context to which an event loop is
614 associated).
615 """
616
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800617 _loop_factory = None
618
619 class _Local(threading.local):
620 _loop = None
621 _set_called = False
622
623 def __init__(self):
624 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700625
626 def get_event_loop(self):
627 """Get the event loop.
628
629 This may be None or an instance of EventLoop.
630 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800631 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500632 not self._local._set_called and
633 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800634 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500635
Victor Stinner3a1c7382014-12-18 01:20:10 +0100636 if self._local._loop is None:
637 raise RuntimeError('There is no current event loop in thread %r.'
638 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500639
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800640 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700641
642 def set_event_loop(self, loop):
643 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800644 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700645 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800646 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700647
648 def new_event_loop(self):
649 """Create a new event loop.
650
651 You must call set_event_loop() to make this the current event
652 loop.
653 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800654 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700655
656
657# Event loop policy. The policy itself is always global, even if the
658# policy's rules say that there is an event loop per thread (or other
659# notion of context). The default policy is installed by the first
660# call to get_event_loop_policy().
661_event_loop_policy = None
662
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800663# Lock for protecting the on-the-fly creation of the event loop policy.
664_lock = threading.Lock()
665
666
Yury Selivanov600a3492016-11-04 14:29:28 -0400667# A TLS for the running event loop, used by _get_running_loop.
668class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700669 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500670
671
Yury Selivanov600a3492016-11-04 14:29:28 -0400672_running_loop = _RunningLoop()
673
674
Yury Selivanovabae67e2017-12-11 10:07:44 -0500675def get_running_loop():
676 """Return the running event loop. Raise a RuntimeError if there is none.
677
678 This function is thread-specific.
679 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500680 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500681 loop = _get_running_loop()
682 if loop is None:
683 raise RuntimeError('no running event loop')
684 return loop
685
686
Yury Selivanov600a3492016-11-04 14:29:28 -0400687def _get_running_loop():
688 """Return the running event loop or None.
689
690 This is a low-level function intended to be used by event loops.
691 This function is thread-specific.
692 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500693 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700694 running_loop, pid = _running_loop.loop_pid
695 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500696 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400697
698
699def _set_running_loop(loop):
700 """Set the running event loop.
701
702 This is a low-level function intended to be used by event loops.
703 This function is thread-specific.
704 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500705 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700706 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400707
708
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800709def _init_event_loop_policy():
710 global _event_loop_policy
711 with _lock:
712 if _event_loop_policy is None: # pragma: no branch
713 from . import DefaultEventLoopPolicy
714 _event_loop_policy = DefaultEventLoopPolicy()
715
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700716
717def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200718 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700719 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800720 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700721 return _event_loop_policy
722
723
724def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200725 """Set the current event loop policy.
726
727 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700728 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700729 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
730 _event_loop_policy = policy
731
732
733def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400734 """Return an asyncio event loop.
735
736 When called from a coroutine or a callback (e.g. scheduled with call_soon
737 or similar API), this function will always return the running event loop.
738
739 If there is no running event loop set, the function will return
740 the result of `get_event_loop_policy().get_event_loop()` call.
741 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500742 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400743 current_loop = _get_running_loop()
744 if current_loop is not None:
745 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700746 return get_event_loop_policy().get_event_loop()
747
748
749def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200750 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700751 get_event_loop_policy().set_event_loop(loop)
752
753
754def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200755 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700756 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800757
758
759def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200760 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800761 return get_event_loop_policy().get_child_watcher()
762
763
764def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200765 """Equivalent to calling
766 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800767 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500768
769
770# Alias pure-Python implementations for testing purposes.
771_py__get_running_loop = _get_running_loop
772_py__set_running_loop = _set_running_loop
773_py_get_running_loop = get_running_loop
774_py_get_event_loop = get_event_loop
775
776
777try:
778 # get_event_loop() is one of the most frequently called
779 # functions in asyncio. Pure Python implementation is
780 # about 4 times slower than C-accelerated.
781 from _asyncio import (_get_running_loop, _set_running_loop,
782 get_running_loop, get_event_loop)
783except ImportError:
784 pass
785else:
786 # Alias C implementations for testing purposes.
787 _c__get_running_loop = _get_running_loop
788 _c__set_running_loop = _set_running_loop
789 _c_get_running_loop = get_running_loop
790 _c_get_event_loop = get_event_loop