blob: af4545b2cbe78de1d0828b9b50b273edafeb774c [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',
6 'Handle', 'TimerHandle',
7 '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
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070023class Handle:
24 """Object returned by callback registration methods."""
25
Victor Stinner80f53aa2014-06-27 13:52:20 +020026 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020027 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050028
Yury Selivanov569efa22014-02-18 18:02:19 -050029 def __init__(self, callback, args, loop):
Yury Selivanov569efa22014-02-18 18:02:19 -050030 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070031 self._callback = callback
32 self._args = args
33 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020034 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020035 if self._loop.get_debug():
Andrew Svetlovf74ef452017-12-15 07:04:38 +020036 self._source_traceback = format_helpers.extract_stack(
37 sys._getframe(1))
Victor Stinner80f53aa2014-06-27 13:52:20 +020038 else:
39 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070040
Victor Stinner1b38bc62014-09-17 23:24:13 +020041 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020042 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070043 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020044 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020045 if self._callback is not None:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020046 info.append(format_helpers._format_callback_source(
47 self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +020048 if self._source_traceback:
49 frame = self._source_traceback[-1]
Yury Selivanov6370f342017-12-10 18:36:12 -050050 info.append(f'created at {frame[0]}:{frame[1]}')
Victor Stinner1b38bc62014-09-17 23:24:13 +020051 return info
52
53 def __repr__(self):
54 if self._repr is not None:
55 return self._repr
56 info = self._repr_info()
Yury Selivanov6370f342017-12-10 18:36:12 -050057 return '<{}>'.format(' '.join(info))
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070058
59 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -040060 if not self._cancelled:
61 self._cancelled = True
62 if self._loop.get_debug():
63 # Keep a representation in debug mode to keep callback and
64 # parameters. For example, to log the warning
65 # "Executing <Handle...> took 2.5 second"
66 self._repr = repr(self)
67 self._callback = None
68 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070069
Marat Sharafutdinov69cfed12017-11-07 12:06:05 +030070 def cancelled(self):
71 return self._cancelled
72
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070073 def _run(self):
74 try:
75 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -050076 except Exception as exc:
Andrew Svetlovf74ef452017-12-15 07:04:38 +020077 cb = format_helpers._format_callback_source(
78 self._callback, self._args)
Yury Selivanov6370f342017-12-10 18:36:12 -050079 msg = f'Exception in callback {cb}'
Victor Stinner80f53aa2014-06-27 13:52:20 +020080 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -050081 'message': msg,
82 'exception': exc,
83 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +020084 }
85 if self._source_traceback:
86 context['source_traceback'] = self._source_traceback
87 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070088 self = None # Needed to break cycles when an exception occurs.
89
90
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070091class TimerHandle(Handle):
92 """Object returned by timed callback registration methods."""
93
Yury Selivanov592ada92014-09-25 12:07:56 -040094 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -050095
Yury Selivanov569efa22014-02-18 18:02:19 -050096 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070097 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -050098 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +020099 if self._source_traceback:
100 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700101 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400102 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700103
Victor Stinner1b38bc62014-09-17 23:24:13 +0200104 def _repr_info(self):
105 info = super()._repr_info()
106 pos = 2 if self._cancelled else 1
Yury Selivanov6370f342017-12-10 18:36:12 -0500107 info.insert(pos, f'when={self._when}')
Victor Stinner1b38bc62014-09-17 23:24:13 +0200108 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700109
110 def __hash__(self):
111 return hash(self._when)
112
113 def __lt__(self, other):
114 return self._when < other._when
115
116 def __le__(self, other):
117 if self._when < other._when:
118 return True
119 return self.__eq__(other)
120
121 def __gt__(self, other):
122 return self._when > other._when
123
124 def __ge__(self, other):
125 if self._when > other._when:
126 return True
127 return self.__eq__(other)
128
129 def __eq__(self, other):
130 if isinstance(other, TimerHandle):
131 return (self._when == other._when and
132 self._callback == other._callback and
133 self._args == other._args and
134 self._cancelled == other._cancelled)
135 return NotImplemented
136
137 def __ne__(self, other):
138 equal = self.__eq__(other)
139 return NotImplemented if equal is NotImplemented else not equal
140
Yury Selivanov592ada92014-09-25 12:07:56 -0400141 def cancel(self):
142 if not self._cancelled:
143 self._loop._timer_handle_cancelled(self)
144 super().cancel()
145
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700146
147class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100148 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700149
150 def close(self):
151 """Stop serving. This leaves existing connections open."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200152 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700153
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200154 async def wait_closed(self):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700155 """Coroutine to wait until service is closed."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200156 raise NotImplementedError
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700157
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530158 def get_loop(self):
159 """ Get the event loop the Server object is attached to."""
Andrew Svetlovffcb4c02017-12-30 18:52:56 +0200160 raise NotImplementedError
Srinivas Reddy Thatiparthy (శ్రీనివాస్ రెడ్డి తాటిపర్తి)1634fc22017-12-30 20:39:32 +0530161
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700162
163class AbstractEventLoop:
164 """Abstract event loop."""
165
166 # Running and stopping the event loop.
167
168 def run_forever(self):
169 """Run the event loop until stop() is called."""
170 raise NotImplementedError
171
172 def run_until_complete(self, future):
173 """Run the event loop until a Future is done.
174
175 Return the Future's result, or raise its exception.
176 """
177 raise NotImplementedError
178
179 def stop(self):
180 """Stop the event loop as soon as reasonable.
181
182 Exactly how soon that is may depend on the implementation, but
183 no more I/O callbacks should be scheduled.
184 """
185 raise NotImplementedError
186
187 def is_running(self):
188 """Return whether the event loop is currently running."""
189 raise NotImplementedError
190
Victor Stinner896a25a2014-07-08 11:29:25 +0200191 def is_closed(self):
192 """Returns True if the event loop was closed."""
193 raise NotImplementedError
194
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700195 def close(self):
196 """Close the loop.
197
198 The loop should not be running.
199
200 This is idempotent and irreversible.
201
202 No other methods should be called after this one.
203 """
204 raise NotImplementedError
205
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200206 async def shutdown_asyncgens(self):
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400207 """Shutdown all active asynchronous generators."""
208 raise NotImplementedError
209
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700210 # Methods scheduling callbacks. All these return Handles.
211
Yury Selivanov592ada92014-09-25 12:07:56 -0400212 def _timer_handle_cancelled(self, handle):
213 """Notification that a TimerHandle has been cancelled."""
214 raise NotImplementedError
215
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700216 def call_soon(self, callback, *args):
217 return self.call_later(0, callback, *args)
218
219 def call_later(self, delay, callback, *args):
220 raise NotImplementedError
221
222 def call_at(self, when, callback, *args):
223 raise NotImplementedError
224
225 def time(self):
226 raise NotImplementedError
227
Yury Selivanov7661db62016-05-16 15:38:39 -0400228 def create_future(self):
229 raise NotImplementedError
230
Victor Stinner896a25a2014-07-08 11:29:25 +0200231 # Method scheduling a coroutine object: create a task.
232
233 def create_task(self, coro):
234 raise NotImplementedError
235
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700236 # Methods for interacting with threads.
237
238 def call_soon_threadsafe(self, callback, *args):
239 raise NotImplementedError
240
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200241 async def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700242 raise NotImplementedError
243
244 def set_default_executor(self, executor):
245 raise NotImplementedError
246
247 # Network I/O methods returning Futures.
248
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200249 async def getaddrinfo(self, host, port, *,
250 family=0, type=0, proto=0, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700251 raise NotImplementedError
252
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200253 async def getnameinfo(self, sockaddr, flags=0):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700254 raise NotImplementedError
255
Neil Aspinallf7686c12017-12-19 19:45:42 +0000256 async def create_connection(
257 self, protocol_factory, host=None, port=None,
258 *, ssl=None, family=0, proto=0,
259 flags=0, sock=None, local_addr=None,
260 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200261 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262 raise NotImplementedError
263
Neil Aspinallf7686c12017-12-19 19:45:42 +0000264 async def create_server(
265 self, protocol_factory, host=None, port=None,
266 *, family=socket.AF_UNSPEC,
267 flags=socket.AI_PASSIVE, sock=None, backlog=100,
268 ssl=None, reuse_address=None, reuse_port=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200269 ssl_handshake_timeout=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700270 """A coroutine which creates a TCP server bound to host and port.
271
272 The return value is a Server object which can be used to stop
273 the service.
274
275 If host is an empty string or None all interfaces are assumed
276 and a list of multiple sockets will be returned (most likely
Yury Selivanov6370f342017-12-10 18:36:12 -0500277 one for IPv4 and another one for IPv6). The host parameter can also be
278 a sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700279
280 family can be set to either AF_INET or AF_INET6 to force the
281 socket to use IPv4 or IPv6. If not set it will be determined
282 from host (defaults to AF_UNSPEC).
283
284 flags is a bitmask for getaddrinfo().
285
286 sock can optionally be specified in order to use a preexisting
287 socket object.
288
289 backlog is the maximum number of queued connections passed to
290 listen() (defaults to 100).
291
292 ssl can be set to an SSLContext to enable SSL over the
293 accepted connections.
294
295 reuse_address tells the kernel to reuse a local socket in
296 TIME_WAIT state, without waiting for its natural timeout to
297 expire. If not specified will automatically be set to True on
298 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700299
300 reuse_port tells the kernel to allow this endpoint to be bound to
301 the same port as other existing endpoints are bound to, so long as
302 they all set this flag when being created. This option is not
303 supported on Windows.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000304
305 ssl_handshake_timeout is the time in seconds that an SSL server
306 will wait for completion of the SSL handshake before aborting the
307 connection. Default is 10s, longer timeouts may increase vulnerability
308 to DoS attacks (see https://support.f5.com/csp/article/K13834)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700309 """
310 raise NotImplementedError
311
Yury Selivanovf111b3d2017-12-30 00:35:36 -0500312 async def start_tls(self, transport, protocol, sslcontext, *,
313 server_side=False,
314 server_hostname=None,
315 ssl_handshake_timeout=None):
316 """Upgrade a transport to TLS.
317
318 Return a new transport that *protocol* should start using
319 immediately.
320 """
321 raise NotImplementedError
322
Neil Aspinallf7686c12017-12-19 19:45:42 +0000323 async def create_unix_connection(
324 self, protocol_factory, path=None, *,
325 ssl=None, sock=None,
326 server_hostname=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200327 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500328 raise NotImplementedError
329
Neil Aspinallf7686c12017-12-19 19:45:42 +0000330 async def create_unix_server(
331 self, protocol_factory, path=None, *,
332 sock=None, backlog=100, ssl=None,
Andrew Svetlov51eb1c62017-12-20 20:24:43 +0200333 ssl_handshake_timeout=None):
Yury Selivanovb057c522014-02-18 12:15:06 -0500334 """A coroutine which creates a UNIX Domain Socket server.
335
Yury Selivanovdec1a452014-02-18 22:27:48 -0500336 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500337 the service.
338
339 path is a str, representing a file systsem path to bind the
340 server socket to.
341
342 sock can optionally be specified in order to use a preexisting
343 socket object.
344
345 backlog is the maximum number of queued connections passed to
346 listen() (defaults to 100).
347
348 ssl can be set to an SSLContext to enable SSL over the
349 accepted connections.
Neil Aspinallf7686c12017-12-19 19:45:42 +0000350
351 ssl_handshake_timeout is the time in seconds that an SSL server
352 will wait for the SSL handshake to complete (defaults to 10s).
Yury Selivanovb057c522014-02-18 12:15:06 -0500353 """
354 raise NotImplementedError
355
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200356 async def create_datagram_endpoint(self, protocol_factory,
357 local_addr=None, remote_addr=None, *,
358 family=0, proto=0, flags=0,
359 reuse_address=None, reuse_port=None,
360 allow_broadcast=None, sock=None):
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700361 """A coroutine which creates a datagram endpoint.
362
363 This method will try to establish the endpoint in the background.
364 When successful, the coroutine returns a (transport, protocol) pair.
365
366 protocol_factory must be a callable returning a protocol instance.
367
Quentin Dawansfe4ea9c2017-10-30 14:43:02 +0100368 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
369 host (or family if specified), socket type SOCK_DGRAM.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700370
371 reuse_address tells the kernel to reuse a local socket in
372 TIME_WAIT state, without waiting for its natural timeout to
373 expire. If not specified it will automatically be set to True on
374 UNIX.
375
376 reuse_port tells the kernel to allow this endpoint to be bound to
377 the same port as other existing endpoints are bound to, so long as
378 they all set this flag when being created. This option is not
379 supported on Windows and some UNIX's. If the
380 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
381 capability is unsupported.
382
383 allow_broadcast tells the kernel to allow this endpoint to send
384 messages to the broadcast address.
385
386 sock can optionally be specified in order to use a preexisting
387 socket object.
388 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700389 raise NotImplementedError
390
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700391 # Pipes and subprocesses.
392
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200393 async def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200394 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700395
396 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200397 pipe is a file-like object.
398 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800399 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700400 # The reason to accept file-like object instead of just file descriptor
401 # is: we need to own pipe and close it at transport finishing
402 # Can got complicated errors if pass f.fileno(),
403 # close fd in pipe transport then close f and vise versa.
404 raise NotImplementedError
405
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200406 async def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500407 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700408
409 protocol_factory should instantiate object with BaseProtocol interface.
410 Pipe is file-like object already switched to nonblocking.
411 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800412 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700413 # The reason to accept file-like object instead of just file descriptor
414 # is: we need to own pipe and close it at transport finishing
415 # Can got complicated errors if pass f.fileno(),
416 # close fd in pipe transport then close f and vise versa.
417 raise NotImplementedError
418
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200419 async def subprocess_shell(self, protocol_factory, cmd, *,
420 stdin=subprocess.PIPE,
421 stdout=subprocess.PIPE,
422 stderr=subprocess.PIPE,
423 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700424 raise NotImplementedError
425
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200426 async def subprocess_exec(self, protocol_factory, *args,
427 stdin=subprocess.PIPE,
428 stdout=subprocess.PIPE,
429 stderr=subprocess.PIPE,
430 **kwargs):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700431 raise NotImplementedError
432
433 # Ready-based callback registration methods.
434 # The add_*() methods return None.
435 # The remove_*() methods return True if something was removed,
436 # False if there was nothing to delete.
437
438 def add_reader(self, fd, callback, *args):
439 raise NotImplementedError
440
441 def remove_reader(self, fd):
442 raise NotImplementedError
443
444 def add_writer(self, fd, callback, *args):
445 raise NotImplementedError
446
447 def remove_writer(self, fd):
448 raise NotImplementedError
449
450 # Completion based I/O methods returning Futures.
451
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200452 async def sock_recv(self, sock, nbytes):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700453 raise NotImplementedError
454
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200455 async def sock_recv_into(self, sock, buf):
Antoine Pitrou525f40d2017-10-19 21:46:40 +0200456 raise NotImplementedError
457
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200458 async def sock_sendall(self, sock, data):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700459 raise NotImplementedError
460
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200461 async def sock_connect(self, sock, address):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700462 raise NotImplementedError
463
Andrew Svetlov5f841b52017-12-09 00:23:48 +0200464 async def sock_accept(self, sock):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700465 raise NotImplementedError
466
467 # Signal handling.
468
469 def add_signal_handler(self, sig, callback, *args):
470 raise NotImplementedError
471
472 def remove_signal_handler(self, sig):
473 raise NotImplementedError
474
Yury Selivanov740169c2015-05-11 14:23:38 -0400475 # Task factory.
476
477 def set_task_factory(self, factory):
478 raise NotImplementedError
479
480 def get_task_factory(self):
481 raise NotImplementedError
482
Yury Selivanov569efa22014-02-18 18:02:19 -0500483 # Error handlers.
484
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400485 def get_exception_handler(self):
486 raise NotImplementedError
487
Yury Selivanov569efa22014-02-18 18:02:19 -0500488 def set_exception_handler(self, handler):
489 raise NotImplementedError
490
491 def default_exception_handler(self, context):
492 raise NotImplementedError
493
494 def call_exception_handler(self, context):
495 raise NotImplementedError
496
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100497 # Debug flag management.
498
499 def get_debug(self):
500 raise NotImplementedError
501
502 def set_debug(self, enabled):
503 raise NotImplementedError
504
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700505
506class AbstractEventLoopPolicy:
507 """Abstract policy for accessing the event loop."""
508
509 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200510 """Get the event loop for the current context.
511
512 Returns an event loop object implementing the BaseEventLoop interface,
513 or raises an exception in case no event loop has been set for the
514 current context and the current policy does not specify to create one.
515
516 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700517 raise NotImplementedError
518
519 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200520 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700521 raise NotImplementedError
522
523 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200524 """Create and return a new event loop object according to this
525 policy's rules. If there's need to set this loop as the event loop for
526 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700527 raise NotImplementedError
528
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800529 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800531 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200532 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800533 raise NotImplementedError
534
535 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200536 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800537 raise NotImplementedError
538
539
540class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700541 """Default policy implementation for accessing the event loop.
542
543 In this policy, each thread has its own event loop. However, we
544 only automatically create an event loop by default for the main
545 thread; other threads by default have no event loop.
546
547 Other policies may have different rules (e.g. a single global
548 event loop, or automatically creating an event loop per thread, or
549 using some other notion of context to which an event loop is
550 associated).
551 """
552
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800553 _loop_factory = None
554
555 class _Local(threading.local):
556 _loop = None
557 _set_called = False
558
559 def __init__(self):
560 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700561
562 def get_event_loop(self):
563 """Get the event loop.
564
565 This may be None or an instance of EventLoop.
566 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800567 if (self._local._loop is None and
Yury Selivanov6370f342017-12-10 18:36:12 -0500568 not self._local._set_called and
569 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800570 self.set_event_loop(self.new_event_loop())
Yury Selivanov6370f342017-12-10 18:36:12 -0500571
Victor Stinner3a1c7382014-12-18 01:20:10 +0100572 if self._local._loop is None:
573 raise RuntimeError('There is no current event loop in thread %r.'
574 % threading.current_thread().name)
Yury Selivanov6370f342017-12-10 18:36:12 -0500575
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800576 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700577
578 def set_event_loop(self, loop):
579 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800580 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700581 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800582 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700583
584 def new_event_loop(self):
585 """Create a new event loop.
586
587 You must call set_event_loop() to make this the current event
588 loop.
589 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800590 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591
592
593# Event loop policy. The policy itself is always global, even if the
594# policy's rules say that there is an event loop per thread (or other
595# notion of context). The default policy is installed by the first
596# call to get_event_loop_policy().
597_event_loop_policy = None
598
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800599# Lock for protecting the on-the-fly creation of the event loop policy.
600_lock = threading.Lock()
601
602
Yury Selivanov600a3492016-11-04 14:29:28 -0400603# A TLS for the running event loop, used by _get_running_loop.
604class _RunningLoop(threading.local):
jimmylai80bbe6a72017-09-05 17:36:59 -0700605 loop_pid = (None, None)
Yury Selivanovba7e1f92017-03-02 20:07:11 -0500606
607
Yury Selivanov600a3492016-11-04 14:29:28 -0400608_running_loop = _RunningLoop()
609
610
Yury Selivanovabae67e2017-12-11 10:07:44 -0500611def get_running_loop():
612 """Return the running event loop. Raise a RuntimeError if there is none.
613
614 This function is thread-specific.
615 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500616 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanovabae67e2017-12-11 10:07:44 -0500617 loop = _get_running_loop()
618 if loop is None:
619 raise RuntimeError('no running event loop')
620 return loop
621
622
Yury Selivanov600a3492016-11-04 14:29:28 -0400623def _get_running_loop():
624 """Return the running event loop or None.
625
626 This is a low-level function intended to be used by event loops.
627 This function is thread-specific.
628 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500629 # NOTE: this function is implemented in C (see _asynciomodule.c)
jimmylai80bbe6a72017-09-05 17:36:59 -0700630 running_loop, pid = _running_loop.loop_pid
631 if running_loop is not None and pid == os.getpid():
Yury Selivanov902e9c52017-03-02 23:57:33 -0500632 return running_loop
Yury Selivanov600a3492016-11-04 14:29:28 -0400633
634
635def _set_running_loop(loop):
636 """Set the running event loop.
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.loop_pid = (loop, os.getpid())
Yury Selivanov600a3492016-11-04 14:29:28 -0400643
644
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800645def _init_event_loop_policy():
646 global _event_loop_policy
647 with _lock:
648 if _event_loop_policy is None: # pragma: no branch
649 from . import DefaultEventLoopPolicy
650 _event_loop_policy = DefaultEventLoopPolicy()
651
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700652
653def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200654 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700655 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800656 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700657 return _event_loop_policy
658
659
660def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200661 """Set the current event loop policy.
662
663 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700664 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700665 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
666 _event_loop_policy = policy
667
668
669def get_event_loop():
Yury Selivanov600a3492016-11-04 14:29:28 -0400670 """Return an asyncio event loop.
671
672 When called from a coroutine or a callback (e.g. scheduled with call_soon
673 or similar API), this function will always return the running event loop.
674
675 If there is no running event loop set, the function will return
676 the result of `get_event_loop_policy().get_event_loop()` call.
677 """
Yury Selivanova70232f2017-12-13 14:49:42 -0500678 # NOTE: this function is implemented in C (see _asynciomodule.c)
Yury Selivanov600a3492016-11-04 14:29:28 -0400679 current_loop = _get_running_loop()
680 if current_loop is not None:
681 return current_loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700682 return get_event_loop_policy().get_event_loop()
683
684
685def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200686 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700687 get_event_loop_policy().set_event_loop(loop)
688
689
690def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200691 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700692 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800693
694
695def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200696 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800697 return get_event_loop_policy().get_child_watcher()
698
699
700def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200701 """Equivalent to calling
702 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800703 return get_event_loop_policy().set_child_watcher(watcher)
Yury Selivanova70232f2017-12-13 14:49:42 -0500704
705
706# Alias pure-Python implementations for testing purposes.
707_py__get_running_loop = _get_running_loop
708_py__set_running_loop = _set_running_loop
709_py_get_running_loop = get_running_loop
710_py_get_event_loop = get_event_loop
711
712
713try:
714 # get_event_loop() is one of the most frequently called
715 # functions in asyncio. Pure Python implementation is
716 # about 4 times slower than C-accelerated.
717 from _asyncio import (_get_running_loop, _set_running_loop,
718 get_running_loop, get_event_loop)
719except ImportError:
720 pass
721else:
722 # Alias C implementations for testing purposes.
723 _c__get_running_loop = _get_running_loop
724 _c__set_running_loop = _set_running_loop
725 _c_get_running_loop = get_running_loop
726 _c_get_event_loop = get_event_loop