blob: 40946bbf65299ddd263c2f47d7a628f89b6feed4 [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 Svetlov7464e872018-01-19 20:04:29 +02006 'Handle', 'TimerHandle', 'SendfileNotAvailableError',
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
Antoine Pitrou921e9432017-11-07 17:23:29 +010022
23
Andrew Svetlov7464e872018-01-19 20:04:29 +020024class SendfileNotAvailableError(RuntimeError):
25 """Sendfile syscall is not available.
26
Miss Islington (bot)211c0db2018-03-27 18:34:15 -070027 Raised if OS does not support sendfile syscall for given socket or
Andrew Svetlov7464e872018-01-19 20:04:29 +020028 file type.
29 """
30
31
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070032class Handle:
33 """Object returned by callback registration methods."""
34
Victor Stinner80f53aa2014-06-27 13:52:20 +020035 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Yury Selivanovf23746a2018-01-22 19:11:18 -050036 '_source_traceback', '_repr', '__weakref__',
37 '_context')
Yury Selivanovb1317782014-02-12 17:01:52 -050038
Yury Selivanovf23746a2018-01-22 19:11:18 -050039 def __init__(self, callback, args, loop, context=None):
40 if context is None:
41 context = contextvars.copy_context()
42 self._context = context
Yury Selivanov569efa22014-02-18 18:02:19 -050043 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070044 self._callback = callback
45 self._args = args
46 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020047 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020048 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020049 self._source_traceback = format_helpers.extract_stack(
50 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020051 else:
52 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070053
Victor Stinner1b38bc62014-09-17 23:24:13 +020054 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020055 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070056 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020057 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020058 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020059 info.append(format_helpers._format_callback_source(
60 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020061 if self._source_traceback:
62 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050063 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020064 return info
65
66 def __repr__(self):
67 if self._repr is not None:
68 return self._repr
69 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050070 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070071
72 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040073 if not self._cancelled:
74 self._cancelled = True
75 if self._loop.get_debug():
76 # Keep a representation in debug mode to keep callback and
77 # parameters. For example, to log the warning
78 # "Executing <Handle...> took 2.5 second"
79 self._repr = repr(self)
80 self._callback = None
81 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070082
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030083 def cancelled(self):
84 return self._cancelled
85
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086 def _run(self):
87 try:
Yury Selivanovf23746a2018-01-22 19:11:18 -050088 self._context.run(self._callback, *self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050089 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020090 cb = format_helpers._format_callback_source(
91 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050092 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020093 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050094 'message': msg,
95 'exception': exc,
96 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020097 }
98 if self._source_traceback:
99 context['source_traceback'] = self._source_traceback
100 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700101 self = None # Needed to break cycles when an exception occurs.
102
103
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700104class TimerHandle(Handle):
105 """Object returned by timed callback registration methods."""
106
Yury Selivanov592ada92014-09-25 12:07:56 -0400107 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500108
Yury Selivanovf23746a2018-01-22 19:11:18 -0500109 def __init__(self, when, callback, args, loop, context=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700110 assert when is not None
Yury Selivanovf23746a2018-01-22 19:11:18 -0500111 super().__init__(callback, args, loop, context)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200112 if self._source_traceback:
113 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700114 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400115 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700116
Victor Stinner1b38bc62014-09-17 23:24:13 +0200117 def _repr_info(self):
118 info = super()._repr_info()
119 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500120 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200121 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700122
123 def __hash__(self):
124 return hash(self._when)
125
126 def __lt__(self, other):
127 return self._when < other._when
128
129 def __le__(self, other):
130 if self._when < other._when:
131 return True
132 return self.__eq__(other)
133
134 def __gt__(self, other):
135 return self._when > other._when
136
137 def __ge__(self, other):
138 if self._when > other._when:
139 return True
140 return self.__eq__(other)
141
142 def __eq__(self, other):
143 if isinstance(other, TimerHandle):
144 return (self._when == other._when and
145 self._callback == other._callback and
146 self._args == other._args and
147 self._cancelled == other._cancelled)
148 return NotImplemented
149
150 def __ne__(self, other):
151 equal = self.__eq__(other)
152 return NotImplemented if equal is NotImplemented else not equal
153
Yury Selivanov592ada92014-09-25 12:07:56 -0400154 def cancel(self):
155 if not self._cancelled:
156 self._loop._timer_handle_cancelled(self)
157 super().cancel()
158
Miss Islington (bot)71a0b0e2018-02-01 11:56:03 -0800159 def when(self):
160 """Return a scheduled callback time.
161
162 The time is an absolute timestamp, using the same time
163 reference as loop.time().
164 """
165 return self._when
166
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700167
168class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100169 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170
171 def close(self):
172 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200173 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700174
Yury Selivanovc9070d02018-01-25 18:08:09 -0500175 def get_loop(self):
176 """Get the event loop the Server object is attached to."""
177 raise NotImplementedError
178
179 def is_serving(self):
180 """Return True if the server is accepting connections."""
181 raise NotImplementedError
182
183 async def start_serving(self):
184 """Start accepting connections.
185
186 This method is idempotent, so it can be called when
187 the server is already being serving.
188 """
189 raise NotImplementedError
190
191 async def serve_forever(self):
192 """Start accepting connections until the coroutine is cancelled.
193
194 The server is closed when the coroutine is cancelled.
195 """
196 raise NotImplementedError
197
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200198 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700199 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200200 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700201
Yury Selivanovc9070d02018-01-25 18:08:09 -0500202 async def __aenter__(self):
203 return self
204
205 async def __aexit__(self, *exc):
206 self.close()
207 await self.wait_closed()
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530208
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700209
210class AbstractEventLoop:
211 """Abstract event loop."""
212
213 # Running and stopping the event loop.
214
215 def run_forever(self):
216 """Run the event loop until stop() is called."""
217 raise NotImplementedError
218
219 def run_until_complete(self, future):
220 """Run the event loop until a Future is done.
221
222 Return the Future's result, or raise its exception.
223 """
224 raise NotImplementedError
225
226 def stop(self):
227 """Stop the event loop as soon as reasonable.
228
229 Exactly how soon that is may depend on the implementation, but
230 no more I/O callbacks should be scheduled.
231 """
232 raise NotImplementedError
233
234 def is_running(self):
235 """Return whether the event loop is currently running."""
236 raise NotImplementedError
237
Victor Stinner896a25a2014-07-08 11:29:25 +0200238 def is_closed(self):
239 """Returns True if the event loop was closed."""
240 raise NotImplementedError
241
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700242 def close(self):
243 """Close the loop.
244
245 The loop should not be running.
246
247 This is idempotent and irreversible.
248
249 No other methods should be called after this one.
250 """
251 raise NotImplementedError
252
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200253 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400254 """Shutdown all active asynchronous generators."""
255 raise NotImplementedError
256
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700257 # Methods scheduling callbacks. All these return Handles.
258
Yury Selivanov592ada92014-09-25 12:07:56 -0400259 def _timer_handle_cancelled(self, handle):
260 """Notification that a TimerHandle has been cancelled."""
261 raise NotImplementedError
262
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700263 def call_soon(self, callback, *args):
264 return self.call_later(0, callback, *args)
265
266 def call_later(self, delay, callback, *args):
267 raise NotImplementedError
268
269 def call_at(self, when, callback, *args):
270 raise NotImplementedError
271
272 def time(self):
273 raise NotImplementedError
274
Yury Selivanov7661db62016-05-16 15:38:39 -0400275 def create_future(self):
276 raise NotImplementedError
277
Victor Stinner896a25a2014-07-08 11:29:25 +0200278 # Method scheduling a coroutine object: create a task.
279
280 def create_task(self, coro):
281 raise NotImplementedError
282
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700283 # Methods for interacting with threads.
284
285 def call_soon_threadsafe(self, callback, *args):
286 raise NotImplementedError
287
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200288 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700289 raise NotImplementedError
290
291 def set_default_executor(self, executor):
292 raise NotImplementedError
293
294 # Network I/O methods returning Futures.
295
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200296 async def getaddrinfo(self, host, port, *,
297 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700298 raise NotImplementedError
299
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200300 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700301 raise NotImplementedError
302
Neil Aspinallf7686c12017-12-19 19:45:42 +0000303 async def create_connection(
304 self, protocol_factory, host=None, port=None,
305 *, ssl=None, family=0, proto=0,
306 flags=0, sock=None, local_addr=None,
307 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200308 ssl_handshake_timeout=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
355 connection. Default is 10s, longer timeouts may increase vulnerability
356 to DoS attacks (see https://support.f5.com/csp/article/K13834)
Yury Selivanovc9070d02018-01-25 18:08:09 -0500357
358 start_serving set to True (default) causes the created server
359 to start accepting connections immediately. When set to False,
360 the user should await Server.start_serving() or Server.serve_forever()
361 to make the server to start accepting connections.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700362 """
363 raise NotImplementedError
364
Andrew Svetlov7c684072018-01-27 21:22:47 +0200365 async def sendfile(self, transport, file, offset=0, count=None,
366 *, fallback=True):
367 """Send a file through a transport.
368
369 Return an amount of sent bytes.
370 """
371 raise NotImplementedError
372
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500373 async def start_tls(self, transport, protocol, sslcontext, *,
374 server_side=False,
375 server_hostname=None,
376 ssl_handshake_timeout=None):
377 """Upgrade a transport to TLS.
378
379 Return a new transport that *protocol* should start using
380 immediately.
381 """
382 raise NotImplementedError
383
Neil Aspinallf7686c12017-12-19 19:45:42 +0000384 async def create_unix_connection(
385 self, protocol_factory, path=None, *,
386 ssl=None, sock=None,
387 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200388 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500389 raise NotImplementedError
390
Neil Aspinallf7686c12017-12-19 19:45:42 +0000391 async def create_unix_server(
392 self, protocol_factory, path=None, *,
393 sock=None, backlog=100, ssl=None,
Yury Selivanovc9070d02018-01-25 18:08:09 -0500394 ssl_handshake_timeout=None,
395 start_serving=True):
Yury Selivanovb057c522014-02-18 12:15:06 -0500396 """A coroutine which creates a UNIX Domain Socket server.
397
Yury Selivanovdec1a452014-02-18 22:27:48 -0500398 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500399 the service.
400
401 path is a str, representing a file systsem path to bind the
402 server socket to.
403
404 sock can optionally be specified in order to use a preexisting
405 socket object.
406
407 backlog is the maximum number of queued connections passed to
408 listen() (defaults to 100).
409
410 ssl can be set to an SSLContext to enable SSL over the
411 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000412
413 ssl_handshake_timeout is the time in seconds that an SSL server
414 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovc9070d02018-01-25 18:08:09 -0500415
416 start_serving set to True (default) causes the created server
417 to start accepting connections immediately. When set to False,
418 the user should await Server.start_serving() or Server.serve_forever()
419 to make the server to start accepting connections.
Yury Selivanovb057c522014-02-18 12:15:06 -0500420 """
421 raise NotImplementedError
422
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200423 async def create_datagram_endpoint(self, protocol_factory,
424 local_addr=None, remote_addr=None, *,
425 family=0, proto=0, flags=0,
426 reuse_address=None, reuse_port=None,
427 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700428 """A coroutine which creates a datagram endpoint.
429
430 This method will try to establish the endpoint in the background.
431 When successful, the coroutine returns a (transport, protocol) pair.
432
433 protocol_factory must be a callable returning a protocol instance.
434
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100435 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
436 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700437
438 reuse_address tells the kernel to reuse a local socket in
439 TIME_WAIT state, without waiting for its natural timeout to
440 expire. If not specified it will automatically be set to True on
441 UNIX.
442
443 reuse_port tells the kernel to allow this endpoint to be bound to
444 the same port as other existing endpoints are bound to, so long as
445 they all set this flag when being created. This option is not
446 supported on Windows and some UNIX's. If the
447 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
448 capability is unsupported.
449
450 allow_broadcast tells the kernel to allow this endpoint to send
451 messages to the broadcast address.
452
453 sock can optionally be specified in order to use a preexisting
454 socket object.
455 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700456 raise NotImplementedError
457
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700458 # Pipes and subprocesses.
459
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200460 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200461 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700462
463 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200464 pipe is a file-like object.
465 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800466 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467 # The reason to accept file-like object instead of just file descriptor
468 # is: we need to own pipe and close it at transport finishing
469 # Can got complicated errors if pass f.fileno(),
470 # close fd in pipe transport then close f and vise versa.
471 raise NotImplementedError
472
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200473 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500474 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700475
476 protocol_factory should instantiate object with BaseProtocol interface.
477 Pipe is file-like object already switched to nonblocking.
478 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800479 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700480 # The reason to accept file-like object instead of just file descriptor
481 # is: we need to own pipe and close it at transport finishing
482 # Can got complicated errors if pass f.fileno(),
483 # close fd in pipe transport then close f and vise versa.
484 raise NotImplementedError
485
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200486 async def subprocess_shell(self, protocol_factory, cmd, *,
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
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200493 async def subprocess_exec(self, protocol_factory, *args,
494 stdin=subprocess.PIPE,
495 stdout=subprocess.PIPE,
496 stderr=subprocess.PIPE,
497 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700498 raise NotImplementedError
499
500 # Ready-based callback registration methods.
501 # The add_*() methods return None.
502 # The remove_*() methods return True if something was removed,
503 # False if there was nothing to delete.
504
505 def add_reader(self, fd, callback, *args):
506 raise NotImplementedError
507
508 def remove_reader(self, fd):
509 raise NotImplementedError
510
511 def add_writer(self, fd, callback, *args):
512 raise NotImplementedError
513
514 def remove_writer(self, fd):
515 raise NotImplementedError
516
517 # Completion based I/O methods returning Futures.
518
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200519 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700520 raise NotImplementedError
521
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200522 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200523 raise NotImplementedError
524
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200525 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526 raise NotImplementedError
527
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200528 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700529 raise NotImplementedError
530
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200531 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700532 raise NotImplementedError
533
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200534 async def sock_sendfile(self, sock, file, offset=0, count=None,
535 *, fallback=None):
536 raise NotImplementedError
537
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538 # Signal handling.
539
540 def add_signal_handler(self, sig, callback, *args):
541 raise NotImplementedError
542
543 def remove_signal_handler(self, sig):
544 raise NotImplementedError
545
Yury Selivanov740169c2015-05-11 14:23:38 -0400546 # Task factory.
547
548 def set_task_factory(self, factory):
549 raise NotImplementedError
550
551 def get_task_factory(self):
552 raise NotImplementedError
553
Yury Selivanov569efa22014-02-18 18:02:19 -0500554 # Error handlers.
555
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400556 def get_exception_handler(self):
557 raise NotImplementedError
558
Yury Selivanov569efa22014-02-18 18:02:19 -0500559 def set_exception_handler(self, handler):
560 raise NotImplementedError
561
562 def default_exception_handler(self, context):
563 raise NotImplementedError
564
565 def call_exception_handler(self, context):
566 raise NotImplementedError
567
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100568 # Debug flag management.
569
570 def get_debug(self):
571 raise NotImplementedError
572
573 def set_debug(self, enabled):
574 raise NotImplementedError
575
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700576
577class AbstractEventLoopPolicy:
578 """Abstract policy for accessing the event loop."""
579
580 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200581 """Get the event loop for the current context.
582
583 Returns an event loop object implementing the BaseEventLoop interface,
584 or raises an exception in case no event loop has been set for the
585 current context and the current policy does not specify to create one.
586
587 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700588 raise NotImplementedError
589
590 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200591 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700592 raise NotImplementedError
593
594 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200595 """Create and return a new event loop object according to this
596 policy's rules. If there's need to set this loop as the event loop for
597 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700598 raise NotImplementedError
599
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800600 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700601
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800602 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200603 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800604 raise NotImplementedError
605
606 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200607 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800608 raise NotImplementedError
609
610
611class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700612 """Default policy implementation for accessing the event loop.
613
614 In this policy, each thread has its own event loop. However, we
615 only automatically create an event loop by default for the main
616 thread; other threads by default have no event loop.
617
618 Other policies may have different rules (e.g. a single global
619 event loop, or automatically creating an event loop per thread, or
620 using some other notion of context to which an event loop is
621 associated).
622 """
623
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800624 _loop_factory = None
625
626 class _Local(threading.local):
627 _loop = None
628 _set_called = False
629
630 def __init__(self):
631 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700632
633 def get_event_loop(self):
634 """Get the event loop.
635
636 This may be None or an instance of EventLoop.
637 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800638 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500639 not self._local._set_called and
640 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800641 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500642
Victor Stinner3a1c7382014-12-18 01:20:10 +0100643 if self._local._loop is None:
644 raise RuntimeError('There is no current event loop in thread %r.'
645 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500646
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800647 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700648
649 def set_event_loop(self, loop):
650 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800651 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700652 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800653 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700654
655 def new_event_loop(self):
656 """Create a new event loop.
657
658 You must call set_event_loop() to make this the current event
659 loop.
660 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800661 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700662
663
664# Event loop policy. The policy itself is always global, even if the
665# policy's rules say that there is an event loop per thread (or other
666# notion of context). The default policy is installed by the first
667# call to get_event_loop_policy().
668_event_loop_policy = None
669
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800670# Lock for protecting the on-the-fly creation of the event loop policy.
671_lock = threading.Lock()
672
673
Yury Selivanov600a3492016-11-04 14:29:28 -0400674# A TLS for the running event loop, used by _get_running_loop.
675class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700676 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500677
678
Yury Selivanov600a3492016-11-04 14:29:28 -0400679_running_loop = _RunningLoop()
680
681
Yury Selivanovabae67e2017-12-11 10:07:44 -0500682def get_running_loop():
683 """Return the running event loop. Raise a RuntimeError if there is none.
684
685 This function is thread-specific.
686 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500687 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500688 loop = _get_running_loop()
689 if loop is None:
690 raise RuntimeError('no running event loop')
691 return loop
692
693
Yury Selivanov600a3492016-11-04 14:29:28 -0400694def _get_running_loop():
695 """Return the running event loop or None.
696
697 This is a low-level function intended to be used by event loops.
698 This function is thread-specific.
699 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500700 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700701 running_loop, pid = _running_loop.loop_pid
702 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500703 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400704
705
706def _set_running_loop(loop):
707 """Set the running event loop.
708
709 This is a low-level function intended to be used by event loops.
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)
jimmylai80bbe6a72017-09-05 17:36:59 -0700713 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400714
715
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800716def _init_event_loop_policy():
717 global _event_loop_policy
718 with _lock:
719 if _event_loop_policy is None: # pragma: no branch
720 from . import DefaultEventLoopPolicy
721 _event_loop_policy = DefaultEventLoopPolicy()
722
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700723
724def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200725 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700726 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800727 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700728 return _event_loop_policy
729
730
731def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200732 """Set the current event loop policy.
733
734 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700735 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700736 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
737 _event_loop_policy = policy
738
739
740def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400741 """Return an asyncio event loop.
742
743 When called from a coroutine or a callback (e.g. scheduled with call_soon
744 or similar API), this function will always return the running event loop.
745
746 If there is no running event loop set, the function will return
747 the result of `get_event_loop_policy().get_event_loop()` call.
748 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500749 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400750 current_loop = _get_running_loop()
751 if current_loop is not None:
752 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700753 return get_event_loop_policy().get_event_loop()
754
755
756def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200757 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700758 get_event_loop_policy().set_event_loop(loop)
759
760
761def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200762 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700763 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800764
765
766def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200767 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800768 return get_event_loop_policy().get_child_watcher()
769
770
771def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200772 """Equivalent to calling
773 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800774 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500775
776
777# Alias pure-Python implementations for testing purposes.
778_py__get_running_loop = _get_running_loop
779_py__set_running_loop = _set_running_loop
780_py_get_running_loop = get_running_loop
781_py_get_event_loop = get_event_loop
782
783
784try:
785 # get_event_loop() is one of the most frequently called
786 # functions in asyncio. Pure Python implementation is
787 # about 4 times slower than C-accelerated.
788 from _asyncio import (_get_running_loop, _set_running_loop,
789 get_running_loop, get_event_loop)
790except ImportError:
791 pass
792else:
793 # Alias C implementations for testing purposes.
794 _c__get_running_loop = _get_running_loop
795 _c__set_running_loop = _set_running_loop
796 _c_get_running_loop = get_running_loop
797 _c_get_event_loop = get_event_loop