blob: 2f06c4ae795d2ad16b29959f2555a1e34cb07af2 [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 Selivanov431b5402019-05-27 14:45:12 +020082 except (SystemExit, KeyboardInterrupt):
83 raise
84 except BaseException as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020085 cb = format_helpers._format_callback_source(
86 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050087 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020088 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050089 'message': msg,
90 'exception': exc,
91 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020092 }
93 if self._source_traceback:
94 context['source_traceback'] = self._source_traceback
95 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070096 self = None # Needed to break cycles when an exception occurs.
97
98
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070099class TimerHandle(Handle):
100 """Object returned by timed callback registration methods."""
101
Yury Selivanov592ada92014-09-25 12:07:56 -0400102 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500103
Yury Selivanovf23746a2018-01-22 19:11:18 -0500104 def __init__(self, when, callback, args, loop, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700105 assert when is not None
Yury Selivanovf23746a2018-01-22 19:11:18 -0500106 super().__init__(callback, args, loop, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200107 if self._source_traceback:
108 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700109 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400110 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700111
Victor Stinner1b38bc62014-09-17 23:24:13 +0200112 def _repr_info(self):
113 info = super()._repr_info()
114 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500115 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200116 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700117
118 def __hash__(self):
119 return hash(self._when)
120
121 def __lt__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300122 if isinstance(other, TimerHandle):
123 return self._when < other._when
124 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700125
126 def __le__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300127 if isinstance(other, TimerHandle):
128 return self._when < other._when or self.__eq__(other)
129 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700130
131 def __gt__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300132 if isinstance(other, TimerHandle):
133 return self._when > other._when
134 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700135
136 def __ge__(self, other):
Serhiy Storchaka662db122019-08-08 08:42:54 +0300137 if isinstance(other, TimerHandle):
138 return self._when > other._when or self.__eq__(other)
139 return NotImplemented
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700140
141 def __eq__(self, other):
142 if isinstance(other, TimerHandle):
143 return (self._when == other._when and
144 self._callback == other._callback and
145 self._args == other._args and
146 self._cancelled == other._cancelled)
147 return NotImplemented
148
Yury Selivanov592ada92014-09-25 12:07:56 -0400149 def cancel(self):
150 if not self._cancelled:
151 self._loop._timer_handle_cancelled(self)
152 super().cancel()
153
Andrew Svetlov3d4dbd82018-02-01 19:59:32 +0200154 def when(self):
155 """Return a scheduled callback time.
156
157 The time is an absolute timestamp, using the same time
158 reference as loop.time().
159 """
160 return self._when
161
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162
163class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100164 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700165
166 def close(self):
167 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200168 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700169
Yury Selivanovc9070d02018-01-25 18:08:09 -0500170 def get_loop(self):
171 """Get the event loop the Server object is attached to."""
172 raise NotImplementedError
173
174 def is_serving(self):
175 """Return True if the server is accepting connections."""
176 raise NotImplementedError
177
178 async def start_serving(self):
179 """Start accepting connections.
180
181 This method is idempotent, so it can be called when
182 the server is already being serving.
183 """
184 raise NotImplementedError
185
186 async def serve_forever(self):
187 """Start accepting connections until the coroutine is cancelled.
188
189 The server is closed when the coroutine is cancelled.
190 """
191 raise NotImplementedError
192
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200193 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700194 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200195 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700196
Yury Selivanovc9070d02018-01-25 18:08:09 -0500197 async def __aenter__(self):
198 return self
199
200 async def __aexit__(self, *exc):
201 self.close()
202 await self.wait_closed()
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530203
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700204
205class AbstractEventLoop:
206 """Abstract event loop."""
207
208 # Running and stopping the event loop.
209
210 def run_forever(self):
211 """Run the event loop until stop() is called."""
212 raise NotImplementedError
213
214 def run_until_complete(self, future):
215 """Run the event loop until a Future is done.
216
217 Return the Future's result, or raise its exception.
218 """
219 raise NotImplementedError
220
221 def stop(self):
222 """Stop the event loop as soon as reasonable.
223
224 Exactly how soon that is may depend on the implementation, but
225 no more I/O callbacks should be scheduled.
226 """
227 raise NotImplementedError
228
229 def is_running(self):
230 """Return whether the event loop is currently running."""
231 raise NotImplementedError
232
Victor Stinner896a25a2014-07-08 11:29:25 +0200233 def is_closed(self):
234 """Returns True if the event loop was closed."""
235 raise NotImplementedError
236
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700237 def close(self):
238 """Close the loop.
239
240 The loop should not be running.
241
242 This is idempotent and irreversible.
243
244 No other methods should be called after this one.
245 """
246 raise NotImplementedError
247
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200248 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400249 """Shutdown all active asynchronous generators."""
250 raise NotImplementedError
251
Kyle Stanley9fdc64c2019-09-19 08:47:22 -0400252 async def shutdown_default_executor(self):
253 """Schedule the shutdown of the default executor."""
254 raise NotImplementedError
255
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256 # Methods scheduling callbacks. All these return Handles.
257
Yury Selivanov592ada92014-09-25 12:07:56 -0400258 def _timer_handle_cancelled(self, handle):
259 """Notification that a TimerHandle has been cancelled."""
260 raise NotImplementedError
261
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262 def call_soon(self, callback, *args):
263 return self.call_later(0, callback, *args)
264
265 def call_later(self, delay, callback, *args):
266 raise NotImplementedError
267
268 def call_at(self, when, callback, *args):
269 raise NotImplementedError
270
271 def time(self):
272 raise NotImplementedError
273
Yury Selivanov7661db62016-05-16 15:38:39 -0400274 def create_future(self):
275 raise NotImplementedError
276
Victor Stinner896a25a2014-07-08 11:29:25 +0200277 # Method scheduling a coroutine object: create a task.
278
Alex Grönholmcca4eec2018-08-09 00:06:47 +0300279 def create_task(self, coro, *, name=None):
Victor Stinner896a25a2014-07-08 11:29:25 +0200280 raise NotImplementedError
281
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700282 # Methods for interacting with threads.
283
284 def call_soon_threadsafe(self, callback, *args):
285 raise NotImplementedError
286
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200287 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700288 raise NotImplementedError
289
290 def set_default_executor(self, executor):
291 raise NotImplementedError
292
293 # Network I/O methods returning Futures.
294
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200295 async def getaddrinfo(self, host, port, *,
296 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 raise NotImplementedError
298
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200299 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700300 raise NotImplementedError
301
Neil Aspinallf7686c12017-12-19 19:45:42 +0000302 async def create_connection(
303 self, protocol_factory, host=None, port=None,
304 *, ssl=None, family=0, proto=0,
305 flags=0, sock=None, local_addr=None,
306 server_hostname=None,
twisteroid ambassador88f07a82019-05-05 19:14:35 +0800307 ssl_handshake_timeout=None,
308 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,
317 start_serving=True):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700318 """A coroutine which creates a TCP server bound to host and port.
319
320 The return value is a Server object which can be used to stop
321 the service.
322
323 If host is an empty string or None all interfaces are assumed
324 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500325 one for IPv4 and another one for IPv6). The host parameter can also be
326 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700327
328 family can be set to either AF_INET or AF_INET6 to force the
329 socket to use IPv4 or IPv6. If not set it will be determined
330 from host (defaults to AF_UNSPEC).
331
332 flags is a bitmask for getaddrinfo().
333
334 sock can optionally be specified in order to use a preexisting
335 socket object.
336
337 backlog is the maximum number of queued connections passed to
338 listen() (defaults to 100).
339
340 ssl can be set to an SSLContext to enable SSL over the
341 accepted connections.
342
343 reuse_address tells the kernel to reuse a local socket in
344 TIME_WAIT state, without waiting for its natural timeout to
345 expire. If not specified will automatically be set to True on
346 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700347
348 reuse_port tells the kernel to allow this endpoint to be bound to
349 the same port as other existing endpoints are bound to, so long as
350 they all set this flag when being created. This option is not
351 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000352
353 ssl_handshake_timeout is the time in seconds that an SSL server
354 will wait for completion of the SSL handshake before aborting the
Yury Selivanov96026432018-06-04 11:32:35 -0400355 connection. Default is 60s.
Yury Selivanovc9070d02018-01-25 18:08:09 -0500356
357 start_serving set to True (default) causes the created server
358 to start accepting connections immediately. When set to False,
359 the user should await Server.start_serving() or Server.serve_forever()
360 to make the server to start accepting connections.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700361 """
362 raise NotImplementedError
363
Andrew Svetlov7c684072018-01-27 21:22:47 +0200364 async def sendfile(self, transport, file, offset=0, count=None,
365 *, fallback=True):
366 """Send a file through a transport.
367
368 Return an amount of sent bytes.
369 """
370 raise NotImplementedError
371
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500372 async def start_tls(self, transport, protocol, sslcontext, *,
373 server_side=False,
374 server_hostname=None,
375 ssl_handshake_timeout=None):
376 """Upgrade a transport to TLS.
377
378 Return a new transport that *protocol* should start using
379 immediately.
380 """
381 raise NotImplementedError
382
Neil Aspinallf7686c12017-12-19 19:45:42 +0000383 async def create_unix_connection(
384 self, protocol_factory, path=None, *,
385 ssl=None, sock=None,
386 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200387 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500388 raise NotImplementedError
389
Neil Aspinallf7686c12017-12-19 19:45:42 +0000390 async def create_unix_server(
391 self, protocol_factory, path=None, *,
392 sock=None, backlog=100, ssl=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500393 ssl_handshake_timeout=None,
394 start_serving=True):
Yury Selivanovb057c522014-02-18 12:15:06 -0500395 """A coroutine which creates a UNIX Domain Socket server.
396
Yury Selivanovdec1a452014-02-18 22:27:48 -0500397 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500398 the service.
399
400 path is a str, representing a file systsem path to bind the
401 server socket to.
402
403 sock can optionally be specified in order to use a preexisting
404 socket object.
405
406 backlog is the maximum number of queued connections passed to
407 listen() (defaults to 100).
408
409 ssl can be set to an SSLContext to enable SSL over the
410 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000411
412 ssl_handshake_timeout is the time in seconds that an SSL server
Yury Selivanov96026432018-06-04 11:32:35 -0400413 will wait for the SSL handshake to complete (defaults to 60s).
Yury Selivanovc9070d02018-01-25 18:08:09 -0500414
415 start_serving set to True (default) causes the created server
416 to start accepting connections immediately. When set to False,
417 the user should await Server.start_serving() or Server.serve_forever()
418 to make the server to start accepting connections.
Yury Selivanovb057c522014-02-18 12:15:06 -0500419 """
420 raise NotImplementedError
421
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200422 async def create_datagram_endpoint(self, protocol_factory,
423 local_addr=None, remote_addr=None, *,
424 family=0, proto=0, flags=0,
425 reuse_address=None, reuse_port=None,
426 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700427 """A coroutine which creates a datagram endpoint.
428
429 This method will try to establish the endpoint in the background.
430 When successful, the coroutine returns a (transport, protocol) pair.
431
432 protocol_factory must be a callable returning a protocol instance.
433
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100434 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
435 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700436
437 reuse_address tells the kernel to reuse a local socket in
438 TIME_WAIT state, without waiting for its natural timeout to
439 expire. If not specified it will automatically be set to True on
440 UNIX.
441
442 reuse_port tells the kernel to allow this endpoint to be bound to
443 the same port as other existing endpoints are bound to, so long as
444 they all set this flag when being created. This option is not
445 supported on Windows and some UNIX's. If the
446 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
447 capability is unsupported.
448
449 allow_broadcast tells the kernel to allow this endpoint to send
450 messages to the broadcast address.
451
452 sock can optionally be specified in order to use a preexisting
453 socket object.
454 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700455 raise NotImplementedError
456
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700457 # Pipes and subprocesses.
458
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200459 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200460 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700461
462 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200463 pipe is a file-like object.
464 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800465 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 # The reason to accept file-like object instead of just file descriptor
467 # is: we need to own pipe and close it at transport finishing
468 # Can got complicated errors if pass f.fileno(),
469 # close fd in pipe transport then close f and vise versa.
470 raise NotImplementedError
471
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200472 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500473 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700474
475 protocol_factory should instantiate object with BaseProtocol interface.
476 Pipe is file-like object already switched to nonblocking.
477 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800478 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479 # The reason to accept file-like object instead of just file descriptor
480 # is: we need to own pipe and close it at transport finishing
481 # Can got complicated errors if pass f.fileno(),
482 # close fd in pipe transport then close f and vise versa.
483 raise NotImplementedError
484
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200485 async def subprocess_shell(self, protocol_factory, cmd, *,
486 stdin=subprocess.PIPE,
487 stdout=subprocess.PIPE,
488 stderr=subprocess.PIPE,
489 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 raise NotImplementedError
491
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200492 async def subprocess_exec(self, protocol_factory, *args,
493 stdin=subprocess.PIPE,
494 stdout=subprocess.PIPE,
495 stderr=subprocess.PIPE,
496 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700497 raise NotImplementedError
498
499 # Ready-based callback registration methods.
500 # The add_*() methods return None.
501 # The remove_*() methods return True if something was removed,
502 # False if there was nothing to delete.
503
504 def add_reader(self, fd, callback, *args):
505 raise NotImplementedError
506
507 def remove_reader(self, fd):
508 raise NotImplementedError
509
510 def add_writer(self, fd, callback, *args):
511 raise NotImplementedError
512
513 def remove_writer(self, fd):
514 raise NotImplementedError
515
516 # Completion based I/O methods returning Futures.
517
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200518 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700519 raise NotImplementedError
520
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200521 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200522 raise NotImplementedError
523
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200524 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700525 raise NotImplementedError
526
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200527 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 raise NotImplementedError
529
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200530 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 raise NotImplementedError
532
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200533 async def sock_sendfile(self, sock, file, offset=0, count=None,
534 *, fallback=None):
535 raise NotImplementedError
536
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 # Signal handling.
538
539 def add_signal_handler(self, sig, callback, *args):
540 raise NotImplementedError
541
542 def remove_signal_handler(self, sig):
543 raise NotImplementedError
544
Yury Selivanov740169c2015-05-11 14:23:38 -0400545 # Task factory.
546
547 def set_task_factory(self, factory):
548 raise NotImplementedError
549
550 def get_task_factory(self):
551 raise NotImplementedError
552
Yury Selivanov569efa22014-02-18 18:02:19 -0500553 # Error handlers.
554
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400555 def get_exception_handler(self):
556 raise NotImplementedError
557
Yury Selivanov569efa22014-02-18 18:02:19 -0500558 def set_exception_handler(self, handler):
559 raise NotImplementedError
560
561 def default_exception_handler(self, context):
562 raise NotImplementedError
563
564 def call_exception_handler(self, context):
565 raise NotImplementedError
566
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100567 # Debug flag management.
568
569 def get_debug(self):
570 raise NotImplementedError
571
572 def set_debug(self, enabled):
573 raise NotImplementedError
574
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700575
576class AbstractEventLoopPolicy:
577 """Abstract policy for accessing the event loop."""
578
579 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200580 """Get the event loop for the current context.
581
582 Returns an event loop object implementing the BaseEventLoop interface,
583 or raises an exception in case no event loop has been set for the
584 current context and the current policy does not specify to create one.
585
586 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700587 raise NotImplementedError
588
589 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200590 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591 raise NotImplementedError
592
593 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200594 """Create and return a new event loop object according to this
595 policy's rules. If there's need to set this loop as the event loop for
596 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700597 raise NotImplementedError
598
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800599 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800601 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200602 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800603 raise NotImplementedError
604
605 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200606 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800607 raise NotImplementedError
608
609
610class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700611 """Default policy implementation for accessing the event loop.
612
613 In this policy, each thread has its own event loop. However, we
614 only automatically create an event loop by default for the main
615 thread; other threads by default have no event loop.
616
617 Other policies may have different rules (e.g. a single global
618 event loop, or automatically creating an event loop per thread, or
619 using some other notion of context to which an event loop is
620 associated).
621 """
622
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800623 _loop_factory = None
624
625 class _Local(threading.local):
626 _loop = None
627 _set_called = False
628
629 def __init__(self):
630 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700631
632 def get_event_loop(self):
633 """Get the event loop.
634
635 This may be None or an instance of EventLoop.
636 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800637 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500638 not self._local._set_called and
639 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800640 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500641
Victor Stinner3a1c7382014-12-18 01:20:10 +0100642 if self._local._loop is None:
643 raise RuntimeError('There is no current event loop in thread %r.'
644 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500645
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800646 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700647
648 def set_event_loop(self, loop):
649 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800650 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700651 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800652 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700653
654 def new_event_loop(self):
655 """Create a new event loop.
656
657 You must call set_event_loop() to make this the current event
658 loop.
659 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800660 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700661
662
663# Event loop policy. The policy itself is always global, even if the
664# policy's rules say that there is an event loop per thread (or other
665# notion of context). The default policy is installed by the first
666# call to get_event_loop_policy().
667_event_loop_policy = None
668
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800669# Lock for protecting the on-the-fly creation of the event loop policy.
670_lock = threading.Lock()
671
672
Yury Selivanov600a3492016-11-04 14:29:28 -0400673# A TLS for the running event loop, used by _get_running_loop.
674class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700675 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500676
677
Yury Selivanov600a3492016-11-04 14:29:28 -0400678_running_loop = _RunningLoop()
679
680
Yury Selivanovabae67e2017-12-11 10:07:44 -0500681def get_running_loop():
682 """Return the running event loop. Raise a RuntimeError if there is none.
683
684 This function is thread-specific.
685 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500686 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500687 loop = _get_running_loop()
688 if loop is None:
689 raise RuntimeError('no running event loop')
690 return loop
691
692
Yury Selivanov600a3492016-11-04 14:29:28 -0400693def _get_running_loop():
694 """Return the running event loop or None.
695
696 This is a low-level function intended to be used by event loops.
697 This function is thread-specific.
698 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500699 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700700 running_loop, pid = _running_loop.loop_pid
701 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500702 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400703
704
705def _set_running_loop(loop):
706 """Set the running event loop.
707
708 This is a low-level function intended to be used by event loops.
709 This function is thread-specific.
710 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500711 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700712 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400713
714
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800715def _init_event_loop_policy():
716 global _event_loop_policy
717 with _lock:
718 if _event_loop_policy is None: # pragma: no branch
719 from . import DefaultEventLoopPolicy
720 _event_loop_policy = DefaultEventLoopPolicy()
721
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700722
723def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200724 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700725 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800726 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700727 return _event_loop_policy
728
729
730def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200731 """Set the current event loop policy.
732
733 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700734 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700735 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
736 _event_loop_policy = policy
737
738
739def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400740 """Return an asyncio event loop.
741
742 When called from a coroutine or a callback (e.g. scheduled with call_soon
743 or similar API), this function will always return the running event loop.
744
745 If there is no running event loop set, the function will return
746 the result of `get_event_loop_policy().get_event_loop()` call.
747 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500748 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400749 current_loop = _get_running_loop()
750 if current_loop is not None:
751 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700752 return get_event_loop_policy().get_event_loop()
753
754
755def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200756 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700757 get_event_loop_policy().set_event_loop(loop)
758
759
760def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200761 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700762 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800763
764
765def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200766 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800767 return get_event_loop_policy().get_child_watcher()
768
769
770def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200771 """Equivalent to calling
772 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800773 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500774
775
776# Alias pure-Python implementations for testing purposes.
777_py__get_running_loop = _get_running_loop
778_py__set_running_loop = _set_running_loop
779_py_get_running_loop = get_running_loop
780_py_get_event_loop = get_event_loop
781
782
783try:
784 # get_event_loop() is one of the most frequently called
785 # functions in asyncio. Pure Python implementation is
786 # about 4 times slower than C-accelerated.
787 from _asyncio import (_get_running_loop, _set_running_loop,
788 get_running_loop, get_event_loop)
789except ImportError:
790 pass
791else:
792 # Alias C implementations for testing purposes.
793 _c__get_running_loop = _get_running_loop
794 _c__set_running_loop = _set_running_loop
795 _c_get_running_loop = get_running_loop
796 _c_get_event_loop = get_event_loop