blob: d5365dc480d3d30e1f5b14b3faebdab8fa3882e9 [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 Selivanovba7e1f92017-03-02 20:07:11 -050014import os
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070015import socket
Victor Stinner313a9802014-07-29 12:58:23 +020016import subprocess
Victor Stinner307bccc2014-06-12 18:39:26 +020017import sys
Victor Stinner313a9802014-07-29 12:58:23 +020018import threading
Victor Stinner307bccc2014-06-12 18:39:26 +020019
Andrew Svetlovf74ef452017-12-15 07:04:38 +020020from . import format_helpers
Antoine Pitrou921e9432017-11-07 17:23:29 +010021
22
Andrew Svetlov7464e872018-01-19 20:04:29 +020023class SendfileNotAvailableError(RuntimeError):
24 """Sendfile syscall is not available.
25
26 Raised if OS does not support senfile syscall for given socket or
27 file type.
28 """
29
30
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031class Handle:
32 """Object returned by callback registration methods."""
33
Victor Stinner80f53aa2014-06-27 13:52:20 +020034 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020035 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050036
Yury Selivanov569efa22014-02-18 18:02:19 -050037 def __init__(self, callback, args, loop):
Yury Selivanov569efa22014-02-18 18:02:19 -050038 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070039 self._callback = callback
40 self._args = args
41 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020042 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020043 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020044 self._source_traceback = format_helpers.extract_stack(
45 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020046 else:
47 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070048
Victor Stinner1b38bc62014-09-17 23:24:13 +020049 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020050 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070051 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020052 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020053 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020054 info.append(format_helpers._format_callback_source(
55 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020056 if self._source_traceback:
57 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050058 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020059 return info
60
61 def __repr__(self):
62 if self._repr is not None:
63 return self._repr
64 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050065 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070066
67 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040068 if not self._cancelled:
69 self._cancelled = True
70 if self._loop.get_debug():
71 # Keep a representation in debug mode to keep callback and
72 # parameters. For example, to log the warning
73 # "Executing <Handle...> took 2.5 second"
74 self._repr = repr(self)
75 self._callback = None
76 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070077
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030078 def cancelled(self):
79 return self._cancelled
80
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070081 def _run(self):
82 try:
83 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050084 except Exception 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 Selivanov569efa22014-02-18 18:02:19 -0500104 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700105 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -0500106 super().__init__(callback, args, loop)
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):
122 return self._when < other._when
123
124 def __le__(self, other):
125 if self._when < other._when:
126 return True
127 return self.__eq__(other)
128
129 def __gt__(self, other):
130 return self._when > other._when
131
132 def __ge__(self, other):
133 if self._when > other._when:
134 return True
135 return self.__eq__(other)
136
137 def __eq__(self, other):
138 if isinstance(other, TimerHandle):
139 return (self._when == other._when and
140 self._callback == other._callback and
141 self._args == other._args and
142 self._cancelled == other._cancelled)
143 return NotImplemented
144
145 def __ne__(self, other):
146 equal = self.__eq__(other)
147 return NotImplemented if equal is NotImplemented else not equal
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
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700154
155class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100156 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700157
158 def close(self):
159 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200160 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700161
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200162 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700163 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200164 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700165
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530166 def get_loop(self):
167 """ Get the event loop the Server object is attached to."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200168 raise NotImplementedError
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530169
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700170
171class AbstractEventLoop:
172 """Abstract event loop."""
173
174 # Running and stopping the event loop.
175
176 def run_forever(self):
177 """Run the event loop until stop() is called."""
178 raise NotImplementedError
179
180 def run_until_complete(self, future):
181 """Run the event loop until a Future is done.
182
183 Return the Future's result, or raise its exception.
184 """
185 raise NotImplementedError
186
187 def stop(self):
188 """Stop the event loop as soon as reasonable.
189
190 Exactly how soon that is may depend on the implementation, but
191 no more I/O callbacks should be scheduled.
192 """
193 raise NotImplementedError
194
195 def is_running(self):
196 """Return whether the event loop is currently running."""
197 raise NotImplementedError
198
Victor Stinner896a25a2014-07-08 11:29:25 +0200199 def is_closed(self):
200 """Returns True if the event loop was closed."""
201 raise NotImplementedError
202
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700203 def close(self):
204 """Close the loop.
205
206 The loop should not be running.
207
208 This is idempotent and irreversible.
209
210 No other methods should be called after this one.
211 """
212 raise NotImplementedError
213
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200214 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400215 """Shutdown all active asynchronous generators."""
216 raise NotImplementedError
217
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700218 # Methods scheduling callbacks. All these return Handles.
219
Yury Selivanov592ada92014-09-25 12:07:56 -0400220 def _timer_handle_cancelled(self, handle):
221 """Notification that a TimerHandle has been cancelled."""
222 raise NotImplementedError
223
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700224 def call_soon(self, callback, *args):
225 return self.call_later(0, callback, *args)
226
227 def call_later(self, delay, callback, *args):
228 raise NotImplementedError
229
230 def call_at(self, when, callback, *args):
231 raise NotImplementedError
232
233 def time(self):
234 raise NotImplementedError
235
Yury Selivanov7661db62016-05-16 15:38:39 -0400236 def create_future(self):
237 raise NotImplementedError
238
Victor Stinner896a25a2014-07-08 11:29:25 +0200239 # Method scheduling a coroutine object: create a task.
240
241 def create_task(self, coro):
242 raise NotImplementedError
243
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700244 # Methods for interacting with threads.
245
246 def call_soon_threadsafe(self, callback, *args):
247 raise NotImplementedError
248
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200249 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700250 raise NotImplementedError
251
252 def set_default_executor(self, executor):
253 raise NotImplementedError
254
255 # Network I/O methods returning Futures.
256
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200257 async def getaddrinfo(self, host, port, *,
258 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700259 raise NotImplementedError
260
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200261 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262 raise NotImplementedError
263
Neil Aspinallf7686c12017-12-19 19:45:42 +0000264 async def create_connection(
265 self, protocol_factory, host=None, port=None,
266 *, ssl=None, family=0, proto=0,
267 flags=0, sock=None, local_addr=None,
268 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200269 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700270 raise NotImplementedError
271
Neil Aspinallf7686c12017-12-19 19:45:42 +0000272 async def create_server(
273 self, protocol_factory, host=None, port=None,
274 *, family=socket.AF_UNSPEC,
275 flags=socket.AI_PASSIVE, sock=None, backlog=100,
276 ssl=None, reuse_address=None, reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200277 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700278 """A coroutine which creates a TCP server bound to host and port.
279
280 The return value is a Server object which can be used to stop
281 the service.
282
283 If host is an empty string or None all interfaces are assumed
284 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500285 one for IPv4 and another one for IPv6). The host parameter can also be
286 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700287
288 family can be set to either AF_INET or AF_INET6 to force the
289 socket to use IPv4 or IPv6. If not set it will be determined
290 from host (defaults to AF_UNSPEC).
291
292 flags is a bitmask for getaddrinfo().
293
294 sock can optionally be specified in order to use a preexisting
295 socket object.
296
297 backlog is the maximum number of queued connections passed to
298 listen() (defaults to 100).
299
300 ssl can be set to an SSLContext to enable SSL over the
301 accepted connections.
302
303 reuse_address tells the kernel to reuse a local socket in
304 TIME_WAIT state, without waiting for its natural timeout to
305 expire. If not specified will automatically be set to True on
306 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700307
308 reuse_port tells the kernel to allow this endpoint to be bound to
309 the same port as other existing endpoints are bound to, so long as
310 they all set this flag when being created. This option is not
311 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000312
313 ssl_handshake_timeout is the time in seconds that an SSL server
314 will wait for completion of the SSL handshake before aborting the
315 connection. Default is 10s, longer timeouts may increase vulnerability
316 to DoS attacks (see https://support.f5.com/csp/article/K13834)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700317 """
318 raise NotImplementedError
319
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500320 async def start_tls(self, transport, protocol, sslcontext, *,
321 server_side=False,
322 server_hostname=None,
323 ssl_handshake_timeout=None):
324 """Upgrade a transport to TLS.
325
326 Return a new transport that *protocol* should start using
327 immediately.
328 """
329 raise NotImplementedError
330
Neil Aspinallf7686c12017-12-19 19:45:42 +0000331 async def create_unix_connection(
332 self, protocol_factory, path=None, *,
333 ssl=None, sock=None,
334 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200335 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500336 raise NotImplementedError
337
Neil Aspinallf7686c12017-12-19 19:45:42 +0000338 async def create_unix_server(
339 self, protocol_factory, path=None, *,
340 sock=None, backlog=100, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200341 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500342 """A coroutine which creates a UNIX Domain Socket server.
343
Yury Selivanovdec1a452014-02-18 22:27:48 -0500344 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500345 the service.
346
347 path is a str, representing a file systsem path to bind the
348 server socket to.
349
350 sock can optionally be specified in order to use a preexisting
351 socket object.
352
353 backlog is the maximum number of queued connections passed to
354 listen() (defaults to 100).
355
356 ssl can be set to an SSLContext to enable SSL over the
357 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000358
359 ssl_handshake_timeout is the time in seconds that an SSL server
360 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovb057c522014-02-18 12:15:06 -0500361 """
362 raise NotImplementedError
363
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200364 async def create_datagram_endpoint(self, protocol_factory,
365 local_addr=None, remote_addr=None, *,
366 family=0, proto=0, flags=0,
367 reuse_address=None, reuse_port=None,
368 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700369 """A coroutine which creates a datagram endpoint.
370
371 This method will try to establish the endpoint in the background.
372 When successful, the coroutine returns a (transport, protocol) pair.
373
374 protocol_factory must be a callable returning a protocol instance.
375
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100376 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
377 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700378
379 reuse_address tells the kernel to reuse a local socket in
380 TIME_WAIT state, without waiting for its natural timeout to
381 expire. If not specified it will automatically be set to True on
382 UNIX.
383
384 reuse_port tells the kernel to allow this endpoint to be bound to
385 the same port as other existing endpoints are bound to, so long as
386 they all set this flag when being created. This option is not
387 supported on Windows and some UNIX's. If the
388 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
389 capability is unsupported.
390
391 allow_broadcast tells the kernel to allow this endpoint to send
392 messages to the broadcast address.
393
394 sock can optionally be specified in order to use a preexisting
395 socket object.
396 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700397 raise NotImplementedError
398
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700399 # Pipes and subprocesses.
400
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200401 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200402 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700403
404 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200405 pipe is a file-like object.
406 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800407 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408 # The reason to accept file-like object instead of just file descriptor
409 # is: we need to own pipe and close it at transport finishing
410 # Can got complicated errors if pass f.fileno(),
411 # close fd in pipe transport then close f and vise versa.
412 raise NotImplementedError
413
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200414 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500415 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700416
417 protocol_factory should instantiate object with BaseProtocol interface.
418 Pipe is file-like object already switched to nonblocking.
419 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800420 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700421 # The reason to accept file-like object instead of just file descriptor
422 # is: we need to own pipe and close it at transport finishing
423 # Can got complicated errors if pass f.fileno(),
424 # close fd in pipe transport then close f and vise versa.
425 raise NotImplementedError
426
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200427 async def subprocess_shell(self, protocol_factory, cmd, *,
428 stdin=subprocess.PIPE,
429 stdout=subprocess.PIPE,
430 stderr=subprocess.PIPE,
431 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700432 raise NotImplementedError
433
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200434 async def subprocess_exec(self, protocol_factory, *args,
435 stdin=subprocess.PIPE,
436 stdout=subprocess.PIPE,
437 stderr=subprocess.PIPE,
438 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700439 raise NotImplementedError
440
441 # Ready-based callback registration methods.
442 # The add_*() methods return None.
443 # The remove_*() methods return True if something was removed,
444 # False if there was nothing to delete.
445
446 def add_reader(self, fd, callback, *args):
447 raise NotImplementedError
448
449 def remove_reader(self, fd):
450 raise NotImplementedError
451
452 def add_writer(self, fd, callback, *args):
453 raise NotImplementedError
454
455 def remove_writer(self, fd):
456 raise NotImplementedError
457
458 # Completion based I/O methods returning Futures.
459
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200460 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700461 raise NotImplementedError
462
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200463 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200464 raise NotImplementedError
465
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200466 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700467 raise NotImplementedError
468
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200469 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700470 raise NotImplementedError
471
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200472 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700473 raise NotImplementedError
474
Andrew Svetlov6b5a2792018-01-16 19:59:34 +0200475 async def sock_sendfile(self, sock, file, offset=0, count=None,
476 *, fallback=None):
477 raise NotImplementedError
478
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479 # Signal handling.
480
481 def add_signal_handler(self, sig, callback, *args):
482 raise NotImplementedError
483
484 def remove_signal_handler(self, sig):
485 raise NotImplementedError
486
Yury Selivanov740169c2015-05-11 14:23:38 -0400487 # Task factory.
488
489 def set_task_factory(self, factory):
490 raise NotImplementedError
491
492 def get_task_factory(self):
493 raise NotImplementedError
494
Yury Selivanov569efa22014-02-18 18:02:19 -0500495 # Error handlers.
496
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400497 def get_exception_handler(self):
498 raise NotImplementedError
499
Yury Selivanov569efa22014-02-18 18:02:19 -0500500 def set_exception_handler(self, handler):
501 raise NotImplementedError
502
503 def default_exception_handler(self, context):
504 raise NotImplementedError
505
506 def call_exception_handler(self, context):
507 raise NotImplementedError
508
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100509 # Debug flag management.
510
511 def get_debug(self):
512 raise NotImplementedError
513
514 def set_debug(self, enabled):
515 raise NotImplementedError
516
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517
518class AbstractEventLoopPolicy:
519 """Abstract policy for accessing the event loop."""
520
521 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200522 """Get the event loop for the current context.
523
524 Returns an event loop object implementing the BaseEventLoop interface,
525 or raises an exception in case no event loop has been set for the
526 current context and the current policy does not specify to create one.
527
528 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700529 raise NotImplementedError
530
531 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200532 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700533 raise NotImplementedError
534
535 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200536 """Create and return a new event loop object according to this
537 policy's rules. If there's need to set this loop as the event loop for
538 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700539 raise NotImplementedError
540
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800541 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700542
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800543 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200544 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800545 raise NotImplementedError
546
547 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200548 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800549 raise NotImplementedError
550
551
552class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700553 """Default policy implementation for accessing the event loop.
554
555 In this policy, each thread has its own event loop. However, we
556 only automatically create an event loop by default for the main
557 thread; other threads by default have no event loop.
558
559 Other policies may have different rules (e.g. a single global
560 event loop, or automatically creating an event loop per thread, or
561 using some other notion of context to which an event loop is
562 associated).
563 """
564
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800565 _loop_factory = None
566
567 class _Local(threading.local):
568 _loop = None
569 _set_called = False
570
571 def __init__(self):
572 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700573
574 def get_event_loop(self):
575 """Get the event loop.
576
577 This may be None or an instance of EventLoop.
578 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800579 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500580 not self._local._set_called and
581 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800582 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500583
Victor Stinner3a1c7382014-12-18 01:20:10 +0100584 if self._local._loop is None:
585 raise RuntimeError('There is no current event loop in thread %r.'
586 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500587
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800588 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700589
590 def set_event_loop(self, loop):
591 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800592 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700593 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800594 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700595
596 def new_event_loop(self):
597 """Create a new event loop.
598
599 You must call set_event_loop() to make this the current event
600 loop.
601 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800602 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700603
604
605# Event loop policy. The policy itself is always global, even if the
606# policy's rules say that there is an event loop per thread (or other
607# notion of context). The default policy is installed by the first
608# call to get_event_loop_policy().
609_event_loop_policy = None
610
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800611# Lock for protecting the on-the-fly creation of the event loop policy.
612_lock = threading.Lock()
613
614
Yury Selivanov600a3492016-11-04 14:29:28 -0400615# A TLS for the running event loop, used by _get_running_loop.
616class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700617 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500618
619
Yury Selivanov600a3492016-11-04 14:29:28 -0400620_running_loop = _RunningLoop()
621
622
Yury Selivanovabae67e2017-12-11 10:07:44 -0500623def get_running_loop():
624 """Return the running event loop. Raise a RuntimeError if there is none.
625
626 This function is thread-specific.
627 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500628 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500629 loop = _get_running_loop()
630 if loop is None:
631 raise RuntimeError('no running event loop')
632 return loop
633
634
Yury Selivanov600a3492016-11-04 14:29:28 -0400635def _get_running_loop():
636 """Return the running event loop or None.
637
638 This is a low-level function intended to be used by event loops.
639 This function is thread-specific.
640 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500641 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700642 running_loop, pid = _running_loop.loop_pid
643 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500644 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400645
646
647def _set_running_loop(loop):
648 """Set the running event loop.
649
650 This is a low-level function intended to be used by event loops.
651 This function is thread-specific.
652 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500653 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700654 _running_loop.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400655
656
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800657def _init_event_loop_policy():
658 global _event_loop_policy
659 with _lock:
660 if _event_loop_policy is None: # pragma: no branch
661 from . import DefaultEventLoopPolicy
662 _event_loop_policy = DefaultEventLoopPolicy()
663
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664
665def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200666 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700667 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800668 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700669 return _event_loop_policy
670
671
672def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200673 """Set the current event loop policy.
674
675 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700676 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700677 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
678 _event_loop_policy = policy
679
680
681def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400682 """Return an asyncio event loop.
683
684 When called from a coroutine or a callback (e.g. scheduled with call_soon
685 or similar API), this function will always return the running event loop.
686
687 If there is no running event loop set, the function will return
688 the result of `get_event_loop_policy().get_event_loop()` call.
689 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500690 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400691 current_loop = _get_running_loop()
692 if current_loop is not None:
693 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700694 return get_event_loop_policy().get_event_loop()
695
696
697def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200698 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700699 get_event_loop_policy().set_event_loop(loop)
700
701
702def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200703 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700704 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800705
706
707def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200708 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800709 return get_event_loop_policy().get_child_watcher()
710
711
712def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200713 """Equivalent to calling
714 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800715 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500716
717
718# Alias pure-Python implementations for testing purposes.
719_py__get_running_loop = _get_running_loop
720_py__set_running_loop = _set_running_loop
721_py_get_running_loop = get_running_loop
722_py_get_event_loop = get_event_loop
723
724
725try:
726 # get_event_loop() is one of the most frequently called
727 # functions in asyncio. Pure Python implementation is
728 # about 4 times slower than C-accelerated.
729 from _asyncio import (_get_running_loop, _set_running_loop,
730 get_running_loop, get_event_loop)
731except ImportError:
732 pass
733else:
734 # Alias C implementations for testing purposes.
735 _c__get_running_loop = _get_running_loop
736 _c__set_running_loop = _set_running_loop
737 _c_get_running_loop = get_running_loop
738 _c_get_event_loop = get_event_loop